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 | cython__cython | Cython/Compiler/Nodes.py | {
"start": 265817,
"end": 266637
} | class ____(StatNode):
# Definition of a property in an extension type.
#
# name string
# doc EncodedString or None Doc string
# entry Symtab.Entry The Entry of the property attribute
# body StatListNode
child_attrs = ["body"]
def analyse_declarations(self, env):
self.entry = env.declare_property(self.name, self.doc, self.pos)
self.body.analyse_declarations(self.entry.scope)
def analyse_expressions(self, env):
self.body = self.body.analyse_expressions(env)
return self
def generate_function_definitions(self, env, code):
self.body.generate_function_definitions(env, code)
def generate_execution_code(self, code):
pass
def annotate(self, code):
self.body.annotate(code)
| PropertyNode |
python | graphql-python__graphene | graphene/types/scalars.py | {
"start": 4585,
"end": 5194
} | class ____(Scalar):
"""
The `ID` scalar type represents a unique identifier, often used to
refetch an object or as key for a cache. The ID type appears in a JSON
response as a String; however, it is not intended to be human-readable.
When expected as an input type, any string (such as `"4"`) or integer
(such as `4`) input value will be accepted as an ID.
"""
serialize = str
parse_value = str
@staticmethod
def parse_literal(ast, _variables=None):
if isinstance(ast, (StringValueNode, IntValueNode)):
return ast.value
return Undefined
| ID |
python | openai__openai-python | src/openai/types/beta/realtime/transcription_session_create_params.py | {
"start": 386,
"end": 2701
} | class ____(TypedDict, total=False):
client_secret: ClientSecret
"""Configuration options for the generated client secret."""
include: List[str]
"""The set of items to include in the transcription. Current available items are:
- `item.input_audio_transcription.logprobs`
"""
input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"]
"""The format of input audio.
Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must
be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian
byte order.
"""
input_audio_noise_reduction: InputAudioNoiseReduction
"""Configuration for input audio noise reduction.
This can be set to `null` to turn off. Noise reduction filters audio added to
the input audio buffer before it is sent to VAD and the model. Filtering the
audio can improve VAD and turn detection accuracy (reducing false positives) and
model performance by improving perception of the input audio.
"""
input_audio_transcription: InputAudioTranscription
"""Configuration for input audio transcription.
The client can optionally set the language and prompt for transcription, these
offer additional guidance to the transcription service.
"""
modalities: List[Literal["text", "audio"]]
"""The set of modalities the model can respond with.
To disable audio, set this to ["text"].
"""
turn_detection: TurnDetection
"""Configuration for turn detection, ether Server VAD or Semantic VAD.
This can be set to `null` to turn off, in which case the client must manually
trigger model response. Server VAD means that the model will detect the start
and end of speech based on audio volume and respond at the end of user speech.
Semantic VAD is more advanced and uses a turn detection model (in conjunction
with VAD) to semantically estimate whether the user has finished speaking, then
dynamically sets a timeout based on this probability. For example, if user audio
trails off with "uhhm", the model will score a low probability of turn end and
wait longer for the user to continue speaking. This can be useful for more
natural conversations, but may have a higher latency.
"""
| TranscriptionSessionCreateParams |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_import_templates.py | {
"start": 344,
"end": 5216
} | class ____(AdminTestMixin, TestCase):
def test_import_export_template(self):
response = self._get_url_response(self.core_book_url)
self.assertTemplateUsed(response, self.change_list_template_url)
self.assertTemplateUsed(response, self.change_list_url)
self.assertTemplateUsed(response, self.change_list_url)
self.assertContains(response, _("Import"))
self.assertContains(response, _("Export"))
self.assertContains(response, "Custom change list item")
@patch("import_export.admin.logger")
def test_issue_1521_change_list_template_as_property(self, mock_logger):
# Test that a warning is logged when change_list_template is a property
class TestImportCls(ImportMixin):
@property
def change_list_template(self):
return ["x"]
TestImportCls()
mock_logger.warning.assert_called_once_with(
"failed to assign change_list_template attribute"
)
@override_settings(DEBUG=True)
def test_correct_scripts_declared_when_debug_is_true(self):
# GET the import form
response = self._get_url_response(
self.book_import_url, str_in_response="form action="
)
self.assertTemplateUsed(response, self.admin_import_template_url)
self.assertContains(
response,
'<script src="/static/admin/js/vendor/jquery/jquery.js">',
count=1,
html=True,
)
self.assertContains(
response,
'<script src="/static/admin/js/jquery.init.js">',
count=1,
html=True,
)
self.assertContains(
response,
'<script src="/static/import_export/guess_format.js">',
count=1,
html=True,
)
@override_settings(DEBUG=False)
def test_correct_scripts_declared_when_debug_is_false(self):
# GET the import form
response = self._get_url_response(self.book_import_url)
self.assertTemplateUsed(response, self.admin_import_template_url)
self.assertContains(response, 'form action=""')
self.assertContains(
response,
'<script src="/static/admin/js/vendor/jquery/jquery.min.js">',
count=1,
html=True,
)
self.assertContains(
response,
'<script src="/static/admin/js/jquery.init.js">',
count=1,
html=True,
)
self.assertContains(
response,
'<script src="/static/import_export/guess_format.js">',
count=1,
html=True,
)
def test_import_with_customized_forms(self):
"""Test if admin import works if forms are customized"""
# We reuse import scheme from `test_import` to import books.csv.
# We use customized BookAdmin (CustomBookAdmin) with modified import
# form, which requires Author to be selected (from available authors).
# Note that url is /admin/core/ebook/import (and not: ...book/import)!
# We need at least a single author in the db to select from in the
# admin import custom forms
Author.objects.create(id=11, name="Test Author")
# GET the import form
response = self._get_url_response(self.ebook_import_url)
self.assertTemplateUsed(response, self.import_export_import_template_url)
self.assertContains(response, 'form action=""')
# POST the import form
input_format = "0"
filename = os.path.join(
os.path.dirname(__file__),
os.path.pardir,
os.path.pardir,
"exports",
"books.csv",
)
with open(filename, "rb") as fobj:
data = {"author": 11, "format": input_format, "import_file": fobj}
self._prepend_form_prefix(data)
response = self._post_url_response(self.ebook_import_url, data)
self.assertIn("result", response.context)
self.assertFalse(response.context["result"].has_errors())
self.assertIn("confirm_form", response.context)
confirm_form = response.context["confirm_form"]
self.assertIsInstance(
confirm_form,
CustomBookAdmin(EBook, "ebook/import").get_confirm_form_class(None),
)
data = confirm_form.initial
self._prepend_form_prefix(data)
self.assertEqual(data["original_file_name"], "books.csv")
response = self._post_url_response(
self.process_ebook_import_url, data, follow=True
)
self.assertContains(
response,
_(
"Import finished: {} new, {} updated, {} deleted and {} skipped {}."
).format(1, 0, 0, 0, EBook._meta.verbose_name_plural),
)
| ImportTemplateTests |
python | has2k1__plotnine | plotnine/_mpl/layout_manager/_engine.py | {
"start": 1324,
"end": 2842
} | class ____(LayoutEngine):
"""
Layout Manager for Plotnine Composition
"""
_adjust_compatible = True
_colorbar_gridspec = False
def __init__(self, composition: Compose):
self.composition = composition
def execute(self, fig: Figure):
from contextlib import nullcontext
renderer = fig._get_renderer() # pyright: ignore[reportAttributeAccessIssue]
# Caculate the space taken up by all plot artists
lookup_spaces: dict[ggplot, LayoutSpaces] = {}
with getattr(renderer, "_draw_disabled", nullcontext)():
for ps in self.composition.plotspecs:
lookup_spaces[ps.plot] = LayoutSpaces(ps.plot)
# Adjust the size and placements of the plots
tree = LayoutTree.create(self.composition, lookup_spaces)
tree.harmonise()
# Set the final positions of the artists in each plot
for plot, spaces in lookup_spaces.items():
gsparams = spaces.get_gridspec_params()
if not gsparams.valid:
warn(
"The layout manager failed, the figure size is too small "
"to contain all the plots. Use theme() increase the "
"figure size and/or reduce the size of the texts.",
PlotnineWarning,
)
break
plot.facet._panels_gridspec.update_params_and_artists(gsparams)
spaces.items._adjust_positions(spaces)
| PlotnineCompositionLayoutEngine |
python | pypa__pip | src/pip/_vendor/packaging/version.py | {
"start": 1751,
"end": 4507
} | class ____:
_key: tuple[Any, ...]
def __hash__(self) -> int:
return hash(self._key)
# Please keep the duplicated `isinstance` check
# in the six comparisons hereunder
# unless you find a way to avoid adding overhead function calls.
def __lt__(self, other: _BaseVersion) -> bool:
if not isinstance(other, _BaseVersion):
return NotImplemented
return self._key < other._key
def __le__(self, other: _BaseVersion) -> bool:
if not isinstance(other, _BaseVersion):
return NotImplemented
return self._key <= other._key
def __eq__(self, other: object) -> bool:
if not isinstance(other, _BaseVersion):
return NotImplemented
return self._key == other._key
def __ge__(self, other: _BaseVersion) -> bool:
if not isinstance(other, _BaseVersion):
return NotImplemented
return self._key >= other._key
def __gt__(self, other: _BaseVersion) -> bool:
if not isinstance(other, _BaseVersion):
return NotImplemented
return self._key > other._key
def __ne__(self, other: object) -> bool:
if not isinstance(other, _BaseVersion):
return NotImplemented
return self._key != other._key
# Deliberately not anchored to the start and end of the string, to make it
# easier for 3rd party code to reuse
_VERSION_PATTERN = r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>alpha|a|beta|b|preview|pre|c|rc)
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
VERSION_PATTERN = _VERSION_PATTERN
"""
A string containing the regular expression used to match a valid version.
The pattern is not anchored at either end, and is intended for embedding in larger
expressions (for example, matching a version number as part of a file name). The
regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
flags set.
:meta hide-value:
"""
| _BaseVersion |
python | falconry__falcon | tests/_inspect_fixture.py | {
"start": 411,
"end": 776
} | class ____:
async def on_get(self, req, res):
pass
async def on_post(self, req, res):
pass
async def on_delete(self, req, res):
pass
async def on_get_id(self, req, res, id):
pass
async def on_put_id(self, req, res, id):
pass
async def on_delete_id(self, req, res, id):
pass
| MyResponderAsync |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 20058,
"end": 20371
} | class ____(GroupType):
type_id = 2007
slug = "profile_regex_main_thread"
description = "Regex on Main Thread"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.MOBILE.value
released = True
default_priority = PriorityLevel.LOW
@dataclass(frozen=True)
| ProfileRegexType |
python | ray-project__ray | python/ray/serve/_private/handle_options.py | {
"start": 301,
"end": 839
} | class ____(ABC):
"""Init options for each ServeHandle instance.
These fields can be set by calling `.init()` on a handle before
sending the first request.
"""
_prefer_local_routing: bool = False
_source: DeploymentHandleSource = DeploymentHandleSource.UNKNOWN
_run_router_in_separate_loop: bool = RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP
@classmethod
@abstractmethod
def create(cls, **kwargs) -> "InitHandleOptionsBase":
raise NotImplementedError
@dataclass(frozen=True)
| InitHandleOptionsBase |
python | conda__conda | conda/models/dist.py | {
"start": 2287,
"end": 11940
} | class ____(Entity, metaclass=DistType):
_cache_ = {}
_lazy_validate = True
channel = StringField(required=False, nullable=True, immutable=True)
dist_name = StringField(immutable=True)
name = StringField(immutable=True)
fmt = StringField(immutable=True)
version = StringField(immutable=True)
build_string = StringField(immutable=True)
build_number = IntegerField(immutable=True)
base_url = StringField(required=False, nullable=True, immutable=True)
platform = StringField(required=False, nullable=True, immutable=True)
def __init__(
self,
channel,
dist_name=None,
name=None,
version=None,
build_string=None,
build_number=None,
base_url=None,
platform=None,
fmt=".tar.bz2",
):
super().__init__(
channel=channel,
dist_name=dist_name,
name=name,
version=version,
build_string=build_string,
build_number=build_number,
base_url=base_url,
platform=platform,
fmt=fmt,
)
def to_package_ref(self):
return PackageRecord(
channel=self.channel,
subdir=self.platform,
name=self.name,
version=self.version,
build=self.build_string,
build_number=self.build_number,
)
@property
def full_name(self):
return self.__str__()
@property
def build(self):
return self.build_string
@property
def subdir(self):
return self.platform
@property
def pair(self):
return self.channel or DEFAULTS_CHANNEL_NAME, self.dist_name
@property
def quad(self):
# returns: name, version, build_string, channel
parts = self.dist_name.rsplit("-", 2) + ["", ""]
return parts[0], parts[1], parts[2], self.channel or DEFAULTS_CHANNEL_NAME
def __str__(self):
return f"{self.channel}::{self.dist_name}" if self.channel else self.dist_name
@property
def is_feature_package(self):
return self.dist_name.endswith("@")
@property
def is_channel(self):
return bool(self.base_url and self.platform)
def to_filename(self, extension=None):
if self.is_feature_package:
return self.dist_name
else:
return self.dist_name + self.fmt
def to_matchspec(self):
return " ".join(self.quad[:3])
def to_match_spec(self):
from .match_spec import MatchSpec
base = "=".join(self.quad[:3])
return MatchSpec(f"{self.channel}::{base}" if self.channel else base)
@classmethod
def from_string(cls, string, channel_override=NULL):
string = str(string)
if is_url(string) and channel_override == NULL:
return cls.from_url(string)
if string.endswith("@"):
return cls(
channel="@",
name=string,
version="",
build_string="",
build_number=0,
dist_name=string,
)
REGEX_STR = (
r"(?:([^\s\[\]]+)::)?" # optional channel
r"([^\s\[\]]+)" # 3.x dist
r"(?:\[([a-zA-Z0-9_-]+)\])?" # with_features_depends
)
channel, original_dist, w_f_d = re.search(REGEX_STR, string).groups()
original_dist, fmt = split_extension(original_dist)
if channel_override != NULL:
channel = channel_override
if not channel:
channel = UNKNOWN_CHANNEL
# enforce dist format
dist_details = cls.parse_dist_name(original_dist)
return cls(
channel=channel,
name=dist_details.name,
version=dist_details.version,
build_string=dist_details.build_string,
build_number=dist_details.build_number,
dist_name=original_dist,
fmt=fmt,
)
@staticmethod
def parse_dist_name(string):
original_string = string
try:
string = ensure_text_type(string)
no_fmt_string, fmt = split_extension(string)
# remove any directory or channel information
if "::" in no_fmt_string:
dist_name = no_fmt_string.rsplit("::", 1)[-1]
else:
dist_name = no_fmt_string.rsplit("/", 1)[-1]
parts = dist_name.rsplit("-", 2)
name = parts[0]
version = parts[1]
build_string = parts[2] if len(parts) >= 3 else ""
build_number_as_string = "".join(
filter(
lambda x: x.isdigit(),
(build_string.rsplit("_")[-1] if build_string else "0"),
)
)
build_number = int(build_number_as_string) if build_number_as_string else 0
return DistDetails(
name, version, build_string, build_number, dist_name, fmt
)
except:
raise CondaError(
f"dist_name is not a valid conda package: {original_string}"
)
@classmethod
def from_url(cls, url):
if not is_url(url):
raise ValueError("'{url}' does not seem to be a valid URL")
if (
not any(url.endswith(ext) for ext in CONDA_PACKAGE_EXTENSIONS)
and "::" not in url
):
raise CondaError(f"url '{url}' is not a conda package")
dist_details = cls.parse_dist_name(url)
if "::" in url:
url_no_tarball = url.rsplit("::", 1)[0]
platform = context.subdir
base_url = url_no_tarball.split("::")[0]
channel = str(Channel(base_url))
else:
url_no_tarball = url.rsplit("/", 1)[0]
platform = has_platform(url_no_tarball, context.known_subdirs)
base_url = url_no_tarball.rsplit("/", 1)[0] if platform else url_no_tarball
channel = Channel(base_url).canonical_name if platform else UNKNOWN_CHANNEL
return cls(
channel=channel,
name=dist_details.name,
version=dist_details.version,
build_string=dist_details.build_string,
build_number=dist_details.build_number,
dist_name=dist_details.dist_name,
base_url=base_url,
platform=platform,
fmt=dist_details.fmt,
)
def to_url(self):
if not self.base_url:
return None
filename = self.dist_name + self.fmt
return (
join_url(self.base_url, self.platform, filename)
if self.platform
else join_url(self.base_url, filename)
)
def __key__(self):
return self.channel, self.dist_name
def __lt__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"Can only compare with objects of the same type. "
f"Left side is {type(self)}, and right side is {type(other)}"
)
return self.__key__() < other.__key__()
def __gt__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"Can only compare with objects of the same type. "
f"Left side is {type(self)}, and right side is {type(other)}"
)
return self.__key__() > other.__key__()
def __le__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"Can only compare with objects of the same type. "
f"Left side is {type(self)}, and right side is {type(other)}"
)
return self.__key__() <= other.__key__()
def __ge__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"Can only compare with objects of the same type. "
f"Left side is {type(self)}, and right side is {type(other)}"
)
return self.__key__() >= other.__key__()
def __hash__(self):
# dists compare equal regardless of fmt, but fmt is taken into account for
# object identity
return hash((self.__key__(), self.fmt))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__key__() == other.__key__()
def __ne__(self, other):
return not self.__eq__(other)
# ############ conda-build compatibility ################
def split(self, sep=None, maxsplit=-1):
if sep != "::":
raise ValueError("'sep' can only be '::'")
return [self.channel, self.dist_name] if self.channel else [self.dist_name]
def rsplit(self, sep=None, maxsplit=-1):
if sep != "-":
raise ValueError("'sep' can only be '-'")
if maxsplit != 2:
raise ValueError("'maxsplit' can only be 2")
name = f"{self.channel}::{self.quad[0]}" if self.channel else self.quad[0]
return name, self.quad[1], self.quad[2]
def startswith(self, match):
return self.dist_name.startswith(match)
def __contains__(self, item):
item = strip_extension(ensure_text_type(item))
return item in self.__str__()
@property
def fn(self):
return self.to_filename()
def dist_str_to_quad(dist_str):
dist_str = strip_extension(dist_str)
if "::" in dist_str:
channel_str, dist_str = dist_str.split("::", 1)
else:
channel_str = UNKNOWN_CHANNEL
name, version, build = dist_str.rsplit("-", 2)
return name, version, build, channel_str
| Dist |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/PlotDataItem.py | {
"start": 1183,
"end": 1448
} | class ____(TypedDict):
useCache: bool
antialias: bool
downsample: int
downsampleMethod: str
autoDownsample: bool
clipToView: bool
dynamicRangeLimit: float | None
dynamicRangeHyst: float
skipFiniteCheck: bool
| OptimizationKeywordArgs |
python | falconry__falcon | tests/test_httperror.py | {
"start": 7157,
"end": 7276
} | class ____:
def on_get(self, req, resp):
raise falcon.HTTPMissingHeader('X-Auth-Token')
| MissingHeaderResource |
python | doocs__leetcode | solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/Solution.py | {
"start": 0,
"end": 704
} | class ____:
def minInsertions(self, s: str) -> int:
ans = x = 0
i, n = 0, len(s)
while i < n:
if s[i] == '(':
# 待匹配的左括号加 1
x += 1
else:
if i < n - 1 and s[i + 1] == ')':
# 有连续两个右括号,i 往后移动
i += 1
else:
# 只有一个右括号,插入一个
ans += 1
if x == 0:
# 无待匹配的左括号,插入一个
ans += 1
else:
# 待匹配的左括号减 1
x -= 1
i += 1
# 遍历结束,仍有待匹配的左括号,说明右括号不足,插入 x << 1 个
ans += x << 1
return ans
| Solution |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 25495,
"end": 25678
} | class ____(BaseModel):
key: str
dag_id: str
run_id: str
task_id: str
offset: int
type: Literal["GetXComSequenceItem"] = "GetXComSequenceItem"
| GetXComSequenceItem |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_experiment_service.py | {
"start": 1717,
"end": 2730
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("ExperimentHook"))
def test_execute(self, mock_hook):
op = CreateExperimentOperator(
task_id=TASK_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
experiment_name=TEST_EXPERIMENT_NAME,
experiment_description=TEST_EXPERIMENT_DESCRIPTION,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
op.execute(context={"ti": mock.MagicMock()})
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.create_experiment.assert_called_once_with(
project_id=GCP_PROJECT,
location=GCP_LOCATION,
experiment_name=TEST_EXPERIMENT_NAME,
experiment_description=TEST_EXPERIMENT_DESCRIPTION,
experiment_tensorboard=TEST_TENSORBOARD,
)
| TestVertexAICreateExperimentOperator |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 6140,
"end": 7063
} | class ____(CallInstr):
def __init__(self, parent, func, args, normal_to, unwind_to, name='',
cconv=None, fastmath=(), attrs=(), arg_attrs=None):
assert isinstance(normal_to, Block)
assert isinstance(unwind_to, Block)
super(InvokeInstr, self).__init__(parent, func, args, name, cconv,
tail=False, fastmath=fastmath,
attrs=attrs, arg_attrs=arg_attrs)
self.opname = "invoke"
self.normal_to = normal_to
self.unwind_to = unwind_to
def descr(self, buf):
super(InvokeInstr, self)._descr(buf, add_metadata=False)
buf.append(" to label {0} unwind label {1}{metadata}\n".format(
self.normal_to.get_reference(),
self.unwind_to.get_reference(),
metadata=self._stringify_metadata(leading_comma=True),
))
| InvokeInstr |
python | getsentry__sentry | src/sentry/prevent/endpoints/pr_review_github_config.py | {
"start": 1097,
"end": 4029
} | class ____(OrganizationEndpoint):
"""
Get and set the GitHub PR review config for a Sentry organization
"""
owner = ApiOwner.CODECOV
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
"PUT": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (PreventAIConfigPermission,)
def get(
self, request: Request, organization: Organization, git_organization_name: str
) -> Response:
"""
Get the Prevent AI GitHub configuration for a specific git organization.
"""
github_org_integrations = integration_service.get_organization_integrations(
organization_id=organization.id,
providers=[IntegrationProviderSlug.GITHUB.value],
status=ObjectStatus.ACTIVE,
name=git_organization_name,
)
if not github_org_integrations:
return Response({"detail": "GitHub integration not found"}, status=404)
config = PreventAIConfiguration.objects.filter(
organization_id=organization.id,
integration_id=github_org_integrations[0].integration_id,
).first()
response_data: dict[str, Any] = deepcopy(PREVENT_AI_CONFIG_DEFAULT)
if config:
response_data["organization"] = config.data
return Response(response_data, status=200)
def put(
self, request: Request, organization: Organization, git_organization_name: str
) -> Response:
"""
Update the Prevent AI GitHub configuration for an organization.
"""
try:
validate(request.data, ORG_CONFIG_SCHEMA)
except Exception:
return Response({"detail": "Invalid config"}, status=400)
github_org_integrations = integration_service.get_organization_integrations(
organization_id=organization.id,
providers=[IntegrationProviderSlug.GITHUB.value],
status=ObjectStatus.ACTIVE,
name=git_organization_name,
)
if not github_org_integrations:
return Response({"detail": "GitHub integration not found"}, status=404)
PreventAIConfiguration.objects.update_or_create(
organization_id=organization.id,
integration_id=github_org_integrations[0].integration_id,
defaults={"data": request.data},
)
self.create_audit_entry(
request=request,
organization=organization,
target_object=organization.id,
event=audit_log.get_event_id("PREVENT_CONFIG_EDIT"),
data={
"git_organization": git_organization_name,
"provider": "github",
},
)
response_data: dict[str, Any] = deepcopy(PREVENT_AI_CONFIG_DEFAULT)
response_data["organization"] = request.data
return Response(response_data, status=200)
| OrganizationPreventGitHubConfigEndpoint |
python | spack__spack | lib/spack/spack/binary_distribution.py | {
"start": 93053,
"end": 93875
} | class ____:
"""Callable object to query if a spec is in a binary cache"""
def __init__(self, all_architectures):
"""
Args:
all_architectures (bool): if True consider all the spec for querying,
otherwise restrict to the current default architecture
"""
self.all_architectures = all_architectures
specs = update_cache_and_get_specs()
if not self.all_architectures:
arch = spack.spec.Spec.default_arch()
specs = [s for s in specs if s.satisfies(arch)]
self.possible_specs = specs
def __call__(self, spec: spack.spec.Spec, **kwargs):
"""
Args:
spec: The spec being searched for
"""
return [s for s in self.possible_specs if s.satisfies(spec)]
| BinaryCacheQuery |
python | fastai__fastai | fastai/medical/imaging.py | {
"start": 14837,
"end": 15632
} | class ____(DataLoaders):
"Basic wrapper around DICOM `DataLoaders` with factory methods for segmentation problems"
@classmethod
@delegates(DataLoaders.from_dblock)
def from_label_func(cls, path, fnames, label_func, valid_pct=0.2, seed=None, codes=None, item_tfms=None, batch_tfms=None, **kwargs):
"Create from list of `fnames` in `path`s with `label_func`."
dblock = DataBlock(blocks=(ImageBlock(cls=PILDicom), MaskBlock(codes=codes)),
splitter=RandomSplitter(valid_pct, seed=seed),
get_y=label_func,
item_tfms=item_tfms,
batch_tfms=batch_tfms)
res = cls.from_dblock(dblock, fnames, path=path, **kwargs)
return res
| DicomSegmentationDataLoaders |
python | jazzband__django-pipeline | tests/tests/test_template.py | {
"start": 2645,
"end": 5329
} | class ____(TestCase):
def render_template(self, template):
return Template(template).render(Context())
def test_compressed_empty(self):
rendered = self.render_template(
"""{% load pipeline %}{% stylesheet "unknow" %}""",
)
self.assertEqual("", rendered)
def test_compressed_css(self):
rendered = self.render_template(
"""{% load pipeline %}{% stylesheet "screen" %}""",
)
self.assertEqual(
'<link href="/static/screen.css" rel="stylesheet" type="text/css" media="all" />', # noqa
rendered,
)
def test_compressed_css_media(self):
rendered = self.render_template(
"""{% load pipeline %}{% stylesheet "screen_media" %}""",
)
self.assertEqual(
'<link href="/static/screen_media.css" rel="stylesheet" type="text/css" media="screen and (min-width:500px)" />', # noqa
rendered,
)
def test_compressed_css_title(self):
rendered = self.render_template(
"""{% load pipeline %}{% stylesheet "screen_title" %}""",
)
self.assertEqual(
'<link href="/static/screen_title.css" rel="stylesheet" type="text/css" media="all" title="Default Style" />', # noqa
rendered,
)
def test_compressed_js(self):
rendered = self.render_template(
"""{% load pipeline %}{% javascript "scripts" %}""",
)
self.assertEqual(
'<script type="text/javascript" src="/static/scripts.js" charset="utf-8"></script>', # noqa
rendered,
)
def test_compressed_js_async(self):
rendered = self.render_template(
"""{% load pipeline %}{% javascript "scripts_async" %}""",
)
self.assertEqual(
'<script async type="text/javascript" src="/static/scripts_async.js" charset="utf-8"></script>', # noqa
rendered,
)
def test_compressed_js_defer(self):
rendered = self.render_template(
"""{% load pipeline %}{% javascript "scripts_defer" %}""",
)
self.assertEqual(
'<script defer type="text/javascript" src="/static/scripts_defer.js" charset="utf-8"></script>', # noqa
rendered,
)
def test_compressed_js_async_defer(self):
rendered = self.render_template(
"""{% load pipeline %}{% javascript "scripts_async_defer" %}""",
)
self.assertEqual(
'<script async defer type="text/javascript" src="/static/scripts_async_defer.js" charset="utf-8"></script>', # noqa
rendered,
)
| DjangoTest |
python | coleifer__peewee | peewee.py | {
"start": 160715,
"end": 160775
} | class ____(AutoField):
field_type = 'BIGAUTO'
| BigAutoField |
python | altair-viz__altair | altair/vegalite/v6/schema/mixins.py | {
"start": 61707,
"end": 68669
} | class ____:
"""A mixin class that defines mark methods."""
@use_signature(_MarkDef)
def mark_arc(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'arc' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="arc", **kwds)
else:
copy.mark = "arc"
return copy
@use_signature(_MarkDef)
def mark_area(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'area' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="area", **kwds)
else:
copy.mark = "area"
return copy
@use_signature(_MarkDef)
def mark_bar(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'bar' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="bar", **kwds)
else:
copy.mark = "bar"
return copy
@use_signature(_MarkDef)
def mark_image(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'image' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="image", **kwds)
else:
copy.mark = "image"
return copy
@use_signature(_MarkDef)
def mark_line(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'line' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="line", **kwds)
else:
copy.mark = "line"
return copy
@use_signature(_MarkDef)
def mark_point(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'point' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="point", **kwds)
else:
copy.mark = "point"
return copy
@use_signature(_MarkDef)
def mark_rect(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'rect' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="rect", **kwds)
else:
copy.mark = "rect"
return copy
@use_signature(_MarkDef)
def mark_rule(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'rule' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="rule", **kwds)
else:
copy.mark = "rule"
return copy
@use_signature(_MarkDef)
def mark_text(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'text' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="text", **kwds)
else:
copy.mark = "text"
return copy
@use_signature(_MarkDef)
def mark_tick(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'tick' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="tick", **kwds)
else:
copy.mark = "tick"
return copy
@use_signature(_MarkDef)
def mark_trail(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'trail' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="trail", **kwds)
else:
copy.mark = "trail"
return copy
@use_signature(_MarkDef)
def mark_circle(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'circle' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="circle", **kwds)
else:
copy.mark = "circle"
return copy
@use_signature(_MarkDef)
def mark_square(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'square' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="square", **kwds)
else:
copy.mark = "square"
return copy
@use_signature(_MarkDef)
def mark_geoshape(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'geoshape' (see :class:`MarkDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.MarkDef(type="geoshape", **kwds)
else:
copy.mark = "geoshape"
return copy
@use_signature(_BoxPlotDef)
def mark_boxplot(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'boxplot' (see :class:`BoxPlotDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.BoxPlotDef(type="boxplot", **kwds)
else:
copy.mark = "boxplot"
return copy
@use_signature(_ErrorBarDef)
def mark_errorbar(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'errorbar' (see :class:`ErrorBarDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.ErrorBarDef(type="errorbar", **kwds)
else:
copy.mark = "errorbar"
return copy
@use_signature(_ErrorBandDef)
def mark_errorband(self, **kwds: Any) -> Self:
"""Set the chart's mark to 'errorband' (see :class:`ErrorBandDef`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.ErrorBandDef(type="errorband", **kwds)
else:
copy.mark = "errorband"
return copy
| MarkMethodMixin |
python | tensorflow__tensorflow | tensorflow/python/distribute/input_lib.py | {
"start": 19970,
"end": 21651
} | class ____(DistributedDatasetAndIteratorSpec):
"""Type specification for `DistributedIterator`."""
@property
def value_type(self):
return DistributedIterator
@property
def _component_specs(self):
specs = []
worker_device_pairs = self._input_workers._worker_device_pairs # pylint: disable=protected-access
for i, (input_device, compute_devices) in enumerate(worker_device_pairs):
element_spec = nest.map_structure(
functools.partial(_replace_per_replica_spec, i=i), self._element_spec)
specs.append(
_SingleWorkerDatasetIteratorSpec(input_device, compute_devices,
element_spec, self._options,
self._canonicalize_devices))
return specs
def _to_components(self, value):
return value._iterators # pylint: disable=protected-access
def _from_components(self, components):
return DistributedIterator(
input_workers=self._input_workers,
iterators=None,
components=components,
element_spec=self._element_spec,
strategy=self._strategy,
cardinality=self._cardinality,
enable_get_next_as_optional=self._enable_get_next_as_optional,
options=self._options,
replica_order=self._replica_order,
)
@staticmethod
def from_value(value):
# pylint: disable=protected-access
return DistributedIteratorSpec(
value._input_workers,
value._element_spec,
value._strategy,
value._options,
cardinality=value._cardinality,
enable_get_next_as_optional=value._enable_get_next_as_optional)
| DistributedIteratorSpec |
python | openai__openai-python | src/openai/resources/chat/chat.py | {
"start": 486,
"end": 1382
} | class ____(SyncAPIResource):
@cached_property
def completions(self) -> Completions:
return Completions(self._client)
@cached_property
def with_raw_response(self) -> ChatWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
"""
return ChatWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> ChatWithStreamingResponse:
"""
An alternative to `.with_raw_response` that doesn't eagerly read the response body.
For more information, see https://www.github.com/openai/openai-python#with_streaming_response
"""
return ChatWithStreamingResponse(self)
| Chat |
python | django__django | tests/auth_tests/test_models.py | {
"start": 13512,
"end": 13844
} | class ____(ModelBackend):
def with_perm(
self, perm, is_active=True, include_superusers=True, backend=None, obj=None
):
if obj is not None and obj.username == "charliebrown":
return User.objects.filter(pk=obj.pk)
return User.objects.filter(username__startswith="charlie")
| CustomModelBackend |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 21182,
"end": 21590
} | class ____(GroupType):
type_id = 3501
slug = "llm_detected_experimental"
description = "LLM Detected Issue"
category = GroupCategory.AI_DETECTED.value
category_v2 = GroupCategory.AI_DETECTED.value
default_priority = PriorityLevel.MEDIUM
released = False
enable_auto_resolve = False
enable_escalation_detection = False
@dataclass(frozen=True)
| LLMDetectedExperimentalGroupType |
python | doocs__leetcode | lcof2/剑指 Offer II 052. 展平二叉搜索树/Solution.py | {
"start": 192,
"end": 683
} | class ____:
def increasingBST(self, root: TreeNode) -> TreeNode:
head, tail = None, None
stack = []
cur = root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if not head:
head = cur
else:
tail.right = cur
tail = cur
cur.left = None
cur = cur.right
return head
| Solution |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 5048,
"end": 5234
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneMessageEvent, GrapheneStepEvent)
name = "ExecutionStepRestartEvent"
| GrapheneExecutionStepRestartEvent |
python | doocs__leetcode | solution/2600-2699/2641.Cousins in Binary Tree II/Solution2.py | {
"start": 192,
"end": 983
} | class ____:
def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
root.val = 0
q = [root]
while q:
t = []
s = 0
for node in q:
if node.left:
t.append(node.left)
s += node.left.val
if node.right:
t.append(node.right)
s += node.right.val
for node in q:
sub = (node.left.val if node.left else 0) + (
node.right.val if node.right else 0
)
if node.left:
node.left.val = s - sub
if node.right:
node.right.val = s - sub
q = t
return root
| Solution |
python | pallets__itsdangerous | src/itsdangerous/signer.py | {
"start": 839,
"end": 1362
} | class ____(SigningAlgorithm):
"""Provides an algorithm that does not perform any signing and
returns an empty signature.
"""
def get_signature(self, key: bytes, value: bytes) -> bytes:
return b""
def _lazy_sha1(string: bytes = b"") -> t.Any:
"""Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
SHA-1, in which case the import and use as a default would fail before the
developer can configure something else.
"""
return hashlib.sha1(string)
| NoneAlgorithm |
python | getsentry__sentry | src/sentry/grouping/fingerprinting/utils.py | {
"start": 501,
"end": 551
} | class ____(TypedDict):
message: str
| _MessageInfo |
python | scipy__scipy | scipy/optimize/tests/test_lsq_linear.py | {
"start": 7459,
"end": 9334
} | class ____:
def test_sparse_and_LinearOperator(self):
m = 5000
n = 1000
rng = np.random.RandomState(0)
A = random_array((m, n), random_state=rng)
b = rng.randn(m)
res = lsq_linear(A, b)
assert_allclose(res.optimality, 0, atol=1e-6)
A = aslinearoperator(A)
res = lsq_linear(A, b)
assert_allclose(res.optimality, 0, atol=1e-6)
@pytest.mark.fail_slow(10)
def test_sparse_bounds(self):
m = 5000
n = 1000
rng = np.random.RandomState(0)
A = random_array((m, n), random_state=rng)
b = rng.randn(m)
lb = rng.randn(n)
ub = lb + 1
res = lsq_linear(A, b, (lb, ub))
assert_allclose(res.optimality, 0.0, atol=1e-6)
res = lsq_linear(A, b, (lb, ub), lsmr_tol=1e-13,
lsmr_maxiter=1500)
assert_allclose(res.optimality, 0.0, atol=1e-6)
res = lsq_linear(A, b, (lb, ub), lsmr_tol='auto')
assert_allclose(res.optimality, 0.0, atol=1e-6)
def test_sparse_ill_conditioned(self):
# Sparse matrix with condition number of ~4 million
data = np.array([1., 1., 1., 1. + 1e-6, 1.])
row = np.array([0, 0, 1, 2, 2])
col = np.array([0, 2, 1, 0, 2])
A = coo_array((data, (row, col)), shape=(3, 3))
# Get the exact solution
exact_sol = lsq_linear(A.toarray(), b, lsq_solver='exact')
# Default lsmr arguments should not fully converge the solution
default_lsmr_sol = lsq_linear(A, b, lsq_solver='lsmr')
with pytest.raises(AssertionError):
assert_allclose(exact_sol.x, default_lsmr_sol.x)
# By increasing the maximum lsmr iters, it will converge
conv_lsmr = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=10)
assert_allclose(exact_sol.x, conv_lsmr.x)
| SparseMixin |
python | dagster-io__dagster | python_modules/dagster/dagster/_loggers/__init__.py | {
"start": 1710,
"end": 4740
} | class ____(logging.Formatter):
def format(self, record):
dict_to_dump = {}
for k, v in record.__dict__.items():
if k == LOG_RECORD_EVENT_ATTR:
# Redundant with the "dagster_event" field under "dagster_meta"
continue
elif k == LOG_RECORD_METADATA_ATTR:
# Events objects are not always JSON-serializable, so need to pack them first
json_serializable_event = pack_value(v[LOG_RECORD_EVENT_ATTR])
json_serializable_dagster_meta = DagsterLogRecordMetadata(
**{**v, "dagster_event": json_serializable_event}
)
dict_to_dump[LOG_RECORD_METADATA_ATTR] = json_serializable_dagster_meta
else:
dict_to_dump[k] = v
return seven.json.dumps(dict_to_dump)
@logger(
Field(
{
"log_level": Field(
str,
is_required=False,
default_value="INFO",
description="The logger's threshold.",
),
"name": Field(
str,
is_required=False,
default_value="dagster",
description="The name of your logger.",
),
},
description="A JSON-formatted console logger.",
),
description="A JSON-formatted console logger.",
)
def json_console_logger(init_context: "InitLoggerContext") -> logging.Logger:
"""This logger provides support for sending Dagster logs to stdout in json format.
Example:
.. code-block:: python
from dagster import op, job
from dagster.loggers import json_console_logger
@op
def hello_op(context):
context.log.info('Hello, world!')
context.log.error('This is an error')
@job(logger_defs={'json_logger': json_console_logger})])
def json_logged_job():
hello_op()
"""
level = coerce_valid_log_level(init_context.logger_config["log_level"])
name = init_context.logger_config["name"]
klass = logging.getLoggerClass()
logger_ = klass(name, level=level)
handler = coloredlogs.StandardErrorHandler()
handler.setFormatter(JsonLogFormatter())
logger_.addHandler(handler)
return logger_
def default_system_loggers(
instance: Optional["DagsterInstance"],
) -> Sequence[tuple["LoggerDefinition", Mapping[str, object]]]:
"""If users don't provide configuration for any loggers, we instantiate these loggers with the
default config.
Returns:
List[Tuple[LoggerDefinition, dict]]: Default loggers and their associated configs.
"""
log_level = instance.python_log_level if (instance and instance.python_log_level) else "DEBUG"
return [(colored_console_logger, {"name": "dagster", "log_level": log_level})]
def default_loggers() -> Mapping[str, "LoggerDefinition"]:
return {"console": colored_console_logger}
| JsonLogFormatter |
python | openai__openai-python | src/openai/types/beta/realtime/session_create_response.py | {
"start": 2013,
"end": 2819
} | class ____(BaseModel):
prefix_padding_ms: Optional[int] = None
"""Amount of audio to include before the VAD detected speech (in milliseconds).
Defaults to 300ms.
"""
silence_duration_ms: Optional[int] = None
"""Duration of silence to detect speech stop (in milliseconds).
Defaults to 500ms. With shorter values the model will respond more quickly, but
may jump in on short pauses from the user.
"""
threshold: Optional[float] = None
"""Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5.
A higher threshold will require louder audio to activate the model, and thus
might perform better in noisy environments.
"""
type: Optional[str] = None
"""Type of turn detection, only `server_vad` is currently supported."""
| TurnDetection |
python | eventlet__eventlet | eventlet/queue.py | {
"start": 2602,
"end": 5302
} | class ____:
"""A low level synchronization class.
Wrapper around greenlet's ``switch()`` and ``throw()`` calls that makes them safe:
* switching will occur only if the waiting greenlet is executing :meth:`wait`
method currently. Otherwise, :meth:`switch` and :meth:`throw` are no-ops.
* any error raised in the greenlet is handled inside :meth:`switch` and :meth:`throw`
The :meth:`switch` and :meth:`throw` methods must only be called from the :class:`Hub` greenlet.
The :meth:`wait` method must be called from a greenlet other than :class:`Hub`.
"""
__slots__ = ['greenlet']
def __init__(self):
self.greenlet = None
def __repr__(self):
if self.waiting:
waiting = ' waiting'
else:
waiting = ''
return '<%s at %s%s greenlet=%r>' % (
type(self).__name__, hex(id(self)), waiting, self.greenlet,
)
def __str__(self):
"""
>>> print(Waiter())
<Waiter greenlet=None>
"""
if self.waiting:
waiting = ' waiting'
else:
waiting = ''
return '<%s%s greenlet=%s>' % (type(self).__name__, waiting, self.greenlet)
def __nonzero__(self):
return self.greenlet is not None
__bool__ = __nonzero__
@property
def waiting(self):
return self.greenlet is not None
def switch(self, value=None):
"""Wake up the greenlet that is calling wait() currently (if there is one).
Can only be called from Hub's greenlet.
"""
assert getcurrent() is get_hub(
).greenlet, "Can only use Waiter.switch method from the mainloop"
if self.greenlet is not None:
try:
self.greenlet.switch(value)
except Exception:
traceback.print_exc()
def throw(self, *throw_args):
"""Make greenlet calling wait() wake up (if there is a wait()).
Can only be called from Hub's greenlet.
"""
assert getcurrent() is get_hub(
).greenlet, "Can only use Waiter.switch method from the mainloop"
if self.greenlet is not None:
try:
self.greenlet.throw(*throw_args)
except Exception:
traceback.print_exc()
# XXX should be renamed to get() ? and the whole class is called Receiver?
def wait(self):
"""Wait until switch() or throw() is called.
"""
assert self.greenlet is None, 'This Waiter is already used by %r' % (self.greenlet, )
self.greenlet = getcurrent()
try:
return get_hub().switch()
finally:
self.greenlet = None
| Waiter |
python | huggingface__transformers | src/transformers/models/siglip2/modular_siglip2.py | {
"start": 11602,
"end": 12697
} | class ____(SiglipMultiheadAttentionPoolingHead):
def __init__(self, config: Siglip2VisionConfig):
super().__init__(config)
self.num_heads = config.num_attention_heads
def forward(self, hidden_state: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
batch_size = hidden_state.shape[0]
probe = self.probe.repeat(batch_size, 1, 1)
if attention_mask is not None:
target_len, source_len = probe.shape[1], hidden_state.shape[1]
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_state.dtype, target_len)
attention_mask = attention_mask.repeat(1, self.num_heads, target_len, 1)
attention_mask = attention_mask.reshape(-1, target_len, source_len)
hidden_state = self.attention(probe, hidden_state, hidden_state, attn_mask=attention_mask)[0]
residual = hidden_state
hidden_state = self.layernorm(hidden_state)
hidden_state = residual + self.mlp(hidden_state)
return hidden_state[:, 0]
| Siglip2MultiheadAttentionPoolingHead |
python | getsentry__sentry | src/sentry/api/serializers/models/dashboard.py | {
"start": 15628,
"end": 15721
} | class ____(PageFiltersOptional):
projects: list[int]
environment: list[str]
| PageFilters |
python | wandb__wandb | wandb/automations/actions.py | {
"start": 4416,
"end": 5722
} | class ____(_BaseActionInput, NotificationActionInput):
"""Defines an automation action that sends a (Slack) notification."""
action_type: Literal[ActionType.NOTIFICATION] = ActionType.NOTIFICATION
integration_id: GQLId
"""The ID of the Slack integration that will be used to send the notification."""
# Note: Validation aliases preserve continuity with the prior `wandb.alert()` API.
title: str = ""
"""The title of the sent notification."""
message: Annotated[str, Field(validation_alias="text")] = ""
"""The message body of the sent notification."""
severity: Annotated[
AlertSeverity,
BeforeValidator(upper_if_str), # Be helpful by ensuring uppercase strings
Field(validation_alias="level"),
] = AlertSeverity.INFO
"""The severity (`INFO`, `WARN`, `ERROR`) of the sent notification."""
@classmethod
def from_integration(
cls,
integration: SlackIntegration,
*,
title: str = "",
text: str = "",
level: AlertSeverity = AlertSeverity.INFO,
) -> Self:
"""Define a notification action that sends to the given (Slack) integration."""
return cls(
integration_id=integration.id, title=title, message=text, severity=level
)
| SendNotification |
python | doocs__leetcode | solution/1900-1999/1944.Number of Visible People in a Queue/Solution.py | {
"start": 0,
"end": 390
} | class ____:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
n = len(heights)
ans = [0] * n
stk = []
for i in range(n - 1, -1, -1):
while stk and stk[-1] < heights[i]:
ans[i] += 1
stk.pop()
if stk:
ans[i] += 1
stk.append(heights[i])
return ans
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/automation_context.py | {
"start": 2002,
"end": 11456
} | class ____(Generic[T_EntityKey]):
evaluation_id: int
condition: AutomationCondition
condition_unique_ids: Sequence[str]
candidate_subset: EntitySubset[T_EntityKey]
create_time: datetime.datetime
asset_graph_view: AssetGraphView
request_subsets_by_key: Mapping[EntityKey, EntitySubset]
parent_context: Optional["AutomationContext"]
_cursor: Optional[AutomationConditionCursor]
_full_cursor: AssetDaemonCursor
_legacy_context: Optional[LegacyRuleEvaluationContext]
_root_log: logging.Logger
@staticmethod
def create(key: EntityKey, evaluator: "AutomationConditionEvaluator") -> "AutomationContext":
asset_graph_view = evaluator.asset_graph_view
condition = check.not_none(
evaluator.asset_graph.get(key).automation_condition or evaluator.default_condition
)
unique_ids = condition.get_node_unique_ids(
parent_unique_ids=[None], child_indices=[None], target_key=None
)
return AutomationContext(
condition=condition,
condition_unique_ids=unique_ids,
candidate_subset=evaluator.asset_graph_view.get_full_subset(key=key),
create_time=get_current_datetime(),
asset_graph_view=asset_graph_view,
request_subsets_by_key=evaluator.request_subsets_by_key,
parent_context=None,
evaluation_id=evaluator.evaluation_id,
_cursor=evaluator.cursor.get_previous_condition_cursor(key),
_full_cursor=evaluator.cursor,
_legacy_context=LegacyRuleEvaluationContext.create(key, evaluator)
if condition.has_rule_condition and isinstance(key, AssetKey)
else None,
_root_log=evaluator.logger,
)
def for_child_condition(
self,
child_condition: AutomationCondition[U_EntityKey],
child_indices: Sequence[Optional[int]],
candidate_subset: EntitySubset[U_EntityKey],
) -> "AutomationContext[U_EntityKey]":
check.invariant(len(child_indices) > 0, "Must be at least one child index")
unique_ids = child_condition.get_node_unique_ids(
parent_unique_ids=self.condition_unique_ids,
child_indices=child_indices,
target_key=candidate_subset.key
if candidate_subset.key != self.root_context.key
else None,
)
return AutomationContext(
condition=child_condition,
condition_unique_ids=unique_ids,
candidate_subset=candidate_subset,
create_time=get_current_datetime(),
asset_graph_view=self.asset_graph_view,
request_subsets_by_key=self.request_subsets_by_key,
parent_context=self,
evaluation_id=self.evaluation_id,
_cursor=self._cursor,
_full_cursor=self._full_cursor,
_legacy_context=self._legacy_context.for_child(
child_condition, unique_ids[0], candidate_subset
)
if self._legacy_context
else None,
_root_log=self._root_log,
)
async def evaluate_async(self) -> AutomationResult[T_EntityKey]:
if inspect.iscoroutinefunction(self.condition.evaluate):
return await self.condition.evaluate(self)
return self.condition.evaluate(self)
@property
def log(self) -> logging.Logger:
"""The logger for the current condition evaluation."""
return self._root_log.getChild(self.condition.__class__.__name__)
@property
def asset_graph(self) -> "BaseAssetGraph":
return self.asset_graph_view.asset_graph
@property
def key(self) -> T_EntityKey:
"""The asset key over which this condition is being evaluated."""
return self.candidate_subset.key
@property
def partitions_def(self) -> Optional[PartitionsDefinition]:
"""The partitions definition for the asset being evaluated, if it exists."""
if isinstance(self.key, AssetKey):
return self.asset_graph.get(self.key).partitions_def
else:
return None
@property
def root_context(self) -> "AutomationContext":
"""Returns the context object at the root of the condition evaluation tree."""
return self.parent_context.root_context if self.parent_context is not None else self
@property
def _node_cursor(self) -> Optional[AutomationConditionNodeCursor]:
"""Returns the evaluation node for this node from the previous evaluation, if this node
was evaluated on the previous tick.
"""
check.invariant(
self.condition.requires_cursor,
f"Attempted to access cursor for a node of type {self.condition.__class__.__name__} "
"which does not store a cursor. Set the `requires_cursor` property to `True` to enable access.",
)
if not self._cursor:
return None
for unique_id in self.condition_unique_ids:
if unique_id in self._cursor.node_cursors_by_unique_id:
return self._cursor.node_cursors_by_unique_id[unique_id]
return None
@property
def cursor(self) -> Optional[str]:
"""The cursor value returned on the previous evaluation for this condition, if any."""
return self._node_cursor.get_structured_cursor(as_type=str) if self._node_cursor else None
@property
def previous_true_subset(self) -> Optional[EntitySubset[T_EntityKey]]:
"""Returns the true subset for this node from the previous evaluation, if this node was
evaluated on the previous tick.
"""
return (
self.asset_graph_view.get_subset_from_serializable_subset(self._node_cursor.true_subset)
if self._node_cursor
else None
)
@property
def previous_metadata(self) -> Optional[MetadataMapping]:
"""Returns the metadata for this node from the previous evaluation, if this node was
evaluated on the previous tick.
"""
return self._node_cursor.metadata if self._node_cursor else None
@property
def evaluation_time(self) -> datetime.datetime:
"""A consistent datetime for all evaluations on this tick."""
return self.asset_graph_view.effective_dt
@property
def max_storage_id(self) -> Optional[int]:
"""A consistent maximum storage id to consider for all evaluations on this tick."""
if self._legacy_context is not None:
# legacy evaluations handle event log tailing in a different manner, and so need to
# use a different storage id cursoring scheme
return self.legacy_context.new_max_storage_id
else:
return self.asset_graph_view.last_event_id
@property
def previous_max_storage_id(self) -> Optional[int]:
"""The `max_storage_id` value used on the previous tick's evaluation."""
return self._cursor.temporal_context.last_event_id if self._cursor else None
@property
def previous_evaluation_time(self) -> Optional[datetime.datetime]:
"""The `evaluation_time` value used on the previous tick's evaluation."""
return self._cursor.temporal_context.effective_dt if self._cursor else None
@property
def previous_temporal_context(self) -> Optional[TemporalContext]:
"""The `temporal_context` value used on the previous tick's evaluation."""
return self._cursor.temporal_context if self._cursor else None
@property
def legacy_context(self) -> LegacyRuleEvaluationContext:
return check.not_none(
self._legacy_context,
"Cannot access legacy context unless evaluating a condition containing a RuleCondition.",
)
@property
def previous_candidate_subset(self) -> Optional[EntitySubset[T_EntityKey]]:
"""Returns the candidate subset for the previous evaluation. If this node has never been
evaluated, returns None.
"""
candidate_subset = self._node_cursor.candidate_subset if self._node_cursor else None
if isinstance(candidate_subset, HistoricalAllPartitionsSubsetSentinel):
return self.asset_graph_view.get_full_subset(key=self.key)
else:
return (
self.asset_graph_view.get_subset_from_serializable_subset(candidate_subset)
if candidate_subset
else None
)
def get_previous_requested_subset(
self, key: T_EntityKey
) -> Optional[EntitySubset[T_EntityKey]]:
"""Returns the requested subset for the previous evaluation. If the entity has never been
evaluated, returns None.
"""
cursor = self._full_cursor.get_previous_condition_cursor(key)
if cursor is None:
return None
return self.asset_graph_view.get_subset_from_serializable_subset(
cursor.previous_requested_subset
)
def get_empty_subset(self) -> EntitySubset[T_EntityKey]:
"""Returns an empty EntitySubset of the currently-evaluated key."""
return self.asset_graph_view.get_empty_subset(key=self.key)
def get_structured_cursor(
self, as_type: type[T_StructuredCursor]
) -> Optional[T_StructuredCursor]:
return (
self._node_cursor.get_structured_cursor(as_type=as_type) if self._node_cursor else None
)
| AutomationContext |
python | django__django | tests/ordering/models.py | {
"start": 564,
"end": 771
} | class ____(models.Model):
name = models.CharField(max_length=63, null=True, blank=True)
editor = models.ForeignKey("self", models.CASCADE, null=True)
class Meta:
ordering = ("-pk",)
| Author |
python | plotly__plotly.py | plotly/graph_objs/indicator/_domain.py | {
"start": 233,
"end": 5051
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "indicator"
_path_str = "indicator.domain"
_valid_props = {"column", "row", "x", "y"}
@property
def column(self):
"""
If there is a layout grid, use the domain for this column in
the grid for this indicator trace .
The 'column' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["column"]
@column.setter
def column(self, val):
self["column"] = val
@property
def row(self):
"""
If there is a layout grid, use the domain for this row in the
grid for this indicator trace .
The 'row' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["row"]
@row.setter
def row(self, val):
self["row"] = val
@property
def x(self):
"""
Sets the horizontal domain of this indicator trace (in plot
fraction).
The 'x' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'x[0]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
(1) The 'x[1]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
list
"""
return self["x"]
@x.setter
def x(self, val):
self["x"] = val
@property
def y(self):
"""
Sets the vertical domain of this indicator trace (in plot
fraction).
The 'y' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'y[0]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
(1) The 'y[1]' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
list
"""
return self["y"]
@y.setter
def y(self, val):
self["y"] = val
@property
def _prop_descriptions(self):
return """\
column
If there is a layout grid, use the domain for this
column in the grid for this indicator trace .
row
If there is a layout grid, use the domain for this row
in the grid for this indicator trace .
x
Sets the horizontal domain of this indicator trace (in
plot fraction).
y
Sets the vertical domain of this indicator trace (in
plot fraction).
"""
def __init__(self, arg=None, column=None, row=None, x=None, y=None, **kwargs):
"""
Construct a new Domain object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.indicator.Domain`
column
If there is a layout grid, use the domain for this
column in the grid for this indicator trace .
row
If there is a layout grid, use the domain for this row
in the grid for this indicator trace .
x
Sets the horizontal domain of this indicator trace (in
plot fraction).
y
Sets the vertical domain of this indicator trace (in
plot fraction).
Returns
-------
Domain
"""
super().__init__("domain")
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.indicator.Domain
constructor must be a dict or
an instance of :class:`plotly.graph_objs.indicator.Domain`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("column", arg, column)
self._set_property("row", arg, row)
self._set_property("x", arg, x)
self._set_property("y", arg, y)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Domain |
python | mkdocs__mkdocs | mkdocs/plugins.py | {
"start": 1538,
"end": 16117
} | class ____(Generic[SomeConfig]):
"""
Plugin base class.
All plugins should subclass this class.
"""
config_class: type[SomeConfig] = LegacyConfig # type: ignore[assignment]
config_scheme: PlainConfigSchema = ()
config: SomeConfig = {} # type: ignore[assignment]
supports_multiple_instances: bool = False
"""Set to true in subclasses to declare support for adding the same plugin multiple times."""
def __class_getitem__(cls, config_class: type[Config]):
"""Eliminates the need to write `config_class = FooConfig` when subclassing BasePlugin[FooConfig]."""
name = f'{cls.__name__}[{config_class.__name__}]'
return type(name, (cls,), dict(config_class=config_class))
def __init_subclass__(cls):
if not issubclass(cls.config_class, Config):
raise TypeError(
f"config_class {cls.config_class} must be a subclass of `mkdocs.config.base.Config`"
)
if cls.config_class is not LegacyConfig:
cls.config_scheme = cls.config_class._schema # For compatibility.
def load_config(
self, options: dict[str, Any], config_file_path: str | None = None
) -> tuple[ConfigErrors, ConfigWarnings]:
"""Load config from a dict of options. Returns a tuple of (errors, warnings)."""
if self.config_class is LegacyConfig:
self.config = LegacyConfig(self.config_scheme, config_file_path=config_file_path) # type: ignore
else:
self.config = self.config_class(config_file_path=config_file_path)
self.config.load_dict(options)
return self.config.validate()
# One-time events
def on_startup(self, *, command: Literal['build', 'gh-deploy', 'serve'], dirty: bool) -> None:
"""
The `startup` event runs once at the very beginning of an `mkdocs` invocation.
New in MkDocs 1.4.
The presence of an `on_startup` method (even if empty) migrates the plugin to the new
system where the plugin object is kept across builds within one `mkdocs serve`.
Note that for initializing variables, the `__init__` method is still preferred.
For initializing per-build variables (and whenever in doubt), use the `on_config` event.
Args:
command: the command that MkDocs was invoked with, e.g. "serve" for `mkdocs serve`.
dirty: whether `--dirty` flag was passed.
"""
def on_shutdown(self) -> None:
"""
The `shutdown` event runs once at the very end of an `mkdocs` invocation, before exiting.
This event is relevant only for support of `mkdocs serve`, otherwise within a
single build it's undistinguishable from `on_post_build`.
New in MkDocs 1.4.
The presence of an `on_shutdown` method (even if empty) migrates the plugin to the new
system where the plugin object is kept across builds within one `mkdocs serve`.
Note the `on_post_build` method is still preferred for cleanups, when possible, as it has
a much higher chance of actually triggering. `on_shutdown` is "best effort" because it
relies on detecting a graceful shutdown of MkDocs.
"""
def on_serve(
self, server: LiveReloadServer, /, *, config: MkDocsConfig, builder: Callable
) -> LiveReloadServer | None:
"""
The `serve` event is only called when the `serve` command is used during
development. It runs only once, after the first build finishes.
It is passed the `Server` instance which can be modified before
it is activated. For example, additional files or directories could be added
to the list of "watched" files for auto-reloading.
Args:
server: `livereload.Server` instance
config: global configuration object
builder: a callable which gets passed to each call to `server.watch`
Returns:
`livereload.Server` instance
"""
return server
# Global events
def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
"""
The `config` event is the first event called on build and is run immediately
after the user configuration is loaded and validated. Any alterations to the
config should be made here.
Args:
config: global configuration object
Returns:
global configuration object
"""
return config
def on_pre_build(self, *, config: MkDocsConfig) -> None:
"""
The `pre_build` event does not alter any variables. Use this event to call
pre-build scripts.
Args:
config: global configuration object
"""
def on_files(self, files: Files, /, *, config: MkDocsConfig) -> Files | None:
"""
The `files` event is called after the files collection is populated from the
`docs_dir`. Use this event to add, remove, or alter files in the
collection. Note that Page objects have not yet been associated with the
file objects in the collection. Use [Page Events](plugins.md#page-events) to manipulate page
specific data.
Args:
files: global files collection
config: global configuration object
Returns:
global files collection
"""
return files
def on_nav(
self, nav: Navigation, /, *, config: MkDocsConfig, files: Files
) -> Navigation | None:
"""
The `nav` event is called after the site navigation is created and can
be used to alter the site navigation.
Args:
nav: global navigation object
config: global configuration object
files: global files collection
Returns:
global navigation object
"""
return nav
def on_env(
self, env: jinja2.Environment, /, *, config: MkDocsConfig, files: Files
) -> jinja2.Environment | None:
"""
The `env` event is called after the Jinja template environment is created
and can be used to alter the
[Jinja environment](https://jinja.palletsprojects.com/en/latest/api/#jinja2.Environment).
Args:
env: global Jinja environment
config: global configuration object
files: global files collection
Returns:
global Jinja Environment
"""
return env
def on_post_build(self, *, config: MkDocsConfig) -> None:
"""
The `post_build` event does not alter any variables. Use this event to call
post-build scripts.
Args:
config: global configuration object
"""
def on_build_error(self, *, error: Exception) -> None:
"""
The `build_error` event is called after an exception of any kind
is caught by MkDocs during the build process.
Use this event to clean things up before MkDocs terminates. Note that any other
events which were scheduled to run after the error will have been skipped. See
[Handling Errors](plugins.md#handling-errors) for more details.
Args:
error: exception raised
"""
# Template events
def on_pre_template(
self, template: jinja2.Template, /, *, template_name: str, config: MkDocsConfig
) -> jinja2.Template | None:
"""
The `pre_template` event is called immediately after the subject template is
loaded and can be used to alter the template.
Args:
template: a Jinja2 [Template](https://jinja.palletsprojects.com/en/latest/api/#jinja2.Template) object
template_name: string filename of template
config: global configuration object
Returns:
a Jinja2 [Template](https://jinja.palletsprojects.com/en/latest/api/#jinja2.Template) object
"""
return template
def on_template_context(
self, context: TemplateContext, /, *, template_name: str, config: MkDocsConfig
) -> TemplateContext | None:
"""
The `template_context` event is called immediately after the context is created
for the subject template and can be used to alter the context for that specific
template only.
Args:
context: dict of template context variables
template_name: string filename of template
config: global configuration object
Returns:
dict of template context variables
"""
return context
def on_post_template(
self, output_content: str, /, *, template_name: str, config: MkDocsConfig
) -> str | None:
"""
The `post_template` event is called after the template is rendered, but before
it is written to disc and can be used to alter the output of the template.
If an empty string is returned, the template is skipped and nothing is is
written to disc.
Args:
output_content: output of rendered template as string
template_name: string filename of template
config: global configuration object
Returns:
output of rendered template as string
"""
return output_content
# Page events
def on_pre_page(self, page: Page, /, *, config: MkDocsConfig, files: Files) -> Page | None:
"""
The `pre_page` event is called before any actions are taken on the subject
page and can be used to alter the `Page` instance.
Args:
page: `mkdocs.structure.pages.Page` instance
config: global configuration object
files: global files collection
Returns:
`mkdocs.structure.pages.Page` instance
"""
return page
def on_page_read_source(self, /, *, page: Page, config: MkDocsConfig) -> str | None:
"""
> DEPRECATED: Instead of this event, prefer one of these alternatives:
>
> * Since MkDocs 1.6, instead set `content_bytes`/`content_string` of a `File` inside [`on_files`][].
> * Usually (although it's not an exact alternative), `on_page_markdown` can serve the same purpose.
The `on_page_read_source` event can replace the default mechanism to read
the contents of a page's source from the filesystem.
Args:
page: `mkdocs.structure.pages.Page` instance
config: global configuration object
Returns:
The raw source for a page as unicode string. If `None` is returned, the
default loading from a file will be performed.
"""
return None
def on_page_markdown(
self, markdown: str, /, *, page: Page, config: MkDocsConfig, files: Files
) -> str | None:
"""
The `page_markdown` event is called after the page's markdown is loaded
from file and can be used to alter the Markdown source text. The meta-
data has been stripped off and is available as `page.meta` at this point.
Args:
markdown: Markdown source text of page as string
page: `mkdocs.structure.pages.Page` instance
config: global configuration object
files: global files collection
Returns:
Markdown source text of page as string
"""
return markdown
def on_page_content(
self, html: str, /, *, page: Page, config: MkDocsConfig, files: Files
) -> str | None:
"""
The `page_content` event is called after the Markdown text is rendered to
HTML (but before being passed to a template) and can be used to alter the
HTML body of the page.
Args:
html: HTML rendered from Markdown source as string
page: `mkdocs.structure.pages.Page` instance
config: global configuration object
files: global files collection
Returns:
HTML rendered from Markdown source as string
"""
return html
def on_page_context(
self, context: TemplateContext, /, *, page: Page, config: MkDocsConfig, nav: Navigation
) -> TemplateContext | None:
"""
The `page_context` event is called after the context for a page is created
and can be used to alter the context for that specific page only.
Args:
context: dict of template context variables
page: `mkdocs.structure.pages.Page` instance
config: global configuration object
nav: global navigation object
Returns:
dict of template context variables
"""
return context
def on_post_page(self, output: str, /, *, page: Page, config: MkDocsConfig) -> str | None:
"""
The `post_page` event is called after the template is rendered, but
before it is written to disc and can be used to alter the output of the
page. If an empty string is returned, the page is skipped and nothing is
written to disc.
Args:
output: output of rendered template as string
page: `mkdocs.structure.pages.Page` instance
config: global configuration object
Returns:
output of rendered template as string
"""
return output
EVENTS = tuple(k[3:] for k in BasePlugin.__dict__ if k.startswith("on_"))
# The above definitions were just for docs and type checking, we don't actually want them.
for k in EVENTS:
delattr(BasePlugin, 'on_' + k)
def event_priority(priority: float) -> Callable[[T], T]:
"""
A decorator to set an event priority for an event handler method.
Recommended priority values:
`100` "first", `50` "early", `0` "default", `-50` "late", `-100` "last".
As different plugins discover more precise relations to each other, the values should be further tweaked.
Usage example:
```python
@plugins.event_priority(-100) # Wishing to run this after all other plugins' `on_files` events.
def on_files(self, files, config, **kwargs):
...
```
New in MkDocs 1.4.
Recommended shim for backwards compatibility:
```python
try:
from mkdocs.plugins import event_priority
except ImportError:
event_priority = lambda priority: lambda f: f # No-op fallback
```
"""
def decorator(event_method):
event_method.mkdocs_priority = priority
return event_method
return decorator
| BasePlugin |
python | tornadoweb__tornado | tornado/test/locks_test.py | {
"start": 7725,
"end": 11116
} | class ____(AsyncTestCase):
def test_negative_value(self):
self.assertRaises(ValueError, locks.Semaphore, value=-1)
def test_repr(self):
sem = locks.Semaphore()
self.assertIn("Semaphore", repr(sem))
self.assertIn("unlocked,value:1", repr(sem))
sem.acquire()
self.assertIn("locked", repr(sem))
self.assertNotIn("waiters", repr(sem))
sem.acquire()
self.assertIn("waiters", repr(sem))
def test_acquire(self):
sem = locks.Semaphore()
f0 = asyncio.ensure_future(sem.acquire())
self.assertTrue(f0.done())
# Wait for release().
f1 = asyncio.ensure_future(sem.acquire())
self.assertFalse(f1.done())
f2 = asyncio.ensure_future(sem.acquire())
sem.release()
self.assertTrue(f1.done())
self.assertFalse(f2.done())
sem.release()
self.assertTrue(f2.done())
sem.release()
# Now acquire() is instant.
self.assertTrue(asyncio.ensure_future(sem.acquire()).done())
self.assertEqual(0, len(sem._waiters))
@gen_test
def test_acquire_timeout(self):
sem = locks.Semaphore(2)
yield sem.acquire()
yield sem.acquire()
acquire = sem.acquire(timedelta(seconds=0.01))
self.io_loop.call_later(0.02, sem.release) # Too late.
yield gen.sleep(0.3)
with self.assertRaises(gen.TimeoutError):
yield acquire
sem.acquire()
f = asyncio.ensure_future(sem.acquire())
self.assertFalse(f.done())
sem.release()
self.assertTrue(f.done())
@gen_test
def test_acquire_timeout_preempted(self):
sem = locks.Semaphore(1)
yield sem.acquire()
# This fires before the wait times out.
self.io_loop.call_later(0.01, sem.release)
acquire = sem.acquire(timedelta(seconds=0.02))
yield gen.sleep(0.03)
yield acquire # No TimeoutError.
def test_release_unacquired(self):
# Unbounded releases are allowed, and increment the semaphore's value.
sem = locks.Semaphore()
sem.release()
sem.release()
# Now the counter is 3. We can acquire three times before blocking.
self.assertTrue(asyncio.ensure_future(sem.acquire()).done())
self.assertTrue(asyncio.ensure_future(sem.acquire()).done())
self.assertTrue(asyncio.ensure_future(sem.acquire()).done())
self.assertFalse(asyncio.ensure_future(sem.acquire()).done())
@gen_test
def test_garbage_collection(self):
# Test that timed-out waiters are occasionally cleaned from the queue.
sem = locks.Semaphore(value=0)
futures = [
asyncio.ensure_future(sem.acquire(timedelta(seconds=0.01)))
for _ in range(101)
]
future = asyncio.ensure_future(sem.acquire())
self.assertEqual(102, len(sem._waiters))
# Let first 101 waiters time out, triggering a collection.
yield gen.sleep(0.02)
self.assertEqual(1, len(sem._waiters))
# Final waiter is still active.
self.assertFalse(future.done())
sem.release()
self.assertTrue(future.done())
# Prevent "Future exception was never retrieved" messages.
for future in futures:
self.assertRaises(TimeoutError, future.result)
| SemaphoreTest |
python | celery__celery | t/unit/worker/test_loops.py | {
"start": 15399,
"end": 17603
} | class ____:
def test_timeout_ignored(self):
x = X(self.app)
x.timeout_then_error(x.connection.drain_events)
with pytest.raises(socket.error):
synloop(*x.args)
assert x.connection.drain_events.call_count == 2
def test_updates_qos_when_changed(self):
x = X(self.app)
x.qos.prev = 2
x.qos.value = 2
x.timeout_then_error(x.connection.drain_events)
with pytest.raises(socket.error):
synloop(*x.args)
x.qos.update.assert_not_called()
x.qos.value = 4
x.timeout_then_error(x.connection.drain_events)
with pytest.raises(socket.error):
synloop(*x.args)
x.qos.update.assert_called_with()
def test_ignores_socket_errors_when_closed(self):
x = X(self.app)
x.close_then_error(x.connection.drain_events)
assert synloop(*x.args) is None
def test_no_connection(self):
x = X(self.app)
x.connection = None
x.hub.timer.call_repeatedly = Mock(
name='x.hub.timer.call_repeatedly()'
)
x.blueprint.state = CLOSE
synloop(*x.args)
x.hub.timer.call_repeatedly.assert_not_called()
def test_heartbeat_error(self):
x = X(self.app, heartbeat=10)
x.obj.pool.is_green = True
def heartbeat_check(rate):
raise RuntimeError('Heartbeat error')
def call_repeatedly(rate, fn, args):
fn(*args)
x.connection.heartbeat_check = Mock(
name='heartbeat_check', side_effect=heartbeat_check
)
x.obj.timer.call_repeatedly = call_repeatedly
with pytest.raises(RuntimeError):
synloop(*x.args)
def test_no_heartbeat_support(self):
x = X(self.app)
x.connection.supports_heartbeats = False
x.obj.pool.is_green = True
x.obj.timer.call_repeatedly = Mock(
name='x.obj.timer.call_repeatedly()'
)
def drain_events(timeout):
x.blueprint.state = CLOSE
x.connection.drain_events.side_effect = drain_events
synloop(*x.args)
x.obj.timer.call_repeatedly.assert_not_called()
| test_synloop |
python | miyuchina__mistletoe | test/test_contrib/test_pygments_renderer.py | {
"start": 195,
"end": 2004
} | class ____(unittest.TestCase):
@parameterized.expand([(True,), (False,)])
def test_render_no_language(self, fail_on_unsupported_language: bool):
renderer = PygmentsRenderer(fail_on_unsupported_language=fail_on_unsupported_language)
token = Document(['```\n', 'no language\n', '```\n'])
output = renderer.render(token)
expected = (
'<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;">'
'<span></span>no language\n</pre></div>\n\n'
)
self.assertEqual(output, expected)
def test_render_known_language(self):
renderer = PygmentsRenderer()
token = Document(['```python\n', '# python language\n', '```\n'])
output = renderer.render(token)
expected = (
'<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;">'
'<span></span><span style="color: #3D7B7B; font-style: italic"># python language</span>\n'
'</pre></div>\n\n'
)
self.assertEqual(output, expected)
def test_render_unknown_language(self):
renderer = PygmentsRenderer()
token = Document(['```foobar\n', 'unknown language\n', '```\n'])
output = renderer.render(token)
expected = (
'<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;">'
'<span></span>unknown language\n</pre></div>\n\n'
)
self.assertEqual(output, expected)
def test_render_fail_on_unsupported_language(self):
renderer = PygmentsRenderer(fail_on_unsupported_language=True)
token = Document(['```foobar\n', 'unknown language\n', '```\n'])
with self.assertRaises(ClassNotFound):
renderer.render(token)
| TestPygmentsRenderer |
python | simonw__datasette | datasette/views/special.py | {
"start": 3503,
"end": 4159
} | class ____(BaseView):
name = "logout"
has_json_alternate = False
async def get(self, request):
if not request.actor:
return Response.redirect(self.ds.urls.instance())
return await self.render(
["logout.html"],
request,
{"actor": request.actor},
)
async def post(self, request):
response = Response.redirect(self.ds.urls.instance())
self.ds.delete_actor_cookie(response)
self.ds.add_message(request, "You are now logged out", self.ds.WARNING)
await self.ds.track_event(LogoutEvent(actor=request.actor))
return response
| LogoutView |
python | pytorch__pytorch | test/jit/test_tracer.py | {
"start": 72485,
"end": 92325
} | class ____(JitTestCase):
def test_trace_script(self):
@torch.jit.script
def func1(x: Tuple[Tensor, Tensor]) -> Tensor:
return x[0] + x[1]
@torch.jit.script
def func2(x: List[Tensor]) -> Tensor:
return x[0] + x[1]
a = torch.randn(5)
b = torch.randn(5)
self.checkTrace(func1, ((a, b),))
self.checkTrace(func2, ((a, b),))
@torch.jit.script
def func3(
x: Tensor, method: str = "bilinear", align_corners: bool = True
) -> Tensor:
hw = x.shape[2:4]
return F.interpolate(x, hw, mode=method, align_corners=align_corners)
inp = torch.rand(1, 3, 6, 6)
self.checkTrace(func3, (inp,))
@torch.jit.script
def func4(x: Tensor, a: List[Optional[str]]) -> Tensor:
if len(a) == 2:
return x + 2
else:
return x
def test_trace_mixed_by_script_with_dict_output(self):
@torch.jit.script
def return_dict(input: torch.Tensor) -> Dict[str, torch.Tensor]:
return {"foo": input + 1}
class TraceModule(torch.nn.Module):
def forward(self, input):
dict = return_dict(input)
return dict["foo"] + dict["foo"]
x = torch.ones(1)
tm = torch.jit.trace(TraceModule(), x)
self.assertEqual(tm(x), x + 1 + x + 1)
def test_trace_of_script(self):
@torch.jit.script
def foo(a, c):
b = 0.0
if bool(a == 0.0):
b = 1.0
return b + c
a = torch.ones(1, dtype=torch.float)
@_trace(torch.zeros(1, dtype=torch.float))
def use(b):
return foo(b - 1.0, a) + 1.0
# test we propagated shapes through the function
self.assertTrue("Dynamic" not in str(use.graph))
self.assertEqual(3, use(torch.ones(1, dtype=torch.float)))
self.assertEqual(2, use(torch.zeros(1, dtype=torch.float)))
def test_trace_with_size(self):
@_trace(torch.zeros(1, 1))
def foo(x):
return x + 1
@torch.jit.script
def bar(x):
y = int(foo(x))
if 1 == 1:
y = 7
return y + 1
self.assertEqual(8, bar(torch.ones(1, 1)))
def test_tracing_slicing(self):
@_trace(torch.zeros(10))
def foo_trace(x):
return x[-5:-3]
@torch.jit.script
def foo_script(x):
return x[-5:-3]
def foo(x):
return x[-5:-3]
a = torch.arange(0, 8)
b = torch.arange(0, 20)
self.assertEqual(foo_trace(a), foo_script(a))
self.assertEqual(foo_trace(a), foo(a))
self.assertNotEqual(foo_trace(a), foo_trace(b))
def test_tracing_indexing(self):
@_trace(torch.zeros(10))
def foo_trace(x):
return x[-2]
@torch.jit.script
def foo_script(x):
return x[-2]
def foo(x):
return x[-2]
a = torch.arange(0, 8)
b = torch.arange(0, 20)
self.assertEqual(foo_script(a), foo_trace(a))
self.assertEqual(foo_trace(a), foo(a))
self.assertNotEqual(foo_trace(a), foo_trace(b))
def test_trace_hierarchy(self):
# Test that we preserve the module hierarchy for a ScriptModule
# submodule during tracing
class AnotherScriptMod(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.param = torch.nn.Parameter(torch.rand(1, 2, 3))
@torch.jit.script_method
def bar(self):
return torch.zeros(4, 5)
class SomeScriptMod(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.asm = AnotherScriptMod()
@torch.jit.script_method
def foo(self):
return torch.zeros(3, 4)
@torch.jit.script_method
def bar(self):
return torch.zeros(4, 3)
class TraceMe(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.ssm = SomeScriptMod()
def forward(self, x):
return self.ssm.bar() + x
orig = TraceMe()
traced = torch.jit.trace(orig, (torch.rand(4, 3),))
# for each of these checks, check that *BOTH* the underlying
# _C.ScriptModule object has the expected method/param, as well as the
# Python object that wraps it.
self.assertTrue(traced.ssm._c._has_method("foo"))
self.assertTrue(hasattr(traced.ssm, "foo"))
imported = self.getExportImportCopy(traced)
self.assertTrue(imported.ssm._c._has_method("foo"))
self.assertTrue(hasattr(imported.ssm, "foo"))
self.assertTrue(imported.ssm.asm._c._has_method("bar"))
self.assertTrue(hasattr(imported.ssm.asm, "bar"))
self.assertTrue(hasattr(imported.ssm.asm, "param"))
def test_trace_parameter(self):
class Param(nn.Module):
def __init__(self) -> None:
super().__init__()
self.register_parameter("bias", nn.Parameter(torch.empty(4, 4)))
def forward(self, x):
return x
class M3(torch.jit.ScriptModule):
def __init__(self, model):
super().__init__()
self.traced = torch.jit.trace(model, (torch.rand(3, 3)))
@torch.jit.script_method
def forward(self, x):
return self.traced(x)
class M2(nn.Module):
def __init__(self, model):
super().__init__()
self.module = M3(model)
def forward(self, x):
return self.module(x)
class M1(torch.jit.ScriptModule):
def __init__(self, model):
super().__init__()
self.traced = torch.jit.trace(M2(model), (torch.rand(3, 3)))
@torch.jit.script_method
def forward(self, x):
return self.traced(x)
with torch.jit.optimized_execution(False):
module = M1(Param())
f = io.BytesIO()
torch.jit.save(module, f)
@_tmp_donotuse_dont_inline_everything
def test_call_script_fn_from_traced_module(self):
@torch.jit.script
def scripted_fn(x):
return torch.neg(x)
class TracedModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.param = torch.nn.Parameter(torch.rand(4, 5))
def forward(self, x):
return scripted_fn(torch.mm(x, self.param))
tm = torch.jit.trace(TracedModule(), torch.rand(3, 4))
FileCheck().check("aten::mm").check('name="scripted_fn"').check(
"prim::CallFunction"
).run(str(tm.graph))
@_tmp_donotuse_dont_inline_everything
def test_call_script_module_from_traced_module(self):
class ScriptMod(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.param_foo = torch.nn.Parameter(torch.rand(5, 7))
@torch.jit.script_method
def forward(self, x):
return torch.mm(x, self.param_foo)
class TracedModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.param = torch.nn.Parameter(torch.rand(4, 5))
self.mod = ScriptMod()
def forward(self, x):
return self.mod(torch.mm(x, self.param)) + 1.0
tm = torch.jit.trace(TracedModule(), torch.rand(3, 4))
FileCheck().check("aten::mm").check("prim::CallMethod").check_same(
"forward"
).check("aten::add").run(str(tm.graph))
@_tmp_donotuse_dont_inline_everything
def test_call_traced_fn_from_script_fn(self):
@_trace(torch.rand(3, 4))
def traced_fn(x):
return torch.neg(x)
@torch.jit.script
def script_fn(x):
return traced_fn(x) + 1
FileCheck().check("prim::CallFunction").check("aten::add").run(
str(script_fn.graph)
)
def test_call_traced_mod_from_script_fn(self):
with self.assertRaisesRegex(
RuntimeError,
"Cannot call a ScriptModule that is not a submodule of the caller",
):
class TracedModule(torch.nn.Module):
def forward(self, x):
return torch.mm(x, torch.zeros(4, 3))
tm = torch.jit.trace(TracedModule(), torch.rand(3, 4))
@torch.jit.script
def script_fn(x):
return tm(x) + 1
@_tmp_donotuse_dont_inline_everything
def test_call_tracing_fn_from_script_module(self):
@_trace(torch.rand(3, 3))
def traced_fn(x):
return torch.neg(x)
class ScriptMod(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.param = torch.nn.Parameter(torch.rand(4, 3))
@torch.jit.script_method
def forward(self, x):
return traced_fn(torch.mm(x, self.param))
sm = ScriptMod()
FileCheck().check("aten::mm").check("prim::CallFunction").run(
str(sm.forward.graph)
)
@_tmp_donotuse_dont_inline_everything
def test_call_tracing_mod_from_script_module(self):
class TracedMod(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.param = torch.nn.Parameter(torch.rand(3, 5))
def forward(self, x):
return torch.mm(x, self.param)
class ScriptMod(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.param = torch.nn.Parameter(torch.rand(4, 3))
self.tm = torch.jit.trace(TracedMod(), torch.rand(3, 3))
@torch.jit.script_method
def forward(self, x):
return self.tm(torch.mm(x, self.param))
sm = ScriptMod()
FileCheck().check("aten::mm").check("prim::CallMethod").run(str(sm.graph))
def test_script_inline_trace_multiple_args(self):
class M(torch.nn.Module):
def forward(self, input, input2):
return input + input2
class M2(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.m = torch.jit.trace(M(), (torch.zeros(4, 3), torch.zeros(4, 3)))
@torch.jit.script_method
def forward(self, inp):
return self.m(inp, inp)
with torch.jit.optimized_execution(False):
m2 = M2()
m2(torch.zeros(4, 3))
def test_trace_dict_mix_script(self):
class testB(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear = torch.nn.Linear(2, 2)
def forward(self, feature_map: Dict[str, List[Tensor]]) -> Tensor:
output = []
for j in feature_map.values():
output.append(self.linear(j[0]))
return torch.stack(output)
class testA(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.b = torch.jit.script(testB())
def forward(self, input_map: Dict[str, List[Tensor]]) -> Tensor:
feature_map = {}
for i, j in input_map.items():
feature_map[i] = [j[0]]
return self.b(feature_map)
input_map = {
"1": [torch.rand(2, 2), torch.rand(2, 2)],
"3": [torch.rand(2, 2), torch.rand(2, 2)],
}
model = testA()
traced_model = torch.jit.trace(model, input_map)
new_input_map = {
"1": [torch.rand(2, 2), torch.randn(2, 2)],
"3": [torch.rand(2, 2), torch.rand(2, 2)],
}
self.assertEqual(model(new_input_map), traced_model(new_input_map))
def test_trace_script_returning_complex_dict(self):
"""Tracing over a script function returning a dictionary should work.
The dictionary can should be able to contain other containers (like a tuple) recursively.
"""
class ReturnsDict(torch.nn.Module):
def forward(
self,
id_score_list: Dict[
str, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]
],
) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
# do some random operations and then return a dict of the same structure
v = id_score_list["1000"]
idx_keys = v[1] - 1500000
weights = v[2]
result = {"1000": (v[0], idx_keys, weights)}
return result
class ChecksDict(torch.nn.Module):
def forward(
self, input: Dict[str, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]
):
v = input["1000"]
return v[1] + 1
class TestModule(torch.nn.Module):
def __init__(self, checks_dict, returns_dict):
super().__init__()
self.checks_dict = checks_dict
self.returns_dict = returns_dict
def forward(
self, input: Dict[str, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]
):
foo = self.returns_dict(input)
return self.checks_dict(foo)
input1 = {
"1000": (
torch.tensor([0]),
torch.tensor([], dtype=torch.int64),
torch.tensor([]),
)
}
input2 = {
"1000": (
torch.tensor([0]),
torch.tensor([1500000, 1500004], dtype=torch.int64),
torch.tensor([2.0, 3.0]),
)
}
checks_dict = torch.jit.script(ChecksDict())
returns_dict = torch.jit.script(ReturnsDict())
eager_module = TestModule(checks_dict, returns_dict)
traced_module = torch.jit.trace(eager_module, input1)
self.assertEqual(traced_module(input1), eager_module(input1))
self.assertEqual(traced_module(input2), eager_module(input2))
def test_trace_returning_dict_with_tensor_tuples(self):
"""Tracing over a module returning a dictionary whose values are tuples of tensors
should work.
"""
class ReturnsDict(torch.nn.Module):
def forward(
self, k: torch.Tensor, v: torch.Tensor
) -> Dict[str, Tuple[torch.Tensor, torch.Tensor]]:
x = 2 * k
y = 3 * v
result = {"imakey": (x, y)}
return result
class ReturnsBadDict(torch.nn.Module):
def forward(
self, k: torch.Tensor, v: torch.Tensor
) -> Dict[str, Tuple[torch.Tensor, float]]:
x = 2 * k
result = {"imakey": (x, 1)}
return result
mod = ReturnsDict()
traced_module = torch.jit.trace(
mod, [torch.ones(1), torch.ones(1)], strict=False
)
out = traced_module(torch.ones(1), torch.ones(1))
expected = {"imakey": (torch.tensor([2.0]), torch.tensor([3.0]))}
self.assertEqual(out, expected)
with self.assertRaisesRegex(
RuntimeError, "cannot be understood by the tracer, only outputs matching"
):
mod = ReturnsBadDict()
traced_module = torch.jit.trace(
mod, [torch.ones(1), torch.ones(1)], strict=False
)
def test_trace_linear(self):
m = torch.nn.Linear(20, 20)
inp = torch.rand([20, 20])
self.checkTrace(m, (inp,))
g = torch.jit.trace(m, (inp,)).graph
FileCheck().check("aten::linear").run(g)
def test_traced_module_implements_interface(self):
@torch.jit.interface
class TestModuleInterface(nn.Module):
def forward(
self, first_arg: torch.Tensor, second_arg: torch.Tensor
) -> torch.Tensor:
pass
make_global(TestModuleInterface)
class TestModule(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = nn.Conv2d(1, 1, 3)
def forward(
self, first_arg: torch.Tensor, second_arg: torch.Tensor
) -> torch.Tensor:
return self.conv(first_arg) + second_arg
def fn_takes_interface(x: TestModuleInterface):
ones = torch.ones(1, 1, 3, 3)
return x.forward(ones, ones)
scripted_test_module = torch.jit.script(TestModule())
self.checkScript(fn_takes_interface, (scripted_test_module,))
def test_traced_module_contains_scripted_interface_types(self):
class LeafModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Parameter(torch.rand(19))
def forward(self, input: torch.Tensor):
return input + self.weight
class LowerModuleImpl(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.leaf = LeafModule()
def forward(self, input: torch.Tensor) -> torch.Tensor:
return self.leaf(input)
@torch.jit.interface
class LowerModuleInterface(torch.nn.Module):
def forward(self, input: torch.Tensor) -> torch.Tensor:
pass
class MiddleModule(torch.nn.Module):
lower: LowerModuleInterface
def __init__(self, feature_processor_modules=None):
super().__init__()
self.lower = LowerModuleImpl()
def forward(self, input):
return self.lower(input)
class WrapperModule(torch.nn.Module):
def __init__(self, m):
super().__init__()
self.middle = m
def forward(self, input):
return self.middle(input)
class TopModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
m = MiddleModule()
m = torch.jit.script(m)
self.sub1 = m
self.sub2 = WrapperModule(m)
def forward(self, input: torch.Tensor):
return self.sub1(input) + self.sub2(input)
top = TopModule()
top_example_input = torch.ones(1)
torch.jit.trace(top, top_example_input)
def test_jit_trace_callfunction_return_shapes(self):
# a torch.jit.script function gets inserted as a CallFunction node
@torch.jit.script
def inner_fn(x):
return torch.cat((x, x))
def outer_fn(x, y):
return inner_fn(x + y).relu()
x, y = [torch.rand((2, 2), dtype=torch.float) for _ in range(2)]
fn_t = torch.jit.trace(outer_fn, (x, y))
# expect that the CallFunction node return type has shape information on it.
FileCheck().check("Float").check("4, 2").check("CallFunction").run(fn_t.graph)
for n in fn_t.graph.nodes():
if n.kind() == "prim::CallFunction":
self.assertTrue(n.output().isCompleteTensor())
if __name__ == "__main__":
raise_on_run_directly("test/test_jit.py")
| TestMixTracingScripting |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/plugin.py | {
"start": 731,
"end": 4491
} | class ____(SpyderDockablePlugin, ShellConnectPluginMixin):
"""
Variable explorer plugin.
"""
NAME = 'variable_explorer'
REQUIRES = [Plugins.IPythonConsole, Plugins.Preferences]
OPTIONAL = [Plugins.Plots]
TABIFY = None
WIDGET_CLASS = VariableExplorerWidget
CONF_SECTION = NAME
CONF_FILE = False
CONF_WIDGET_CLASS = VariableExplorerConfigPage
DISABLE_ACTIONS_WHEN_HIDDEN = False
# Open binary data files in this plugin
FILE_EXTENSIONS = [
ext for ext in iofunctions.load_funcs
if ext not in ['.csv', '.txt', '.json']
]
# ---- SpyderDockablePlugin API
# ------------------------------------------------------------------------
@staticmethod
def get_name():
return _('Variable explorer')
@staticmethod
def get_description():
return _("Explore, edit, save and load the lists, arrays, dataframes "
"and other global variables generated by running your code.")
@classmethod
def get_icon(cls):
return cls.create_icon('variable_explorer')
def on_initialize(self):
widget = self.get_widget()
widget.sig_open_preferences_requested.connect(self._open_preferences)
widget.sig_show_figure_requested.connect(self._show_figure)
@on_plugin_available(plugin=Plugins.Plots)
def on_plots_available(self):
self.get_widget().set_plots_plugin_enabled(True)
@on_plugin_teardown(plugin=Plugins.Plots)
def on_plots_teardown(self):
self.get_widget().set_plots_plugin_enabled(False)
@on_plugin_available(plugin=Plugins.Preferences)
def on_preferences_available(self):
preferences = self.get_plugin(Plugins.Preferences)
preferences.register_plugin_preferences(self)
@on_plugin_teardown(plugin=Plugins.Preferences)
def on_preferences_teardown(self):
preferences = self.get_plugin(Plugins.Preferences)
preferences.deregister_plugin_preferences(self)
def open_file(self, filename: str):
"""
Load data file in variable explorer.
"""
self.get_widget().import_data([filename])
# ---- Private API
# -------------------------------------------------------------------------
def _open_preferences(self):
"""Open the Preferences dialog in the Variable Explorer section."""
self._main.show_preferences()
preferences = self.get_plugin(Plugins.Preferences)
if preferences:
container = preferences.get_container()
dlg = container.dialog
index = dlg.get_index_by_name(self.NAME)
dlg.set_current_index(index)
def _show_figure(self, image, mime_type, shellwidget):
"""
Show figure in Plots plugin.
This shows the figure in the figure browser associated with the given
shellwidget. The shellwidget is activated and the Plots plugin and the
window containing the Plots plugin are both raised so that the user
will see the figure.
Parameters
----------
image: bytes
The image to show. SVG images should be encoded so that the type
of this parameter is `bytes`, not `str`.
mime_type: str
The image's mime type.
shellwidget: ShellWidget
The shellwidget associated with the figure.
"""
ipython_console = self.get_plugin(Plugins.IPythonConsole)
if ipython_console:
ipython_console.set_current_shellwidget(shellwidget)
plots = self.get_plugin(Plugins.Plots)
if plots:
if mime_type == 'image/svg+xml':
image = image.decode()
plots.add_plot(image, mime_type, shellwidget)
| VariableExplorer |
python | pytorch__pytorch | test/fx/quantization.py | {
"start": 920,
"end": 1443
} | class ____:
def __init__(self, quantizer, node):
self.min, self.max = float("inf"), float("-inf")
self.all_tensors = True
def observe(self, node, env):
v = env[node.name]
if not isinstance(v, torch.Tensor):
self.all_tensors = False
return
self.max = max(self.max, float(v.max()))
self.min = min(self.min, float(v.min()))
def scale_zeropoint(self):
return _minmax_scale_zeropoint(self.min, self.max, qmin=0, qmax=255)
| MinMaxObserver |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule_test.py | {
"start": 299,
"end": 1358
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_fit_lr_correctness(self):
model = Sequential(
[
layers.Dense(
2, kernel_initializer="ones", bias_initializer="ones"
)
]
)
optimizer = optimizers.Adam(
learning_rate=schedules.ExponentialDecay(
initial_learning_rate=0.05, decay_steps=1, decay_rate=0.9
)
)
self.assertEqual(len(optimizer.variables), 1)
self.assertEqual(optimizer.variables[0], 0)
model.compile(optimizer=optimizer, loss="mse")
x = np.arange(32).reshape((16, 2))
y = np.arange(32).reshape((16, 2))
history = model.fit(x, y, epochs=3, batch_size=4, shuffle=False)
self.assertEqual(optimizer.variables[0], 4 * 3)
self.assertAllClose(
history.history["loss"],
[230.79457092285156, 128.30319213867188, 79.33648681640625],
rtol=5e-5,
)
| TestFitLRSchedulesFlow |
python | PrefectHQ__prefect | tests/test_flow_engine.py | {
"start": 61486,
"end": 63290
} | class ____:
def test_load_flow_from_entrypoint(self, monkeypatch, tmp_path, flow_run):
flow_code = """
from prefect import flow
@flow
def dog():
return "woof!"
"""
fpath = tmp_path / "f.py"
fpath.write_text(dedent(flow_code))
monkeypatch.setenv("PREFECT__FLOW_ENTRYPOINT", f"{fpath}:dog")
loaded_flow_run, flow = load_flow_and_flow_run(flow_run.id)
assert loaded_flow_run.id == flow_run.id
assert flow.fn() == "woof!"
async def test_load_flow_from_script_with_module_level_sync_compatible_call(
self, prefect_client: PrefectClient, tmp_path
):
"""
This test ensures that when a worker or runner loads a flow from a script, and
that script contains a module-level call to a sync-compatible function, the sync
compatible function is correctly runs as sync and does not prevent the flow from
being loaded.
Regression test for https://github.com/PrefectHQ/prefect/issues/14625
"""
flow_id = await prefect_client.create_flow_from_name(flow_name="uses_block")
deployment_id = await prefect_client.create_deployment(
flow_id=flow_id,
name="test-load-flow-from-script-with-module-level-sync-compatible-call",
path=str(__development_base_path__ / "tests" / "test-projects" / "flows"),
entrypoint="uses_block.py:uses_block",
)
api_flow_run = await prefect_client.create_flow_run_from_deployment(
deployment_id=deployment_id
)
with tmpchdir(tmp_path):
flow_run, flow = load_flow_and_flow_run(api_flow_run.id)
assert flow_run.id == api_flow_run.id
assert await flow() == "bar"
| TestLoadFlowAndFlowRun |
python | huggingface__transformers | src/transformers/utils/dummy_speech_objects.py | {
"start": 129,
"end": 294
} | class ____(metaclass=DummyObject):
_backends = ["speech"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["speech"])
| ASTFeatureExtractor |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 670,
"end": 798
} | class ____(models.Model):
name = models.CharField(max_length=50)
class Meta:
app_label = "django_extensions"
| Name |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_web_search_tool_result_block.py | {
"start": 296,
"end": 459
} | class ____(BaseModel):
content: BetaWebSearchToolResultBlockContent
tool_use_id: str
type: Literal["web_search_tool_result"]
| BetaWebSearchToolResultBlock |
python | dask__distributed | distributed/scheduler.py | {
"start": 35669,
"end": 39652
} | class ____(TaskCollection):
"""Collection tracking all tasks within a group
See also
--------
TaskPrefix
"""
#: The other TaskGroups on which this one depends
dependencies: set[TaskGroup]
#: The worker most recently assigned a task from this group, or None when the group
#: is not identified to be root-like by `SchedulerState.decide_worker`.
last_worker: WorkerState | None
#: If `last_worker` is not None, the number of times that worker should be assigned
#: subsequent tasks until a new worker is chosen.
last_worker_tasks_left: int
prefix: TaskPrefix
#: Earliest time when a task belonging to this group started computing;
#: 0 if no task has *finished* computing yet
#:
#: Notes
#: -----
#: This is not updated until at least one task has *finished* computing.
#: It could move backwards as tasks complete.
start: float
#: Latest time when a task belonging to this group finished computing,
#: 0 if no task has finished computing yet
stop: float
#: Span ID (see ``distributed.spans``).
#: Matches ``distributed.worker_state_machine.TaskState.span_id``.
#: It is possible to end up in situation where different tasks of the same TaskGroup
#: belong to different spans; the purpose of this attribute is to arbitrarily force
#: everything onto the earliest encountered one.
span_id: str | None
__slots__ = tuple(__annotations__)
def __init__(self, name: str, prefix: TaskPrefix):
TaskCollection.__init__(self, name)
self.dependencies = set()
self.start = 0.0
self.stop = 0.0
self.last_worker = None
self.last_worker_tasks_left = 0
self.span_id = None
self.prefix = prefix
prefix.add_group(self)
def add_duration(self, action: str, start: float, stop: float) -> None:
duration_us = max(round((stop - start) * 1e6), 0)
self._duration_us += duration_us
self._all_durations_us[action] += duration_us
if action == "compute":
if self.stop < stop:
self.stop = stop
if self.start == 0.0 or self.start > start:
self.start = start
self.prefix.add_duration(action, start, stop)
def add(self, other: TaskState) -> None:
self.states[other.state] += 1
self._size += 1
self.prefix.states[other.state] += 1
self.prefix._size += 1
other.group = self
def add_type(self, typename: str) -> None:
self._types[typename] += 1
self.prefix._types[typename] += 1
def update_nbytes(self, diff: int) -> None:
self.nbytes_total += diff
self.prefix.nbytes_total += diff
def __repr__(self) -> str:
return (
"<"
+ (self.name or "no-group")
+ ": "
+ ", ".join(
"%s: %d" % (k, v) for (k, v) in sorted(self.states.items()) if v
)
+ ">"
)
def _to_dict_no_nest(self, *, exclude: Container[str] = ()) -> dict[str, Any]:
"""Dictionary representation for debugging purposes.
Not type stable and not intended for roundtrips.
See also
--------
Client.dump_cluster_state
distributed.utils.recursive_to_dict
TaskState._to_dict
"""
return recursive_to_dict(self, exclude=exclude, members=True)
@property
def done(self) -> bool:
"""Return True if all computations for this group have completed; False
otherwise.
Notes
-----
This property may transition from True to False, e.g. when a worker that
contained the only replica of a task in memory crashes and the task need to be
recomputed.
"""
return all(
count == 0 or state in {"memory", "erred", "released", "forgotten"}
for state, count in self.states.items()
)
| TaskGroup |
python | tensorflow__tensorflow | tensorflow/python/saved_model/pywrap_saved_model_metrics_test.py | {
"start": 1034,
"end": 10013
} | class ____(test.TestCase):
def _get_histogram_proto(self, proto_bytes):
histogram_proto = summary_pb2.HistogramProto()
histogram_proto.ParseFromString(proto_bytes)
return histogram_proto
def _get_serialized_fingerprint_def(self):
return fingerprint_pb2.FingerprintDef(
saved_model_checksum=1,
graph_def_program_hash=2,
signature_def_hash=3,
saved_object_graph_hash=4,
checkpoint_hash=5,
version=versions_pb2.VersionDef(producer=6)).SerializeToString()
def test_SM_increment_write(self):
self.assertEqual(metrics.GetWrite(write_version="1"), 0)
metrics.IncrementWriteApi("foo")
self.assertEqual(metrics.GetWriteApi("foo"), 1)
metrics.IncrementWrite(write_version="1")
self.assertEqual(metrics.GetWrite(write_version="1"), 1)
def test_SM_increment_read(self):
self.assertEqual(metrics.GetRead(write_version="2"), 0)
metrics.IncrementReadApi("bar")
self.assertEqual(metrics.GetReadApi("bar"), 1)
metrics.IncrementRead(write_version="2")
self.assertEqual(metrics.GetRead(write_version="2"), 1)
def test_checkpoint_add_write_duration(self):
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointWriteDurations(api_label="foo")).num, 0)
metrics.AddCheckpointWriteDuration(api_label="foo", microseconds=100)
metrics.AddCheckpointWriteDuration(api_label="foo", microseconds=200)
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointWriteDurations(api_label="foo")).num, 2)
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointWriteDurations(api_label="foo")).min, 100)
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointWriteDurations(api_label="foo")).max, 200)
def test_async_checkpoint_add_write_duration(self):
self.assertEqual(
self._get_histogram_proto(
metrics.GetAsyncCheckpointWriteDurations(api_label="foo")).num, 0)
metrics.AddAsyncCheckpointWriteDuration(api_label="foo", microseconds=20)
metrics.AddAsyncCheckpointWriteDuration(api_label="foo", microseconds=50)
self.assertEqual(
self._get_histogram_proto(
metrics.GetAsyncCheckpointWriteDurations(api_label="foo")).num, 2)
self.assertEqual(
self._get_histogram_proto(
metrics.GetAsyncCheckpointWriteDurations(api_label="foo")).min, 20)
self.assertEqual(
self._get_histogram_proto(
metrics.GetAsyncCheckpointWriteDurations(api_label="foo")).max, 50)
def test_checkpoint_add_read_duration(self):
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointReadDurations(api_label="bar")).num, 0)
metrics.AddCheckpointReadDuration(api_label="bar", microseconds=200)
metrics.AddCheckpointReadDuration(api_label="bar", microseconds=20000)
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointReadDurations(api_label="bar")).num, 2)
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointReadDurations(api_label="bar")).min, 200)
self.assertEqual(
self._get_histogram_proto(
metrics.GetCheckpointReadDurations(api_label="bar")).max, 20000)
def test_training_time_saved(self):
self.assertEqual(metrics.GetTrainingTimeSaved(api_label="baz"), 0)
metrics.AddTrainingTimeSaved(api_label="baz", microseconds=1000)
self.assertEqual(metrics.GetTrainingTimeSaved(api_label="baz"), 1000)
def test_checkpoint_size(self):
self.assertEqual(
metrics.GetCheckpointSize(api_label="baz", filesize=100), 0)
metrics.RecordCheckpointSize(api_label="baz", filesize=100)
metrics.RecordCheckpointSize(api_label="baz", filesize=100)
self.assertEqual(
metrics.GetCheckpointSize(api_label="baz", filesize=100), 2)
def test_filesize(self):
filename = os.path.join(self.get_temp_dir(), "test.txt")
with open(filename, "w") as file:
file.write("Hello! \n")
self.assertEqual(metrics.CalculateFileSize(filename), 0)
def test_invalid_file(self):
self.assertEqual(metrics.CalculateFileSize("not_a_file.txt"), -1)
def test_SM_read_fingerprint(self):
self.assertEqual(metrics.GetReadFingerprint(), "")
metrics.SetReadFingerprint(
fingerprint=self._get_serialized_fingerprint_def())
read_fingerprint = metrics.GetReadFingerprint()
self.assertIn('"saved_model_checksum" : 1', read_fingerprint)
self.assertIn('"graph_def_program_hash" : 2', read_fingerprint)
self.assertIn('"signature_def_hash" : 3', read_fingerprint)
self.assertIn('"saved_object_graph_hash" : 4', read_fingerprint)
self.assertIn('"checkpoint_hash" : 5', read_fingerprint)
def test_SM_write_fingerprint(self):
self.assertEqual(metrics.GetWriteFingerprint(), "")
metrics.SetWriteFingerprint(
fingerprint=self._get_serialized_fingerprint_def())
write_fingerprint = metrics.GetWriteFingerprint()
self.assertIn('"saved_model_checksum" : 1', write_fingerprint)
self.assertIn('"graph_def_program_hash" : 2', write_fingerprint)
self.assertIn('"signature_def_hash" : 3', write_fingerprint)
self.assertIn('"saved_object_graph_hash" : 4', write_fingerprint)
self.assertIn('"checkpoint_hash" : 5', write_fingerprint)
def test_SM_read_path(self):
self.assertEqual(metrics.GetReadPath(), "")
metrics.SetReadPath(saved_model_path="foo")
self.assertEqual(metrics.GetReadPath(), "foo")
def test_SM_write_path(self):
self.assertEqual(metrics.GetWritePath(), "")
metrics.SetWritePath(saved_model_path="foo")
self.assertEqual(metrics.GetWritePath(), "foo")
def test_SM_read_path_and_singleprint(self):
self.assertEqual(metrics.GetReadPathAndSingleprint(), ("", ""))
metrics.SetReadPathAndSingleprint(path="foo", singleprint="bar")
self.assertEqual(metrics.GetReadPathAndSingleprint(), ("foo", "bar"))
def test_SM_read_invalid_path_and_singleprint(self):
with self.assertRaises(metrics.MetricException) as excinfo:
metrics.SetReadPathAndSingleprint(path="", singleprint="bar")
self.assertRegex(str(excinfo.exception),
"Invalid path_and_singleprint argument. Empty path.")
with self.assertRaises(metrics.MetricException) as excinfo:
metrics.SetReadPathAndSingleprint(path="foo", singleprint="")
self.assertRegex(
str(excinfo.exception),
"Invalid path_and_singleprint argument. Empty singleprint.")
def test_SM_write_path_and_singleprint(self):
self.assertEqual(metrics.GetWritePathAndSingleprint(), ("", ""))
metrics.SetWritePathAndSingleprint(path="foo", singleprint="bar")
self.assertEqual(metrics.GetWritePathAndSingleprint(), ("foo", "bar"))
def test_SM_write_invalid_path_and_singleprint(self):
with self.assertRaises(metrics.MetricException) as excinfo:
metrics.SetWritePathAndSingleprint(path="", singleprint="bar")
self.assertRegex(str(excinfo.exception),
"Invalid path_and_singleprint argument. Empty path.")
with self.assertRaises(metrics.MetricException) as excinfo:
metrics.SetWritePathAndSingleprint(path="foo", singleprint="")
self.assertRegex(
str(excinfo.exception),
"Invalid path_and_singleprint argument. Empty singleprint.")
def test_SM_found_fingerprint_on_load(self):
metrics.SetFoundFingerprintOnLoad(found_status=metrics.kFingerprintFound)
self.assertEqual(metrics.GetFoundFingerprintOnLoad(), "FOUND")
metrics.SetFoundFingerprintOnLoad(found_status=metrics.kFingerprintNotFound)
self.assertEqual(metrics.GetFoundFingerprintOnLoad(), "NOT_FOUND")
metrics.SetFoundFingerprintOnLoad(found_status=metrics.kFingerprintError)
self.assertEqual(metrics.GetFoundFingerprintOnLoad(), "ERROR")
def test_invalid_SM_found_fingerprint_on_load(self):
metrics.SetFoundFingerprintOnLoad(found_status="absolute nonsense")
self.assertEqual(metrics.GetFoundFingerprintOnLoad(), "")
metrics.SetFoundFingerprintOnLoad(found_status="found")
self.assertEqual(metrics.GetFoundFingerprintOnLoad(), "")
def test_checkpoint_sharding_callback_duration(self):
self.assertEqual(metrics.GetShardingCallbackDuration(), 0)
metrics.AddShardingCallbackDuration(callback_duration=100)
self.assertEqual(metrics.GetShardingCallbackDuration(), 100)
def test_num_checkpoint_shards_written(self):
self.assertEqual(metrics.GetNumCheckpointShardsWritten(), 0)
metrics.AddNumCheckpointShardsWritten(num_shards=10)
self.assertEqual(metrics.GetNumCheckpointShardsWritten(), 10)
def test_sharding_callback_description(self):
self.assertEqual(metrics.GetShardingCallbackDescription(), "")
metrics.SetShardingCallbackDescription(description="foo")
self.assertEqual(metrics.GetShardingCallbackDescription(), "foo")
if __name__ == "__main__":
test.main()
| MetricsTest |
python | redis__redis-py | redis/background.py | {
"start": 78,
"end": 5927
} | class ____:
"""
Schedules background tasks execution either in separate thread or in the running event loop.
"""
def __init__(self):
self._next_timer = None
self._event_loops = []
self._lock = threading.Lock()
self._stopped = False
def __del__(self):
self.stop()
def stop(self):
"""
Stop all scheduled tasks and clean up resources.
"""
with self._lock:
if self._stopped:
return
self._stopped = True
if self._next_timer:
self._next_timer.cancel()
self._next_timer = None
# Stop all event loops
for loop in self._event_loops:
if loop.is_running():
loop.call_soon_threadsafe(loop.stop)
self._event_loops.clear()
def run_once(self, delay: float, callback: Callable, *args):
"""
Runs callable task once after certain delay in seconds.
"""
with self._lock:
if self._stopped:
return
# Run loop in a separate thread to unblock main thread.
loop = asyncio.new_event_loop()
with self._lock:
self._event_loops.append(loop)
thread = threading.Thread(
target=_start_event_loop_in_thread,
args=(loop, self._call_later, delay, callback, *args),
daemon=True,
)
thread.start()
def run_recurring(self, interval: float, callback: Callable, *args):
"""
Runs recurring callable task with given interval in seconds.
"""
with self._lock:
if self._stopped:
return
# Run loop in a separate thread to unblock main thread.
loop = asyncio.new_event_loop()
with self._lock:
self._event_loops.append(loop)
thread = threading.Thread(
target=_start_event_loop_in_thread,
args=(loop, self._call_later_recurring, interval, callback, *args),
daemon=True,
)
thread.start()
async def run_recurring_async(
self, interval: float, coro: Callable[..., Coroutine[Any, Any, Any]], *args
):
"""
Runs recurring coroutine with given interval in seconds in the current event loop.
To be used only from an async context. No additional threads are created.
"""
with self._lock:
if self._stopped:
return
loop = asyncio.get_running_loop()
wrapped = _async_to_sync_wrapper(loop, coro, *args)
def tick():
with self._lock:
if self._stopped:
return
# Schedule the coroutine
wrapped()
# Schedule next tick
self._next_timer = loop.call_later(interval, tick)
# Schedule first tick
self._next_timer = loop.call_later(interval, tick)
def _call_later(
self, loop: asyncio.AbstractEventLoop, delay: float, callback: Callable, *args
):
with self._lock:
if self._stopped:
return
self._next_timer = loop.call_later(delay, callback, *args)
def _call_later_recurring(
self,
loop: asyncio.AbstractEventLoop,
interval: float,
callback: Callable,
*args,
):
with self._lock:
if self._stopped:
return
self._call_later(
loop, interval, self._execute_recurring, loop, interval, callback, *args
)
def _execute_recurring(
self,
loop: asyncio.AbstractEventLoop,
interval: float,
callback: Callable,
*args,
):
"""
Executes recurring callable task with given interval in seconds.
"""
with self._lock:
if self._stopped:
return
try:
callback(*args)
except Exception:
# Silently ignore exceptions during shutdown
pass
with self._lock:
if self._stopped:
return
self._call_later(
loop, interval, self._execute_recurring, loop, interval, callback, *args
)
def _start_event_loop_in_thread(
event_loop: asyncio.AbstractEventLoop, call_soon_cb: Callable, *args
):
"""
Starts event loop in a thread and schedule callback as soon as event loop is ready.
Used to be able to schedule tasks using loop.call_later.
:param event_loop:
:return:
"""
asyncio.set_event_loop(event_loop)
event_loop.call_soon(call_soon_cb, event_loop, *args)
try:
event_loop.run_forever()
finally:
try:
# Clean up pending tasks
pending = asyncio.all_tasks(event_loop)
for task in pending:
task.cancel()
# Run loop once more to process cancellations
event_loop.run_until_complete(
asyncio.gather(*pending, return_exceptions=True)
)
except Exception:
pass
finally:
event_loop.close()
def _async_to_sync_wrapper(loop, coro_func, *args, **kwargs):
"""
Wraps an asynchronous function so it can be used with loop.call_later.
:param loop: The event loop in which the coroutine will be executed.
:param coro_func: The coroutine function to wrap.
:param args: Positional arguments to pass to the coroutine function.
:param kwargs: Keyword arguments to pass to the coroutine function.
:return: A regular function suitable for loop.call_later.
"""
def wrapped():
# Schedule the coroutine in the event loop
asyncio.ensure_future(coro_func(*args, **kwargs), loop=loop)
return wrapped
| BackgroundScheduler |
python | getsentry__sentry | src/sentry/uptime/endpoints/organization_uptime_alert_index_count.py | {
"start": 708,
"end": 2384
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.CRONS
permission_classes = (OrganizationPermission,)
def get(self, request: AuthenticatedHttpRequest, organization: Organization) -> Response:
"""
Retrieves the count of uptime monitors for an organization.
"""
try:
filter_params = self.get_filter_params(request, organization, date_filter_optional=True)
except NoProjects:
return self.respond(
{
"counts": {
"total": 0,
"active": 0,
"disabled": 0,
},
}
)
queryset = Detector.objects.filter(
status=ObjectStatus.ACTIVE,
type=GROUP_TYPE_UPTIME_DOMAIN_CHECK_FAILURE,
project__organization_id=organization.id,
project_id__in=filter_params["project_id"],
)
if "environment" in filter_params:
queryset = queryset.filter(config__environment__in=filter_params["environment"])
enabled_uptime_alerts_count = queryset.filter(enabled=True).count()
disabled_uptime_alerts_count = queryset.filter(enabled=False).count()
return self.respond(
{
"counts": {
"total": enabled_uptime_alerts_count + disabled_uptime_alerts_count,
"active": enabled_uptime_alerts_count,
"disabled": disabled_uptime_alerts_count,
},
}
)
| OrganizationUptimeAlertIndexCountEndpoint |
python | scrapy__scrapy | tests/AsyncCrawlerProcess/sleeping.py | {
"start": 90,
"end": 355
} | class ____(scrapy.Spider):
name = "sleeping"
start_urls = ["data:,;"]
async def parse(self, response):
await asyncio.sleep(int(sys.argv[1]))
process = AsyncCrawlerProcess(settings={})
process.crawl(SleepingSpider)
process.start()
| SleepingSpider |
python | kamyu104__LeetCode-Solutions | Python/find-the-longest-balanced-substring-of-a-binary-string.py | {
"start": 524,
"end": 939
} | class ____(object):
def findTheLongestBalancedSubstring(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
prev, cnt = [0]*2, [0]*2
for c in s:
cnt[int(c)] += 1
if cnt[int(c)^1]:
prev[int(c)^1], cnt[int(c)^1] = cnt[int(c)^1], 0
result = max(result, 2*min(prev[0], cnt[1]))
return result
| Solution2 |
python | PrefectHQ__prefect | src/prefect/server/orchestration/global_policy.py | {
"start": 12673,
"end": 13797
} | class ____(
BaseUniversalTransform[orm_models.FlowRun, core.FlowRunPolicy]
):
"""
Whenever a subflow changes state, it must update its parent task run's state.
"""
async def after_transition(
self, context: OrchestrationContext[orm_models.FlowRun, core.FlowRunPolicy]
) -> None:
if self.nullified_transition():
return
# only applies to flow runs with a parent task run id
if (
context.run.parent_task_run_id is not None
and context.validated_state is not None
):
# avoid mutation of the flow run state
subflow_parent_task_state = context.validated_state.fresh_copy()
# set the task's "child flow run id" to be the subflow run id
subflow_parent_task_state.state_details.child_flow_run_id = context.run.id
await models.task_runs.set_task_run_state(
session=context.session,
task_run_id=context.run.parent_task_run_id,
state=subflow_parent_task_state,
force=True,
)
| UpdateSubflowParentTask |
python | tensorflow__tensorflow | tensorflow/python/distribute/ps_values.py | {
"start": 11345,
"end": 17481
} | class ____(resource_variable_ops.BaseResourceVariable, core.Tensor):
"""A wrapper around a variable that caches read value locally."""
def __init__(self, v):
self._v = v
self._cache = None
self._current_new_cache_scope_count = 0
def get(self):
return self._v
def __getattr__(self, name):
return getattr(self._v, name)
def read_value(self):
if distribute_utils.caching_scope_local.in_caching_scope():
return self.cached_read_value()
return self._v.read_value()
def sparse_read(self, indices, name=None):
return self._v.sparse_read(indices, name=name)
def cached_read_value(self):
if (distribute_utils.caching_scope_local.new_cache_scope_count >
self._current_new_cache_scope_count):
self._current_new_cache_scope_count += 1
self._cache = None
with ops.device("CPU:0"):
if self._cache is not None:
return self._cache
else:
self._cache = array_ops.identity(self._v)
return self._cache
def assign_sub(self, *args, **kwargs):
return self._v.assign_sub(*args, **kwargs)
def assign_add(self, *args, **kwargs):
return self._v.assign_add(*args, **kwargs)
def assign(self, *args, **kwargs):
return self._v.assign(*args, **kwargs)
@property
def initializer(self):
return self._v.initializer
def initialized_value(self):
return self._v.initialized_value()
@property
def initial_value(self):
return self._v.initial_value
@property
def op(self) -> ops.Operation:
return self._v.op
def value(self):
if distribute_utils.caching_scope_local.in_caching_scope():
return self.cached_read_value()
return self._v.value()
def eval(self, session=None):
return self._v.eval(session)
@property
def graph(self):
return self._v.graph
@property
def device(self):
return self._v.device
@property
def shape(self):
return self._v.shape
@property
def synchronization(self):
return self._v.synchronization
@property
def name(self):
return self._v.name
@property
def trainable(self):
return self._v.trainable
@property
def dtype(self):
return self._v.dtype
@property
def constraint(self):
return self._v.constraint
def __array__(self, dtype=None):
return numpy_compat.np_asarray(self.numpy(), dtype=dtype)
def __complex__(self):
return complex(self.value().numpy())
def __int__(self):
return int(self.value().numpy())
def __float__(self):
return float(self.value().numpy())
def numpy(self):
if context.executing_eagerly():
return self.read_value().numpy()
else:
raise NotImplementedError(
"numpy() is only available when eager execution is enabled.")
def __str__(self):
return str(self._v)
def __repr__(self):
return repr(self._v)
def _should_act_as_resource_variable(self):
"""Pass resource_variable_ops.is_resource_variable check."""
pass
def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
if distribute_utils.caching_scope_local.in_caching_scope():
return self.cached_read_value()
return self._v._dense_var_to_tensor(dtype=dtype, name=name, as_ref=False) # pylint: disable=protected-access
@classmethod
def _overload_overloadable_operators(cls):
"""Register overloads for all operators."""
for operator in tensor.Tensor.OVERLOADABLE_OPERATORS:
# Overloading __eq__ or __ne__ does not work as expected.
if operator == "__eq__" or operator == "__ne__":
continue
cls._tensor_overload_operator(operator)
@classmethod
def _tensor_overload_operator(cls, operator):
"""Delegate an operator overload to `tensor.Tensor`."""
tensor_operator = getattr(tensor.Tensor, operator)
def _operator(v, *args, **kwargs):
return tensor_operator(v.value(), *args, **kwargs) # pylint: disable=protected-access
setattr(cls, operator, _operator)
def _gather_saveables_for_checkpoint(self):
return {trackable.VARIABLE_VALUE_KEY: self._v}
def _export_to_saved_model_graph(self, object_map, tensor_map,
options, **kwargs):
"""For implementing `Trackable`."""
# By delegating this method to the wrapped variable, SavedModel with
# AggregatingVariable are identical to SavedModel with normal variables.
resource_list = self._v._export_to_saved_model_graph(object_map, tensor_map, # pylint:disable=protected-access
options, **kwargs)
object_map[self] = object_map[self._v]
return resource_list
def _copy_trackable_to_cpu(self, object_map):
"""For implementing `Trackable`."""
# Create a copy of `self._v` to object_map, then create a new copy of self
# that wraps the copy of `self._v`.
# When updating value, only the lowest-level variable will actually do that,
# the copy of `CachingVariable` is more like a shell.
self._v._copy_trackable_to_cpu(object_map) # pylint:disable=protected-access
if self not in object_map:
# If copy of `self` not populated yet, initialize one.
object_map[self] = CachingVariable(object_map[self._v])
# Register a conversion function which reads the value of the variable,
# allowing instances of the class to be used as tensors.
def _tensor_conversion_aggregate(var, dtype=None, name=None, as_ref=False):
return var._dense_var_to_tensor(dtype, name, as_ref) # pylint: disable=protected-access
tensor_conversion_registry.register_tensor_conversion_function(
AggregatingVariable, _tensor_conversion_aggregate)
# Register a conversion function which reads the value of the variable,
# allowing instances of the class to be used as tensors.
def _tensor_conversion_caching(var, dtype=None, name=None, as_ref=False):
return var._dense_var_to_tensor(dtype, name, as_ref) # pylint: disable=protected-access
tensor_conversion_registry.register_tensor_conversion_function(
CachingVariable, _tensor_conversion_caching)
CachingVariable._overload_overloadable_operators() # pylint: disable=protected-access
| CachingVariable |
python | PyCQA__pylint | pylint/config/exceptions.py | {
"start": 269,
"end": 438
} | class ____(Exception):
"""Raised if an ArgumentManager instance tries to add an argument for which the
action is not recognized.
"""
| UnrecognizedArgumentAction |
python | ethereum__web3.py | web3/providers/ipc.py | {
"start": 1032,
"end": 3374
} | class ____:
sock = None
def __init__(self, ipc_path: str) -> None:
self.ipc_path = ipc_path
def __enter__(self) -> socket.socket:
if not self.ipc_path:
raise FileNotFoundError(
f"cannot connect to IPC socket at path: {self.ipc_path!r}"
)
if not self.sock:
self.sock = self._open()
return self.sock
def __exit__(
self,
exc_type: type[BaseException],
exc_value: BaseException,
traceback: TracebackType,
) -> None:
# only close the socket if there was an error
if exc_value is not None:
try:
self.sock.close()
except Exception:
pass
self.sock = None
def _open(self) -> socket.socket:
return get_ipc_socket(self.ipc_path)
def reset(self) -> socket.socket:
self.sock.close()
self.sock = self._open()
return self.sock
def get_default_ipc_path() -> str:
if sys.platform == "darwin":
return os.path.expanduser(os.path.join("~", "Library", "Ethereum", "geth.ipc"))
elif sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
return os.path.expanduser(os.path.join("~", ".ethereum", "geth.ipc"))
elif sys.platform == "win32":
return r"\\.\pipe\geth.ipc"
else:
raise Web3ValueError(
f"Unsupported platform '{sys.platform}'. Only darwin/linux/win32/"
"freebsd are supported. You must specify the ipc_path"
)
def get_dev_ipc_path() -> str:
web3_provider_uri = os.environ.get("WEB3_PROVIDER_URI", "")
if web3_provider_uri and "geth.ipc" in web3_provider_uri:
return web3_provider_uri
elif sys.platform == "darwin" or sys.platform.startswith("linux"):
tmpdir = os.environ.get("TMPDIR", "/tmp")
return os.path.expanduser(os.path.join(tmpdir, "geth.ipc"))
elif sys.platform.endswith("freebsd"):
return os.path.expanduser(os.path.join("/tmp", "geth.ipc"))
elif sys.platform == "win32":
return r"\\.\pipe\geth.ipc"
else:
raise Web3ValueError(
f"Unsupported platform '{sys.platform}'. Only darwin/linux/win32/"
"freebsd are supported. You must specify the ipc_path"
)
| PersistentSocket |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 172698,
"end": 177706
} | class ____(DataplexCatalogBaseOperator):
"""
Look up a single Entry by name using the permission on the source system.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogLookupEntryOperator`
:param entry_id: Required. Entry identifier. It has to be unique within an Entry Group.
Entries corresponding to Google Cloud resources use an Entry ID format based on `full resource
names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__.
The format is a full resource name of the resource without the prefix double slashes in the API
service name part of the full resource name. This allows retrieval of entries using their associated
resource name.
For example, if the full resource name of a resource is
``//library.googleapis.com/shelves/shelf1/books/book2``, then the suggested entry_id is
``library.googleapis.com/shelves/shelf1/books/book2``.
It is also suggested to follow the same convention for entries corresponding to resources from
providers or systems other than Google Cloud.
The maximum size of the field is 4000 characters.
:param entry_group_id: Required. EntryGroup resource name to which created Entry will belong to.
:param project_id: Required. The ID of the Google Cloud project where the service is used.
:param location: Required. The ID of the Google Cloud region where the service is used.
:param view: Optional. View to control which parts of an Entry the service should return.
:param aspect_types: Optional. Limits the aspects returned to the provided aspect types. It only works
for CUSTOM view.
:param paths: Optional. Limits the aspects returned to those associated with the provided paths within
the Entry. It only works for CUSTOM view.
:param gcp_conn_id: Optional. The connection ID to use to connect to Google Cloud.
:param retry: Optional. A retry object used to retry requests. If `None` is specified, requests will not
be retried.
:param timeout: Optional. The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Optional. Additional metadata that is provided to the method.
:param impersonation_chain: Optional. Service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = tuple(
{"entry_id", "entry_group_id"} | set(DataplexCatalogBaseOperator.template_fields)
)
operator_extra_links = (DataplexCatalogEntryLink(),)
def __init__(
self,
entry_id: str,
entry_group_id: str,
view: EntryView | str | None = None,
aspect_types: MutableSequence[str] | None = None,
paths: MutableSequence[str] | None = None,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.entry_id = entry_id
self.entry_group_id = entry_group_id
self.view = view
self.aspect_types = aspect_types
self.paths = paths
@property
def extra_links_params(self) -> dict[str, Any]:
return {
**super().extra_links_params,
"entry_id": self.entry_id,
"entry_group_id": self.entry_group_id,
}
def execute(self, context: Context):
DataplexCatalogEntryLink.persist(context=context)
self.log.info(
"Looking for Dataplex Catalog Entry %s.",
self.entry_id,
)
try:
entry = self.hook.lookup_entry(
entry_id=self.entry_id,
entry_group_id=self.entry_group_id,
view=self.view,
aspect_types=self.aspect_types,
paths=self.paths,
location=self.location,
project_id=self.project_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
except NotFound:
self.log.info(
"Dataplex Catalog Entry %s not found.",
self.entry_id,
)
raise AirflowException(NotFound)
except Exception as ex:
raise AirflowException(ex)
return Entry.to_dict(entry)
| DataplexCatalogLookupEntryOperator |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_arithmetic.py | {
"start": 273,
"end": 1561
} | class ____:
def test_arithmetic_zero_freq(self):
# GH#51575 don't get a .freq with freq.n = 0
tdi = timedelta_range(0, periods=100, freq="ns")
result = tdi / 2
assert result.freq is None
expected = tdi[:50].repeat(2)
tm.assert_index_equal(result, expected)
result2 = tdi // 2
assert result2.freq is None
expected2 = expected
tm.assert_index_equal(result2, expected2)
result3 = tdi * 0
assert result3.freq is None
expected3 = tdi[:1].repeat(100)
tm.assert_index_equal(result3, expected3)
def test_tdi_division(self, index_or_series):
# doc example
scalar = Timedelta(days=31)
td = index_or_series(
[scalar, scalar, scalar + Timedelta(minutes=5, seconds=3), NaT],
dtype="m8[ns]",
)
result = td / np.timedelta64(1, "D")
expected = index_or_series(
[31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan]
)
tm.assert_equal(result, expected)
result = td / np.timedelta64(1, "s")
expected = index_or_series(
[31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]
)
tm.assert_equal(result, expected)
| TestTimedeltaIndexArithmetic |
python | dask__distributed | distributed/diagnostics/task_stream.py | {
"start": 355,
"end": 5677
} | class ____(SchedulerPlugin):
name = "task-stream"
def __init__(self, scheduler, maxlen=None):
if maxlen is None:
maxlen = max(
dask.config.get(
"distributed.scheduler.dashboard.status.task-stream-length"
),
dask.config.get(
"distributed.scheduler.dashboard.tasks.task-stream-length"
),
)
self.buffer = deque(maxlen=maxlen)
self.scheduler = scheduler
self.index = 0
def transition(self, key, start, finish, *args, **kwargs):
if start == "processing":
if key not in self.scheduler.tasks:
return
if not kwargs.get("startstops"):
# Other methods require `kwargs` to have a non-empty list of `startstops`
return
kwargs["key"] = key
if finish == "memory" or finish == "erred":
self.buffer.append(kwargs)
self.index += 1
def collect(self, start=None, stop=None, count=None):
def bisect(target, left, right):
if left == right:
return left
mid = (left + right) // 2
value = max(
startstop["stop"] for startstop in self.buffer[mid]["startstops"]
)
if value < target:
return bisect(target, mid + 1, right)
else:
return bisect(target, left, mid)
if isinstance(start, str):
start = time() - parse_timedelta(start)
if start is not None:
start = bisect(start, 0, len(self.buffer))
if isinstance(stop, str):
stop = time() - parse_timedelta(stop)
if stop is not None:
stop = bisect(stop, 0, len(self.buffer))
if count is not None:
if start is None and stop is None:
stop = len(self.buffer)
start = stop - count
elif start is None and stop is not None:
start = stop - count
elif start is not None and stop is None:
stop = start + count
if stop is None:
stop = len(self.buffer)
if start is None:
start = 0
start = max(0, start)
stop = min(stop, len(self.buffer))
return [self.buffer[i] for i in range(start, stop)]
def rectangles(self, istart, istop=None, workers=None, start_boundary=0):
msgs = []
diff = self.index - len(self.buffer)
if istop is None:
istop = self.index
for i in range(max(0, (istart or 0) - diff), istop - diff if istop else istop):
msg = self.buffer[i]
msgs.append(msg)
return rectangles(msgs, workers=workers, start_boundary=start_boundary)
def rectangles(msgs, workers=None, start_boundary=0):
if workers is None:
workers = {}
L_start = []
L_duration = []
L_duration_text = []
L_key = []
L_name = []
L_color = []
L_alpha = []
L_worker = []
L_worker_thread = []
L_y = []
for msg in msgs:
key = msg["key"]
name = key_split(key)
startstops = msg.get("startstops", [])
try:
worker_thread = "%s-%d" % (msg["worker"], msg["thread"])
except Exception:
continue
logger.warning("Message contained bad information: %s", msg, exc_info=True)
worker_thread = ""
if worker_thread not in workers:
workers[worker_thread] = len(workers) / 2
for startstop in startstops:
if startstop["start"] < start_boundary:
continue
color = colors[startstop["action"]]
if type(color) is not str:
color = color(msg)
L_start.append((startstop["start"] + startstop["stop"]) / 2 * 1000)
L_duration.append(1000 * (startstop["stop"] - startstop["start"]))
L_duration_text.append(format_time(startstop["stop"] - startstop["start"]))
L_key.append(key)
L_name.append(prefix[startstop["action"]] + name)
L_color.append(color)
L_alpha.append(alphas[startstop["action"]])
L_worker.append(msg["worker"])
L_worker_thread.append(worker_thread)
L_y.append(workers[worker_thread])
return {
"start": L_start,
"duration": L_duration,
"duration_text": L_duration_text,
"key": L_key,
"name": L_name,
"color": L_color,
"alpha": L_alpha,
"worker": L_worker,
"worker_thread": L_worker_thread,
"y": L_y,
}
def color_of_message(msg):
if msg["status"] == "OK":
split = key_split(msg["key"])
return color_of(split)
else:
return "black"
colors = {
"transfer": "red",
"disk-write": "orange",
"disk-read": "orange",
"deserialize": "gray",
"compute": color_of_message,
}
alphas = {
"transfer": 0.4,
"compute": 1,
"deserialize": 0.4,
"disk-write": 0.4,
"disk-read": 0.4,
}
prefix = {
"transfer": "transfer-",
"disk-write": "disk-write-",
"disk-read": "disk-read-",
"deserialize": "deserialize-",
"compute": "",
}
| TaskStreamPlugin |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_utf8_04.py | {
"start": 314,
"end": 832
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("utf8_04.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with utf-8 strings."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet("Café & Café")
worksheet.write("A1", "Café & Café")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | instagram__MonkeyType | tests/test_stubs.py | {
"start": 38460,
"end": 41798
} | class ____:
def test_update_return(self):
"""Update return annotations from types"""
sig = Signature.from_callable(UpdateSignatureHelper.a_class_method)
sig = update_signature_return(sig, return_type=str)
assert sig == Signature(return_annotation=str)
def test_update_return_with_anno(self):
"""Leave existing return annotations alone"""
sig = Signature.from_callable(UpdateSignatureHelper.has_annos)
sig = update_signature_return(sig, return_type=str)
expected = Signature(
parameters=[
Parameter('a', Parameter.POSITIONAL_OR_KEYWORD, annotation=int),
Parameter('b', Parameter.POSITIONAL_OR_KEYWORD)
],
return_annotation=int
)
assert sig == expected
def test_avoid_incompatible_return(self):
"""Generate stub for application with no annotation where source has one"""
sig = Signature.from_callable(UpdateSignatureHelper.has_annos)
sig = update_signature_return(
sig, return_type=str, existing_annotation_strategy=ExistingAnnotationStrategy.OMIT)
expected = Signature(
parameters=[
Parameter('a', Parameter.POSITIONAL_OR_KEYWORD, annotation=int),
Parameter('b', Parameter.POSITIONAL_OR_KEYWORD)
],
)
assert sig == expected
def test_update_return_with_anno_ignored(self):
"""Leave existing return annotations alone"""
sig = Signature.from_callable(UpdateSignatureHelper.has_annos)
sig = update_signature_return(
sig, return_type=str, existing_annotation_strategy=ExistingAnnotationStrategy.IGNORE)
expected = Signature(
parameters=[
Parameter('a', Parameter.POSITIONAL_OR_KEYWORD, annotation=int),
Parameter('b', Parameter.POSITIONAL_OR_KEYWORD)
],
return_annotation=str
)
assert sig == expected
def test_update_yield(self):
sig = Signature.from_callable(UpdateSignatureHelper.a_class_method)
sig = update_signature_return(sig, yield_type=int)
assert sig == Signature(return_annotation=Iterator[int])
sig = update_signature_return(sig, return_type=NoneType, yield_type=int)
assert sig == Signature(return_annotation=Iterator[int])
def test_update_yield_and_return(self):
sig = Signature.from_callable(UpdateSignatureHelper.a_class_method)
sig = update_signature_return(sig, return_type=str, yield_type=int)
assert sig == Signature(return_annotation=Generator[int, NoneType, str])
def test_update_yield_none_and_return(self):
sig = Signature.from_callable(UpdateSignatureHelper.a_class_method)
sig = update_signature_return(sig, return_type=str, yield_type=NoneType)
assert sig == Signature(return_annotation=Generator[NoneType, NoneType, str])
def test_update_yield_and_return_none(self):
sig = Signature.from_callable(UpdateSignatureHelper.a_class_method)
sig = update_signature_return(sig, return_type=NoneType, yield_type=str)
assert sig == Signature(return_annotation=Iterator[str])
def a_module_func() -> None:
pass
async def an_async_func() -> None:
pass
| TestUpdateSignatureReturn |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 137726,
"end": 140439
} | class ____(Response):
"""
Response of tasks.dequeue endpoint.
:param dequeued: Number of tasks dequeued (0 or 1)
:type dequeued: int
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "dequeue"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"dequeued": {
"description": "Number of tasks dequeued (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
},
"fields": {
"additionalProperties": True,
"description": "Updated fields names and values",
"type": ["object", "null"],
},
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(
self,
dequeued: Optional[int] = None,
updated: Optional[int] = None,
fields: Optional[dict] = None,
**kwargs: Any
) -> None:
super(DequeueResponse, self).__init__(**kwargs)
self.dequeued = dequeued
self.updated = updated
self.fields = fields
@schema_property("dequeued")
def dequeued(self) -> Optional[int]:
return self._property_dequeued
@dequeued.setter
def dequeued(self, value: Optional[int]) -> None:
if value is None:
self._property_dequeued = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "dequeued", six.integer_types)
self._property_dequeued = value
@schema_property("updated")
def updated(self) -> Optional[int]:
return self._property_updated
@updated.setter
def updated(self, value: Optional[int]) -> None:
if value is None:
self._property_updated = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated", six.integer_types)
self._property_updated = value
@schema_property("fields")
def fields(self) -> Optional[dict]:
return self._property_fields
@fields.setter
def fields(self, value: Optional[dict]) -> None:
if value is None:
self._property_fields = None
return
self.assert_isinstance(value, "fields", (dict,))
self._property_fields = value
| DequeueResponse |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 102646,
"end": 106216
} | class ____(_FilterInvalids):
def test_reduce(self):
dflt = np.typecodes['AllFloat']
dint = np.typecodes['AllInteger']
seq1 = np.arange(11)
seq2 = seq1[::-1]
func = np.minimum.reduce
for dt in dint:
tmp1 = seq1.astype(dt)
tmp2 = seq2.astype(dt)
assert_equal(func(tmp1), 0)
assert_equal(func(tmp2), 0)
for dt in dflt:
tmp1 = seq1.astype(dt)
tmp2 = seq2.astype(dt)
assert_equal(func(tmp1), 0)
assert_equal(func(tmp2), 0)
tmp1[::2] = np.nan
tmp2[::2] = np.nan
assert_equal(func(tmp1), np.nan)
assert_equal(func(tmp2), np.nan)
def test_reduce_complex(self):
assert_equal(np.minimum.reduce([1, 2j]), 2j)
assert_equal(np.minimum.reduce([1 + 3j, 2j]), 2j)
def test_float_nans(self):
nan = np.nan
arg1 = np.array([0, nan, nan])
arg2 = np.array([nan, 0, nan])
out = np.array([nan, nan, nan])
assert_equal(np.minimum(arg1, arg2), out)
def test_object_nans(self):
# Multiple checks to give this a chance to
# fail if cmp is used instead of rich compare.
# Failure cannot be guaranteed.
for i in range(1):
x = np.array(float('nan'), object)
y = 1.0
z = np.array(float('nan'), object)
assert_(np.minimum(x, y) == 1.0)
assert_(np.minimum(z, y) == 1.0)
def test_complex_nans(self):
nan = np.nan
for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
arg1 = np.array([0, cnan, cnan], dtype=complex)
arg2 = np.array([cnan, 0, cnan], dtype=complex)
out = np.array([nan, nan, nan], dtype=complex)
assert_equal(np.minimum(arg1, arg2), out)
def test_object_array(self):
arg1 = np.arange(5, dtype=object)
arg2 = arg1 + 1
assert_equal(np.minimum(arg1, arg2), arg1)
def test_strided_array(self):
arr1 = np.array([-4.0, 1.0, 10.0, 0.0, np.nan, -np.nan, np.inf, -np.inf])
arr2 = np.array([-2.0, -1.0, np.nan, 1.0, 0.0, np.nan, 1.0, -3.0])
mintrue = np.array([-4.0, -1.0, np.nan, 0.0, np.nan, np.nan, 1.0, -np.inf])
out = np.ones(8)
out_mintrue = np.array([-4.0, 1.0, 1.0, 1.0, 1.0, 1.0, np.nan, 1.0])
assert_equal(np.minimum(arr1, arr2), mintrue)
assert_equal(np.minimum(arr1[::2], arr2[::2]), mintrue[::2])
assert_equal(np.minimum(arr1[:4:], arr2[::2]), np.array([-4.0, np.nan, 0.0, 0.0]))
assert_equal(np.minimum(arr1[::3], arr2[:3:]), np.array([-4.0, -1.0, np.nan]))
assert_equal(np.minimum(arr1[:6:2], arr2[::3], out=out[::3]), np.array([-4.0, 1.0, np.nan]))
assert_equal(out, out_mintrue)
def test_precision(self):
dtypes = [np.float16, np.float32, np.float64, np.longdouble]
for dt in dtypes:
dtmin = np.finfo(dt).min
dtmax = np.finfo(dt).max
d1 = dt(0.1)
d1_next = np.nextafter(d1, np.inf)
test_cases = [
# v1 v2 expected
(dtmin, np.inf, dtmin),
(dtmax, np.inf, dtmax),
(d1, d1_next, d1),
(dtmin, np.nan, np.nan),
]
for v1, v2, expected in test_cases:
assert_equal(np.minimum([v1], [v2]), [expected])
assert_equal(np.minimum.reduce([v1, v2]), expected)
| TestMinimum |
python | ansible__ansible | lib/ansible/module_utils/facts/system/ssh_pub_keys.py | {
"start": 841,
"end": 2211
} | class ____(BaseFactCollector):
name = 'ssh_pub_keys'
_fact_ids = set(['ssh_host_pub_keys',
'ssh_host_key_dsa_public',
'ssh_host_key_rsa_public',
'ssh_host_key_ecdsa_public',
'ssh_host_key_ed25519_public']) # type: t.Set[str]
def collect(self, module=None, collected_facts=None):
ssh_pub_key_facts = {}
algos = ('dsa', 'rsa', 'ecdsa', 'ed25519')
# list of directories to check for ssh keys
# used in the order listed here, the first one with keys is used
keydirs = ['/etc/ssh', '/etc/openssh', '/etc']
for keydir in keydirs:
for algo in algos:
factname = 'ssh_host_key_%s_public' % algo
if factname in ssh_pub_key_facts:
# a previous keydir was already successful, stop looking
# for keys
return ssh_pub_key_facts
key_filename = '%s/ssh_host_%s_key.pub' % (keydir, algo)
keydata = get_file_content(key_filename)
if keydata is not None:
(keytype, key) = keydata.split()[0:2]
ssh_pub_key_facts[factname] = key
ssh_pub_key_facts[factname + '_keytype'] = keytype
return ssh_pub_key_facts
| SshPubKeyFactCollector |
python | coleifer__peewee | tests/db_tests.py | {
"start": 28096,
"end": 28208
} | class ____(TestModel):
key = TextField()
value = TextField()
class Meta:
schema = 'main'
| Data |
python | django-haystack__django-haystack | test_haystack/test_backends.py | {
"start": 144,
"end": 2480
} | class ____(TestCase):
def test_load_solr(self):
try:
import pysolr
except ImportError:
warnings.warn(
"Pysolr doesn't appear to be installed. Unable to test loading the Solr backend."
)
return
backend = loading.load_backend("haystack.backends.solr_backend.SolrEngine")
self.assertEqual(backend.__name__, "SolrEngine")
def test_load_whoosh(self):
try:
import whoosh
except ImportError:
warnings.warn(
"Whoosh doesn't appear to be installed. Unable to test loading the Whoosh backend."
)
return
backend = loading.load_backend("haystack.backends.whoosh_backend.WhooshEngine")
self.assertEqual(backend.__name__, "WhooshEngine")
def test_load_elasticsearch(self):
try:
import elasticsearch
except ImportError:
warnings.warn(
"elasticsearch-py doesn't appear to be installed. Unable to test loading the ElasticSearch backend."
)
return
backend = loading.load_backend(
"haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine"
)
self.assertEqual(backend.__name__, "ElasticsearchSearchEngine")
def test_load_simple(self):
backend = loading.load_backend("haystack.backends.simple_backend.SimpleEngine")
self.assertEqual(backend.__name__, "SimpleEngine")
def test_load_nonexistent(self):
try:
backend = loading.load_backend("foobar")
self.fail()
except ImproperlyConfigured as e:
self.assertEqual(
str(e),
"The provided backend 'foobar' is not a complete Python path to a BaseEngine subclass.",
)
try:
backend = loading.load_backend("foobar.FooEngine")
self.fail()
except ImportError as e:
pass
try:
backend = loading.load_backend("haystack.backends.simple_backend.FooEngine")
self.fail()
except ImportError as e:
self.assertEqual(
str(e),
"The Python module 'haystack.backends.simple_backend' has no 'FooEngine' class.",
)
| LoadBackendTestCase |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 41618,
"end": 41809
} | class ____(Structure):
_fields_ = (
("n_un", n_un),
("n_type", p_uint8),
("n_sect", p_uint8),
("n_desc", p_short),
("n_value", p_uint32),
)
| nlist |
python | eventlet__eventlet | eventlet/zipkin/_thrift/zipkinCore/ttypes.py | {
"start": 8873,
"end": 13497
} | class ____:
"""
Attributes:
- trace_id
- name
- id
- parent_id
- annotations
- binary_annotations
"""
thrift_spec = (
None, # 0
(1, TType.I64, 'trace_id', None, None, ), # 1
None, # 2
(3, TType.STRING, 'name', None, None, ), # 3
(4, TType.I64, 'id', None, None, ), # 4
(5, TType.I64, 'parent_id', None, None, ), # 5
(6, TType.LIST, 'annotations', (TType.STRUCT,(Annotation, Annotation.thrift_spec)), None, ), # 6
None, # 7
(8, TType.LIST, 'binary_annotations', (TType.STRUCT,(BinaryAnnotation, BinaryAnnotation.thrift_spec)), None, ), # 8
)
def __init__(self, trace_id=None, name=None, id=None, parent_id=None, annotations=None, binary_annotations=None,):
self.trace_id = trace_id
self.name = name
self.id = id
self.parent_id = parent_id
self.annotations = annotations
self.binary_annotations = binary_annotations
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I64:
self.trace_id = iprot.readI64();
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRING:
self.name = iprot.readString();
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.I64:
self.id = iprot.readI64();
else:
iprot.skip(ftype)
elif fid == 5:
if ftype == TType.I64:
self.parent_id = iprot.readI64();
else:
iprot.skip(ftype)
elif fid == 6:
if ftype == TType.LIST:
self.annotations = []
(_etype3, _size0) = iprot.readListBegin()
for _i4 in xrange(_size0):
_elem5 = Annotation()
_elem5.read(iprot)
self.annotations.append(_elem5)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 8:
if ftype == TType.LIST:
self.binary_annotations = []
(_etype9, _size6) = iprot.readListBegin()
for _i10 in xrange(_size6):
_elem11 = BinaryAnnotation()
_elem11.read(iprot)
self.binary_annotations.append(_elem11)
iprot.readListEnd()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('Span')
if self.trace_id is not None:
oprot.writeFieldBegin('trace_id', TType.I64, 1)
oprot.writeI64(self.trace_id)
oprot.writeFieldEnd()
if self.name is not None:
oprot.writeFieldBegin('name', TType.STRING, 3)
oprot.writeString(self.name)
oprot.writeFieldEnd()
if self.id is not None:
oprot.writeFieldBegin('id', TType.I64, 4)
oprot.writeI64(self.id)
oprot.writeFieldEnd()
if self.parent_id is not None:
oprot.writeFieldBegin('parent_id', TType.I64, 5)
oprot.writeI64(self.parent_id)
oprot.writeFieldEnd()
if self.annotations is not None:
oprot.writeFieldBegin('annotations', TType.LIST, 6)
oprot.writeListBegin(TType.STRUCT, len(self.annotations))
for iter12 in self.annotations:
iter12.write(oprot)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.binary_annotations is not None:
oprot.writeFieldBegin('binary_annotations', TType.LIST, 8)
oprot.writeListBegin(TType.STRUCT, len(self.binary_annotations))
for iter13 in self.binary_annotations:
iter13.write(oprot)
oprot.writeListEnd()
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
| Span |
python | Textualize__textual | src/textual/events.py | {
"start": 4589,
"end": 4750
} | class ____(Event, bubble=False, verbose=False):
"""Sent when a widget is *mounted* and may receive messages.
- [ ] Bubbles
- [ ] Verbose
"""
| Mount |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 118408,
"end": 121564
} | class ____(Request):
"""
Indicates that task is closed
:param force: Allows forcing state change even if transition is not supported
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
"""
_service = "tasks"
_action = "close"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"force": {
"default": False,
"description": "Allows forcing state change even if transition is not supported",
"type": ["boolean", "null"],
},
"status_message": {
"description": "Extra information regarding status change",
"type": "string",
},
"status_reason": {
"description": "Reason for status change",
"type": "string",
},
"task": {"description": "Task ID", "type": "string"},
},
"required": ["task"],
"type": "object",
}
def __init__(
self,
task: str,
force: Optional[bool] = False,
status_reason: Optional[str] = None,
status_message: Optional[str] = None,
**kwargs: Any
) -> None:
super(CloseRequest, self).__init__(**kwargs)
self.force = force
self.task = task
self.status_reason = status_reason
self.status_message = status_message
@schema_property("force")
def force(self) -> Optional[bool]:
return self._property_force
@force.setter
def force(self, value: Optional[bool]) -> None:
if value is None:
self._property_force = None
return
self.assert_isinstance(value, "force", (bool,))
self._property_force = value
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("status_reason")
def status_reason(self) -> Optional[str]:
return self._property_status_reason
@status_reason.setter
def status_reason(self, value: Optional[str]) -> None:
if value is None:
self._property_status_reason = None
return
self.assert_isinstance(value, "status_reason", six.string_types)
self._property_status_reason = value
@schema_property("status_message")
def status_message(self) -> Optional[str]:
return self._property_status_message
@status_message.setter
def status_message(self, value: Optional[str]) -> None:
if value is None:
self._property_status_message = None
return
self.assert_isinstance(value, "status_message", six.string_types)
self._property_status_message = value
| CloseRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/components.py | {
"start": 17604,
"end": 19219
} | class ____(Decoder):
"""
Custom decoder that always attempts GZip decompression before parsing CSV data.
This is needed because Bing Ads now sends GZip compressed files from Azure Blob Storage
without proper compression headers, so the standard GzipDecoder fails to detect compression.
"""
def is_stream_response(self) -> bool:
return False
def decode(self, response) -> Generator[MutableMapping[str, Any], None, None]:
"""
Always attempt GZip decompression first, then fall back to plain CSV if that fails.
"""
try:
# First, try to decompress as GZip
decompressed_content = gzip.decompress(response.content)
# Parse as CSV with utf-8-sig encoding (handles BOM)
text_content = decompressed_content.decode("utf-8-sig")
csv_reader = csv.DictReader(StringIO(text_content))
for row in csv_reader:
yield row
except (gzip.BadGzipFile, OSError):
# If GZip decompression fails, try parsing as plain CSV
try:
text_content = response.content.decode("utf-8-sig")
csv_reader = csv.DictReader(StringIO(text_content))
for row in csv_reader:
yield row
except Exception as e:
# If both fail, log the error and yield empty
import logging
logger = logging.getLogger(__name__)
logger.error(f"Failed to parse response as either GZip or plain CSV: {e}")
yield {}
| BingAdsGzipCsvDecoder |
python | getsentry__sentry | src/sentry/replays/endpoints/organization_replay_index.py | {
"start": 1406,
"end": 5243
} | class ____(OrganizationEndpoint):
owner = ApiOwner.REPLAY
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
@extend_schema(
operation_id="List an Organization's Replays",
parameters=[GlobalParams.ORG_ID_OR_SLUG, ReplayValidator],
responses={
200: inline_sentry_response_serializer("ListReplays", list[ReplayDetailsResponse]),
400: RESPONSE_BAD_REQUEST,
403: RESPONSE_FORBIDDEN,
},
examples=ReplayExamples.GET_REPLAYS,
)
@handled_snuba_exceptions
def get(self, request: Request, organization: Organization) -> Response:
"""
Return a list of replays belonging to an organization.
"""
if not features.has("organizations:session-replay", organization, actor=request.user):
return Response(status=404)
try:
filter_params = self.get_filter_params(request, organization)
except NoProjects:
return Response({"data": []}, status=200)
result = ReplayValidator(data=request.GET)
if not result.is_valid():
raise ParseError(result.errors)
for key, value in result.validated_data.items():
if key not in filter_params:
filter_params[key] = value # type: ignore[literal-required]
# We allow the requester to make their own decision about where to source the data.
# Because this is a stateless, isolated interaction its okay for the user to decide where
# to source the data. At worst they receive an exception and stop manually specifying the
# header. This allows us to quickly test and compare multiple data sources without
# interacting with a feature flagging system.
preferred_source = request.headers.get("X-Preferred-Data-Source")
preferred_source = cast(PREFERRED_SOURCE, preferred_source)
headers = {}
def data_fn(offset: int, limit: int):
try:
search_filters = parse_search_query(
request.query_params.get("query", ""), config=replay_url_parser_config
)
except InvalidSearchQuery as e:
raise ParseError(str(e))
# Sort is optionally specified.
sort = (
filter_params.get("orderBy")
or filter_params.get("sortBy")
or filter_params.get("sort")
)
if not isinstance(sort, str):
sort = None
response = query_replays_collection_paginated(
project_ids=filter_params["project_id"],
start=filter_params["start"],
end=filter_params["end"],
environment=filter_params.get("environment") or [],
sort=sort,
fields=request.query_params.getlist("field"),
limit=limit,
offset=offset,
search_filters=search_filters,
preferred_source=preferred_source,
organization=organization,
actor=request.user,
)
# We set the data-source header so we can figure out which query is giving
# incorrect or slow results.
headers["X-Data-Source"] = response.source
return response
response = self.paginate(
request=request,
paginator=ReplayPaginator(data_fn=data_fn),
on_results=lambda results: {
"data": process_raw_response(
results,
fields=request.query_params.getlist("field"),
)
},
)
for header, value in headers.items():
response[header] = value
return response
| OrganizationReplayIndexEndpoint |
python | walkccc__LeetCode | solutions/1945. Sum of Digits of String After Convert/1945.py | {
"start": 0,
"end": 355
} | class ____:
def getLucky(self, s: str, k: int) -> int:
ans = self._convert(s)
for _ in range(k):
ans = self._getDigitSum(ans)
return ans
def _convert(self, s: str) -> int:
return int(''.join(str(ord(c) - ord('a') + 1) for c in s))
def _getDigitSum(self, num: int) -> int:
return sum(int(digit) for digit in str(num))
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_autofit08.py | {
"start": 315,
"end": 1008
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("autofit08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.write_string(0, 0, "a")
worksheet.write_string(1, 0, "aaa")
worksheet.write_string(2, 0, "a")
worksheet.write_string(3, 0, "aaaa")
worksheet.write_string(4, 0, "a")
worksheet.autofit()
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | coleifer__peewee | tests/reflection.py | {
"start": 21050,
"end": 22605
} | class ____(BaseReflectionTestCase):
def setUp(self):
super(TestCyclicalFK, self).setUp()
warnings.filterwarnings('ignore')
@requires_sqlite
def test_cyclical_fk(self):
# NOTE: this schema was provided by a user.
cursor = self.database.cursor()
cursor.executescript(
'CREATE TABLE flow_run_state (id CHAR(36) NOT NULL, '
'flow_run_id CHAR(36) NOT NULL, '
'CONSTRAINT pk_flow_run_state PRIMARY KEY (id), '
'CONSTRAINT fk_flow_run_state__flow_run_id__flow_run '
'FOREIGN KEY(flow_run_id) REFERENCES flow_run (id) '
'ON DELETE cascade); '
'CREATE TABLE flow_run (id CHAR(36) NOT NULL, '
'state_id CHAR(36) NOT NULL, '
'CONSTRAINT pk_flow_run PRIMARY KEY (id), '
'CONSTRAINT fk_flow_run__state_id__flow_run_state '
'FOREIGN KEY(state_id) REFERENCES flow_run_state (id) '
'ON DELETE SET NULL);')
M = self.introspector.generate_models()
FRS = M['flow_run_state']
FR = M['flow_run']
self.assertEqual(sorted(FR._meta.fields), ['id', 'state'])
self.assertEqual(sorted(FRS._meta.fields), ['flow_run', 'id'])
self.assertTrue(isinstance(FR.id, CharField))
self.assertTrue(isinstance(FR.state, ForeignKeyField))
self.assertTrue(FR.state.rel_model is FRS)
self.assertTrue(isinstance(FRS.id, CharField))
self.assertTrue(isinstance(FRS.flow_run, ForeignKeyField))
self.assertTrue(FRS.flow_run.rel_model is FR)
| TestCyclicalFK |
python | jina-ai__jina | tests/integration/docarray_v2/test_streaming.py | {
"start": 5519,
"end": 5793
} | class ____(Executor):
@requests
def generator(self, doc: MyDocument, **kwargs) -> MyDocument:
yield MyDocument(text='new document')
@requests(on='/non_generator')
def non_generator(self, docs: DocList[BaseDoc], **kwargs):
return docs
| Executor1 |
python | apache__airflow | airflow-core/tests/unit/plugins/test_plugins_manager.py | {
"start": 14913,
"end": 15327
} | class ____:
def test_should_return_correct_path_name(self):
from airflow import plugins_manager
source = plugins_manager.PluginsDirectorySource(__file__)
assert source.path == "test_plugins_manager.py"
assert str(source) == "$PLUGINS_FOLDER/test_plugins_manager.py"
assert source.__html__() == "<em>$PLUGINS_FOLDER/</em>test_plugins_manager.py"
| TestPluginsDirectorySource |
python | pypa__pipenv | pipenv/vendor/tomlkit/exceptions.py | {
"start": 4658,
"end": 5134
} | class ____(ParseError):
def __init__(self, line: int, col: int, char: int, type: str) -> None:
display_code = "\\u00"
if char < 16:
display_code += "0"
display_code += hex(char)[2:]
message = (
"Control characters (codes less than 0x1f and 0x7f)"
f" are not allowed in {type}, "
f"use {display_code} instead"
)
super().__init__(line, col, message=message)
| InvalidControlChar |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/types.py | {
"start": 424,
"end": 2833
} | class ____(BaseComponent, DispatcherSpanMixin, ABC):
model_config = ConfigDict(arbitrary_types_allowed=True)
callback_manager: CallbackManager = Field(
default_factory=CallbackManager, exclude=True
)
def _get_prompts(self) -> PromptDictType:
"""Get prompts."""
# set by default since most postprocessors don't require prompts
return {}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
def _get_prompt_modules(self) -> PromptMixinType:
"""Get prompt modules."""
return {}
# implement class_name so users don't have to worry about it when extending
@classmethod
def class_name(cls) -> str:
return "BaseNodePostprocessor"
def postprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
query_str: Optional[str] = None,
) -> List[NodeWithScore]:
"""Postprocess nodes."""
if query_str is not None and query_bundle is not None:
raise ValueError("Cannot specify both query_str and query_bundle")
elif query_str is not None:
query_bundle = QueryBundle(query_str)
else:
pass
return self._postprocess_nodes(nodes, query_bundle)
@abstractmethod
def _postprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
) -> List[NodeWithScore]:
"""Postprocess nodes."""
async def apostprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
query_str: Optional[str] = None,
) -> List[NodeWithScore]:
"""Postprocess nodes (async)."""
if query_str is not None and query_bundle is not None:
raise ValueError("Cannot specify both query_str and query_bundle")
elif query_str is not None:
query_bundle = QueryBundle(query_str)
else:
pass
return await self._apostprocess_nodes(nodes, query_bundle)
async def _apostprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
) -> List[NodeWithScore]:
"""Postprocess nodes (async)."""
return await asyncio.to_thread(self._postprocess_nodes, nodes, query_bundle)
| BaseNodePostprocessor |
python | great-expectations__great_expectations | tests/datasource/fluent/test_config.py | {
"start": 6497,
"end": 30286
} | class ____:
"""
Ensure that DataAsset fields are excluded from serialization if they have not be explicitly set.
We are trying to ensure that our configs aren't filled with default values from DataAssets that
users never set.
"""
@pytest.mark.unit
def test_from_datasource(self, asset_dict: dict):
asset_dict_config = copy.deepcopy(asset_dict)
ds_mapping = {"csv": "pandas_filesystem", "json": "pandas_filesystem"}
ds_type_: str = ds_mapping[asset_dict_config["type"]]
ds_class = DataSourceManager.type_lookup[ds_type_]
# fill in required args
asset_dict_config.update(
{
"name": "my_asset",
}
)
asset_name = asset_dict_config["name"]
ds_dict = {
"name": "my_ds",
"base_directory": pathlib.Path(__file__),
"assets": [
asset_dict_config,
],
}
datasource: Datasource = ds_class.parse_obj(ds_dict)
assert (
asset_dict_config
== list(
filter(
lambda element: element["name"] == asset_name,
datasource.dict()["assets"],
)
)[0]
)
@pytest.mark.unit
def test_from_gx_config(self, asset_dict: dict):
"""
Ensure that unset fields are excluded even when being parsed by the top-level `GxConfig` class.
""" # noqa: E501 # FIXME CoP
# fill in required args
asset_dict.update(
{
"name": "my_asset",
}
)
asset_dict_config = copy.deepcopy(asset_dict)
ds_dict = {
"type": "pandas_filesystem",
"name": "my_ds",
"base_directory": pathlib.Path(__file__),
"assets": [
asset_dict_config,
],
}
gx_config = GxConfig.parse_obj(
{
_FLUENT_DATASOURCES_KEY: [
ds_dict,
]
}
)
gx_config_dict = gx_config.dict()
print(f"gx_config_dict\n{pf(gx_config_dict)}")
my_datasoure_config_dict = list(
filter(
lambda element: element["name"] == "my_ds",
gx_config_dict[_FLUENT_DATASOURCES_KEY],
)
)[0]
my_asset_config_dict = list(
filter(
lambda element: element["name"] == "my_asset",
my_datasoure_config_dict["assets"],
)
)[0]
assert asset_dict == my_asset_config_dict
@pytest.mark.big
def test_id_only_serialized_if_present(ds_dict_config: dict):
print(f"\tInput:\n\n{pf(ds_dict_config, depth=3)}")
all_ids: list[str] = []
with_ids: dict = {}
no_ids: dict = {}
# remove or add ids
for ds in ds_dict_config[_FLUENT_DATASOURCES_KEY]:
ds_name = ds[_DATASOURCE_NAME_KEY]
with_ids[ds_name] = copy.deepcopy(ds)
no_ids[ds_name] = copy.deepcopy(ds)
ds_id = uuid.uuid4()
all_ids.append(str(ds_id))
with_ids[ds_name]["id"] = ds_id
no_ids[ds_name].pop("id", None)
with_ids[ds_name]["assets"] = {
asset_config[_DATA_ASSET_NAME_KEY]: asset_config
for asset_config in with_ids[ds_name]["assets"]
}
no_ids[ds_name]["assets"] = {
asset_config[_DATA_ASSET_NAME_KEY]: asset_config
for asset_config in no_ids[ds_name]["assets"]
}
for asset_config in ds["assets"]:
asset_name = asset_config[_DATA_ASSET_NAME_KEY]
asset_id = uuid.uuid4()
all_ids.append(str(asset_id))
with_ids[ds_name]["assets"][asset_name]["id"] = asset_id
no_ids[ds_name]["assets"][asset_name].pop("id", None)
if _BATCH_DEFINITIONS_KEY in asset_config:
with_ids[ds_name]["assets"][asset_name][_BATCH_DEFINITIONS_KEY] = {
batch_definition[_BATCH_DEFINITION_NAME_KEY]: batch_definition
for batch_definition in with_ids[ds_name]["assets"][asset_name][
_BATCH_DEFINITIONS_KEY
]
}
for batch_definition in with_ids[ds_name]["assets"][asset_name][
_BATCH_DEFINITIONS_KEY
].values():
batch_asset_id = uuid.uuid4()
all_ids.append(str(batch_asset_id))
batch_definition["id"] = str(batch_asset_id)
no_ids[ds_name]["assets"][asset_name][_BATCH_DEFINITIONS_KEY] = {
batch_definition[_BATCH_DEFINITION_NAME_KEY]: batch_definition
for batch_definition in no_ids[ds_name]["assets"][asset_name][
_BATCH_DEFINITIONS_KEY
]
}
for batch_definition in no_ids[ds_name]["assets"][asset_name][
_BATCH_DEFINITIONS_KEY
].values():
batch_definition.pop("id", None)
no_ids = _convert_fluent_datasources_loaded_from_yaml_to_internal_object_representation(
config={
_FLUENT_DATASOURCES_KEY: no_ids,
}
)
with_ids = _convert_fluent_datasources_loaded_from_yaml_to_internal_object_representation(
config={
_FLUENT_DATASOURCES_KEY: with_ids,
}
)
gx_config_no_ids = GxConfig.parse_obj(no_ids)
gx_config_with_ids = GxConfig.parse_obj(with_ids)
assert "id" not in str(gx_config_no_ids.dict())
assert "id" not in gx_config_no_ids.json()
assert "id" not in gx_config_no_ids.yaml()
for serialized_str in [
str(gx_config_with_ids.dict()),
gx_config_with_ids.json(),
gx_config_with_ids.yaml(),
]:
for id_ in all_ids:
assert id_ in serialized_str
@pytest.mark.unit
@pytest.mark.parametrize(
["load_method", "input_"],
[
p(GxConfig.parse_obj, SIMPLE_DS_DICT, id="simple pg config dict"),
p(
GxConfig.parse_obj,
COMBINED_FLUENT_AND_OLD_STYLE_CFG_DICT,
id="fluent + old style config",
),
p(GxConfig.parse_raw, json.dumps(SIMPLE_DS_DICT), id="simple pg json"),
p(GxConfig.parse_obj, COMPLEX_CONFIG_DICT, id="complex dict"),
p(GxConfig.parse_raw, COMPLEX_CONFIG_JSON, id="complex json"),
p(GxConfig.parse_yaml, PG_CONFIG_YAML_FILE, id="pg_config.yaml file"),
p(GxConfig.parse_yaml, PG_CONFIG_YAML_STR, id="pg_config yaml string"),
],
)
def test_load_config(inject_engine_lookup_double, load_method: Callable, input_):
loaded: GxConfig = load_method(input_)
pp(loaded)
assert loaded
assert loaded.datasources
for datasource in loaded.datasources:
assert isinstance(datasource, Datasource)
@pytest.mark.unit
@pytest.mark.parametrize(
["load_method", "input_"],
[
p(GxConfig.parse_obj, COMPLEX_CONFIG_DICT, id="complex dict"),
p(GxConfig.parse_raw, COMPLEX_CONFIG_JSON, id="complex json"),
p(GxConfig.parse_yaml, PG_CONFIG_YAML_FILE, id="pg_config.yaml file"),
p(GxConfig.parse_yaml, PG_CONFIG_YAML_STR, id="pg_config yaml string"),
],
)
def test_batch_definitions_are_assigned_data_assets(
inject_engine_lookup_double, load_method: Callable, input_
):
loaded: GxConfig = load_method(input_)
assert loaded
batch_definitions: List[BatchDefinition] = []
assert loaded.datasources
for datasource in loaded.datasources:
for data_asset in datasource.assets:
batch_definitions.extend(data_asset.batch_definitions)
assert len(batch_definitions) > 0
for batch_definition in batch_definitions:
assert batch_definition.data_asset is not None
assert batch_definition in batch_definition.data_asset.batch_definitions
@pytest.mark.unit
@pytest.mark.parametrize(
["config", "expected_error_loc", "expected_msg"],
[
p({}, (_FLUENT_DATASOURCES_KEY,), "field required", id="no datasources"),
p(
{
_FLUENT_DATASOURCES_KEY: [
{
"name": "my_bad_ds_missing_type",
},
],
},
(_FLUENT_DATASOURCES_KEY,),
"'my_bad_ds_missing_type' is missing a 'type' entry",
id="missing 'type' field",
),
],
)
def test_catch_bad_top_level_config(
inject_engine_lookup_double,
config: dict,
expected_error_loc: tuple,
expected_msg: str,
):
print(f" config\n{pf(config)}\n")
with pytest.raises(pydantic.ValidationError) as exc_info:
loaded = GxConfig.parse_obj(config)
print(f"Erroneously loaded config\n{loaded}\n")
print(f"\n{exc_info.typename}:{exc_info.value}")
all_errors = exc_info.value.errors()
print(f"\nErrors dict\n{pf(all_errors)}")
assert len(all_errors) == 1, "Expected 1 error"
assert expected_error_loc == all_errors[0]["loc"]
assert expected_msg == all_errors[0]["msg"]
@pytest.mark.unit
@pytest.mark.parametrize(
["bad_asset_config", "expected_error_loc", "expected_msg"],
[
p(
{
"name": "unknown partitioner",
"type": "table",
"table_name": "pool",
"batch_definitions": [
{
"name": "unknown_partitioner_batch_definition",
"partitioner": {
"method_name": "not_a_valid_method_name",
"column_name": "foo",
},
}
],
},
(
_FLUENT_DATASOURCES_KEY,
"assets",
0,
"TableAsset",
"batch_definitions",
0,
"partitioner",
"method_name",
),
"unexpected value; permitted:",
id="unknown partitioner method",
),
p(
{
"type": "table",
"table_name": "pool",
},
(
_FLUENT_DATASOURCES_KEY,
"assets",
0,
"TableAsset",
"name",
),
"field required",
id="missing name",
),
p(
{
"type": "query",
"name": "missing query string",
},
(
_FLUENT_DATASOURCES_KEY,
"assets",
0,
"QueryAsset",
"query",
),
"field required",
id="missing query",
),
],
)
def test_catch_bad_asset_configs(
inject_engine_lookup_double,
bad_asset_config: dict,
expected_error_loc: tuple,
expected_msg: str,
):
config: list = [
{
"type": "postgres",
"name": "my_test_ds",
"connection_string": "postgres://userName:@hostname/dbName",
"assets": [
bad_asset_config,
],
},
]
print(f" Config\n{pf(config)}\n")
with pytest.raises(pydantic.ValidationError) as exc_info:
GxConfig.parse_obj(
{
_FLUENT_DATASOURCES_KEY: config,
}
)
print(f"\n{exc_info.typename}:{exc_info.value}")
all_errors = exc_info.value.errors()
assert len(all_errors) >= 1, "Expected at least 1 error"
test_msg = ""
for error in all_errors:
if expected_error_loc == all_errors[0]["loc"]:
test_msg = error["msg"]
break
print(f"\n\ttest_msg:\n{test_msg}")
assert test_msg.startswith(expected_msg)
@pytest.mark.unit
@pytest.mark.parametrize(
["bad_column_kwargs", "expected_error_type", "expected_msg"],
[
(
{
"column_name": "flavor",
"method_name": "NOT_VALID",
},
"value_error.const",
"unexpected value; permitted:",
)
],
)
def test_general_partitioner_errors(
inject_engine_lookup_double,
bad_column_kwargs: dict,
expected_error_type: str,
expected_msg: str,
):
with pytest.raises(pydantic.ValidationError) as exc_info:
SqlPartitionerYearAndMonth(**bad_column_kwargs)
print(f"\n{exc_info.typename}:{exc_info.value}")
all_errors = exc_info.value.errors()
assert len(all_errors) == 1, "Expected 1 error"
assert expected_error_type == all_errors[0]["type"]
assert all_errors[0]["msg"].startswith(expected_msg)
@pytest.fixture
@functools.lru_cache(maxsize=1)
def from_dict_gx_config() -> GxConfig:
gx_config = GxConfig.parse_obj(COMPLEX_CONFIG_DICT)
assert gx_config
return gx_config
@pytest.fixture
@functools.lru_cache(maxsize=1)
def from_json_gx_config() -> GxConfig:
gx_config = GxConfig.parse_raw(COMPLEX_CONFIG_JSON)
return gx_config
@pytest.fixture
@functools.lru_cache(maxsize=1)
def from_yaml_gx_config() -> GxConfig:
gx_config = GxConfig.parse_yaml(PG_CONFIG_YAML_STR)
return gx_config
@pytest.fixture(
params=[
pytest.param(from_dict_gx_config, marks=pytest.mark.unit),
pytest.param(from_json_gx_config, marks=pytest.mark.unit),
pytest.param(from_yaml_gx_config, marks=pytest.mark.filesystem),
]
)
def from_all_config(request: FixtureRequest) -> GxConfig:
"""
This fixture parametrizes all our config fixtures.
This will in-turn parametrize any test that uses it, creating a test case for each
`from_*_config` fixture
"""
fixture_name = request.param.__name__
return request.getfixturevalue(fixture_name)
@pytest.mark.unit
def test_dict_config_round_trip(inject_engine_lookup_double, from_dict_gx_config: GxConfig):
dumped: dict = from_dict_gx_config.dict()
print(f" Dumped Dict ->\n\n{pf(dumped)}\n")
re_loaded: GxConfig = GxConfig.parse_obj(dumped)
pp(re_loaded)
assert re_loaded
assert from_dict_gx_config == re_loaded
@pytest.mark.unit
def test_json_config_round_trip(inject_engine_lookup_double, from_json_gx_config: GxConfig):
dumped: str = from_json_gx_config.json(indent=2)
print(f" Dumped JSON ->\n\n{dumped}\n")
re_loaded: GxConfig = GxConfig.parse_raw(dumped)
pp(re_loaded)
assert re_loaded
assert from_json_gx_config.dict() == re_loaded.dict()
@pytest.mark.filesystem
def test_yaml_config_round_trip(inject_engine_lookup_double, from_yaml_gx_config: GxConfig):
dumped: str = from_yaml_gx_config.yaml()
print(f" Dumped YAML ->\n\n{dumped}\n")
re_loaded: GxConfig = GxConfig.parse_yaml(dumped)
pp(re_loaded)
assert re_loaded
assert sorted(from_yaml_gx_config.dict()) == sorted(re_loaded.dict())
assert dumped == re_loaded.yaml()
@pytest.mark.filesystem
def test_yaml_file_config_round_trip(
inject_engine_lookup_double, tmp_path: pathlib.Path, from_yaml_gx_config: GxConfig
):
yaml_file = tmp_path / "test.yaml"
assert not yaml_file.exists()
result_path = from_yaml_gx_config.yaml(yaml_file)
assert yaml_file.exists()
assert result_path == yaml_file
print(f" yaml_file -> \n\n{yaml_file.read_text()}")
re_loaded: GxConfig = GxConfig.parse_yaml(yaml_file)
pp(re_loaded)
assert re_loaded
assert sorted(from_yaml_gx_config.dict()) == sorted(re_loaded.dict())
@pytest.mark.filesystem
def test_assets_key_presence(inject_engine_lookup_double, from_yaml_gx_config: GxConfig):
ds_wo_assets = None
ds_with_assets = None
for ds in from_yaml_gx_config.datasources:
if ds.assets:
ds_with_assets = ds
else:
ds_wo_assets = ds
assert ds_with_assets, "Need at least one Datasource with assets for this test"
assert ds_wo_assets, "Need at least one Datasource without assets for this test"
dumped_as_dict: dict = yaml.load(from_yaml_gx_config.yaml())
print(f" dict from dumped yaml ->\n\n{pf(dumped_as_dict['fluent_datasources'], depth=2)}")
assert _ASSETS_KEY in dumped_as_dict[_FLUENT_DATASOURCES_KEY][ds_with_assets.name]
assert _ASSETS_KEY not in dumped_as_dict[_FLUENT_DATASOURCES_KEY][ds_wo_assets.name]
# Marked via from_all_config fixture
def test_partitioners_deserialization(inject_engine_lookup_double, from_all_config: GxConfig):
table_asset: TableAsset = from_all_config.get_datasource(name="my_pg_ds").get_asset(
name="with_partitioner"
)
partitioner = table_asset.batch_definitions[0].partitioner
assert isinstance(partitioner, ColumnPartitionerMonthly)
assert partitioner.method_name == "partition_on_year_and_month"
# TDD Tests for future work
@pytest.mark.xfail(reason="Key Ordering needs to be implemented")
@pytest.mark.filesystem
def test_yaml_config_round_trip_ordering(
inject_engine_lookup_double, from_yaml_gx_config: GxConfig
):
dumped: str = from_yaml_gx_config.yaml()
assert dumped == PG_CONFIG_YAML_STR
@pytest.mark.big
def test_dict_default_pandas_config_round_trip(inject_engine_lookup_double):
# the default data asset should be dropped, but one named asset should remain
datasource_without_default_pandas_data_asset_config_dict = copy.deepcopy(
DEFAULT_PANDAS_DATASOURCE_AND_DATA_ASSET_CONFIG_DICT
)
from_dict_default_pandas_config = GxConfig.parse_obj(
DEFAULT_PANDAS_DATASOURCE_AND_DATA_ASSET_CONFIG_DICT
)
assert (
DEFAULT_PANDAS_DATA_ASSET_NAME
not in from_dict_default_pandas_config.get_datasource(
name=DEFAULT_PANDAS_DATASOURCE_NAME
).get_asset_names()
)
dumped: dict = from_dict_default_pandas_config.dict()
print(f" Dumped Dict ->\n\n{pf(dumped)}\n")
default_pandas_datasoure_config_dict = list(
filter(
lambda element: element["name"] == DEFAULT_PANDAS_DATASOURCE_NAME,
datasource_without_default_pandas_data_asset_config_dict[_FLUENT_DATASOURCES_KEY],
)
)[0]
default_pandas_datasoure_config_dict["assets"] = list(
filter(
lambda element: element["name"] != DEFAULT_PANDAS_DATA_ASSET_NAME,
default_pandas_datasoure_config_dict["assets"],
)
)
assert datasource_without_default_pandas_data_asset_config_dict == dumped
re_loaded: GxConfig = GxConfig.parse_obj(dumped)
pp(re_loaded)
assert re_loaded
assert from_dict_default_pandas_config == re_loaded
# removing just the named asset results in nothing being serialized
# since all we are left with is the default datasource and default data asset
only_default_pandas_datasource_and_data_asset_config_dict = copy.deepcopy(
DEFAULT_PANDAS_DATASOURCE_AND_DATA_ASSET_CONFIG_DICT
)
default_pandas_datasoure_config_dict = list(
filter(
lambda element: element["name"] == DEFAULT_PANDAS_DATASOURCE_NAME,
only_default_pandas_datasource_and_data_asset_config_dict[_FLUENT_DATASOURCES_KEY],
)
)[0]
default_pandas_datasoure_config_dict["assets"] = list(
filter(
lambda element: element["name"] != "my_csv_asset",
default_pandas_datasoure_config_dict["assets"],
)
)
from_dict_only_default_pandas_config = GxConfig.parse_obj(
only_default_pandas_datasource_and_data_asset_config_dict
)
assert from_dict_only_default_pandas_config.fluent_datasources == []
@pytest.fixture
def file_dc_config_dir_init(tmp_path: pathlib.Path) -> pathlib.Path:
"""
Initialize an regular/old-style FileDataContext project config directory.
Removed on teardown.
"""
gx_yml = tmp_path / FileDataContext.GX_DIR / FileDataContext.GX_YML
assert gx_yml.exists() is False
gx.get_context(mode="file", project_root_dir=tmp_path)
assert gx_yml.exists()
tmp_gx_dir = gx_yml.parent.absolute()
LOGGER.info(f"tmp_gx_dir -> {tmp_gx_dir}")
return tmp_gx_dir
@pytest.fixture
def file_dc_config_file_with_substitutions(
file_dc_config_dir_init: pathlib.Path,
) -> pathlib.Path:
config_file = file_dc_config_dir_init / FileDataContext.GX_YML
assert config_file.exists()
with open(config_file, mode="a") as file_append:
file_append.write(PG_CONFIG_YAML_STR)
print(config_file.read_text())
return config_file
@pytest.mark.sqlite
def test_config_substitution_retains_original_value_on_save(
unset_gx_env_variables,
seed_ds_env_vars: tuple,
file_dc_config_file_with_substitutions: pathlib.Path,
sqlite_database_path: pathlib.Path,
cloud_storage_get_client_doubles,
):
# show injected env variable
print(f"injected env variables:\n{pf(seed_ds_env_vars)}\n")
my_conn_str = os.environ["MY_CONN_STR"]
original: dict = cast("dict", yaml.load(file_dc_config_file_with_substitutions.read_text()))[
_FLUENT_DATASOURCES_KEY
]["my_sqlite_ds_w_subs"]
from great_expectations import get_context
context = get_context(context_root_dir=file_dc_config_file_with_substitutions.parent)
print(context.fluent_config)
ds_w_subs: SqliteDatasource = context.fluent_config.get_datasource(name="my_sqlite_ds_w_subs") # type: ignore[assignment] # FIXME CoP
assert str(ds_w_subs.connection_string) == r"${MY_CONN_STR}"
assert (
ds_w_subs.connection_string.get_config_value( # type: ignore[union-attr] # might not be ConfigStr
context.config_provider
)
== my_conn_str
)
context._save_project_config()
round_tripped = cast("dict", yaml.load(file_dc_config_file_with_substitutions.read_text()))[
_FLUENT_DATASOURCES_KEY
]["my_sqlite_ds_w_subs"]
assert round_tripped == original
@pytest.mark.sqlite
def test_config_substitution_retains_original_value_on_save_w_run_time_mods(
unset_gx_env_variables,
seed_ds_env_vars: tuple,
file_dc_config_file_with_substitutions: pathlib.Path,
cloud_storage_get_client_doubles,
):
# show injected env variable
print(f"injected env variables:\n{pf(seed_ds_env_vars)}")
original: dict = cast("dict", yaml.load(file_dc_config_file_with_substitutions.read_text()))[
_FLUENT_DATASOURCES_KEY
]
assert original.get("my_sqlite_ds_w_subs") # will be modified
assert original.get("my_pg_ds") # will be deleted
assert not original.get("my_sqlite") # will be added
from great_expectations import get_context
context = get_context(context_root_dir=file_dc_config_file_with_substitutions.parent)
datasources = context.fluent_datasources
assert (
str(datasources["my_sqlite_ds_w_subs"].connection_string) # type: ignore[attr-defined] # FIXME CoP
== r"${MY_CONN_STR}"
)
# add a new datasource
context.data_sources.add_sqlite("my_new_one", connection_string="sqlite://")
# add a new asset to an existing data
sqlite_ds_w_subs: SqliteDatasource = context.data_sources.get( # type: ignore[assignment] # FIXME CoP
"my_sqlite_ds_w_subs"
)
sqlite_ds_w_subs.add_table_asset("new_asset", table_name="yellow_tripdata_sample_2019_01")
context._save_project_config()
round_tripped_datasources = cast(
"dict", yaml.load(file_dc_config_file_with_substitutions.read_text())
)[_FLUENT_DATASOURCES_KEY]
assert round_tripped_datasources["my_new_one"]
assert round_tripped_datasources["my_sqlite_ds_w_subs"]["assets"]["new_asset"]
@pytest.mark.unit
def test_table_asset_omit_table_name():
name = "my_table"
asset = TableAsset(name=name)
assert asset.table_name == name
| TestExcludeUnsetAssetFields |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/storage_tests/test_compute_log_manager.py | {
"start": 899,
"end": 6244
} | class ____(ComputeLogManager):
def __init__(self, fail_on_setup=False, fail_on_teardown=False):
self._fail_on_setup = check.opt_bool_param(fail_on_setup, "fail_on_setup")
self._fail_on_teardown = check.opt_bool_param(fail_on_teardown, "fail_on_teardown")
@contextmanager
def capture_logs(self, log_key: Sequence[str]) -> Generator[CapturedLogContext, None, None]:
if self._fail_on_setup:
raise Exception("fail on setup")
yield CapturedLogContext(log_key=log_key)
if self._fail_on_teardown:
raise Exception("fail on teardown")
@contextmanager
def open_log_stream(
self, log_key: Sequence[str], io_type: ComputeIOType
) -> Generator[Optional[IO], None, None]:
yield None
def is_capture_complete(self, log_key: Sequence[str]) -> bool:
return True
def get_log_data_for_type(
self,
log_key: Sequence[str],
io_type: ComputeIOType,
offset: int,
max_bytes: Optional[int],
) -> tuple[Optional[bytes], int]:
return None, 0
def get_log_metadata(self, log_key: Sequence[str]) -> CapturedLogMetadata:
return CapturedLogMetadata()
def delete_logs(
self, log_key: Optional[Sequence[str]] = None, prefix: Optional[Sequence[str]] = None
):
pass
def subscribe(
self, log_key: Sequence[str], cursor: Optional[str] = None
) -> CapturedLogSubscription:
return CapturedLogSubscription(self, log_key, cursor)
def unsubscribe(self, subscription: CapturedLogSubscription):
return
@contextmanager
def broken_compute_log_manager_instance(fail_on_setup=False, fail_on_teardown=False):
with tempfile.TemporaryDirectory() as temp_dir:
with environ({"DAGSTER_HOME": temp_dir}):
yield dg.DagsterInstance(
instance_type=InstanceType.PERSISTENT,
local_artifact_storage=LocalArtifactStorage(temp_dir),
run_storage=SqliteRunStorage.from_local(temp_dir),
event_storage=SqliteEventLogStorage(temp_dir),
compute_log_manager=BrokenComputeLogManager(
fail_on_setup=fail_on_setup, fail_on_teardown=fail_on_teardown
),
run_coordinator=DefaultRunCoordinator(),
run_launcher=dg.DefaultRunLauncher(),
ref=InstanceRef.from_dir(temp_dir),
)
def _has_setup_exception(execute_result):
return any(
[
"Exception while setting up compute log capture" in str(event)
for event in execute_result.all_events
]
)
def _has_teardown_exception(execute_result):
return any(
[
"Exception while cleaning up compute log capture" in str(event)
for event in execute_result.all_events
]
)
@dg.op
def yay(context):
context.log.info("yay")
print("HELLOOO") # noqa: T201
return "yay"
@dg.op
def boo(context):
context.log.info("boo")
print("HELLOOO") # noqa: T201
raise Exception("booo")
@dg.job
def yay_job():
yay()
@dg.job
def boo_job():
boo()
def test_broken_compute_log_manager():
with broken_compute_log_manager_instance(fail_on_setup=True) as instance:
yay_result = yay_job.execute_in_process(instance=instance)
assert yay_result.success
assert _has_setup_exception(yay_result)
boo_result = boo_job.execute_in_process(instance=instance, raise_on_error=False)
assert not boo_result.success
assert _has_setup_exception(boo_result)
with broken_compute_log_manager_instance(fail_on_teardown=True) as instance:
yay_result = yay_job.execute_in_process(instance=instance)
assert yay_result.success
assert _has_teardown_exception(yay_result)
boo_result = boo_job.execute_in_process(instance=instance, raise_on_error=False)
assert not boo_result.success
assert _has_teardown_exception(boo_result)
with broken_compute_log_manager_instance() as instance:
yay_result = yay_job.execute_in_process(instance=instance)
assert yay_result.success
assert not _has_setup_exception(yay_result)
assert not _has_teardown_exception(yay_result)
boo_result = boo_job.execute_in_process(instance=instance, raise_on_error=False)
assert not boo_result.success
assert not _has_setup_exception(boo_result)
assert not _has_teardown_exception(boo_result)
import os
import sys
from collections.abc import Generator, Mapping, Sequence
from contextlib import contextmanager
from typing import Any
import pytest
from dagster._core.events import DagsterEventType
from dagster._core.storage.compute_log_manager import CapturedLogContext, ComputeIOType
from dagster._core.storage.local_compute_log_manager import LocalComputeLogManager
from dagster._core.storage.noop_compute_log_manager import NoOpComputeLogManager
from dagster._serdes import ConfigurableClassData
from dagster._time import get_current_datetime
from typing_extensions import Self
def test_compute_log_manager_instance():
with dg.instance_for_test() as instance:
assert instance.compute_log_manager
assert instance.compute_log_manager._instance # noqa: SLF001
| BrokenComputeLogManager |
python | chroma-core__chroma | chromadb/types.py | {
"start": 9444,
"end": 9831
} | class ____:
"""A sentinel value used to indicate that a value should not be updated"""
_instance: Optional["Unspecified"] = None
def __new__(cls) -> "Unspecified":
if cls._instance is None:
cls._instance = super(Unspecified, cls).__new__(cls)
return cls._instance
T = TypeVar("T")
OptionalArgument = Union[T, Unspecified]
@dataclass
| Unspecified |
python | tiangolo__fastapi | docs_src/extra_models/tutorial003.py | {
"start": 104,
"end": 168
} | class ____(BaseModel):
description: str
type: str
| BaseItem |
python | streamlit__streamlit | lib/streamlit/watcher/event_based_path_watcher.py | {
"start": 4452,
"end": 8600
} | class ____:
"""Watches multiple paths."""
_singleton: _MultiPathWatcher | None = None
@classmethod
def get_singleton(cls) -> _MultiPathWatcher:
"""Return the singleton _MultiPathWatcher object.
Instantiates one if necessary.
"""
if cls._singleton is None:
_LOGGER.debug("No singleton. Registering one.")
_MultiPathWatcher()
return cast("_MultiPathWatcher", _MultiPathWatcher._singleton)
# Don't allow constructor to be called more than once.
def __new__(cls) -> Self:
"""Constructor."""
if _MultiPathWatcher._singleton is not None:
raise RuntimeError("Use .get_singleton() instead")
return super().__new__(cls)
def __init__(self) -> None:
"""Constructor."""
_MultiPathWatcher._singleton = self
# Map of folder_to_watch -> _FolderEventHandler.
self._folder_handlers: dict[str, _FolderEventHandler] = {}
# Used for mutation of _folder_handlers dict
self._lock = threading.Lock()
# The Observer object from the Watchdog module. Since this class is
# only instantiated once, we only have a single Observer in Streamlit,
# and it's in charge of watching all paths we're interested in.
self._observer = Observer()
self._observer.start() # Start observer thread.
def __repr__(self) -> str:
return repr_(self)
def watch_path(
self,
path: str,
callback: Callable[[str], None],
*, # keyword-only arguments:
glob_pattern: str | None = None,
allow_nonexistent: bool = False,
) -> None:
"""Start watching a path."""
folder_path = _get_abs_folder_path(path)
with self._lock:
folder_handler = self._folder_handlers.get(folder_path)
if folder_handler is None:
folder_handler = _FolderEventHandler()
try:
folder_handler.watch = self._observer.schedule(
folder_handler, folder_path, recursive=True
)
self._folder_handlers[folder_path] = folder_handler
except Exception as ex:
_LOGGER.warning(
"Failed to schedule watch observer for path %s",
folder_path,
exc_info=ex,
)
return
folder_handler.add_path_change_listener(
path,
callback,
glob_pattern=glob_pattern,
allow_nonexistent=allow_nonexistent,
)
def stop_watching_path(self, path: str, callback: Callable[[str], None]) -> None:
"""Stop watching a path."""
folder_path = _get_abs_folder_path(path)
with self._lock:
folder_handler = self._folder_handlers.get(folder_path)
if folder_handler is None:
_LOGGER.debug(
"Cannot stop watching path, because it is already not being "
"watched. %s",
folder_path,
)
return
folder_handler.remove_path_change_listener(path, callback)
if (
not folder_handler.is_watching_paths()
and folder_handler.watch is not None
):
self._observer.unschedule(folder_handler.watch)
del self._folder_handlers[folder_path]
def close(self) -> None:
with self._lock:
"""Close this _MultiPathWatcher object forever."""
if len(self._folder_handlers) != 0:
_LOGGER.debug(
"Stopping observer thread even though there is a non-zero "
"number of event observers!"
)
self._observer.unschedule_all()
self._folder_handlers = {}
else:
_LOGGER.debug("Stopping observer thread")
self._observer.stop()
self._observer.join(timeout=5)
| _MultiPathWatcher |
python | huggingface__transformers | src/transformers/models/vilt/modeling_vilt.py | {
"start": 28043,
"end": 28703
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
@auto_docstring(
custom_intro="""
ViLT Model with a language modeling head on top as done during pretraining.
"""
)
| ViltPooler |
python | apache__airflow | task-sdk/tests/task_sdk/api/test_client.py | {
"start": 1812,
"end": 10116
} | class ____:
@pytest.mark.parametrize(
("path", "json_response"),
[
(
"/task-instances/1/run",
{
"dag_run": {
"dag_id": "test_dag",
"run_id": "test_run",
"logical_date": "2021-01-01T00:00:00Z",
"start_date": "2021-01-01T00:00:00Z",
"run_type": "manual",
"run_after": "2021-01-01T00:00:00Z",
"consumed_asset_events": [],
},
"max_tries": 0,
"should_retry": False,
},
),
],
)
def test_dry_run(self, path, json_response):
client = make_client_w_dry_run()
assert client.base_url == "dry-run://server"
resp = client.get(path)
assert resp.status_code == 200
assert resp.json() == json_response
@mock.patch("airflow.sdk.api.client.API_SSL_CERT_PATH", "/capath/does/not/exist/")
def test_add_capath(self):
def handle_request(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200)
with pytest.raises(FileNotFoundError) as err:
make_client(httpx.MockTransport(handle_request))
assert isinstance(err.value, FileNotFoundError)
@mock.patch("airflow.sdk.api.client.API_TIMEOUT", 60.0)
def test_timeout_configuration(self):
def handle_request(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200)
client = make_client(httpx.MockTransport(handle_request))
assert client.timeout == httpx.Timeout(60.0)
def test_timeout_can_be_overridden(self):
def handle_request(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200)
client = Client(
base_url="test://server", token="", transport=httpx.MockTransport(handle_request), timeout=120.0
)
assert client.timeout == httpx.Timeout(120.0)
def test_error_parsing(self):
responses = [
httpx.Response(422, json={"detail": [{"loc": ["#0"], "msg": "err", "type": "required"}]})
]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert isinstance(err.value, ServerResponseError)
assert isinstance(err.value.detail, list)
assert err.value.detail == [
RemoteValidationError(loc=["#0"], msg="err", type="required"),
]
def test_error_parsing_plain_text(self):
responses = [httpx.Response(422, content=b"Internal Server Error")]
client = make_client_w_responses(responses)
with pytest.raises(httpx.HTTPStatusError) as err:
client.get("http://error")
assert not isinstance(err.value, ServerResponseError)
def test_error_parsing_other_json(self):
responses = [httpx.Response(404, json={"detail": "Not found"})]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert err.value.args == ("Not found",)
assert err.value.detail is None
def test_server_response_error_pickling(self):
responses = [httpx.Response(404, json={"detail": {"message": "Invalid input"}})]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as exc_info:
client.get("http://error")
err = exc_info.value
assert err.args == ("Server returned error",)
assert err.detail == {"detail": {"message": "Invalid input"}}
# Check that the error is picklable
pickled = pickle.dumps(err)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, ServerResponseError)
# Test that unpickled error has the same attributes as the original
assert unpickled.response.json() == {"detail": {"message": "Invalid input"}}
assert unpickled.detail == {"detail": {"message": "Invalid input"}}
assert unpickled.response.status_code == 404
assert unpickled.request.url == "http://error"
def test_retry_handling_unrecoverable_error(self):
with time_machine.travel("2023-01-01T00:00:00Z", tick=False):
responses: list[httpx.Response] = [
*[httpx.Response(500, text="Internal Server Error")] * 6,
httpx.Response(200, json={"detail": "Recovered from error - but will fail before"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
with pytest.raises(httpx.HTTPStatusError) as err:
client.get("http://error")
assert not isinstance(err.value, ServerResponseError)
assert len(responses) == 3
def test_retry_handling_recovered(self):
with time_machine.travel("2023-01-01T00:00:00Z", tick=False):
responses: list[httpx.Response] = [
*[httpx.Response(500, text="Internal Server Error")] * 2,
httpx.Response(200, json={"detail": "Recovered from error"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
response = client.get("http://error")
assert response.status_code == 200
assert len(responses) == 1
def test_retry_handling_non_retry_error(self):
with time_machine.travel("2023-01-01T00:00:00Z", tick=False):
responses: list[httpx.Response] = [
httpx.Response(422, json={"detail": "Somehow this is a bad request"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
with pytest.raises(ServerResponseError) as err:
client.get("http://error")
assert len(responses) == 1
assert err.value.args == ("Somehow this is a bad request",)
def test_retry_handling_ok(self):
with time_machine.travel("2023-01-01T00:00:00Z", tick=False):
responses: list[httpx.Response] = [
httpx.Response(200, json={"detail": "Recovered from error"}),
httpx.Response(400, json={"detail": "Should not get here"}),
]
client = make_client_w_responses(responses)
response = client.get("http://error")
assert response.status_code == 200
assert len(responses) == 1
def test_token_renewal(self):
responses: list[httpx.Response] = [
httpx.Response(200, json={"ok": "1"}),
httpx.Response(404, json={"var": "not_found"}, headers={"Refreshed-API-Token": "abc"}),
httpx.Response(200, json={"ok": "3"}),
]
client = make_client_w_responses(responses)
response = client.get("/")
assert response.status_code == 200
assert client.auth is not None
assert not client.auth.token
with pytest.raises(ServerResponseError):
response = client.get("/")
# Even thought it was Not Found, we should still respect the header
assert client.auth is not None
assert client.auth.token == "abc"
# Test that the next request is made with that new auth token
response = client.get("/")
assert response.status_code == 200
assert response.request.headers["Authorization"] == "Bearer abc"
@pytest.mark.parametrize(
("status_code", "description"),
[
(399, "status code < 400"),
(301, "3xx redirect status code"),
(600, "status code >= 600"),
],
)
def test_server_response_error_invalid_status_codes(self, status_code, description):
"""Test that ServerResponseError.from_response returns None for invalid status codes."""
response = httpx.Response(status_code, json={"detail": f"Test {description}"})
assert ServerResponseError.from_response(response) is None
| TestClient |
python | dagster-io__dagster | python_modules/libraries/dagster-powerbi/dagster_powerbi/translator.py | {
"start": 2749,
"end": 3273
} | class ____:
"""A record representing a piece of content in PowerBI and the PowerBI workspace data.
Includes the content's type and data as returned from the API.
"""
content_data: "PowerBIContentData"
workspace_data: "PowerBIWorkspaceData"
@property
def content_type(self) -> PowerBIContentType:
return self.content_data.content_type
@property
def properties(self) -> dict[str, Any]:
return self.content_data.properties
@whitelist_for_serdes
@record
| PowerBITranslatorData |
python | getsentry__sentry | tests/sentry/workflow_engine/models/test_data_condition.py | {
"start": 452,
"end": 1794
} | class ____(TestCase):
def test_str(self) -> None:
dc = self.create_data_condition(condition_result="wrong")
with mock.patch("sentry.workflow_engine.models.data_condition.logger") as mock_logger:
assert dc.get_condition_result() == ConditionError(msg="Invalid condition result")
assert mock_logger.error.call_args[0][0] == "Invalid condition result"
def test_int(self) -> None:
dc = self.create_data_condition(condition_result=1)
assert dc.get_condition_result() == 1
def test_float(self) -> None:
dc = self.create_data_condition(condition_result=1.0)
assert dc.get_condition_result() == 1.0
def test_int__overlaps_with_priority_low(self) -> None:
dc = self.create_data_condition(condition_result=25)
assert dc.get_condition_result() == 25
assert dc.get_condition_result() == DetectorPriorityLevel.LOW
def test_priority_level__as_level(self) -> None:
dc = self.create_data_condition(condition_result=DetectorPriorityLevel.HIGH)
assert dc.get_condition_result() == DetectorPriorityLevel.HIGH
assert dc.get_condition_result() == 75
def test_boolean(self) -> None:
dc = self.create_data_condition(condition_result=True)
assert dc.get_condition_result() is True
| GetConditionResultTest |
python | ethereum__web3.py | tests/core/utilities/test_datatypes.py | {
"start": 200,
"end": 1096
} | class ____(InheritedBaseClass):
arg2 = None
arg3 = None
def test_property_checking_metaclass_attribute_error():
# Test proper attribute checking, arg from both bases.
namespace = {"arg2": True, "arg0": True, "arg4": True}
with pytest.raises(Web3AttributeError):
PropertyCheckingFactory("class_name", (BaseClass,), namespace)
# Test proper attribute checking, only absent arg.
namespace = {"arg4": True}
with pytest.raises(AttributeError):
PropertyCheckingFactory("class_name", (BaseClass,), namespace)
def test_property_checking_metaclass_inherited_attributes():
from_inherited_namespace = {"arg0": True, "arg1": True}
PropertyCheckingFactory("class_name", (BaseClass,), from_inherited_namespace)
from_base_namespace = {"arg2": True, "arg3": True}
PropertyCheckingFactory("class_name", (BaseClass,), from_base_namespace)
| BaseClass |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/relationships/tutorial001_py310.py | {
"start": 1185,
"end": 1260
} | class ____(HeroPublic):
team: TeamPublic | None = None
| HeroPublicWithTeam |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 2220,
"end": 2342
} | class ____(RootModel[list[dict[str, Any]]]):
model_config = {"json_schema_extra": _tolerations_schema_extra}
| Tolerations |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.