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 | plotly__plotly.py | plotly/graph_objs/scatterpolargl/marker/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8584
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolargl.marker.colorbar"
_path_str = "scatterpolargl.marker.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
"""
return self["dtickrange"]
@dtickrange.setter
def dtickrange(self, val):
self["dtickrange"] = val
@property
def enabled(self):
"""
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["enabled"]
@enabled.setter
def enabled(self, val):
self["enabled"] = val
@property
def name(self):
"""
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["name"]
@name.setter
def name(self, val):
self["name"] = val
@property
def templateitemname(self):
"""
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["templateitemname"]
@templateitemname.setter
def templateitemname(self, val):
self["templateitemname"] = val
@property
def value(self):
"""
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["value"]
@value.setter
def value(self, val):
self["value"] = val
@property
def _prop_descriptions(self):
return """\
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
"""
def __init__(
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs,
):
"""
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scatterpolargl
.marker.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
"""
super().__init__("tickformatstops")
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.scatterpolargl.marker.colorbar.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.Tickformatstop`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("dtickrange", arg, dtickrange)
self._set_property("enabled", arg, enabled)
self._set_property("name", arg, name)
self._set_property("templateitemname", arg, templateitemname)
self._set_property("value", arg, value)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Tickformatstop |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 322289,
"end": 325399
} | class ____:
def test_endpoints_7491(self):
# gh-7491
# Compute the pdf at the left endpoint dst.a.
data = [
[stats.fisk, (1,), 1],
[stats.burr, (0.5, 2), 1],
[stats.burr, (1, 1), 1],
[stats.burr, (2, 0.5), 1],
[stats.burr12, (1, 0.5), 0.5],
[stats.burr12, (1, 1), 1.0],
[stats.burr12, (1, 2), 2.0]]
ans = [_f.pdf(_f.a, *_args) for _f, _args, _ in data]
correct = [_correct_ for _f, _args, _correct_ in data]
assert_array_almost_equal(ans, correct)
ans = [_f.logpdf(_f.a, *_args) for _f, _args, _ in data]
correct = [np.log(_correct_) for _f, _args, _correct_ in data]
assert_array_almost_equal(ans, correct)
def test_burr_stats_9544(self):
# gh-9544. Test from gh-9978
c, d = 5.0, 3
mean, variance = stats.burr(c, d).stats()
# mean = sc.beta(3 + 1/5, 1. - 1/5) * 3 = 1.4110263...
# var = sc.beta(3 + 2 / 5, 1. - 2 / 5) * 3 -
# (sc.beta(3 + 1 / 5, 1. - 1 / 5) * 3) ** 2
mean_hc, variance_hc = 1.4110263183925857, 0.22879948026191643
assert_allclose(mean, mean_hc)
assert_allclose(variance, variance_hc)
def test_burr_nan_mean_var_9544(self):
# gh-9544. Test from gh-9978
c, d = 0.5, 3
mean, variance = stats.burr(c, d).stats()
assert_(np.isnan(mean))
assert_(np.isnan(variance))
c, d = 1.5, 3
mean, variance = stats.burr(c, d).stats()
assert_(np.isfinite(mean))
assert_(np.isnan(variance))
c, d = 0.5, 3
e1, e2, e3, e4 = stats.burr._munp(np.array([1, 2, 3, 4]), c, d)
assert_(np.isnan(e1))
assert_(np.isnan(e2))
assert_(np.isnan(e3))
assert_(np.isnan(e4))
c, d = 1.5, 3
e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
assert_(np.isfinite(e1))
assert_(np.isnan(e2))
assert_(np.isnan(e3))
assert_(np.isnan(e4))
c, d = 2.5, 3
e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
assert_(np.isfinite(e1))
assert_(np.isfinite(e2))
assert_(np.isnan(e3))
assert_(np.isnan(e4))
c, d = 3.5, 3
e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
assert_(np.isfinite(e1))
assert_(np.isfinite(e2))
assert_(np.isfinite(e3))
assert_(np.isnan(e4))
c, d = 4.5, 3
e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
assert_(np.isfinite(e1))
assert_(np.isfinite(e2))
assert_(np.isfinite(e3))
assert_(np.isfinite(e4))
def test_burr_isf(self):
# reference values were computed via the reference distribution, e.g.
# mp.dps = 100
# Burr(c=5, d=3).isf([0.1, 1e-10, 1e-20, 1e-40])
c, d = 5.0, 3.0
q = [0.1, 1e-10, 1e-20, 1e-40]
ref = [1.9469686558286508, 124.57309395989076, 12457.309396155173,
124573093.96155174]
assert_allclose(stats.burr.isf(q, c, d), ref, rtol=1e-14)
| TestBurr |
python | getsentry__sentry | src/sentry/grouping/component.py | {
"start": 9184,
"end": 9275
} | class ____(BaseGroupingComponent[str]):
id: str = "domain"
| NSErrorDomainGroupingComponent |
python | encode__django-rest-framework | tests/test_routers.py | {
"start": 6716,
"end": 7339
} | class ____(URLPatternsTestCase, TestCase):
urlpatterns = [
path('non-namespaced/', include(namespaced_router.urls)),
path('namespaced/', include((namespaced_router.urls, 'namespaced'), namespace='namespaced')),
]
def test_retrieve_namespaced_root(self):
response = self.client.get('/namespaced/')
assert response.data == {"example": "http://testserver/namespaced/example/"}
def test_retrieve_non_namespaced_root(self):
response = self.client.get('/non-namespaced/')
assert response.data == {"example": "http://testserver/non-namespaced/example/"}
| TestRootView |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_drypython_returns.py | {
"start": 2289,
"end": 2352
} | class ____(Generic[C, D]):
pass
# To be tested:
| _SecondBase |
python | pypa__pip | src/pip/_vendor/distlib/util.py | {
"start": 55800,
"end": 57646
} | class ____(BaseConfigurator):
value_converters = dict(BaseConfigurator.value_converters)
value_converters['inc'] = 'inc_convert'
def __init__(self, config, base=None):
super(Configurator, self).__init__(config)
self.base = base or os.getcwd()
def configure_custom(self, config):
def convert(o):
if isinstance(o, (list, tuple)):
result = type(o)([convert(i) for i in o])
elif isinstance(o, dict):
if '()' in o:
result = self.configure_custom(o)
else:
result = {}
for k in o:
result[k] = convert(o[k])
else:
result = self.convert(o)
return result
c = config.pop('()')
if not callable(c):
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
args = config.pop('[]', ())
if args:
args = tuple([convert(o) for o in args])
items = [(k, convert(config[k])) for k in config if valid_ident(k)]
kwargs = dict(items)
result = c(*args, **kwargs)
if props:
for n, v in props.items():
setattr(result, n, convert(v))
return result
def __getitem__(self, key):
result = self.config[key]
if isinstance(result, dict) and '()' in result:
self.config[key] = result = self.configure_custom(result)
return result
def inc_convert(self, value):
"""Default converter for the inc:// protocol."""
if not os.path.isabs(value):
value = os.path.join(self.base, value)
with codecs.open(value, 'r', encoding='utf-8') as f:
result = json.load(f)
return result
| Configurator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 984047,
"end": 984581
} | class ____(sgqlc.types.Type):
"""Represents a user that's starred a repository."""
__schema__ = github_schema
__field_names__ = ("cursor", "node", "starred_at")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field(sgqlc.types.non_null("User"), graphql_name="node")
starred_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="starredAt")
"""Identifies when the item was starred."""
| StargazerEdge |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 61432,
"end": 61837
} | class ____(sgqlc.types.Enum):
"""Properties by which project v2 field connections can be ordered.
Enumeration Choices:
* `CREATED_AT`: Order project v2 fields by creation time
* `NAME`: Order project v2 fields by name
* `POSITION`: Order project v2 fields by position
"""
__schema__ = github_schema
__choices__ = ("CREATED_AT", "NAME", "POSITION")
| ProjectV2FieldOrderField |
python | python__mypy | mypyc/irbuild/targets.py | {
"start": 1171,
"end": 1969
} | class ____(AssignmentTarget):
"""obj.attr as assignment target"""
def __init__(self, obj: Value, attr: str, can_borrow: bool = False) -> None:
self.obj = obj
self.attr = attr
self.can_borrow = can_borrow
if isinstance(obj.type, RInstance) and obj.type.class_ir.has_attr(attr):
# Native attribute reference
self.obj_type: RType = obj.type
self.type = obj.type.attr_type(attr)
else:
# Python attribute reference
self.obj_type = object_rprimitive
self.type = object_rprimitive
def __repr__(self) -> str:
can_borrow_str = ", can_borrow=True" if self.can_borrow else ""
return f"AssignmentTargetAttr({self.obj!r}.{self.attr}{can_borrow_str})"
| AssignmentTargetAttr |
python | pypa__warehouse | warehouse/utils/crypto.py | {
"start": 570,
"end": 674
} | class ____(_Signer):
default_digest_method = hashlib.sha512
default_key_derivation = "hmac"
| Signer |
python | getsentry__sentry | src/sentry/flags/providers.py | {
"start": 6585,
"end": 6778
} | class ____(serializers.Serializer):
data = GenericItemSerializer(many=True, required=True) # type: ignore[assignment]
meta = GenericMetaSerializer(required=True)
| GenericRequestSerializer |
python | realpython__materials | python-bitwise-operators/src/stegano/cli.py | {
"start": 147,
"end": 1278
} | class ____:
"""Parsed command line arguments."""
bitmap: pathlib.Path
encode: Optional[pathlib.Path]
decode: bool
erase: bool
def parse_args() -> CommandLineArguments:
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("bitmap", type=path_factory)
modes = parser.add_mutually_exclusive_group()
modes.add_argument("--encode", "-e", metavar="file", type=path_factory)
modes.add_argument("--decode", "-d", action="store_true")
modes.add_argument("--erase", "-x", action="store_true")
args = parser.parse_args()
if not any([args.encode, args.decode, args.erase]):
parser.error("Mode required: --encode file | --decode | --erase")
return CommandLineArguments(**vars(args))
def path_factory(argument: str) -> pathlib.Path:
"""Convert the argument to a path instance."""
path = pathlib.Path(argument)
if not path.exists():
raise argparse.ArgumentTypeError("file doesn't exist")
if not path.is_file():
raise argparse.ArgumentTypeError("must be a file")
return path
| CommandLineArguments |
python | getsentry__sentry | tests/sentry/integrations/jira/test_ticket_action.py | {
"start": 890,
"end": 9619
} | class ____(RuleTestCase, BaseAPITestCase):
rule_cls = JiraCreateTicketAction
def setUp(self) -> None:
super().setUp()
self.project_name = "Jira Cloud"
self.integration, _ = self.create_provider_integration_for(
self.organization,
self.user,
provider="jira",
name=self.project_name,
metadata={
"oauth_client_id": "oauth-client-id",
"shared_secret": "a-super-secret-key-from-atlassian",
"base_url": "https://example.atlassian.net",
"domain_name": "example.atlassian.net",
},
)
self.installation = self.integration.get_installation(self.organization.id)
self.login_as(user=self.user)
def trigger(self, event, rule_object):
action = rule_object.data.get("actions", ())[0]
action_inst = self.get_rule(data=action, rule=rule_object)
results = list(action_inst.after(event=event))
assert len(results) == 1
rule_future = RuleFuture(rule=rule_object, kwargs=results[0].kwargs)
return results[0].callback(event, futures=[rule_future])
def get_key(self, event: GroupEvent):
return ExternalIssue.objects.get_linked_issues(event, self.integration).values_list(
"key", flat=True
)[0]
def configure_valid_alert_rule(self):
response = self.client.post(
reverse(
"sentry-api-0-project-rules",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
},
),
format="json",
data={
"name": "hello world",
"owner": self.user.id,
"environment": None,
"actionMatch": "any",
"frequency": 5,
"actions": [
{
"id": "sentry.integrations.jira.notify_action.JiraCreateTicketAction",
"integration": self.integration.id,
"dynamic_form_fields": [{"name": "project"}],
"issuetype": "1",
"name": "Create a Jira ticket in the Jira Cloud account",
"project": "10000",
}
],
"conditions": [],
},
)
assert response.status_code == 200
return response
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_ticket_rules(self, mock_record_event: mock.MagicMock) -> None:
with mock.patch(
"sentry.integrations.jira.integration.JiraIntegration.get_client",
return_value=MockJira(),
):
response = self.configure_valid_alert_rule()
# Get the rule from DB
rule_object = Rule.objects.get(id=response.data["id"])
event = self.get_group_event()
# Trigger its `after`
self.trigger(event, rule_object)
# assert ticket created in DB
key = self.get_key(event)
external_issue_count = len(ExternalIssue.objects.filter(key=key))
assert external_issue_count == 1
# assert ticket created on jira
assert isinstance(self.installation, JiraIntegration)
data = self.installation.get_issue(key)
assert event.message in data["description"]
# Trigger its `after` _again_
self.trigger(event, rule_object)
# assert new ticket NOT created in DB
assert ExternalIssue.objects.count() == external_issue_count
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None, False, None)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@mock.patch.object(MockJira, "create_issue")
def test_misconfigured_ticket_rule(
self, mock_create_issue: mock.MagicMock, mock_record_event: mock.MagicMock
) -> None:
def raise_api_error(*args, **kwargs):
raise ApiInvalidRequestError("Invalid data entered")
mock_create_issue.side_effect = raise_api_error
with mock.patch(
"sentry.integrations.jira.integration.JiraIntegration.get_client",
return_value=MockJira(),
):
response = self.configure_valid_alert_rule()
rule_object = Rule.objects.get(id=response.data["id"])
event = self.get_event()
with pytest.raises(IntegrationConfigurationError):
self.trigger(event, rule_object)
assert mock_record_event.call_count == 2
start, halt = mock_record_event.call_args_list
assert start.args == (EventLifecycleOutcome.STARTED,)
assert_halt_metric(
mock_record_event,
IntegrationConfigurationError(),
)
def test_fails_validation(self) -> None:
"""
Test that the absence of dynamic_form_fields in the action fails validation
"""
# Create a new Rule
response = self.client.post(
reverse(
"sentry-api-0-project-rules",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
},
),
format="json",
data={
"name": "hello world",
"environment": None,
"actionMatch": "any",
"frequency": 5,
"actions": [
{
"id": "sentry.integrations.jira.notify_action.JiraCreateTicketAction",
"integration": self.integration.id,
"issuetype": "1",
"name": "Create a Jira ticket in the Jira Cloud account",
"project": "10000",
}
],
"conditions": [],
},
)
assert response.status_code == 400
assert response.data["actions"][0] == "Must configure issue link settings."
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@mock.patch.object(MockJira, "create_issue")
def test_fails_with_field_configuration_error(
self, mock_create_issue: mock.MagicMock, mock_record_event: mock.MagicMock
) -> None:
# Mock an error from the client response that cotains a field
def raise_api_error_with_payload(*args, **kwargs):
raise ApiInvalidRequestError(json.dumps({"errors": {"foo": "bar"}}))
mock_create_issue.side_effect = raise_api_error_with_payload
with mock.patch(
"sentry.integrations.jira.integration.JiraIntegration.get_client",
return_value=MockJira(),
):
response = self.configure_valid_alert_rule()
rule_object = Rule.objects.get(id=response.data["id"])
event = self.get_event()
with pytest.raises(IntegrationFormError):
self.trigger(event, rule_object)
assert mock_record_event.call_count == 2
start, halt = mock_record_event.call_args_list
assert start.args == (EventLifecycleOutcome.STARTED,)
assert_halt_metric(mock_record_event, IntegrationFormError({"foo": ["bar"]}))
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@mock.patch.object(MockJira, "get_create_meta_for_project", return_value=None)
def test_halts_with_external_api_configuration_error(
self, mock_get_create_meta_for_project, mock_record_event
):
with mock.patch(
"sentry.integrations.jira.integration.JiraIntegration.get_client",
return_value=MockJira(),
):
response = self.configure_valid_alert_rule()
# Get the rule from DB
rule_object = Rule.objects.get(id=response.data["id"])
event = self.get_event()
with pytest.raises(IntegrationConfigurationError):
self.trigger(event, rule_object)
assert mock_record_event.call_count == 2
start, halt = mock_record_event.call_args_list
assert start.args == (EventLifecycleOutcome.STARTED,)
assert_halt_metric(
mock_record_event,
IntegrationConfigurationError(
"Could not fetch issue create configuration from Jira."
),
)
| JiraTicketRulesTestCase |
python | plotly__plotly.py | plotly/graph_objs/densitymap/_stream.py | {
"start": 233,
"end": 3526
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "densitymap"
_path_str = "densitymap.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000]
Returns
-------
int|float
"""
return self["maxpoints"]
@maxpoints.setter
def maxpoints(self, val):
self["maxpoints"] = val
@property
def token(self):
"""
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["token"]
@token.setter
def token(self, val):
self["token"] = val
@property
def _prop_descriptions(self):
return """\
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
"""
def __init__(self, arg=None, maxpoints=None, token=None, **kwargs):
"""
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.densitymap.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
Returns
-------
Stream
"""
super().__init__("stream")
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.densitymap.Stream
constructor must be a dict or
an instance of :class:`plotly.graph_objs.densitymap.Stream`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("maxpoints", arg, maxpoints)
self._set_property("token", arg, token)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Stream |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/test_waiter.py | {
"start": 1874,
"end": 4162
} | class ____:
@pytest.mark.parametrize(
("get_state_responses", "fails", "expected_exception", "expected_num_calls"),
[
([generate_response("Created")], False, None, 1),
([generate_response("Failed")], True, AirflowException, 1),
(
[generate_response("Pending"), generate_response("Pending"), generate_response("Created")],
False,
None,
3,
),
(
[generate_response("Pending"), generate_response("Failed")],
True,
AirflowException,
2,
),
(
[generate_response("Pending"), generate_response("Pending"), generate_response("Failed")],
True,
AirflowException,
3,
),
([generate_response("Pending") for i in range(10)], True, RuntimeError, 5),
],
)
@mock.patch("time.sleep", return_value=None)
def test_waiter(self, _, get_state_responses, fails, expected_exception, expected_num_calls):
mock_get_state = MagicMock()
mock_get_state.side_effect = get_state_responses
get_state_args = {}
if fails:
with pytest.raises(expected_exception):
waiter(
get_state_callable=mock_get_state,
get_state_args=get_state_args,
parse_response=["Status", "State"],
desired_state=SUCCESS_STATES,
failure_states=FAILURE_STATES,
object_type="test_object",
action="testing",
check_interval_seconds=1,
countdown=5,
)
else:
waiter(
get_state_callable=mock_get_state,
get_state_args=get_state_args,
parse_response=["Status", "State"],
desired_state=SUCCESS_STATES,
failure_states=FAILURE_STATES,
object_type="test_object",
action="testing",
check_interval_seconds=1,
countdown=5,
)
assert mock_get_state.call_count == expected_num_calls
| TestWaiter |
python | huggingface__transformers | src/transformers/models/timesfm/modeling_timesfm.py | {
"start": 22120,
"end": 33937
} | class ____(TimesFmPreTrainedModel):
"""TimesFM model for quantile and mean prediction."""
def __init__(self, config: TimesFmConfig):
super().__init__(config)
self.config = config
self.context_len = config.context_length
self.horizon_len = config.horizon_length
self.decoder = TimesFmModel(config)
# quantile and mean output
self.horizon_ff_layer = TimesFmResidualBlock(
input_dims=config.hidden_size,
output_dims=config.horizon_length * (1 + len(config.quantiles)),
hidden_dims=config.intermediate_size,
)
# Initialize weights and apply final processing
self.post_init()
def _preprocess(
self, inputs: Sequence[torch.Tensor], freq: Sequence[int]
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Formats and pads raw inputs to feed into the model.
This function both pads each time series to match the context length, and
pads the inputs to meet the SPMD shape requirement.
Args:
inputs: A list of 1d Tensors. Each Tensor is the context time series of
a single forecast task.
freq: list of frequencies
Returns:
A tuple of:
- the padded input time series to meet the model required context.
- the padding indicator.
- the number of padded examples for SPMD so that each core has the same
number (a multiple of `batch_size`) of examples.
"""
input_ts, input_padding, inp_freq = [], [], []
for i, ts in enumerate(inputs):
input_len = ts.shape[0]
padding = torch.zeros(input_len + self.horizon_len, dtype=ts.dtype, device=ts.device)
if input_len < self.context_len:
num_front_pad = self.context_len - input_len
ts = torch.cat([torch.zeros(num_front_pad, dtype=ts.dtype, device=ts.device), ts], dim=0)
padding = torch.cat([torch.ones(num_front_pad, dtype=ts.dtype, device=padding.device), padding], dim=0)
elif input_len > self.context_len:
ts = ts[-self.context_len :]
padding = padding[-(self.context_len + self.horizon_len) :]
input_ts.append(ts)
input_padding.append(padding)
inp_freq.append(freq[i])
return (
torch.stack(input_ts, dim=0),
torch.stack(input_padding, dim=0),
torch.tensor(inp_freq, dtype=torch.int32).reshape(-1, 1),
)
def _postprocess_output(
self, model_output: torch.Tensor, stats: tuple[torch.Tensor, torch.Tensor]
) -> torch.Tensor:
"""Postprocess output of stacked transformer."""
# B x N x (H.Q)
output_ts = self.horizon_ff_layer(model_output)
# Reshape using view
b, n, _ = output_ts.shape
output_ts = output_ts.view(b, n, self.config.horizon_length, len(self.config.quantiles) + 1)
mu, sigma = stats
return output_ts * sigma[:, None, None, None] + mu[:, None, None, None]
def _quantile_loss(self, predictions: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
losses = []
for i, q in enumerate(self.config.quantiles):
errors = targets - predictions[..., i]
loss = torch.max((q - 1) * errors, q * errors)
losses.append(loss.mean())
return torch.stack(losses).mean()
@can_return_tuple
@auto_docstring
def forward(
self,
past_values: Sequence[torch.Tensor],
freq: Optional[Sequence[Union[torch.Tensor, int]]] = None,
window_size: Optional[int] = None,
future_values: Optional[torch.Tensor] = None,
forecast_context_len: Optional[int] = None,
return_forecast_on_context: bool = False,
truncate_negative: bool = False,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
) -> TimesFmOutputForPrediction:
r"""
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
Past values of the time series that serves as input to the model.
freq (`torch.LongTensor` of shape `(batch_size,)`):
Frequency indices for the time series data.
window_size (`int`, *optional*):
Window size of trend + residual decomposition. If None then we do not do decomposition.
future_values (`torch.Tensor`, *optional*):
Optional future time series values to be used for loss computation.
forecast_context_len (`int`, *optional*):
Optional max context length.
return_forecast_on_context (`bool`, *optional*):
True to return the forecast on the context when available, i.e. after the first input patch.
truncate_negative (`bool`, *optional*):
Truncate to only non-negative values if any of the contexts have non-negative values,
otherwise do nothing.
output_attentions (`bool`, *optional*):
Whether to output the attentions.
output_hidden_states (`bool`, *optional*):
Whether to output the hidden states.
Example:
```python
>>> from transformers import TimesFmModelForPrediction
>>> model = TimesFmModelForPrediction.from_pretrained("google/timesfm-2.0-500m-pytorch")
>>> forecast_input = [torch.linspace(0, 20, 100).sin(), torch.linspace(0, 20, 200).sin(), torch.linspace(0, 20, 400).sin()]
>>> frequency_input = torch.tensor([0, 1, 2], dtype=torch.long)
>>> # Generate
>>> with torch.no_grad():
>>> outputs = model(past_values=forecast_input, freq=frequency_input, return_dict=True)
>>> point_forecast_conv = outputs.mean_predictions
>>> quantile_forecast_conv = outputs.full_predictions
```
"""
if forecast_context_len is None:
fcontext_len = self.context_len
else:
fcontext_len = forecast_context_len
# Get device from first input tensor
device = past_values[0].device
# Truncate inputs to forecast_context_len
inputs = [ts[-fcontext_len:] for ts in past_values]
inp_min = torch.min(torch.stack([torch.min(ts) for ts in inputs]))
if window_size is not None:
new_inputs = []
new_freqs = []
for i, ts in enumerate(inputs):
new_inputs.extend(self._timesfm_moving_average(ts, window_size))
if freq is not None:
new_freqs.extend([freq[i]] * 2)
inputs = new_inputs
if freq is not None:
freq = new_freqs
if freq is None:
logger.info("No frequency provided via `freq`. Default to high (0).")
freq = [0] * len(inputs)
if output_attentions is None:
output_attentions = self.config.output_attentions
if output_hidden_states is None:
output_hidden_states = self.config.output_hidden_states
input_ts, input_padding, inp_freq = self._preprocess(inputs, freq)
# Move tensors to the same device as input
input_ts = input_ts.to(device)
input_padding = input_padding.to(device)
inp_freq = inp_freq.to(device)
final_out = input_ts
context_len = final_out.shape[1]
full_outputs = []
if input_padding.shape[1] != final_out.shape[1] + self.horizon_len:
raise ValueError(
"Length of paddings must match length of input + horizon_len:"
f" {input_padding.shape[1]} != {final_out.shape[1]} + {self.horizon_len}"
)
output_patch_len = self.config.horizon_length
num_decode_patches = (self.horizon_len + output_patch_len - 1) // output_patch_len
for step_index in range(num_decode_patches):
current_padding = input_padding[:, 0 : final_out.shape[1]]
input_ts = final_out[:, -fcontext_len:]
input_padding = current_padding[:, -fcontext_len:]
decoder_output = self.decoder(
past_values=input_ts,
past_values_padding=input_padding,
freq=inp_freq,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
fprop_outputs = self._postprocess_output(
decoder_output.last_hidden_state,
(decoder_output.loc, decoder_output.scale),
)
if return_forecast_on_context and step_index == 0:
# For the first decodings step, collect the model forecast on the
# context except the unavailable first input batch forecast.
new_full_ts = fprop_outputs[:, :-1, : self.config.patch_length, :]
# We have to use reshape and not view for non-contiguous memory
new_full_ts = new_full_ts.reshape(new_full_ts.size(0), -1, new_full_ts.size(3))
full_outputs.append(new_full_ts)
# (full batch, last patch, output_patch_len, index of mean forecast = 0)
new_ts = fprop_outputs[:, -1, :output_patch_len, 0]
new_full_ts = fprop_outputs[:, -1, :output_patch_len, :]
# (full batch, last patch, output_patch_len, all output indices)
full_outputs.append(new_full_ts)
final_out = torch.concatenate([final_out, new_ts], axis=-1)
if return_forecast_on_context:
# `full_outputs` indexing starts at after the first input patch.
full_outputs = torch.concatenate(full_outputs, axis=1)[
:, : (context_len - self.config.patch_length + self.horizon_len), :
]
else:
# `full_outputs` indexing starts at the forecast horizon.
full_outputs = torch.concatenate(full_outputs, axis=1)[:, 0 : self.horizon_len, :]
mean_outputs = full_outputs[:, :, 0]
if window_size is not None:
mean_outputs = mean_outputs[0::2, ...] + mean_outputs[1::2, ...]
full_outputs = full_outputs[0::2, ...] + full_outputs[1::2, ...]
if inp_min >= 0 and truncate_negative:
mean_outputs = torch.maximum(mean_outputs, 0.0)
full_outputs = torch.maximum(full_outputs, 0.0)
loss = None
if future_values is not None:
mse_loss = F.mse_loss(mean_outputs, future_values)
quantile_loss = self._quantile_loss(full_outputs[:, :, 1:], future_values)
loss = mse_loss + quantile_loss
return TimesFmOutputForPrediction(
last_hidden_state=decoder_output.last_hidden_state,
attentions=decoder_output.attentions if output_attentions else None,
hidden_states=decoder_output.hidden_states if output_hidden_states else None,
mean_predictions=mean_outputs,
full_predictions=full_outputs,
loss=loss,
)
@staticmethod
def _timesfm_moving_average(arr: torch.Tensor, window_size: int) -> list[torch.Tensor]:
"""Calculates the moving average using PyTorch's convolution function."""
# Pad with zeros to handle initial window positions
arr_padded = F.pad(arr, (window_size - 1, 0), "constant", 0)
# Create a convolution kernel
kernel = torch.ones(window_size, dtype=arr.dtype, device=arr.device) / window_size
# Apply convolution to calculate the moving average
smoothed_arr = F.conv1d(arr_padded.view(1, 1, -1), kernel.view(1, 1, -1)).squeeze()
return [smoothed_arr, arr - smoothed_arr]
__all__ = ["TimesFmModelForPrediction", "TimesFmPreTrainedModel", "TimesFmModel"]
| TimesFmModelForPrediction |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 69318,
"end": 75897
} | class ____(_fixtures.FixtureTest):
"""Test explicit relationships that are backrefs to each other."""
run_inserts = None
def test_o2m(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, back_populates="user")
},
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={
"user": relationship(User, back_populates="addresses")
},
)
sess = fixture_session()
u1 = User(name="u1")
a1 = Address(email_address="foo")
u1.addresses.append(a1)
assert a1.user is u1
sess.add(u1)
sess.flush()
sess.expire_all()
assert sess.query(Address).one() is a1
assert a1.user is u1
assert a1 in u1.addresses
@testing.variation(
"argtype", ["str", "callable_str", "prop", "callable_prop"]
)
def test_o2m_with_callable(self, argtype):
"""test #10050"""
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
if argtype.str:
abp, ubp = "user", "addresses"
elif argtype.callable_str:
abp, ubp = lambda: "user", lambda: "addresses"
elif argtype.prop:
abp, ubp = lambda: "user", lambda: "addresses"
elif argtype.callable_prop:
abp, ubp = lambda: Address.user, lambda: User.addresses
else:
argtype.fail()
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, back_populates=abp)
},
)
if argtype.prop:
ubp = User.addresses
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={"user": relationship(User, back_populates=ubp)},
)
sess = fixture_session()
u1 = User(name="u1")
a1 = Address(email_address="foo")
u1.addresses.append(a1)
assert a1.user is u1
sess.add(u1)
sess.flush()
sess.expire_all()
assert sess.query(Address).one() is a1
assert a1.user is u1
assert a1 in u1.addresses
@testing.variation("argtype", ["plain", "callable"])
def test_invalid_backref_type(self, argtype):
"""test #10050"""
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
if argtype.plain:
abp, ubp = object(), "addresses"
elif argtype.callable:
abp, ubp = lambda: object(), lambda: "addresses"
else:
argtype.fail()
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, back_populates=abp)
},
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={"user": relationship(User, back_populates=ubp)},
)
with expect_raises_message(
exc.ArgumentError, r"Invalid back_populates value: <object"
):
self.mapper_registry.configure()
def test_invalid_key(self):
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.addresses,
self.classes.User,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, back_populates="userr")
},
)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={
"user": relationship(User, back_populates="addresses")
},
)
assert_raises(sa.exc.InvalidRequestError, configure_mappers)
def test_invalid_target(self):
addresses, Dingaling, User, dingalings, Address, users = (
self.tables.addresses,
self.classes.Dingaling,
self.classes.User,
self.tables.dingalings,
self.classes.Address,
self.tables.users,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, back_populates="dingaling")
},
)
self.mapper_registry.map_imperatively(Dingaling, dingalings)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={"dingaling": relationship(Dingaling)},
)
assert_raises_message(
sa.exc.ArgumentError,
r"reverse_property 'dingaling' on relationship "
r"User.addresses references "
r"relationship Address.dingaling, "
r"which does not "
r"reference mapper Mapper\[User\(users\)\]",
configure_mappers,
)
def test_back_propagates_not_relationship(self):
addr, Addr, users, User = (
self.tables.addresses,
self.classes.Address,
self.tables.users,
self.classes.User,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Addr, back_populates="user_id")
},
)
self.mapper_registry.map_imperatively(
Addr,
addr,
properties={
"users": relationship(User, back_populates="addresses")
},
)
assert_raises_message(
sa.exc.InvalidRequestError,
"back_populates on relationship 'User.addresses' refers to "
"attribute 'Address.user_id' that is not a relationship. "
"The back_populates parameter should refer to the name of "
"a relationship on the target class.",
configure_mappers,
)
| ManualBackrefTest |
python | lazyprogrammer__machine_learning_examples | unsupervised_class3/vae_tf.py | {
"start": 755,
"end": 1090
} | class ____(object):
def __init__(self, M1, M2, f=tf.nn.relu):
# self.M1 = M1
# self.M2 = M2
self.W = tf.Variable(tf.random_normal(shape=(M1, M2)) * 2 / np.sqrt(M1))
self.b = tf.Variable(np.zeros(M2).astype(np.float32))
self.f = f
def forward(self, X):
return self.f(tf.matmul(X, self.W) + self.b)
| DenseLayer |
python | lxml__lxml | src/lxml/cssselect.py | {
"start": 684,
"end": 1444
} | class ____(external_cssselect.GenericTranslator):
"""
A custom CSS selector to XPath translator with lxml-specific extensions.
"""
def xpath_contains_function(self, xpath, function):
# Defined there, removed in later drafts:
# http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#content-selectors
if function.argument_types() not in (['STRING'], ['IDENT']):
raise ExpressionError(
"Expected a single string or ident for :contains(), got %r"
% function.arguments)
value = function.arguments[0].value
return xpath.add_condition(
'contains(__lxml_internal_css:lower-case(string(.)), %s)'
% self.xpath_literal(value.lower()))
| LxmlTranslator |
python | django__django | tests/test_client_regress/tests.py | {
"start": 32006,
"end": 32819
} | class ____(SimpleTestCase):
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(os.path.dirname(__file__), "bad_templates")],
}
]
)
def test_bad_404_template(self):
"Errors found when rendering 404 error templates are re-raised"
with self.assertRaises(TemplateSyntaxError):
self.client.get("/no_such_view/")
# We need two different tests to check URLconf substitution - one to check it
# was changed, and another one (without self.urls) to check it was reverted on
# teardown. This pair of tests relies upon the alphabetical ordering of test
# execution.
@override_settings(ROOT_URLCONF="test_client_regress.urls")
| TemplateExceptionTests |
python | doocs__leetcode | solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/Solution.py | {
"start": 0,
"end": 369
} | class ____:
def subsequenceSumOr(self, nums: List[int]) -> int:
cnt = [0] * 64
ans = 0
for v in nums:
for i in range(31):
if (v >> i) & 1:
cnt[i] += 1
for i in range(63):
if cnt[i]:
ans |= 1 << i
cnt[i + 1] += cnt[i] // 2
return ans
| Solution |
python | pypa__pipenv | pipenv/vendor/click/types.py | {
"start": 20103,
"end": 20650
} | class ____(ParamType):
name = "uuid"
def convert(
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
) -> t.Any:
import uuid
if isinstance(value, uuid.UUID):
return value
value = value.strip()
try:
return uuid.UUID(value)
except ValueError:
self.fail(
_("{value!r} is not a valid UUID.").format(value=value), param, ctx
)
def __repr__(self) -> str:
return "UUID"
| UUIDParameterType |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 15707,
"end": 17251
} | class ____(SimpleShuffle):
"""Disk-based shuffle implementation"""
@staticmethod
def _shuffle_group(df, col, _filter, p):
with ensure_cleanup_on_exception(p):
g = df.groupby(col)
d = {i: g.get_group(i) for i in g.groups if i in _filter}
p.append(d, fsync=True)
def _layer(self):
from dask.dataframe.dispatch import partd_encode_dispatch
column = self.partitioning_index
df = self.frame
always_new_token = uuid.uuid1().hex
p = (f"zpartd-{always_new_token}",)
encode_cls = partd_encode_dispatch(df._meta)
dsk1 = {p: (maybe_buffered_partd(encode_cls=encode_cls),)}
# Partition data on disk
name = f"shuffle-partition-{always_new_token}"
dsk2 = {
(name, i): (self._shuffle_group, key, column, self._partitions, p)
for i, key in enumerate(df.__dask_keys__())
}
# Barrier
barrier_token = (f"barrier-{always_new_token}",)
dsk3 = {barrier_token: (barrier, list(dsk2))}
# Collect groups
dsk4 = {
(self._name, j): (collect, p, k, df._meta, barrier_token)
for j, k in enumerate(self._partitions)
}
return toolz.merge(dsk1, dsk2, dsk3, dsk4)
def _shuffle_transfer(
input: pd.DataFrame,
id,
input_partition: int,
) -> int:
from distributed.shuffle._shuffle import shuffle_transfer
return shuffle_transfer(
input,
id,
input_partition,
)
| DiskShuffle |
python | gevent__gevent | src/gevent/tests/test__socket_dns6.py | {
"start": 3462,
"end": 3716
} | class ____(Test6):
# host that has both A and AAAA records
host = 'ds.test-ipv6.com'
_normalize_result_gethostbyname = Test6._normalize_result_gethostbyaddr
add(Test6_ds, Test6_ds.host)
if __name__ == '__main__':
greentest.main()
| Test6_ds |
python | Textualize__textual | examples/merlin.py | {
"start": 2283,
"end": 4694
} | class ____(App):
"""A simple reproduction of one game on the Merlin hand held console."""
CSS = """
Screen {
align: center middle;
}
Screen.-win {
background: transparent;
}
Screen.-win Timer {
color: $success;
}
Grid {
width: auto;
height: auto;
border: thick $border;
padding: 1 2;
grid-size: 3 3;
grid-rows: auto;
grid-columns: auto;
grid-gutter: 1 1;
background: $surface;
}
"""
def render(self) -> LinearGradient:
"""Renders a gradient, when the background is transparent."""
stops = [(i / (len(COLORS) - 1), c) for i, c in enumerate(COLORS)]
return LinearGradient(30.0, stops)
def compose(self) -> ComposeResult:
"""Compose a timer, and a grid of 9 switches."""
yield Timer()
with Grid():
for switch in (7, 8, 9, 4, 5, 6, 1, 2, 3):
yield LabelSwitch(switch)
def on_mount(self) -> None:
"""Randomize the switches on mount."""
for switch_no in range(1, 10):
if random.randint(0, 1):
self.query_one(f"#switch-{switch_no}", Switch).toggle()
def check_win(self) -> bool:
"""Check for a win."""
on_switches = {
int(switch.name or "0") for switch in self.query(Switch) if switch.value
}
return on_switches == {1, 2, 3, 4, 6, 7, 8, 9}
def on_switch_changed(self, event: Switch.Changed) -> None:
"""Called when a switch is toggled."""
# The switch that was pressed
switch_no = int(event.switch.name or "0")
# Also toggle corresponding switches
with self.prevent(Switch.Changed):
for toggle_no in TOGGLES[switch_no]:
self.query_one(f"#switch-{toggle_no}", Switch).toggle()
# Check the win
if self.check_win():
self.screen.add_class("-win")
self.query_one(Timer).running = False
self.notify("You win!", title="congratulations", severity="information")
def on_key(self, event: events.Key) -> None:
"""Maps switches to keys, so we can use the keyboard as well."""
if event.character and event.character.isdigit():
self.query_one(f"#switch-{event.character}", Switch).toggle()
if __name__ == "__main__":
MerlinApp().run()
| MerlinApp |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py | {
"start": 120,
"end": 160
} | class ____(
#
object,
):
...
| A |
python | django__django | django/views/generic/detail.py | {
"start": 3664,
"end": 4029
} | class ____(SingleObjectMixin, View):
"""
Base view for displaying a single object.
This requires subclassing to provide a response mixin.
"""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
| BaseDetailView |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_on_duplicate.py | {
"start": 471,
"end": 8188
} | class ____(fixtures.TablesTest):
__only_on__ = ("mysql", "mariadb")
__backend__ = True
run_define_tables = "each"
@classmethod
def define_tables(cls, metadata):
Table(
"foos",
metadata,
Column("id", Integer, primary_key=True, autoincrement=True),
Column("bar", String(10)),
Column("baz", String(10)),
Column("updated_once", Boolean, default=False),
)
def test_bad_args(self):
assert_raises(
ValueError,
insert(self.tables.foos).values({}).on_duplicate_key_update,
)
assert_raises(
exc.ArgumentError,
insert(self.tables.foos).values({}).on_duplicate_key_update,
{"id": 1, "bar": "b"},
id=1,
bar="b",
)
assert_raises(
exc.ArgumentError,
insert(self.tables.foos).values({}).on_duplicate_key_update,
{"id": 1, "bar": "b"},
{"id": 2, "bar": "baz"},
)
def test_on_duplicate_key_update_multirow(self, connection):
foos = self.tables.foos
conn = connection
conn.execute(insert(foos).values(dict(id=1, bar="b", baz="bz")))
stmt = insert(foos).values([dict(id=1, bar="ab"), dict(id=2, bar="b")])
stmt = stmt.on_duplicate_key_update(bar=stmt.inserted.bar)
result = conn.execute(stmt)
# multirow, so its ambiguous. this is a behavioral change
# in 1.4
eq_(result.inserted_primary_key, (None,))
eq_(
conn.execute(foos.select().where(foos.c.id == 1)).fetchall(),
[(1, "ab", "bz", False)],
)
def test_on_duplicate_key_from_select(self, connection):
foos = self.tables.foos
conn = connection
conn.execute(insert(foos).values(dict(id=1, bar="b", baz="bz")))
stmt = insert(foos).from_select(
["id", "bar", "baz"],
select(foos.c.id, literal("bar2"), literal("baz2")),
)
stmt = stmt.on_duplicate_key_update(bar=stmt.inserted.bar)
conn.execute(stmt)
eq_(
conn.execute(foos.select().where(foos.c.id == 1)).fetchall(),
[(1, "bar2", "bz", False)],
)
def test_on_duplicate_key_update_singlerow(self, connection):
foos = self.tables.foos
conn = connection
conn.execute(insert(foos).values(dict(id=1, bar="b", baz="bz")))
stmt = insert(foos).values(dict(id=2, bar="b"))
stmt = stmt.on_duplicate_key_update(bar=stmt.inserted.bar)
result = conn.execute(stmt)
# only one row in the INSERT so we do inserted_primary_key
eq_(result.inserted_primary_key, (2,))
eq_(
conn.execute(foos.select().where(foos.c.id == 1)).fetchall(),
[(1, "b", "bz", False)],
)
def test_on_duplicate_key_update_null_multirow(self, connection):
foos = self.tables.foos
conn = connection
conn.execute(insert(foos).values(dict(id=1, bar="b", baz="bz")))
stmt = insert(foos).values([dict(id=1, bar="ab"), dict(id=2, bar="b")])
stmt = stmt.on_duplicate_key_update(updated_once=None)
result = conn.execute(stmt)
# ambiguous
eq_(result.inserted_primary_key, (None,))
eq_(
conn.execute(foos.select().where(foos.c.id == 1)).fetchall(),
[(1, "b", "bz", None)],
)
def test_on_duplicate_key_update_expression_multirow(self, connection):
foos = self.tables.foos
conn = connection
conn.execute(insert(foos).values(dict(id=1, bar="b", baz="bz")))
stmt = insert(foos).values([dict(id=1, bar="ab"), dict(id=2, bar="b")])
stmt = stmt.on_duplicate_key_update(
bar=func.concat(stmt.inserted.bar, "_foo"),
baz=func.concat(stmt.inserted.bar, "_", foos.c.baz),
)
result = conn.execute(stmt)
eq_(result.inserted_primary_key, (None,))
eq_(
conn.execute(foos.select()).fetchall(),
[
# first entry triggers ON DUPLICATE
(1, "ab_foo", "ab_bz", False),
# second entry must be an insert
(2, "b", None, False),
],
)
def test_on_duplicate_key_update_preserve_order(self, connection):
foos = self.tables.foos
conn = connection
conn.execute(
insert(foos).values(
[
dict(id=1, bar="b", baz="bz"),
dict(id=2, bar="b", baz="bz2"),
],
)
)
stmt = insert(foos)
update_condition = foos.c.updated_once == False
# The following statements show importance of the columns update
# ordering as old values being referenced in UPDATE clause are
# getting replaced one by one from left to right with their new
# values.
stmt1 = stmt.on_duplicate_key_update(
[
(
"bar",
func.if_(
update_condition,
func.values(foos.c.bar),
foos.c.bar,
),
),
(
"updated_once",
func.if_(update_condition, True, foos.c.updated_once),
),
]
)
stmt2 = stmt.on_duplicate_key_update(
[
(
"updated_once",
func.if_(update_condition, True, foos.c.updated_once),
),
(
"bar",
func.if_(
update_condition,
func.values(foos.c.bar),
foos.c.bar,
),
),
]
)
# First statement should succeed updating column bar
conn.execute(stmt1, dict(id=1, bar="ab"))
eq_(
conn.execute(foos.select().where(foos.c.id == 1)).fetchall(),
[(1, "ab", "bz", True)],
)
# Second statement will do noop update of column bar
conn.execute(stmt2, dict(id=2, bar="ab"))
eq_(
conn.execute(foos.select().where(foos.c.id == 2)).fetchall(),
[(2, "b", "bz2", True)],
)
def test_last_inserted_id(self, connection):
foos = self.tables.foos
conn = connection
stmt = insert(foos).values({"bar": "b", "baz": "bz"})
result = conn.execute(
stmt.on_duplicate_key_update(bar=stmt.inserted.bar, baz="newbz")
)
eq_(result.inserted_primary_key, (1,))
stmt = insert(foos).values({"id": 1, "bar": "b", "baz": "bz"})
result = conn.execute(
stmt.on_duplicate_key_update(bar=stmt.inserted.bar, baz="newbz")
)
eq_(result.inserted_primary_key, (1,))
def test_bound_caching(self, connection):
foos = self.tables.foos
connection.execute(insert(foos).values(dict(id=1, bar="b", baz="bz")))
for scenario in [
(random.choice(["c", "d", "e"]), random.choice(["f", "g", "h"]))
for i in range(10)
]:
stmt = insert(foos).values(dict(id=1, bar="q"))
stmt = stmt.on_duplicate_key_update(
bar=scenario[0], baz=scenario[1]
)
connection.execute(stmt)
eq_(
connection.execute(
foos.select().where(foos.c.id == 1)
).fetchall(),
[(1, scenario[0], scenario[1], False)],
)
| OnDuplicateTest |
python | modin-project__modin | modin/utils.py | {
"start": 31164,
"end": 32039
} | class ____(Exception):
"""An exception that allows us defaults to pandas if any assumption fails."""
pass
def _maybe_warn_on_default(message: str = "", *, reason: str = "") -> None:
"""
Raise a warning on an operation that defaults to pandas if necessary.
This checks the query compiler used by the current configured active backend, and prints
a warning message about defaulting to pandas if needed.
Parameters
----------
message : str, default: ""
The message to show.
reason : str, default: ""
The reason for defaulting.
"""
# Avoids a module-level circular import
from modin.core.execution.dispatching.factories.dispatcher import FactoryDispatcher
FactoryDispatcher.get_factory().io_cls.query_compiler_cls._maybe_warn_on_default(
message=message, reason=reason
)
| ModinAssumptionError |
python | viewflow__viewflow | viewflow/jsonstore.py | {
"start": 7459,
"end": 7519
} | class ____(JSONFieldMixin, fields.URLField):
pass
| URLField |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 69925,
"end": 73785
} | class ____(Function):
"""
To prevent PyTorch from performing the usual backpropagation, a customized backward function is implemented here.
This way it is made sure that no memory expensive activations are saved during the forward pass. This function is
heavily inspired by https://github.com/lucidrains/reformer-pytorch/blob/master/reformer_pytorch/reversible.py
"""
@staticmethod
def forward(
ctx,
hidden_states,
layers,
attention_mask,
num_hashes,
all_hidden_states,
all_attentions,
past_buckets_states,
use_cache,
orig_sequence_length,
output_hidden_states,
output_attentions,
):
all_buckets = ()
# split duplicated tensor
hidden_states, attn_output = torch.chunk(hidden_states, 2, dim=-1)
for layer in layers:
if output_hidden_states is True:
all_hidden_states.append(hidden_states)
layer_outputs = layer(
prev_attn_output=attn_output,
hidden_states=hidden_states,
attention_mask=attention_mask,
num_hashes=num_hashes,
past_buckets_states=past_buckets_states,
use_cache=use_cache,
orig_sequence_length=orig_sequence_length,
output_attentions=output_attentions,
)
attn_output = layer_outputs.attn_output
hidden_states = layer_outputs.hidden_states
all_buckets = all_buckets + (layer_outputs.buckets,)
if output_attentions:
all_attentions.append(layer_outputs.attention_probs)
# Add last layer
if output_hidden_states is True:
all_hidden_states.append(hidden_states)
# attach params to ctx for backward
ctx.save_for_backward(attn_output.detach(), hidden_states.detach())
ctx.layers = layers
ctx.all_buckets = all_buckets
ctx.attention_mask = attention_mask
# Concatenate 2 RevNet outputs
return torch.cat([attn_output, hidden_states], dim=-1)
@staticmethod
def backward(ctx, grad_hidden_states):
grad_attn_output, grad_hidden_states = torch.chunk(grad_hidden_states, 2, dim=-1)
# retrieve params from ctx for backward
attn_output, hidden_states = ctx.saved_tensors
# create tuple
output = ReformerBackwardOutput(
attn_output=attn_output,
hidden_states=hidden_states,
grad_attn_output=grad_attn_output,
grad_hidden_states=grad_hidden_states,
)
# free memory
del grad_attn_output, grad_hidden_states, attn_output, hidden_states
layers = ctx.layers
all_buckets = ctx.all_buckets
attention_mask = ctx.attention_mask
for idx, layer in enumerate(layers[::-1]):
# pop last buckets from stack
buckets = all_buckets[-1]
all_buckets = all_buckets[:-1]
# backprop
output = layer.backward_pass(
next_attn_output=output.attn_output,
hidden_states=output.hidden_states,
grad_attn_output=output.grad_attn_output,
grad_hidden_states=output.grad_hidden_states,
attention_mask=attention_mask,
buckets=buckets,
)
assert all_buckets == (), "buckets have to be empty after backpropagation"
grad_hidden_states = torch.cat([output.grad_attn_output, output.grad_hidden_states], dim=-1)
# num of return vars has to match num of forward() args
# return gradient for hidden_states arg and None for other args
return grad_hidden_states, None, None, None, None, None, None, None, None, None, None, None
| _ReversibleFunction |
python | ansible__ansible | lib/ansible/_internal/_datatag/_tags.py | {
"start": 4599,
"end": 4907
} | class ____(AnsibleSingletonTagBase):
"""
Indicates the tagged string is trusted to parse and render as a template.
Do *NOT* apply this tag to data from untrusted sources, as this would allow code injection during templating.
"""
@dataclasses.dataclass(**_tag_dataclass_kwargs)
| TrustedAsTemplate |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 4867,
"end": 6420
} | class ____(Converter):
def converted(self) -> Tokenizer:
vocab = self.original_tokenizer.vocab
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
tokenize_chinese_chars = False
strip_accents = False
do_lower_case = False
if hasattr(self.original_tokenizer, "basic_tokenizer"):
tokenize_chinese_chars = self.original_tokenizer.basic_tokenizer.tokenize_chinese_chars
strip_accents = self.original_tokenizer.basic_tokenizer.strip_accents
do_lower_case = self.original_tokenizer.basic_tokenizer.do_lower_case
tokenizer.normalizer = normalizers.BertNormalizer(
clean_text=True,
handle_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
lowercase=do_lower_case,
)
tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
cls = str(self.original_tokenizer.cls_token)
sep = str(self.original_tokenizer.sep_token)
cls_token_id = self.original_tokenizer.cls_token_id
sep_token_id = self.original_tokenizer.sep_token_id
tokenizer.post_processor = processors.TemplateProcessing(
single=f"{cls}:0 $A:0 {sep}:0",
pair=f"{cls}:0 $A:0 {sep}:0 $B:1 {sep}:1",
special_tokens=[
(cls, cls_token_id),
(sep, sep_token_id),
],
)
tokenizer.decoder = decoders.WordPiece(prefix="##")
return tokenizer
| BertConverter |
python | kamyu104__LeetCode-Solutions | Python/count-elements-with-strictly-smaller-and-greater-elements.py | {
"start": 36,
"end": 261
} | class ____(object):
def countElements(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
mn = min(nums)
mx = max(nums)
return sum(mn < x < mx for x in nums)
| Solution |
python | rapidsai__cudf | python/cudf/cudf/pandas/_benchmarks/utils.py | {
"start": 1061,
"end": 1217
} | class ____:
"""Information about the commit of the software used to run the query."""
version: str
commit: str
@dataclasses.dataclass
| VersionInfo |
python | tensorflow__tensorflow | tensorflow/compiler/tests/approx_topk_test.py | {
"start": 1223,
"end": 9417
} | class ____(test.TestCase, parameterized.TestCase):
def setUp(self):
test.TestCase.setUp(self)
self._rng = np.random.default_rng(42)
def compute_recall(self, result_neighbors, ground_truth_neighbors):
"""Computes the recall of an approximate nearest neighbor search.
Args:
result_neighbors: int32 numpy array of the shape [num_queries,
neighbors_per_query] where the values are the indices of the dataset.
ground_truth_neighbors: int32 numpy array of with shape [num_queries,
ground_truth_neighbors_per_query] where the values are the indices of
the dataset.
Returns:
The recall.
"""
self.assertLen(result_neighbors.shape, 2)
self.assertLen(ground_truth_neighbors.shape, 2)
self.assertEqual(result_neighbors.shape[0], ground_truth_neighbors.shape[0])
gt_sets = [set(np.asarray(x)) for x in ground_truth_neighbors]
def hits_per_q(q, nn_per_q):
return len(list(x for x in nn_per_q if x.item() in gt_sets[q]))
hits = sum(
hits_per_q(q, nn_per_q) for q, nn_per_q in enumerate(result_neighbors))
return hits / ground_truth_neighbors.size
@parameterized.parameters(
itertools.product(
[1, 10], # k
[100, 500], # row_size
[1, 10, 128], # num_rows
[True, False], # aggregate_to_topk
))
def test_non_fused_max_k(self, k, row_size, num_rows, aggregate_to_topk):
row = np.arange(row_size, dtype=np.float32)
db = np.stack(list(self._rng.permutation(row) for _ in range(num_rows)))
@function(jit_compile=True)
def ann(db, k):
return nn_ops.approx_max_k(db, k, aggregate_to_topk=aggregate_to_topk)
with ops.device('/device:TPU:0'):
db_op = variables.Variable(db)
result = ann(db_op, k)[1]
gt = np.argsort(-db)[:, :k]
ann_recall = self.compute_recall(result.numpy(), gt)
self.assertGreaterEqual(ann_recall, 0.95)
@parameterized.parameters(
itertools.product(
[1, 10], # k
[100, 500], # row_size
[1, 10, 128], # num_rows
[True, False], # aggregate_to_topk
))
def test_non_fused_min_k(self, k, row_size, num_rows, aggregate_to_topk):
# Use the new rng api
row = np.arange(row_size, dtype=np.float32)
db = np.stack(list(self._rng.permutation(row) for _ in range(num_rows)))
@function(jit_compile=True)
def ann(db, k=10):
return nn_ops.approx_min_k(db, k, aggregate_to_topk=aggregate_to_topk)
with ops.device('/device:TPU:0'):
db_op = variables.Variable(db)
result = ann(db_op, k)[1]
gt = np.argsort(db)[:, :k]
ann_recall = self.compute_recall(result.numpy(), gt)
self.assertGreaterEqual(ann_recall, 0.95)
@parameterized.parameters(
itertools.product(
[1, 10], # k
[100, 500], # db_size
[1, 10, 128], # qy_size
[2, 32], # feature dim
))
# MIPS = Maximal Inner Product Search
def test_mips(self, k, db_size, qy_size, feature_dim):
qy = self._rng.random([qy_size, feature_dim], dtype=np.float32)
db = self._rng.random([db_size, feature_dim], dtype=np.float32)
@function(jit_compile=True)
def ann(qy, db, k):
scores = math_ops.matmul(qy, db, transpose_b=True)
return nn_ops.approx_max_k(scores, k)
with ops.device('/device:TPU:0'):
qy_op = variables.Variable(qy)
db_op = variables.Variable(db)
result = ann(qy_op, db_op, k)[1]
scores = -math_ops.matmul(qy_op, db_op, transpose_b=True)
gt = np.argsort(scores.numpy())[:, :k]
ann_recall = self.compute_recall(result.numpy(), gt)
self.assertGreaterEqual(ann_recall, 0.95)
@parameterized.parameters(
itertools.product(
[1, 10], # k
[100, 500], # db_size
[10, 128], # qy_size
[2, 8], # feature dim
))
# L2ANN = Approximate Nearest Neighbor search in the L2 metric space
def test_l2ann(self, k, db_size, qy_size, feature_dim):
qy = self._rng.random([qy_size, feature_dim], dtype=np.float32)
db = self._rng.random([db_size, feature_dim], dtype=np.float32)
db_half_norm_sq = np.linalg.norm(db, axis=1)**2 / 2
@function(jit_compile=True)
def ann(qy, db, db_half_norm_sq, k):
scores = db_half_norm_sq - math_ops.matmul(qy, db, transpose_b=True)
return nn_ops.approx_min_k(scores, k)
with ops.device('/device:TPU:0'):
qy_op = variables.Variable(qy)
db_op = variables.Variable(db)
db_half_norm_sq_op = variables.Variable(db_half_norm_sq)
result = ann(qy_op, db_op, db_half_norm_sq_op, k)[1]
scores = db_half_norm_sq_op - math_ops.matmul(
qy_op, db_op, transpose_b=True)
gt = np.argsort(scores.numpy())[:, :k]
ann_recall = self.compute_recall(result.numpy(), gt)
self.assertGreaterEqual(ann_recall, 0.95)
def test_highdim(self):
db = self._rng.random([2, 10, 200, 3], dtype=np.float32)
k = 5
@function(jit_compile=True)
def ann(db, k):
return nn_ops.approx_min_k(db, k=k, reduction_dimension=2)
with ops.device('/device:TPU:0'):
db_op = variables.Variable(db)
result = ann(db_op, k)[1]
gt = np.argsort(db, axis=2)[:, :, :k, :]
flat_idx = np.reshape(
np.transpose(result.numpy(), [0, 1, 3, 2]), [2 * 10 * 3, k])
flat_gt = np.reshape(np.transpose(gt, [0, 1, 3, 2]), [2 * 10 * 3, k])
ann_recall = self.compute_recall(flat_idx, flat_gt)
self.assertGreaterEqual(ann_recall, 0.95)
@parameterized.parameters(
itertools.product(
[dtypes.bfloat16, dtypes.float16, dtypes.float32],
[1, 10], # k
[100, 500], # row_size
[1, 10, 128], # num_rows
))
def test_gradients(self, dtype, k, row_size, num_rows):
row = np.arange(row_size, dtype=np.float32)
db = np.stack(list(self._rng.permutation(row) for _ in range(num_rows)))
out_grads = self._rng.random([num_rows, k])
@function(jit_compile=True)
def ann_with_grads(db, out_grads):
with backprop.GradientTape() as tape:
val, idx = nn_ops.approx_max_k(db, k)
result_in_grads = tape.gradient(val, db, out_grads)
lifted_k_idx = array_ops.reshape(idx, [num_rows, k, 1])
iota_idx = array_ops.broadcast_to(
array_ops.reshape(math_ops.range(num_rows), [num_rows, 1, 1]),
[num_rows, k, 1])
lifted_idx = array_ops.concat([iota_idx, lifted_k_idx], axis=2)
k_idx_s = array_ops.reshape(lifted_idx, [num_rows * k, 2])
k_gra_s = array_ops.reshape(out_grads, [num_rows * k])
expected_in_grads = array_ops.scatter_nd(k_idx_s, k_gra_s,
[num_rows, row_size])
return [expected_in_grads, result_in_grads]
with ops.device('/device:TPU:0'):
db_op = variables.Variable(db, dtype=dtype)
out_grads_op = variables.Variable(out_grads, dtype=dtype)
expected_in_grads, result_in_grads = ann_with_grads(db_op, out_grads_op)
self.assertAllClose(expected_in_grads, result_in_grads)
# Tests that multiple ops are supported and the comparison functions are
# renamed properly to avoid conflict while using the MLIR bridge.
def test_multiple_ops(self):
k = 1
row_size = 100
num_rows = 10
row = np.arange(row_size, dtype=np.float32)
db1 = np.stack(list(self._rng.permutation(row) for _ in range(num_rows)))
db2 = np.stack(list(self._rng.permutation(row) for _ in range(num_rows)))
@function(jit_compile=True)
def ann(db1, db2):
result1 = nn_ops.approx_max_k(db1, k, aggregate_to_topk=True)
result2 = nn_ops.approx_max_k(db2, k, aggregate_to_topk=True)
return (result1, result2)
with ops.device('/device:TPU:0'):
db1_op = variables.Variable(db1)
db2_op = variables.Variable(db2)
result1, result2 = ann(db1_op, db2_op)
gt = np.argsort(-db1)[:, :k]
ann_recall = self.compute_recall(result1[1].numpy(), gt)
self.assertGreaterEqual(ann_recall, 0.95)
gt = np.argsort(-db2)[:, :k]
ann_recall = self.compute_recall(result2[1].numpy(), gt)
self.assertGreaterEqual(ann_recall, 0.95)
if __name__ == '__main__':
test.main()
| ApproxTopkTest |
python | huggingface__transformers | src/transformers/models/moonshine/modular_moonshine.py | {
"start": 35624,
"end": 40705
} | class ____(MoonshinePreTrainedModel, GenerationMixin):
_tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
def __init__(self, config: MoonshineConfig):
super().__init__(config)
self.model = MoonshineModel(config)
self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.proj_out
def set_output_embeddings(self, new_embeddings):
self.proj_out = new_embeddings
def get_input_embeddings(self) -> nn.Module:
return self.model.get_input_embeddings()
@can_return_tuple
@auto_docstring
def forward(
self,
input_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
past_key_values: Optional[EncoderDecoderCache] = None,
decoder_inputs_embeds: Optional[tuple[torch.FloatTensor]] = None,
decoder_position_ids: Optional[tuple[torch.LongTensor]] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
labels: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Seq2SeqLMOutput:
r"""
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
Float values of the raw speech waveform. Raw speech waveform can be
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
the soundfile library (`pip install soundfile`). To prepare the array into
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
and conversion into a tensor of type `torch.FloatTensor`.
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
Indices of positions of each input sequence tokens in the position embeddings.
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
Example:
```python
>>> import torch
>>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
>>> from datasets import load_dataset
>>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
>>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_values = inputs.input_values
>>> generated_ids = model.generate(input_values, max_new_tokens=100)
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> transcription
'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
```"""
if labels is not None:
if decoder_input_ids is None and decoder_inputs_embeds is None:
decoder_input_ids = shift_tokens_right(
labels, self.config.pad_token_id, self.config.decoder_start_token_id
)
outputs: Seq2SeqModelOutput = self.model(
input_values,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
encoder_outputs=encoder_outputs,
decoder_attention_mask=decoder_attention_mask,
past_key_values=past_key_values,
decoder_inputs_embeds=decoder_inputs_embeds,
decoder_position_ids=decoder_position_ids,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
logits = self.proj_out(outputs.last_hidden_state)
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
return Seq2SeqLMOutput(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
cross_attentions=outputs.cross_attentions,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
encoder_hidden_states=outputs.encoder_hidden_states,
encoder_attentions=outputs.encoder_attentions,
)
__all__ = [
"MoonshineConfig",
"MoonshineModel",
"MoonshinePreTrainedModel",
"MoonshineForConditionalGeneration",
]
| MoonshineForConditionalGeneration |
python | pydata__xarray | xarray/namedarray/_aggregations.py | {
"start": 327,
"end": 30195
} | class ____:
__slots__ = ()
def reduce(
self,
func: Callable[..., Any],
dim: Dims = None,
*,
axis: int | Sequence[int] | None = None,
keepdims: bool = False,
**kwargs: Any,
) -> Self:
raise NotImplementedError()
def count(
self,
dim: Dims = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``count`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``count``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``count`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``count`` applied to its data and the
indicated dimension(s) removed
See Also
--------
pandas.DataFrame.count
dask.dataframe.DataFrame.count
Dataset.count
DataArray.count
:ref:`agg`
User guide on reduction or aggregation operations.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.count()
<xarray.NamedArray ()> Size: 8B
array(5)
"""
return self.reduce(
duck_array_ops.count,
dim=dim,
**kwargs,
)
def all(
self,
dim: Dims = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``all`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``all``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``all`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``all`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.all
dask.array.all
Dataset.all
DataArray.all
:ref:`agg`
User guide on reduction or aggregation operations.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray(
... "x", np.array([True, True, True, True, True, False], dtype=bool)
... )
>>> na
<xarray.NamedArray (x: 6)> Size: 6B
array([ True, True, True, True, True, False])
>>> na.all()
<xarray.NamedArray ()> Size: 1B
array(False)
"""
return self.reduce(
duck_array_ops.array_all,
dim=dim,
**kwargs,
)
def any(
self,
dim: Dims = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``any`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``any``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``any`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``any`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.any
dask.array.any
Dataset.any
DataArray.any
:ref:`agg`
User guide on reduction or aggregation operations.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray(
... "x", np.array([True, True, True, True, True, False], dtype=bool)
... )
>>> na
<xarray.NamedArray (x: 6)> Size: 6B
array([ True, True, True, True, True, False])
>>> na.any()
<xarray.NamedArray ()> Size: 1B
array(True)
"""
return self.reduce(
duck_array_ops.array_any,
dim=dim,
**kwargs,
)
def max(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``max`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``max``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``max`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``max`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.max
dask.array.max
Dataset.max
DataArray.max
:ref:`agg`
User guide on reduction or aggregation operations.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.max()
<xarray.NamedArray ()> Size: 8B
array(3.)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.max(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
"""
return self.reduce(
duck_array_ops.max,
dim=dim,
skipna=skipna,
**kwargs,
)
def min(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``min`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``min``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``min`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``min`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.min
dask.array.min
Dataset.min
DataArray.min
:ref:`agg`
User guide on reduction or aggregation operations.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.min()
<xarray.NamedArray ()> Size: 8B
array(0.)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.min(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
"""
return self.reduce(
duck_array_ops.min,
dim=dim,
skipna=skipna,
**kwargs,
)
def mean(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``mean`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``mean``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``mean`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``mean`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.mean
dask.array.mean
Dataset.mean
DataArray.mean
:ref:`agg`
User guide on reduction or aggregation operations.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.mean()
<xarray.NamedArray ()> Size: 8B
array(1.6)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.mean(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
"""
return self.reduce(
duck_array_ops.mean,
dim=dim,
skipna=skipna,
**kwargs,
)
def prod(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
min_count: int | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``prod`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``prod``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
min_count : int or None, optional
The required number of valid values to perform the operation. If
fewer than min_count non-NA values are present the result will be
NA. Only used if skipna is set to True or defaults to True for the
array's dtype. Changed in version 0.17.0: if specified on an integer
array and skipna=True, the result will be a float array.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``prod`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``prod`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.prod
dask.array.prod
Dataset.prod
DataArray.prod
:ref:`agg`
User guide on reduction or aggregation operations.
Notes
-----
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.prod()
<xarray.NamedArray ()> Size: 8B
array(0.)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.prod(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
Specify ``min_count`` for finer control over when NaNs are ignored.
>>> na.prod(skipna=True, min_count=2)
<xarray.NamedArray ()> Size: 8B
array(0.)
"""
return self.reduce(
duck_array_ops.prod,
dim=dim,
skipna=skipna,
min_count=min_count,
**kwargs,
)
def sum(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
min_count: int | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``sum`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``sum``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
min_count : int or None, optional
The required number of valid values to perform the operation. If
fewer than min_count non-NA values are present the result will be
NA. Only used if skipna is set to True or defaults to True for the
array's dtype. Changed in version 0.17.0: if specified on an integer
array and skipna=True, the result will be a float array.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``sum`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``sum`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.sum
dask.array.sum
Dataset.sum
DataArray.sum
:ref:`agg`
User guide on reduction or aggregation operations.
Notes
-----
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.sum()
<xarray.NamedArray ()> Size: 8B
array(8.)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.sum(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
Specify ``min_count`` for finer control over when NaNs are ignored.
>>> na.sum(skipna=True, min_count=2)
<xarray.NamedArray ()> Size: 8B
array(8.)
"""
return self.reduce(
duck_array_ops.sum,
dim=dim,
skipna=skipna,
min_count=min_count,
**kwargs,
)
def std(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
ddof: int = 0,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``std`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``std``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
ddof : int, default: 0
“Delta Degrees of Freedom”: the divisor used in the calculation is ``N - ddof``,
where ``N`` represents the number of elements.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``std`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``std`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.std
dask.array.std
Dataset.std
DataArray.std
:ref:`agg`
User guide on reduction or aggregation operations.
Notes
-----
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.std()
<xarray.NamedArray ()> Size: 8B
array(1.0198039)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.std(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
Specify ``ddof=1`` for an unbiased estimate.
>>> na.std(skipna=True, ddof=1)
<xarray.NamedArray ()> Size: 8B
array(1.14017543)
"""
return self.reduce(
duck_array_ops.std,
dim=dim,
skipna=skipna,
ddof=ddof,
**kwargs,
)
def var(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
ddof: int = 0,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``var`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``var``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
ddof : int, default: 0
“Delta Degrees of Freedom”: the divisor used in the calculation is ``N - ddof``,
where ``N`` represents the number of elements.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``var`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``var`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.var
dask.array.var
Dataset.var
DataArray.var
:ref:`agg`
User guide on reduction or aggregation operations.
Notes
-----
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.var()
<xarray.NamedArray ()> Size: 8B
array(1.04)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.var(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
Specify ``ddof=1`` for an unbiased estimate.
>>> na.var(skipna=True, ddof=1)
<xarray.NamedArray ()> Size: 8B
array(1.3)
"""
return self.reduce(
duck_array_ops.var,
dim=dim,
skipna=skipna,
ddof=ddof,
**kwargs,
)
def median(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``median`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``median``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``median`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``median`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.median
dask.array.median
Dataset.median
DataArray.median
:ref:`agg`
User guide on reduction or aggregation operations.
Notes
-----
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.median()
<xarray.NamedArray ()> Size: 8B
array(2.)
Use ``skipna`` to control whether NaNs are ignored.
>>> na.median(skipna=False)
<xarray.NamedArray ()> Size: 8B
array(nan)
"""
return self.reduce(
duck_array_ops.median,
dim=dim,
skipna=skipna,
**kwargs,
)
def cumsum(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``cumsum`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``cumsum``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``cumsum`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``cumsum`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.cumsum
dask.array.cumsum
Dataset.cumsum
DataArray.cumsum
NamedArray.cumulative
:ref:`agg`
User guide on reduction or aggregation operations.
Notes
-----
Non-numeric variables will be removed prior to reducing.
Note that the methods on the ``cumulative`` method are more performant (with numbagg installed)
and better supported. ``cumsum`` and ``cumprod`` may be deprecated
in the future.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.cumsum()
<xarray.NamedArray (x: 6)> Size: 48B
array([1., 3., 6., 6., 8., 8.])
Use ``skipna`` to control whether NaNs are ignored.
>>> na.cumsum(skipna=False)
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 3., 6., 6., 8., nan])
"""
return self.reduce(
duck_array_ops.cumsum,
dim=dim,
skipna=skipna,
**kwargs,
)
def cumprod(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
**kwargs: Any,
) -> Self:
"""
Reduce this NamedArray's data by applying ``cumprod`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``cumprod``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``cumprod`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : NamedArray
New NamedArray with ``cumprod`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.cumprod
dask.array.cumprod
Dataset.cumprod
DataArray.cumprod
NamedArray.cumulative
:ref:`agg`
User guide on reduction or aggregation operations.
Notes
-----
Non-numeric variables will be removed prior to reducing.
Note that the methods on the ``cumulative`` method are more performant (with numbagg installed)
and better supported. ``cumsum`` and ``cumprod`` may be deprecated
in the future.
Examples
--------
>>> from xarray.namedarray.core import NamedArray
>>> na = NamedArray("x", np.array([1, 2, 3, 0, 2, np.nan]))
>>> na
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
>>> na.cumprod()
<xarray.NamedArray (x: 6)> Size: 48B
array([1., 2., 6., 0., 0., 0.])
Use ``skipna`` to control whether NaNs are ignored.
>>> na.cumprod(skipna=False)
<xarray.NamedArray (x: 6)> Size: 48B
array([ 1., 2., 6., 0., 0., nan])
"""
return self.reduce(
duck_array_ops.cumprod,
dim=dim,
skipna=skipna,
**kwargs,
)
| NamedArrayAggregations |
python | networkx__networkx | networkx/classes/tests/test_graphviews.py | {
"start": 2790,
"end": 4021
} | class ____:
def setup_method(self):
self.G = nx.path_graph(9)
self.dv = nx.to_directed(self.G)
self.MG = nx.path_graph(9, create_using=nx.MultiGraph())
self.Mdv = nx.to_directed(self.MG)
def test_directed(self):
assert not self.G.is_directed()
assert self.dv.is_directed()
def test_already_directed(self):
dd = nx.to_directed(self.dv)
Mdd = nx.to_directed(self.Mdv)
assert edges_equal(dd.edges, self.dv.edges, directed=True)
assert edges_equal(Mdd.edges, self.Mdv.edges, directed=True)
def test_pickle(self):
import pickle
dv = self.dv
pdv = pickle.loads(pickle.dumps(dv, -1))
assert dv._node == pdv._node
assert dv._succ == pdv._succ
assert dv._pred == pdv._pred
assert dv.graph == pdv.graph
def test_contains(self):
assert (2, 3) in self.G.edges
assert (3, 2) in self.G.edges
assert (2, 3) in self.dv.edges
assert (3, 2) in self.dv.edges
def test_iter(self):
revd = [tuple(reversed(e)) for e in self.G.edges]
expected = sorted(list(self.G.edges) + revd)
assert sorted(self.dv.edges) == expected
| TestToDirected |
python | PrefectHQ__prefect | src/prefect/infrastructure/provisioners/ecs.py | {
"start": 17771,
"end": 20540
} | class ____:
def __init__(self, cluster_name: str = "prefect-ecs-cluster"):
self._ecs_client = boto3.client("ecs")
self._cluster_name = cluster_name
self._requires_provisioning = None
async def get_task_count(self) -> int:
"""
Returns the number of tasks that will be executed to provision this resource.
Returns:
int: The number of tasks to be provisioned.
"""
return 1 if await self.requires_provisioning() else 0
async def requires_provisioning(self) -> bool:
"""
Check if this resource requires provisioning.
Returns:
bool: True if provisioning is required, False otherwise.
"""
if self._requires_provisioning is None:
response = await anyio.to_thread.run_sync(
partial(
self._ecs_client.describe_clusters, clusters=[self._cluster_name]
)
)
if response["clusters"] and response["clusters"][0]["status"] == "ACTIVE":
self._requires_provisioning = False
else:
self._requires_provisioning = True
return self._requires_provisioning
async def get_planned_actions(self) -> List[str]:
"""
Returns a description of the planned actions for provisioning this resource.
Returns:
Optional[str]: A description of the planned actions for provisioning the resource,
or None if provisioning is not required.
"""
if await self.requires_provisioning():
return [
"Creating an ECS cluster for running Prefect flows:"
f" [blue]{self._cluster_name}[/]"
]
return []
async def provision(
self,
base_job_template: dict[str, Any],
advance: Callable[[], None],
) -> None:
"""
Provisions an ECS cluster.
Will update the `cluster` variable in the job template to reference the cluster.
Args:
base_job_template: The base job template of the work pool to provision
infrastructure for.
advance: A callback function to indicate progress.
"""
if await self.requires_provisioning():
console = current_console.get()
console.print("Provisioning ECS cluster")
await anyio.to_thread.run_sync(
partial(self._ecs_client.create_cluster, clusterName=self._cluster_name)
)
advance()
base_job_template["variables"]["properties"]["cluster"]["default"] = (
self._cluster_name
)
@property
def next_steps(self) -> list[str]:
return []
| ClusterResource |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/enumerate_test.py | {
"start": 2118,
"end": 3046
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_enumerate_dataset(self, start, stop, options=None):
dataset = dataset_ops.Dataset.range(start, stop).enumerate()
if options:
dataset = dataset.with_options(options)
return dataset
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
checkpoint_test_base.default_test_combinations(),
combinations.combine(symbolic_checkpoint=[False, True])))
def test(self, verify_fn, symbolic_checkpoint):
start = 2
stop = 10
options = options_lib.Options()
options.experimental_symbolic_checkpoint = symbolic_checkpoint
verify_fn(
self, lambda: self._build_enumerate_dataset(
start=start, stop=stop, options=options), stop - start)
if __name__ == "__main__":
test.main()
| EnumerateCheckpointTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/chat_engine/types.py | {
"start": 1357,
"end": 1506
} | class ____(str, Enum):
"""Flag toggling waiting/streaming in `Agent._chat`."""
WAIT = "wait"
STREAM = "stream"
@dataclass
| ChatResponseMode |
python | cython__cython | Cython/Build/Tests/TestIpythonMagic.py | {
"start": 1961,
"end": 9004
} | class ____(CythonTest):
@classmethod
def setUpClass(cls):
CythonTest.setUpClass()
cls._ip = IPython.testing.globalipapp.get_ipython()
def setUp(self):
CythonTest.setUp(self)
self._ip.extension_manager.load_extension('cython')
def test_cython_inline(self):
ip = self._ip
ip.ex('a=10; b=20')
result = ip.run_cell_magic('cython_inline', '', 'return a+b')
self.assertEqual(result, 30)
@skip_win32
def test_cython_pyximport(self):
ip = self._ip
module_name = '_test_cython_pyximport'
ip.run_cell_magic('cython_pyximport', module_name, code)
ip.ex('g = f(10)')
self.assertEqual(ip.user_ns['g'], 20.0)
ip.run_cell_magic('cython_pyximport', module_name, code)
ip.ex('h = f(-10)')
self.assertEqual(ip.user_ns['h'], -20.0)
try:
os.remove(module_name + '.pyx')
except OSError:
pass
def test_cython(self):
ip = self._ip
ip.run_cell_magic('cython', '', code)
ip.ex('g = f(10)')
self.assertEqual(ip.user_ns['g'], 20.0)
def test_cython_name(self):
# The Cython module named 'mymodule' defines the function f.
ip = self._ip
ip.run_cell_magic('cython', '--name=mymodule', code)
# This module can now be imported in the interactive namespace.
ip.ex('import mymodule; g = mymodule.f(10)')
self.assertEqual(ip.user_ns['g'], 20.0)
def test_cython_language_level(self):
# The Cython cell defines the functions f() and call().
ip = self._ip
ip.run_cell_magic('cython', '', cython3_code)
ip.ex('g = f(10); h = call(10)')
self.assertEqual(ip.user_ns['g'], 2.0 / 10.0)
self.assertEqual(ip.user_ns['h'], 2.0 / 10.0)
def test_cython3(self):
# The Cython cell defines the functions f() and call().
ip = self._ip
ip.run_cell_magic('cython', '-3', cython3_code)
ip.ex('g = f(10); h = call(10)')
self.assertEqual(ip.user_ns['g'], 2.0 / 10.0)
self.assertEqual(ip.user_ns['h'], 2.0 / 10.0)
def test_cython2(self):
# The Cython cell defines the functions f() and call().
ip = self._ip
ip.run_cell_magic('cython', '-2', cython3_code)
ip.ex('g = f(10); h = call(10)')
self.assertEqual(ip.user_ns['g'], 2 // 10)
self.assertEqual(ip.user_ns['h'], 2 // 10)
def test_cython_compile_error_shown(self):
ip = self._ip
with capture_output() as out:
ip.run_cell_magic('cython', '-3', compile_error_code)
captured_out, captured_err = out
# it could be that c-level output is captured by distutil-extension
# (and not by us) and is printed to stdout:
captured_all = captured_out + "\n" + captured_err
self.assertTrue("error" in captured_all, msg="error in " + captured_all)
def test_cython_link_error_shown(self):
ip = self._ip
with capture_output() as out:
ip.run_cell_magic('cython', '-3 -l=xxxxxxxx', code)
captured_out, captured_err = out
# it could be that c-level output is captured by distutil-extension
# (and not by us) and is printed to stdout:
captured_all = captured_out + "\n!" + captured_err
self.assertTrue("error" in captured_all, msg="error in " + captured_all)
def test_cython_warning_shown(self):
ip = self._ip
with capture_output() as out:
# force rebuild, otherwise no warning as after the first success
# no build step is performed
ip.run_cell_magic('cython', '-3 -f', compile_warning_code)
captured_out, captured_err = out
# check that warning was printed to stdout even if build hasn't failed
self.assertTrue("CWarning" in captured_out)
@skip_win32
def test_cython3_pgo(self):
# The Cython cell defines the functions f() and call().
ip = self._ip
ip.run_cell_magic('cython', '-3 --pgo', pgo_cython3_code)
ip.ex('g = f(10); h = call(10); main()')
self.assertEqual(ip.user_ns['g'], 2.0 / 10.0)
self.assertEqual(ip.user_ns['h'], 2.0 / 10.0)
@skip_win32
def test_extlibs(self):
ip = self._ip
code = """
from libc.math cimport sin
x = sin(0.0)
"""
ip.user_ns['x'] = 1
ip.run_cell_magic('cython', '-l m', code)
self.assertEqual(ip.user_ns['x'], 0)
def test_cython_verbose(self):
ip = self._ip
ip.run_cell_magic('cython', '--verbose', code)
ip.ex('g = f(10)')
self.assertEqual(ip.user_ns['g'], 20.0)
def test_cython_verbose_thresholds(self):
@contextmanager
def mock_distutils():
class MockLog:
DEBUG = 1
INFO = 2
thresholds = [INFO]
def set_threshold(self, val):
self.thresholds.append(val)
return self.thresholds[-2]
new_log = MockLog()
old_log = IpythonMagic.distutils.log
try:
IpythonMagic.distutils.log = new_log
yield new_log
finally:
IpythonMagic.distutils.log = old_log
ip = self._ip
with mock_distutils() as verbose_log:
ip.run_cell_magic('cython', '--verbose', code)
ip.ex('g = f(10)')
self.assertEqual(ip.user_ns['g'], 20.0)
self.assertEqual([verbose_log.INFO, verbose_log.DEBUG, verbose_log.INFO],
verbose_log.thresholds)
with mock_distutils() as normal_log:
ip.run_cell_magic('cython', '', code)
ip.ex('g = f(10)')
self.assertEqual(ip.user_ns['g'], 20.0)
self.assertEqual([normal_log.INFO], normal_log.thresholds)
def test_cython_no_annotate(self):
ip = self._ip
html = ip.run_cell_magic('cython', '', code)
self.assertTrue(html is None)
def test_cython_annotate(self):
ip = self._ip
html = ip.run_cell_magic('cython', '--annotate', code)
# somewhat brittle way to differentiate between annotated htmls
# with/without complete source code:
self.assertTrue(AnnotationCCodeWriter.COMPLETE_CODE_TITLE not in html.data)
def test_cython_annotate_default(self):
ip = self._ip
html = ip.run_cell_magic('cython', '-a', code)
# somewhat brittle way to differentiate between annotated htmls
# with/without complete source code:
self.assertTrue(AnnotationCCodeWriter.COMPLETE_CODE_TITLE not in html.data)
def test_cython_annotate_complete_c_code(self):
ip = self._ip
html = ip.run_cell_magic('cython', '--annotate-fullc', code)
# somewhat brittle way to differentiate between annotated htmls
# with/without complete source code:
self.assertTrue(AnnotationCCodeWriter.COMPLETE_CODE_TITLE in html.data)
| TestIPythonMagic |
python | getsentry__sentry-python | sentry_sdk/integrations/litestar.py | {
"start": 2864,
"end": 11830
} | class ____(SentryAsgiMiddleware):
def __init__(self, app, span_origin=LitestarIntegration.origin):
# type: (ASGIApp, str) -> None
super().__init__(
app=app,
unsafe_context_data=False,
transaction_style="endpoint",
mechanism_type="asgi",
span_origin=span_origin,
asgi_version=3,
)
def _capture_request_exception(self, exc):
# type: (Exception) -> None
"""Avoid catching exceptions from request handlers.
Those exceptions are already handled in Litestar.after_exception handler.
We still catch exceptions from application lifespan handlers.
"""
pass
def patch_app_init():
# type: () -> None
"""
Replaces the Litestar class's `__init__` function in order to inject `after_exception` handlers and set the
`SentryLitestarASGIMiddleware` as the outmost middleware in the stack.
See:
- https://docs.litestar.dev/2/usage/applications.html#after-exception
- https://docs.litestar.dev/2/usage/middleware/using-middleware.html
"""
old__init__ = Litestar.__init__
@ensure_integration_enabled(LitestarIntegration, old__init__)
def injection_wrapper(self, *args, **kwargs):
# type: (Litestar, *Any, **Any) -> None
kwargs["after_exception"] = [
exception_handler,
*(kwargs.get("after_exception") or []),
]
middleware = kwargs.get("middleware") or []
kwargs["middleware"] = [SentryLitestarASGIMiddleware, *middleware]
old__init__(self, *args, **kwargs)
Litestar.__init__ = injection_wrapper
def patch_middlewares():
# type: () -> None
old_resolve_middleware_stack = BaseRouteHandler.resolve_middleware
@ensure_integration_enabled(LitestarIntegration, old_resolve_middleware_stack)
def resolve_middleware_wrapper(self):
# type: (BaseRouteHandler) -> list[Middleware]
return [
enable_span_for_middleware(middleware)
for middleware in old_resolve_middleware_stack(self)
]
BaseRouteHandler.resolve_middleware = resolve_middleware_wrapper
def enable_span_for_middleware(middleware):
# type: (Middleware) -> Middleware
if (
not hasattr(middleware, "__call__") # noqa: B004
or middleware is SentryLitestarASGIMiddleware
):
return middleware
if isinstance(middleware, DefineMiddleware):
old_call = middleware.middleware.__call__ # type: ASGIApp
else:
old_call = middleware.__call__
async def _create_span_call(self, scope, receive, send):
# type: (MiddlewareProtocol, LitestarScope, Receive, Send) -> None
if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
return await old_call(self, scope, receive, send)
middleware_name = self.__class__.__name__
with sentry_sdk.start_span(
op=OP.MIDDLEWARE_LITESTAR,
name=middleware_name,
origin=LitestarIntegration.origin,
) as middleware_span:
middleware_span.set_tag("litestar.middleware_name", middleware_name)
# Creating spans for the "receive" callback
async def _sentry_receive(*args, **kwargs):
# type: (*Any, **Any) -> Union[HTTPReceiveMessage, WebSocketReceiveMessage]
if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
return await receive(*args, **kwargs)
with sentry_sdk.start_span(
op=OP.MIDDLEWARE_LITESTAR_RECEIVE,
name=getattr(receive, "__qualname__", str(receive)),
origin=LitestarIntegration.origin,
) as span:
span.set_tag("litestar.middleware_name", middleware_name)
return await receive(*args, **kwargs)
receive_name = getattr(receive, "__name__", str(receive))
receive_patched = receive_name == "_sentry_receive"
new_receive = _sentry_receive if not receive_patched else receive
# Creating spans for the "send" callback
async def _sentry_send(message):
# type: (Message) -> None
if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
return await send(message)
with sentry_sdk.start_span(
op=OP.MIDDLEWARE_LITESTAR_SEND,
name=getattr(send, "__qualname__", str(send)),
origin=LitestarIntegration.origin,
) as span:
span.set_tag("litestar.middleware_name", middleware_name)
return await send(message)
send_name = getattr(send, "__name__", str(send))
send_patched = send_name == "_sentry_send"
new_send = _sentry_send if not send_patched else send
return await old_call(self, scope, new_receive, new_send)
not_yet_patched = old_call.__name__ not in ["_create_span_call"]
if not_yet_patched:
if isinstance(middleware, DefineMiddleware):
middleware.middleware.__call__ = _create_span_call
else:
middleware.__call__ = _create_span_call
return middleware
def patch_http_route_handle():
# type: () -> None
old_handle = HTTPRoute.handle
async def handle_wrapper(self, scope, receive, send):
# type: (HTTPRoute, HTTPScope, Receive, Send) -> None
if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
return await old_handle(self, scope, receive, send)
sentry_scope = sentry_sdk.get_isolation_scope()
request = scope["app"].request_class(scope=scope, receive=receive, send=send) # type: Request[Any, Any]
extracted_request_data = ConnectionDataExtractor(
parse_body=True, parse_query=True
)(request)
body = extracted_request_data.pop("body")
request_data = await body
def event_processor(event, _):
# type: (Event, Hint) -> Event
route_handler = scope.get("route_handler")
request_info = event.get("request", {})
request_info["content_length"] = len(scope.get("_body", b""))
if should_send_default_pii():
request_info["cookies"] = extracted_request_data["cookies"]
if request_data is not None:
request_info["data"] = request_data
func = None
if route_handler.name is not None:
tx_name = route_handler.name
# Accounts for use of type `Ref` in earlier versions of litestar without the need to reference it as a type
elif hasattr(route_handler.fn, "value"):
func = route_handler.fn.value
else:
func = route_handler.fn
if func is not None:
tx_name = transaction_from_function(func)
tx_info = {"source": SOURCE_FOR_STYLE["endpoint"]}
if not tx_name:
tx_name = _DEFAULT_TRANSACTION_NAME
tx_info = {"source": TransactionSource.ROUTE}
event.update(
{
"request": deepcopy(request_info),
"transaction": tx_name,
"transaction_info": tx_info,
}
)
return event
sentry_scope._name = LitestarIntegration.identifier
sentry_scope.add_event_processor(event_processor)
return await old_handle(self, scope, receive, send)
HTTPRoute.handle = handle_wrapper
def retrieve_user_from_scope(scope):
# type: (LitestarScope) -> Optional[dict[str, Any]]
scope_user = scope.get("user")
if isinstance(scope_user, dict):
return scope_user
if hasattr(scope_user, "asdict"): # dataclasses
return scope_user.asdict()
return None
@ensure_integration_enabled(LitestarIntegration)
def exception_handler(exc, scope):
# type: (Exception, LitestarScope) -> None
user_info = None # type: Optional[dict[str, Any]]
if should_send_default_pii():
user_info = retrieve_user_from_scope(scope)
if user_info and isinstance(user_info, dict):
sentry_scope = sentry_sdk.get_isolation_scope()
sentry_scope.set_user(user_info)
if isinstance(exc, HTTPException):
integration = sentry_sdk.get_client().get_integration(LitestarIntegration)
if (
integration is not None
and exc.status_code not in integration.failed_request_status_codes
):
return
event, hint = event_from_exception(
exc,
client_options=sentry_sdk.get_client().options,
mechanism={"type": LitestarIntegration.identifier, "handled": False},
)
sentry_sdk.capture_event(event, hint=hint)
| SentryLitestarASGIMiddleware |
python | pytorch__pytorch | torch/_inductor/triton_bundler.py | {
"start": 1151,
"end": 1687
} | class ____:
"""
Represents a statically compiled CachingAutotuner object that we can
save directly in the cache. A CachingAutotuner is made up of a list of
StaticTritonCompileResults, each of which uses the cubin from a TritonKernelArtifact.
Statically saved here have their cubin files saved by a corresponding TritonBundleEntry.
"""
cache_key: str
kernel_name: str
kernel: "CachingAutotuner" # type: ignore[name-defined] # noqa: F821
@dataclasses.dataclass(frozen=True)
| StaticallyLaunchedAutotuner |
python | PrefectHQ__prefect | src/prefect/_vendor/croniter/croniter.py | {
"start": 49664,
"end": 53009
} | class ____:
def __init__(self, cronit):
self.cron = cronit
def do(self, idx, hash_type="h", hash_id=None, range_end=None, range_begin=None):
"""Return a hashed/random integer given range/hash information"""
if range_end is None:
range_end = self.cron.RANGES[idx][1]
if range_begin is None:
range_begin = self.cron.RANGES[idx][0]
if hash_type == "r":
crc = random.randint(0, 0xFFFFFFFF)
else:
crc = binascii.crc32(hash_id) & 0xFFFFFFFF
return ((crc >> idx) % (range_end - range_begin + 1)) + range_begin
def match(self, efl, idx, expr, hash_id=None, **kw):
return hash_expression_re.match(expr)
def expand(self, efl, idx, expr, hash_id=None, match="", **kw):
"""Expand a hashed/random expression to its normal representation"""
if match == "":
match = self.match(efl, idx, expr, hash_id, **kw)
if not match:
return expr
m = match.groupdict()
if m["hash_type"] == "h" and hash_id is None:
raise CroniterBadCronError("Hashed definitions must include hash_id")
if m["range_begin"] and m["range_end"]:
if int(m["range_begin"]) >= int(m["range_end"]):
raise CroniterBadCronError("Range end must be greater than range begin")
if m["range_begin"] and m["range_end"] and m["divisor"]:
# Example: H(30-59)/10 -> 34-59/10 (i.e. 34,44,54)
if int(m["divisor"]) == 0:
raise CroniterBadCronError("Bad expression: {0}".format(expr))
return "{0}-{1}/{2}".format(
self.do(
idx,
hash_type=m["hash_type"],
hash_id=hash_id,
range_begin=int(m["range_begin"]),
range_end=int(m["divisor"]) - 1 + int(m["range_begin"]),
),
int(m["range_end"]),
int(m["divisor"]),
)
elif m["range_begin"] and m["range_end"]:
# Example: H(0-29) -> 12
return str(
self.do(
idx,
hash_type=m["hash_type"],
hash_id=hash_id,
range_end=int(m["range_end"]),
range_begin=int(m["range_begin"]),
)
)
elif m["divisor"]:
# Example: H/15 -> 7-59/15 (i.e. 7,22,37,52)
if int(m["divisor"]) == 0:
raise CroniterBadCronError("Bad expression: {0}".format(expr))
return "{0}-{1}/{2}".format(
self.do(
idx,
hash_type=m["hash_type"],
hash_id=hash_id,
range_begin=self.cron.RANGES[idx][0],
range_end=int(m["divisor"]) - 1 + self.cron.RANGES[idx][0],
),
self.cron.RANGES[idx][1],
int(m["divisor"]),
)
else:
# Example: H -> 32
return str(
self.do(
idx,
hash_type=m["hash_type"],
hash_id=hash_id,
)
)
EXPANDERS = OrderedDict(
[
("hash", HashExpander),
]
)
| HashExpander |
python | getsentry__sentry | src/sentry/search/events/datasets/profiles.py | {
"start": 1287,
"end": 3911
} | class ____:
# the external name to expose
alias: str
# the internal name in snuba
column: str
# data type associated with this column
kind: Kind
# some kinds will have an unit associated with it
unit: Unit | None = None
COLUMNS = [
Column(alias="organization.id", column="organization_id", kind=Kind.INTEGER),
Column(alias="project.id", column="project_id", kind=Kind.INTEGER),
Column(alias="trace.transaction", column="transaction_id", kind=Kind.STRING),
Column(alias="id", column="profile_id", kind=Kind.STRING),
Column(alias="profile.id", column="profile_id", kind=Kind.STRING),
Column(alias="timestamp", column="received", kind=Kind.DATE),
Column(alias="device.arch", column="architecture", kind=Kind.STRING),
Column(alias="device.classification", column="device_classification", kind=Kind.STRING),
Column(alias="device.locale", column="device_locale", kind=Kind.STRING),
Column(alias="device.manufacturer", column="device_manufacturer", kind=Kind.STRING),
Column(alias="device.model", column="device_model", kind=Kind.STRING),
Column(alias="os.build", column="device_os_build_number", kind=Kind.STRING),
Column(alias="os.name", column="device_os_name", kind=Kind.STRING),
Column(alias="os.version", column="device_os_version", kind=Kind.STRING),
Column(
alias="profile.duration",
column="duration_ns",
kind=Kind.DURATION,
unit=Duration.NANOSECOND,
),
Column(
alias="transaction.duration",
column="duration_ns",
kind=Kind.DURATION,
unit=Duration.NANOSECOND,
),
Column(alias="environment", column="environment", kind=Kind.STRING),
Column(alias="platform.name", column="platform", kind=Kind.STRING),
Column(alias="trace", column="trace_id", kind=Kind.STRING),
Column(alias="transaction", column="transaction_name", kind=Kind.STRING),
# There is a `version_code` column that exists for
# legacy profiles, we've decided not to support that.
Column(alias="release", column="version_name", kind=Kind.STRING),
# We want to alias `project_id` to the column as well
# because the query builder uses that internally
Column(alias="project_id", column="project_id", kind=Kind.INTEGER),
# Snuba adds a time column for the dataset that rounds the timestamp.
# The exact rounding depends on the granularity in the query.
Column(alias="time", column="time", kind=Kind.DATE),
Column(alias="message", column="transaction_name", kind=Kind.STRING),
]
COLUMN_MAP = {column.alias: column for column in COLUMNS}
| Column |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 94091,
"end": 94295
} | class ____(
ScalarRemoveTest, fixtures.DeclarativeMappedTest
):
run_create_tables = None
useobject = True
cascade_scalar_deletes = False
uselist = False
| ScalarRemoveScalarObjectNoCascade |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/dialects/postgresql/pg_stuff.py | {
"start": 1341,
"end": 3953
} | class ____(Base):
__tablename__ = "test_table_json"
id = mapped_column(Integer, primary_key=True)
data: Mapped[Dict[str, Any]] = mapped_column(JSONB)
ident: Mapped[_py_uuid] = mapped_column(UUID())
ident_str: Mapped[str] = mapped_column(UUID(as_uuid=False))
elem = func.jsonb_array_elements(Test.data, type_=JSONB).column_valued("elem")
stmt = select(Test).where(
or_(
cast("example code", ARRAY(Text)).contained_by(
array([select(elem["code"].astext).scalar_subquery()])
),
cast("stefan", ARRAY(Text)).contained_by(
array([select(elem["code"]["new_value"].astext).scalar_subquery()])
),
)
)
print(stmt)
t1 = Test()
assert_type(t1.data, dict[str, Any])
assert_type(t1.ident, _py_uuid)
unique = UniqueConstraint(name="my_constraint")
insert(Test).on_conflict_do_nothing(
"foo", [Test.id], Test.id > 0
).on_conflict_do_update(
unique, ["foo"], Test.id > 0, {"id": 42, Test.ident: 99}, Test.id == 22
).excluded.foo.desc()
s1 = insert(Test)
s1.on_conflict_do_update(set_=s1.excluded)
assert_type(Column(INT4RANGE()), Column[Range[int]])
assert_type(Column("foo", DATERANGE()), Column[Range[date]])
assert_type(Column(INT8MULTIRANGE()), Column[Sequence[Range[int]]])
assert_type(Column("foo", TSTZMULTIRANGE()), Column[Sequence[Range[datetime]]])
range_col_stmt = select(Column(INT4RANGE()), Column(INT8MULTIRANGE()))
assert_type(range_col_stmt, Select[Range[int], Sequence[Range[int]]])
array_from_ints = array(range(2))
assert_type(array_from_ints, array[int])
array_of_strings = array([], type_=Text)
assert_type(array_of_strings, array[str])
array_of_ints = array([0], type_=Integer)
assert_type(array_of_ints, array[int])
# EXPECTED_MYPY_RE: Cannot infer .* of "array"
array([0], type_=Text)
assert_type(ARRAY(Text), ARRAY[str])
assert_type(Column(type_=ARRAY(Integer)), Column[Sequence[int]])
stmt_array_agg = select(func.array_agg(Column("num", type_=Integer)))
assert_type(stmt_array_agg, Select[Sequence[int]])
assert_type(select(func.array_agg(Test.ident_str)), Select[Sequence[str]])
stmt_array_agg_order_by_1 = select(
func.array_agg(
aggregate_order_by(
Column("title", type_=Text),
Column("date", type_=DATERANGE).desc(),
Column("id", type_=Integer),
),
)
)
assert_type(stmt_array_agg_order_by_1, Select[Sequence[str]])
stmt_array_agg_order_by_2 = select(
func.array_agg(
aggregate_order_by(Test.ident_str, Test.id.desc(), Test.ident),
)
)
assert_type(stmt_array_agg_order_by_2, Select[Sequence[str]])
| Test |
python | huggingface__transformers | tests/models/bridgetower/test_modeling_bridgetower.py | {
"start": 17148,
"end": 20297
} | class ____(unittest.TestCase):
@cached_property
def default_processor(self):
return (
BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
if is_vision_available()
else None
)
@slow
def test_image_and_text_retrieval(self):
model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm").to(
torch_device
)
model.eval()
processor = self.default_processor
image = prepare_img()
text = "a bunch of cats laying on a tower."
inputs = processor(image, text, return_tensors="pt").to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
# verify the logits
expected_shape = torch.Size([1, 2])
self.assertEqual(outputs.logits.shape, expected_shape)
self.assertTrue(outputs.logits[0, 1].item() > outputs.logits[0, 0].item())
# verify loss
inputs["labels"] = torch.ones(1, dtype=torch.long, device=torch_device)
inputs = inputs.to(torch_device)
with torch.no_grad():
outputs = model(**inputs)
self.assertAlmostEqual(outputs.loss.item(), 0.5108, places=4)
@slow
def test_masked_language_modeling(self):
model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm").to(torch_device)
model.eval()
processor = self.default_processor
image = prepare_img()
text = "a bunch of <mask> laying on a tower."
inputs = processor(image, text, return_tensors="pt").to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
# verify the logits
expected_shape = torch.Size([1, 11, 50265])
self.assertEqual(outputs.logits.shape, expected_shape)
# verify predicted word
predicted_id = outputs.logits.argmax(dim=-1).squeeze(0).tolist()[4]
self.assertTrue(processor.decode([predicted_id]) == " cats")
# verify loss
inputs["labels"] = inputs["input_ids"].clone()
inputs = inputs.to(torch_device)
with torch.no_grad():
outputs = model(**inputs)
self.assertAlmostEqual(outputs.loss.item(), 5.7373, places=4)
@slow
def test_constrastive_learning(self):
model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc").to(
torch_device
)
model.eval()
processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
image = prepare_img()
text = "a bunch of cats laying on a tower."
inputs = processor(image, text, padding=True, return_tensors="pt").to(torch_device)
with torch.no_grad():
outputs = model(**inputs, output_hidden_states=True, return_loss=True)
# verify the logits
expected_shape = torch.Size([1, 3, 512])
self.assertEqual(outputs.logits.shape, expected_shape)
@slow
@require_torch
| BridgeTowerModelIntegrationTest |
python | pytorch__pytorch | torch/autograd/function.py | {
"start": 13811,
"end": 19393
} | class ____(
_C._FunctionBase, FunctionCtx, _HookMixin, metaclass=FunctionMeta
):
@staticmethod
def forward(*args: Any, **kwargs: Any) -> Any:
r"""Define the forward of the custom autograd Function.
This function is to be overridden by all subclasses.
There are two ways to define forward:
Usage 1 (Combined forward and ctx)::
@staticmethod
def forward(ctx: Any, *args: Any, **kwargs: Any) -> Any:
pass
- It must accept a context ctx as the first argument, followed by any
number of arguments (tensors or other types).
- See :ref:`combining-forward-context` for more details
Usage 2 (Separate forward and ctx)::
@staticmethod
def forward(*args: Any, **kwargs: Any) -> Any:
pass
@staticmethod
def setup_context(ctx: Any, inputs: Tuple[Any, ...], output: Any) -> None:
pass
- The forward no longer accepts a ctx argument.
- Instead, you must also override the :meth:`torch.autograd.Function.setup_context`
staticmethod to handle setting up the ``ctx`` object.
``output`` is the output of the forward, ``inputs`` are a Tuple of inputs
to the forward.
- See :ref:`extending-autograd` for more details
The context can be used to store arbitrary data that can be then
retrieved during the backward pass. Tensors should not be stored
directly on `ctx` (though this is not currently enforced for
backward compatibility). Instead, tensors should be saved either with
:func:`ctx.save_for_backward` if they are intended to be used in
``backward`` (equivalently, ``vjp``) or :func:`ctx.save_for_forward`
if they are intended to be used for in ``jvp``.
"""
raise NotImplementedError(
"You must implement the forward function for custom autograd.Function."
)
@staticmethod
def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> Any:
r"""There are two ways to define the forward pass of an autograd.Function.
Either:
1. Override forward with the signature ``forward(ctx, *args, **kwargs)``.
``setup_context`` is not overridden. Setting up the ctx for backward
happens inside the ``forward``.
2. Override forward with the signature ``forward(*args, **kwargs)`` and
override ``setup_context``. Setting up the ctx for backward happens
inside ``setup_context`` (as opposed to inside the ``forward``)
See :meth:`torch.autograd.Function.forward` and :ref:`extending-autograd` for more details.
"""
raise NotImplementedError("setup_context is not implemented.")
@staticmethod
def backward(ctx: Any, *grad_outputs: Any) -> Any:
r"""Define a formula for differentiating the operation with backward mode automatic differentiation.
This function is to be overridden by all subclasses.
(Defining this function is equivalent to defining the ``vjp`` function.)
It must accept a context :attr:`ctx` as the first argument, followed by
as many outputs as the :func:`forward` returned (None will be passed in
for non tensor outputs of the forward function),
and it should return as many tensors, as there were inputs to
:func:`forward`. Each argument is the gradient w.r.t the given output,
and each returned value should be the gradient w.r.t. the
corresponding input. If an input is not a Tensor or is a Tensor not
requiring grads, you can just pass None as a gradient for that input.
The context can be used to retrieve tensors saved during the forward
pass. It also has an attribute :attr:`ctx.needs_input_grad` as a tuple
of booleans representing whether each input needs gradient. E.g.,
:func:`backward` will have ``ctx.needs_input_grad[0] = True`` if the
first input to :func:`forward` needs gradient computed w.r.t. the
output.
"""
raise NotImplementedError(
"You must implement either the backward or vjp method for "
"your custom autograd.Function to use it with backward "
"mode AD."
)
# vjp and backward are alias of each other
vjp = backward
@staticmethod
def jvp(ctx: Any, *grad_inputs: Any) -> Any:
r"""Define a formula for differentiating the operation with forward mode automatic differentiation.
This function is to be overridden by all subclasses.
It must accept a context :attr:`ctx` as the first argument, followed by
as many inputs as the :func:`forward` got (None will be passed in
for non tensor inputs of the forward function),
and it should return as many tensors as there were outputs to
:func:`forward`. Each argument is the gradient w.r.t the given input,
and each returned value should be the gradient w.r.t. the
corresponding output. If an output is not a Tensor or the function is not
differentiable with respect to that output, you can just pass None as a
gradient for that input.
You can use the :attr:`ctx` object to pass any value from the forward to this
functions.
"""
raise NotImplementedError(
"You must implement the jvp function for custom "
"autograd.Function to use it with forward mode AD."
)
| _SingleLevelFunction |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 7069,
"end": 8136
} | class ____(_scale_color_continuous):
"""
Create a 3 point diverging color gradient
See Also
--------
plotnine.scale_color_gradient
plotnine.scale_color_gradientn
mizani.palettes.gradient_n_pal : The palette class that generates
the colour gradient.
"""
low: InitVar[str] = "#832424"
"""
Low color.
"""
mid: InitVar[str] = "#FFFFFF"
"""
Mid-point color.
"""
high: InitVar[str] = "#3A3A98"
"""
High color.
"""
midpoint: InitVar[float] = 0
"""
Mid point of the input data range.
"""
def __post_init__(self, low, mid, high, midpoint):
from mizani.bounds import rescale_mid
from mizani.palettes import gradient_n_pal
# All rescale functions should have the same signature
def _rescale_mid(*args, **kwargs):
return rescale_mid(*args, mid=midpoint, **kwargs)
self.rescaler = _rescale_mid
self.palette = gradient_n_pal([low, mid, high])
super().__post_init__()
@dataclass
| scale_color_gradient2 |
python | getsentry__sentry | tests/sentry/integrations/aws_lambda/test_integration.py | {
"start": 1227,
"end": 23350
} | class ____(IntegrationTestCase):
provider = AwsLambdaIntegrationProvider
def setUp(self) -> None:
super().setUp()
self.projectA = self.create_project(organization=self.organization, slug="projA")
self.projectB = self.create_project(organization=self.organization, slug="projB")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_project_select(self, mock_react_view: MagicMock) -> None:
resp = self.client.get(self.setup_path)
assert resp.status_code == 200
serialized_projects = project_service.serialize_many(
organization_id=self.projectA.organization_id,
filter=dict(project_ids=[self.projectA.id, self.projectB.id]),
)
mock_react_view.assert_called_with(
ANY, "awsLambdaProjectSelect", {"projects": serialized_projects}
)
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_one_project(self, mock_react_view: MagicMock) -> None:
with assume_test_silo_mode(SiloMode.MONOLITH):
self.projectB.delete()
resp = self.client.get(self.setup_path)
assert resp.status_code == 200
mock_react_view.assert_called_with(ANY, "awsLambdaCloudformation", ANY)
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_render_cloudformation_view(self, mock_react_view: MagicMock) -> None:
self.pipeline.state.step_index = 1
resp = self.client.get(self.setup_path)
assert resp.status_code == 200
mock_react_view.assert_called_with(
ANY,
"awsLambdaCloudformation",
{
"baseCloudformationUrl": "https://console.aws.amazon.com/cloudformation/home#/stacks/create/review",
"templateUrl": "https://example.com/file.json",
"stackName": "Sentry-Monitoring-Stack",
"regionList": ALL_AWS_REGIONS,
"region": None,
"accountNumber": None,
"error": None,
"initialStepNumber": 1,
"organization": organization_service.serialize_organization(
id=self.organization.id, as_user=serialize_rpc_user(self.user)
),
"awsExternalId": None,
},
)
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_set_valid_arn(
self, mock_react_view: MagicMock, mock_gen_aws_client: MagicMock
) -> None:
self.pipeline.state.step_index = 1
data = {"region": region, "accountNumber": account_number, "awsExternalId": "my-id"}
resp = self.client.get(self.setup_path + "?" + urlencode(data))
assert resp.status_code == 200
mock_react_view.assert_called_with(ANY, "awsLambdaFunctionSelect", ANY)
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_set_arn_with_error(
self, mock_react_view: MagicMock, mock_gen_aws_client: MagicMock
) -> None:
self.pipeline.state.step_index = 1
mock_gen_aws_client.side_effect = ClientError({"Error": {}}, "assume_role")
data = {"region": region, "accountNumber": account_number, "awsExternalId": "my-id"}
resp = self.client.get(self.setup_path + "?" + urlencode(data))
assert resp.status_code == 200
mock_react_view.assert_called_with(
ANY,
"awsLambdaCloudformation",
# Ensure that the expected value passes through json serialization
{
"baseCloudformationUrl": "https://console.aws.amazon.com/cloudformation/home#/stacks/create/review",
"templateUrl": "https://example.com/file.json",
"stackName": "Sentry-Monitoring-Stack",
"regionList": ALL_AWS_REGIONS,
"region": region,
"accountNumber": account_number,
"error": "Please validate the Cloudformation stack was created successfully",
"initialStepNumber": 1,
"organization": organization_service.serialize_organization(
id=self.organization.id, as_user=serialize_rpc_user(self.user)
),
"awsExternalId": "my-id",
},
)
@patch("sentry.integrations.aws_lambda.integration.get_supported_functions")
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_lambda_list(
self,
mock_react_view: MagicMock,
mock_gen_aws_client: MagicMock,
mock_get_supported_functions: MagicMock,
) -> None:
mock_get_supported_functions.return_value = [
{"FunctionName": "lambdaA", "Runtime": "nodejs12.x"},
{"FunctionName": "lambdaB", "Runtime": "nodejs10.x"},
{"FunctionName": "lambdaC", "Runtime": "python3.6"},
{"FunctionName": "lambdaD", "Runtime": "python3.7"},
{"FunctionName": "lambdaE", "Runtime": "python3.8"},
{"FunctionName": "lambdaD", "Runtime": "python3.9"},
]
aws_external_id = "12-323"
self.pipeline.state.step_index = 2
self.pipeline.state.data = {
"region": region,
"accountNumber": account_number,
"aws_external_id": aws_external_id,
"project_id": self.projectA.id,
}
resp = self.client.get(self.setup_path)
assert resp.status_code == 200
mock_react_view.assert_called_with(
ANY,
"awsLambdaFunctionSelect",
{
"lambdaFunctions": [
{"FunctionName": "lambdaA", "Runtime": "nodejs12.x"},
{"FunctionName": "lambdaB", "Runtime": "nodejs10.x"},
{"FunctionName": "lambdaC", "Runtime": "python3.6"},
{"FunctionName": "lambdaD", "Runtime": "python3.7"},
{"FunctionName": "lambdaE", "Runtime": "python3.8"},
{"FunctionName": "lambdaD", "Runtime": "python3.9"},
],
"initialStepNumber": 3,
},
)
@patch("sentry.integrations.aws_lambda.integration.get_supported_functions")
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
def test_node_lambda_setup_layer_success(
self,
mock_gen_aws_client,
mock_get_supported_functions,
):
for layer_name, layer_version, expected_node_options in [
("SentryNodeServerlessSDKv7", "5", "-r @sentry/serverless/dist/awslambda-auto"),
("SentryNodeServerlessSDK", "168", "-r @sentry/serverless/dist/awslambda-auto"),
("SentryNodeServerlessSDK", "235", "-r @sentry/serverless/dist/awslambda-auto"),
("SentryNodeServerlessSDK", "236", "-r @sentry/aws-serverless/awslambda-auto"),
("SentryNodeServerlessSDKv8", "3", "-r @sentry/aws-serverless/awslambda-auto"),
("SentryNodeServerlessSDKv9", "235", "-r @sentry/aws-serverless/awslambda-auto"),
]:
with override_options(
{
"aws-lambda.node.layer-name": layer_name,
"aws-lambda.node.layer-version": layer_version,
}
):
# Ensure we reset everything
self.setUp()
mock_get_supported_functions.reset_mock()
mock_gen_aws_client.reset_mock()
mock_client = mock_gen_aws_client.return_value
mock_client.update_function_configuration = MagicMock()
mock_client.describe_account = MagicMock(
return_value={"Account": {"Name": "my_name"}}
)
mock_get_supported_functions.return_value = [
{
"FunctionName": "lambdaA",
"Runtime": "nodejs12.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaA",
},
{
"FunctionName": "lambdaB",
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
},
]
aws_external_id = "12-323"
self.pipeline.state.step_index = 2
self.pipeline.state.data = {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
"project_id": self.projectA.id,
}
with assume_test_silo_mode(SiloMode.REGION):
sentry_project_dsn = ProjectKey.get_default(project=self.projectA).get_dsn(
public=True
)
# TODO: pass in lambdaA=false
# having issues with reading json data
# request.POST looks like {"lambdaB": "True"}
# string instead of boolean
resp = self.client.post(self.setup_path, {"lambdaB": "true", "lambdaA": "false"})
assert resp.status_code == 200
mock_client.update_function_configuration.assert_called_once_with(
FunctionName="lambdaB",
Layers=[f"arn:aws:lambda:us-east-2:1234:layer:{layer_name}:{layer_version}"],
Environment={
"Variables": {
"NODE_OPTIONS": expected_node_options,
"SENTRY_DSN": sentry_project_dsn,
"SENTRY_TRACES_SAMPLE_RATE": "1.0",
}
},
)
integration = Integration.objects.get(provider=self.provider.key)
assert integration.name == "my_name us-east-2"
assert integration.external_id == "599817902985-us-east-2"
assert integration.metadata == {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
}
assert OrganizationIntegration.objects.filter(
integration=integration, organization_id=self.organization.id
)
@patch("sentry.integrations.aws_lambda.integration.get_supported_functions")
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
def test_python_lambda_setup_layer_success(
self, mock_gen_aws_client, mock_get_supported_functions
):
mock_client = mock_gen_aws_client.return_value
mock_client.update_function_configuration = MagicMock()
mock_client.describe_account = MagicMock(return_value={"Account": {"Name": "my_name"}})
mock_get_supported_functions.return_value = [
{
"FunctionName": "lambdaA",
"Handler": "lambda_handler.test_handler",
"Runtime": "python3.6",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaA",
}
]
aws_external_id = "12-323"
self.pipeline.state.step_index = 2
self.pipeline.state.data = {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
"project_id": self.projectA.id,
}
with assume_test_silo_mode(SiloMode.REGION):
sentry_project_dsn = ProjectKey.get_default(project=self.projectA).get_dsn(public=True)
resp = self.client.post(self.setup_path, {"lambdaA": "true"})
assert resp.status_code == 200
mock_client.update_function_configuration.assert_called_once_with(
FunctionName="lambdaA",
Layers=["arn:aws:lambda:us-east-2:1234:layer:my-python-layer:34"],
Environment={
"Variables": {
"SENTRY_INITIAL_HANDLER": "lambda_handler.test_handler",
"SENTRY_DSN": sentry_project_dsn,
"SENTRY_TRACES_SAMPLE_RATE": "1.0",
}
},
Handler="sentry_sdk.integrations.init_serverless_sdk.sentry_lambda_handler",
)
integration = Integration.objects.get(provider=self.provider.key)
assert integration.name == "my_name us-east-2"
assert integration.external_id == "599817902985-us-east-2"
assert integration.metadata == {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
}
assert OrganizationIntegration.objects.filter(
integration=integration, organization_id=self.organization.id
)
@patch("sentry.integrations.aws_lambda.integration.get_supported_functions")
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_lambda_setup_layer_error(
self, mock_react_view, mock_gen_aws_client, mock_get_supported_functions
):
class MockException(Exception):
pass
bad_layer = "arn:aws:lambda:us-east-2:546545:layer:another-layer:5"
mock_client = mock_gen_aws_client.return_value
mock_client.update_function_configuration = MagicMock(
side_effect=Exception(f"Layer version {bad_layer} does not exist")
)
mock_client.describe_account = MagicMock(return_value={"Account": {"Name": "my_name"}})
mock_client.exceptions = MagicMock()
mock_client.exceptions.ResourceConflictException = MockException
mock_get_supported_functions.return_value = [
{
"FunctionName": "lambdaA",
"Runtime": "nodejs12.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaA",
},
{
"FunctionName": "lambdaB",
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
},
]
aws_external_id = "12-323"
self.pipeline.state.step_index = 2
self.pipeline.state.data = {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
"project_id": self.projectA.id,
}
resp = self.client.post(self.setup_path, {"lambdaB": "true"})
assert resp.status_code == 200
assert not Integration.objects.filter(provider=self.provider.key).exists()
failures = [{"name": "lambdaB", "error": "Invalid existing layer another-layer"}]
mock_react_view.assert_called_with(
ANY, "awsLambdaFailureDetails", {"lambdaFunctionFailures": failures, "successCount": 0}
)
@patch("sentry.integrations.aws_lambda.integration.get_supported_functions")
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_lambda_setup_layer_missing_role_error(
self, mock_react_view, mock_gen_aws_client, mock_get_supported_functions
):
class MockException(Exception):
pass
missing_role_err = (
"An error occurred (InvalidParameterValueException) when "
"calling the UpdateFunctionConfiguration operation: "
"The role defined for the function cannot be "
"assumed by Lambda."
)
mock_client = mock_gen_aws_client.return_value
mock_client.update_function_configuration = MagicMock(
side_effect=Exception(missing_role_err)
)
mock_client.describe_account = MagicMock(return_value={"Account": {"Name": "my_name"}})
mock_client.exceptions = MagicMock()
mock_client.exceptions.ResourceConflictException = MockException
mock_get_supported_functions.return_value = [
{
"FunctionName": "lambdaB",
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
},
]
aws_external_id = "12-323"
self.pipeline.state.step_index = 2
self.pipeline.state.data = {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
"project_id": self.projectA.id,
}
resp = self.client.post(self.setup_path, {"lambdaB": "true"})
assert resp.status_code == 200
assert not Integration.objects.filter(provider=self.provider.key).exists()
failures = [
{"name": "lambdaB", "error": "Invalid role associated with the lambda function"}
]
mock_react_view.assert_called_with(
ANY, "awsLambdaFailureDetails", {"lambdaFunctionFailures": failures, "successCount": 0}
)
@patch("sentry.integrations.aws_lambda.integration.get_supported_functions")
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_lambda_setup_layer_too_many_requests_exception(
self, mock_react_view, mock_gen_aws_client, mock_get_supported_functions
):
class MockException(Exception):
pass
too_many_requests_err = (
"An error occurred (TooManyRequestsException) when calling the "
"UpdateFunctionConfiguration operation (reached max retries: 4): "
"Rate exceeded"
)
mock_client = mock_gen_aws_client.return_value
mock_client.update_function_configuration = MagicMock(
side_effect=Exception(too_many_requests_err)
)
mock_client.describe_account = MagicMock(return_value={"Account": {"Name": "my_name"}})
mock_client.exceptions = MagicMock()
mock_client.exceptions.ResourceConflictException = MockException
mock_get_supported_functions.return_value = [
{
"FunctionName": "lambdaB",
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
},
]
aws_external_id = "12-323"
self.pipeline.state.step_index = 2
self.pipeline.state.data = {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
"project_id": self.projectA.id,
}
resp = self.client.post(self.setup_path, {"lambdaB": "true"})
assert resp.status_code == 200
assert not Integration.objects.filter(provider=self.provider.key).exists()
failures = [
{
"name": "lambdaB",
"error": "Something went wrong! Please enable function manually after installation",
}
]
mock_react_view.assert_called_with(
ANY, "awsLambdaFailureDetails", {"lambdaFunctionFailures": failures, "successCount": 0}
)
@patch("sentry.integrations.aws_lambda.integration.get_supported_functions")
@patch("sentry.integrations.aws_lambda.integration.gen_aws_client")
@patch.object(aws_lambda_integration, "render_react_view", return_value=HttpResponse())
def test_lambda_setup_layer_env_vars_limit_exceeded_exception(
self, mock_react_view, mock_gen_aws_client, mock_get_supported_functions
):
class MockException(Exception):
pass
env_vars_size_limit_err = (
"An error occurred (InvalidParameterValueException) when calling the "
"UpdateFunctionConfiguration operation: Lambda was unable to configure "
"your environment variables because the environment variables you have "
"provided exceeded the 4KB limit. String measured: {'MESSAGE':'This is production "
"environment','TARGET_ENV' :'pre-production','IS_SERVERLESS':'true','STAGE':'pre-prod'"
)
mock_client = mock_gen_aws_client.return_value
mock_client.update_function_configuration = MagicMock(
side_effect=Exception(env_vars_size_limit_err)
)
mock_client.describe_account = MagicMock(return_value={"Account": {"Name": "my_name"}})
mock_client.exceptions = MagicMock()
mock_client.exceptions.ResourceConflictException = MockException
mock_get_supported_functions.return_value = [
{
"FunctionName": "lambdaB",
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
},
]
aws_external_id = "12-323"
self.pipeline.state.step_index = 2
self.pipeline.state.data = {
"region": region,
"account_number": account_number,
"aws_external_id": aws_external_id,
"project_id": self.projectA.id,
}
resp = self.client.post(self.setup_path, {"lambdaB": "true"})
assert resp.status_code == 200
assert not Integration.objects.filter(provider=self.provider.key).exists()
failures = [
{
"name": "lambdaB",
"error": "Environment variables size limit of 4KB was exceeded",
}
]
mock_react_view.assert_called_with(
ANY, "awsLambdaFailureDetails", {"lambdaFunctionFailures": failures, "successCount": 0}
)
| AwsLambdaIntegrationTest |
python | huggingface__transformers | src/transformers/models/aimv2/modeling_aimv2.py | {
"start": 9914,
"end": 12429
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
if self.head_dim * self.num_heads != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
f" {self.num_heads})."
)
self.scale = self.head_dim**-0.5
self.dropout = config.attention_dropout
self.is_causal = False
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_bias)
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_bias)
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_bias)
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.qkv_bias)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
"""Input shape: Batch x Time x Channel"""
batch_size, seq_length, embed_dim = hidden_states.shape
queries = self.q_proj(hidden_states)
keys = self.k_proj(hidden_states)
values = self.v_proj(hidden_states)
queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
queries,
keys,
values,
attention_mask,
is_causal=self.is_causal,
scaling=self.scale,
dropout=0.0 if not self.training else self.dropout,
)
attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
| Aimv2Attention |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/timedelta.py | {
"start": 1188,
"end": 1594
} | class ____:
def setup_cache(self):
td = Timedelta(days=365, minutes=35, seconds=25, milliseconds=35)
return td
def time_timedelta_days(self, td):
td.days
def time_timedelta_seconds(self, td):
td.seconds
def time_timedelta_microseconds(self, td):
td.microseconds
def time_timedelta_nanoseconds(self, td):
td.nanoseconds
| TimedeltaProperties |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 5959,
"end": 6148
} | class ____(models.Model):
title = models.CharField(max_length=42)
slug = AutoSlugField(populate_from="title")
class Meta:
app_label = "django_extensions"
| SluggedTestModel |
python | gevent__gevent | src/gevent/pywsgi.py | {
"start": 60224,
"end": 60849
} | class ____(SecureEnviron):
"""
Specializes the default list of whitelisted keys to a few
common WSGI variables.
Example::
>>> environ = WSGISecureEnviron(REMOTE_ADDR='::1', HTTP_AUTHORIZATION='secret')
>>> environ
{'REMOTE_ADDR': '::1', (hidden keys: 1)}
>>> import pprint
>>> pprint.pprint(environ)
{'REMOTE_ADDR': '::1', (hidden keys: 1)}
>>> print(pprint.pformat(environ))
{'REMOTE_ADDR': '::1', (hidden keys: 1)}
"""
default_whitelist_keys = ('REMOTE_ADDR', 'REMOTE_PORT', 'HTTP_HOST')
default_print_masked_keys = False
| WSGISecureEnviron |
python | huggingface__transformers | src/transformers/models/esm/modeling_esmfold.py | {
"start": 36429,
"end": 38503
} | class ____(nn.Module):
def __init__(self, embed_dim, num_heads, head_width, gated=False):
super().__init__()
assert embed_dim == num_heads * head_width
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_width = head_width
self.proj = nn.Linear(embed_dim, embed_dim * 3, bias=False)
self.o_proj = nn.Linear(embed_dim, embed_dim, bias=True)
self.gated = gated
if gated:
self.g_proj = nn.Linear(embed_dim, embed_dim)
init.zeros_(self.g_proj.weight)
init.ones_(self.g_proj.bias)
self.rescale_factor = self.head_width**-0.5
init.zeros_(self.o_proj.bias)
def forward(self, x, mask=None, bias=None, indices=None):
"""
Basic self attention with optional mask and external pairwise bias. To handle sequences of different lengths,
use mask.
Inputs:
x: batch of input sequences (.. x L x C) mask: batch of boolean masks where 1=valid, 0=padding position (..
x L_k) bias: batch of scalar pairwise attention biases (.. x Lq x Lk x num_heads)
Outputs:
sequence projection (B x L x embed_dim), attention maps (B x L x L x num_heads)
"""
t = self.proj(x).view(*x.shape[:2], self.num_heads, -1)
t = t.permute(0, 2, 1, 3)
q, k, v = t.chunk(3, dim=-1)
q = self.rescale_factor * q
a = torch.einsum("...qc,...kc->...qk", q, k)
# Add external attention bias.
if bias is not None:
a = a + bias.permute(0, 3, 1, 2)
# Do not attend to padding tokens.
if mask is not None:
mask = mask[:, None, None]
a = a.masked_fill(mask == False, -np.inf) # noqa: E712
a = nn.functional.softmax(a, dim=-1)
y = torch.einsum("...hqk,...hkc->...qhc", a, v)
y = y.reshape(*y.shape[:2], -1)
if self.gated:
y = self.g_proj(x).sigmoid() * y
y = self.o_proj(y)
return y, a.permute(0, 3, 1, 2)
| EsmFoldSelfAttention |
python | getsentry__sentry | src/sentry_plugins/segment/plugin.py | {
"start": 535,
"end": 4069
} | class ____(CorePluginMixin, DataForwardingPlugin):
title = "Segment"
slug = "segment"
description = DESCRIPTION
conf_key = "segment"
required_field = "write_key"
endpoint = "https://api.segment.io/v1/track"
feature_descriptions = [
FeatureDescription(
"""
Forward Sentry errors and events to Segment.
""",
IntegrationFeatures.DATA_FORWARDING,
)
]
def get_config(self, project, user=None, initial=None, add_additional_fields: bool = False):
return [
get_secret_field_config(
name="write_key",
label="Write Key",
secret=self.get_option("write_key", project),
help_text="Your Segment write key",
)
]
def get_rate_limit(self):
return (200, 1)
# https://segment.com/docs/spec/track/
def get_event_payload(self, event):
context = {"library": {"name": "sentry", "version": self.version}}
props = {
"eventId": event.event_id,
"transaction": event.get_tag("transaction") or "",
"release": event.get_tag("sentry:release") or "",
"level": event.get_tag("level") or "",
"environment": event.get_tag("environment") or "",
}
if "user" in event.interfaces:
user = event.interfaces["user"]
if user.ip_address:
context["ip"] = user.ip_address
user_id = user.id
else:
user_id = None
if "request" in event.interfaces:
http = event.interfaces["request"]
headers = http.headers
if not isinstance(headers, dict):
headers = dict(headers or ())
context.update(
{
"userAgent": headers.get("User-Agent", ""),
"page": {
"url": http.url,
"method": http.method,
"search": http.query_string or "",
"referrer": headers.get("Referer", ""),
},
}
)
if "exception" in event.interfaces:
exc = event.interfaces["exception"].values[0]
props.update({"exceptionType": exc.type})
return {
"context": context,
"userId": user_id,
"event": "Error Captured",
"properties": props,
"integration": {"name": "sentry", "version": self.version},
"timestamp": event.datetime.isoformat() + "Z",
}
def forward_event(self, event, payload, **kwargs):
# TODO(dcramer): we currently only support authenticated events, as the
# value of anonymous errors/crashes/etc is much less meaningful in the
# context of Segment
# we currently only support errors
if event.get_event_type() != "error":
return
# we avoid instantiating interfaces here as they're only going to be
# used if there's a User present
user_interface = event.data.get("user")
if not user_interface:
return
user_id = user_interface.get("id")
if not user_id:
return
write_key = self.get_option("write_key", event.project)
if not write_key:
return
with http.build_session() as session:
session.post(self.endpoint, json=payload, auth=(write_key, ""))
| SegmentPlugin |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 46959,
"end": 53460
} | class ____:
IN = [[50, 50, 50, 50, 50, 92, 18, 27, 65, 46],
[50, 50, 50, 50, 50, 0, 72, 77, 68, 66],
[50, 50, 50, 50, 50, 46, 47, 19, 64, 77],
[50, 50, 50, 50, 50, 42, 15, 29, 95, 35],
[50, 50, 50, 50, 50, 46, 34, 9, 21, 66],
[70, 97, 28, 68, 78, 77, 61, 58, 71, 42],
[64, 53, 44, 29, 68, 32, 19, 68, 24, 84],
[3, 33, 53, 67, 1, 78, 74, 55, 12, 83],
[7, 11, 46, 70, 60, 47, 24, 43, 61, 26],
[32, 61, 88, 7, 39, 4, 92, 64, 45, 61]]
OUT = [[0, 50, 50, 50, 42, 15, 15, 18, 27, 0],
[0, 50, 50, 50, 50, 42, 19, 21, 29, 0],
[50, 50, 50, 50, 50, 47, 34, 34, 46, 35],
[50, 50, 50, 50, 50, 50, 42, 47, 64, 42],
[50, 50, 50, 50, 50, 50, 46, 55, 64, 35],
[33, 50, 50, 50, 50, 47, 46, 43, 55, 26],
[32, 50, 50, 50, 50, 47, 46, 45, 55, 26],
[7, 46, 50, 50, 47, 46, 46, 43, 45, 21],
[0, 32, 33, 39, 32, 32, 43, 43, 43, 0],
[0, 7, 11, 7, 4, 4, 19, 19, 24, 0]]
KERNEL_SIZE = [7,3]
@make_xp_test_case(signal.medfilt, signal.medfilt2d)
def test_basic(self, xp):
in_ = xp.asarray(self.IN)
out_ = xp.asarray(self.OUT)
kernel_size = xp.asarray(self.KERNEL_SIZE)
d = signal.medfilt(in_, kernel_size)
e = signal.medfilt2d(xp.asarray(in_, dtype=xp.float64), kernel_size)
xp_assert_equal(d, out_)
xp_assert_equal(d, e, check_dtype=False)
@pytest.mark.parametrize('dtype', ["uint8", "int8", "uint16", "int16",
"uint32", "int32", "uint64", "int64",
"float32", "float64"])
@make_xp_test_case(signal.medfilt, signal.medfilt2d)
def test_types(self, dtype, xp):
# volume input and output types match
if is_torch(xp) and dtype in ["uint16", "uint32", "uint64"]:
pytest.skip("torch does not support unisigned ints")
dtype = getattr(xp, dtype)
in_typed = xp.asarray(self.IN, dtype=dtype)
assert signal.medfilt(in_typed).dtype == dtype
assert signal.medfilt2d(in_typed).dtype == dtype
@skip_xp_backends(np_only=True, reason="assertions may differ")
@pytest.mark.parametrize('dtype', [np.bool_, np.complex64, np.complex128,
np.clongdouble, np.float16,
"float96", "float128"])
@make_xp_test_case(signal.medfilt, signal.medfilt2d)
def test_invalid_dtypes(self, dtype, xp):
# We can only test this on platforms that support a native type of float96 or
# float128; comparing to np.longdouble allows us to filter out non-native types
if (dtype in ["float96", "float128"]
and np.finfo(np.longdouble).dtype != dtype):
pytest.skip(f"Platform does not support {dtype}")
in_typed = np.array(self.IN, dtype=dtype)
with pytest.raises(ValueError, match="not supported"):
signal.medfilt(in_typed)
with pytest.raises(ValueError, match="not supported"):
signal.medfilt2d(in_typed)
@skip_xp_backends(np_only=True, reason="object arrays")
@make_xp_test_case(signal.medfilt)
def test_none(self, xp):
# gh-1651, trac #1124. Ensure this does not segfault.
with assert_raises((ValueError, TypeError)):
signal.medfilt(None)
@skip_xp_backends(np_only=True, reason="strides are only writeable in NumPy")
@make_xp_test_case(signal.medfilt)
def test_odd_strides(self, xp):
# Avoid a regression with possible contiguous
# numpy arrays that have odd strides. The stride value below gets
# us into wrong memory if used (but it does not need to be used)
dummy = xp.arange(10, dtype=xp.float64)
a = dummy[5:6]
a = np.lib.stride_tricks.as_strided(a, strides=(16,))
xp_assert_close(signal.medfilt(a, 1), xp.asarray([5.]))
@skip_xp_backends(
"jax.numpy",
reason="chunk assignment does not work on jax immutable arrays"
)
@pytest.mark.parametrize("dtype", ["uint8", "float32", "float64"])
@make_xp_test_case(signal.medfilt2d)
def test_medfilt2d_parallel(self, dtype, xp):
dtype = getattr(xp, dtype)
in_typed = xp.asarray(self.IN, dtype=dtype)
expected = xp.asarray(self.OUT, dtype=dtype)
# This is used to simplify the indexing calculations.
assert in_typed.shape == expected.shape
# We'll do the calculation in four chunks. M1 and N1 are the dimensions
# of the first output chunk. We have to extend the input by half the
# kernel size to be able to calculate the full output chunk.
M1 = expected.shape[0] // 2
N1 = expected.shape[1] // 2
offM = self.KERNEL_SIZE[0] // 2 + 1
offN = self.KERNEL_SIZE[1] // 2 + 1
def apply(chunk):
# in = slice of in_typed to use.
# sel = slice of output to crop it to the correct region.
# out = slice of output array to store in.
M, N = chunk
if M == 0:
Min = slice(0, M1 + offM)
Msel = slice(0, -offM)
Mout = slice(0, M1)
else:
Min = slice(M1 - offM, None)
Msel = slice(offM, None)
Mout = slice(M1, None)
if N == 0:
Nin = slice(0, N1 + offN)
Nsel = slice(0, -offN)
Nout = slice(0, N1)
else:
Nin = slice(N1 - offN, None)
Nsel = slice(offN, None)
Nout = slice(N1, None)
# Do the calculation, but do not write to the output in the threads.
chunk_data = in_typed[Min, Nin]
med = signal.medfilt2d(chunk_data, self.KERNEL_SIZE)
return med[Msel, Nsel], Mout, Nout
# Give each chunk to a different thread.
output = xp.zeros_like(expected)
with ThreadPoolExecutor(max_workers=4) as pool:
chunks = {(0, 0), (0, 1), (1, 0), (1, 1)}
futures = {pool.submit(apply, chunk) for chunk in chunks}
# Store each result in the output as it arrives.
for future in as_completed(futures):
data, Mslice, Nslice = future.result()
output[Mslice, Nslice] = data
xp_assert_equal(output, expected)
@make_xp_test_case(signal.wiener)
| TestMedFilt |
python | huggingface__transformers | tests/models/ernie4_5/test_modeling_ernie4_5.py | {
"start": 1243,
"end": 1698
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = Ernie4_5ModelTester
# Need to use `0.8` instead of `0.9` for `test_cpu_offload`
# This is because we are hitting edge cases with the causal_mask buffer
model_split_percents = [0.5, 0.7, 0.8]
# used in `test_torch_compile_for_training`
_torch_compile_train_cls = Ernie4_5ForCausalLM if is_torch_available() else None
@require_torch_accelerator
| Ernie4_5ModelTest |
python | spyder-ide__spyder | external-deps/spyder-kernels/spyder_kernels/comms/utils.py | {
"start": 1047,
"end": 2734
} | class ____(object):
"""Wrapper to warn user when text is printed."""
def __init__(self, write, name, thread_id):
self._write = write
self._name = name
self._thread_id = thread_id
self._warning_shown = False
def is_benign_message(self, message):
"""Determine if a message is benign in order to filter it."""
benign_messages = [
# Fixes spyder-ide/spyder#14928
# Fixes spyder-ide/spyder-kernels#343
'DeprecationWarning',
# Fixes spyder-ide/spyder-kernels#365
'IOStream.flush timed out',
# Avoid unnecessary messages from set_configuration when changing
# Matplotlib options.
"Warning: Cannot change to a different GUI toolkit",
"%pylab is deprecated",
"Populating the interactive namespace",
"\n",
# Fixes spyder-ide/spyder#21652
"WARNING",
"Active device does not have an attribute",
]
return any([msg in message for msg in benign_messages])
def __call__(self, string):
"""Print warning once."""
if self._thread_id != threading.get_ident():
return self._write(string)
if not self.is_benign_message(string):
if not self._warning_shown:
self._warning_shown = True
# request_pdb_stop is expected to print messages.
if self._name not in ['request_pdb_stop']:
self._write(
"\nOutput from spyder call " + repr(self._name) + ":\n"
)
return self._write(string)
| WriteWrapper |
python | pypa__pip | src/pip/_vendor/packaging/markers.py | {
"start": 1190,
"end": 1339
} | class ____(ValueError):
"""
A name was attempted to be used that does not exist inside of the
environment.
"""
| UndefinedEnvironmentName |
python | realpython__materials | wordcount/tests/task_05.py | {
"start": 467,
"end": 863
} | class ____:
def test_displays_counts_and_a_filename_on_the_same_line(
self, wc, small_files
):
for file in small_files:
assert_equals(file.format_line(), wc(str(file.path)))
def test_treats_the_dash_character_as_standard_input(self, wc):
"""Treats the dash character (-) as standard input"""
assert b"1 1 6\n" == wc("-", stdin=b"latte\n")
| Test |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pep8_naming/ignore_names/N804.py | {
"start": 246,
"end": 349
} | class ____(ABCMeta):
def badAllowed(self):
pass
def stillBad(self):
pass
| MetaClass |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/translator.py | {
"start": 655,
"end": 969
} | class ____(str, Enum):
RUNNING = "running"
SUCCEEDED = "succeeded"
CANCELLED = "cancelled"
PENDING = "pending"
FAILED = "failed"
ERROR = "error"
INCOMPLETE = "incomplete"
@deprecated(breaking_version="1.10", additional_warn_text="Use `AirbyteJobStatusType` instead.")
| AirbyteJobStatusType |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF053.py | {
"start": 1799,
"end": 1876
} | class ____[
T # Comment
](Generic[_E]): ... # TODO: Type parameter defaults
| C |
python | protocolbuffers__protobuf | python/minimal_test.py | {
"start": 2315,
"end": 5275
} | class ____(unittest.TestCase):
def test_descriptor_pool(self):
serialized_desc = b'\n\ntest.proto\"\x0e\n\x02M1*\x08\x08\x01\x10\x80\x80\x80\x80\x02:\x15\n\x08test_ext\x12\x03.M1\x18\x01 \x01(\x05'
pool = _message.DescriptorPool()
file_desc = pool.AddSerializedFile(serialized_desc)
self.assertEqual("test.proto", file_desc.name)
ext_desc = pool.FindExtensionByName("test_ext")
self.assertEqual(1, ext_desc.number)
# Test object cache: repeatedly retrieving the same descriptor
# should result in the same object
self.assertIs(ext_desc, pool.FindExtensionByName("test_ext"))
def test_lib_is_upb(self):
# Ensure we are not pulling in a different protobuf library on the
# system.
print(_message._IS_UPB)
self.assertTrue(_message._IS_UPB)
self.assertEqual(api_implementation.Type(), "cpp")
def test_repeated_field_slice_delete(self):
def test_slice(start, end, step):
vals = list(range(20))
message = unittest_pb2.TestAllTypes(repeated_int32=vals)
del vals[start:end:step]
del message.repeated_int32[start:end:step]
self.assertEqual(vals, list(message.repeated_int32))
test_slice(3, 11, 1)
test_slice(3, 11, 2)
test_slice(3, 11, 3)
test_slice(11, 3, -1)
test_slice(11, 3, -2)
test_slice(11, 3, -3)
test_slice(10, 25, 4)
def testExtensionsErrors(self):
msg = unittest_pb2.TestAllTypes()
self.assertRaises(AttributeError, getattr, msg, 'Extensions')
def testClearStubMapField(self):
msg = map_unittest_pb2.TestMapSubmessage()
int32_map = msg.test_map.map_int32_int32
msg.test_map.ClearField("map_int32_int32")
int32_map[123] = 456
self.assertEqual(0, msg.test_map.ByteSize())
def testClearReifiedMapField(self):
msg = map_unittest_pb2.TestMap()
int32_map = msg.map_int32_int32
int32_map[123] = 456
msg.ClearField("map_int32_int32")
int32_map[111] = 222
self.assertEqual(0, msg.ByteSize())
def testClearStubRepeatedField(self):
msg = unittest_pb2.NestedTestAllTypes()
int32_array = msg.payload.repeated_int32
msg.payload.ClearField("repeated_int32")
int32_array.append(123)
self.assertEqual(0, msg.payload.ByteSize())
def testClearReifiedRepeatdField(self):
msg = unittest_pb2.TestAllTypes()
int32_array = msg.repeated_int32
int32_array.append(123)
self.assertNotEqual(0, msg.ByteSize())
msg.ClearField("repeated_int32")
int32_array.append(123)
self.assertEqual(0, msg.ByteSize())
def testFloatPrinting(self):
message = unittest_pb2.TestAllTypes()
message.optional_float = -0.0
self.assertEqual(str(message), 'optional_float: -0\n')
| TestMessageExtension |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/common.py | {
"start": 1479,
"end": 2455
} | class ____(BaseModel, metaclass=AllOptional):
class Config:
arbitrary_types_allowed = True
@classmethod
def schema_extra(cls, schema: Dict[str, Any], model: Type["BaseModel"]) -> None:
schema.pop("title", None)
schema.pop("description", None)
for name, prop in schema.get("properties", {}).items():
prop.pop("title", None)
prop.pop("description", None)
allow_none = model.__fields__[name].allow_none
if allow_none:
if "type" in prop:
prop["type"] = ["null", prop["type"]]
elif "$ref" in prop:
ref = prop.pop("$ref")
prop["oneOf"] = [{"type": "null"}, {"$ref": ref}]
@classmethod
def schema(cls, **kwargs) -> Dict[str, Any]:
schema = super().schema(**kwargs)
expand_refs(schema)
return schema
| CatalogModel |
python | python__mypy | mypy/types.py | {
"start": 38761,
"end": 39649
} | class ____(ProperType):
"""Represents a Arg(type, 'name') inside a Callable's type list.
Note that this is a synthetic type for helping parse ASTs, not a real type.
"""
__slots__ = ("typ", "name", "constructor")
typ: Type
name: str | None
constructor: str | None
def __init__(
self,
typ: Type,
name: str | None,
constructor: str | None,
line: int = -1,
column: int = -1,
) -> None:
super().__init__(line, column)
self.typ = typ
self.name = name
self.constructor = constructor
def accept(self, visitor: TypeVisitor[T]) -> T:
assert isinstance(visitor, SyntheticTypeVisitor)
ret: T = visitor.visit_callable_argument(self)
return ret
def serialize(self) -> JsonDict:
assert False, "Synthetic types don't serialize"
| CallableArgument |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataform.py | {
"start": 18552,
"end": 21829
} | class ____(GoogleCloudBaseOperator):
"""
Requests cancellation of a running WorkflowInvocation.
:param project_id: Required. The ID of the Google Cloud project that the task belongs to.
:param region: Required. The ID of the Google Cloud region that the task belongs to.
:param repository_id: Required. The ID of the Dataform repository that the task belongs to.
:param workflow_invocation_id: the workflow invocation resource's id.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
:param gcp_conn_id: The connection ID to use when fetching connection info.
: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 = (
"project_id",
"region",
"repository_id",
"workflow_invocation_id",
"impersonation_chain",
)
operator_extra_links = (DataformWorkflowInvocationLink(),)
def __init__(
self,
project_id: str,
region: str,
repository_id: str,
workflow_invocation_id: str,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.project_id = project_id
self.region = region
self.repository_id = repository_id
self.workflow_invocation_id = workflow_invocation_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook = DataformHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
DataformWorkflowInvocationLink.persist(
context=context,
project_id=self.project_id,
region=self.region,
repository_id=self.repository_id,
workflow_invocation_id=self.workflow_invocation_id,
)
hook.cancel_workflow_invocation(
project_id=self.project_id,
region=self.region,
repository_id=self.repository_id,
workflow_invocation_id=self.workflow_invocation_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
| DataformCancelWorkflowInvocationOperator |
python | getsentry__sentry | tests/sentry_plugins/github/endpoints/test_webhooks.py | {
"start": 209,
"end": 1999
} | class ____(APITestCase):
def test_get(self) -> None:
project = self.project # force creation
url = f"/plugins/github/organizations/{project.organization.id}/webhook/"
response = self.client.get(url)
assert response.status_code == 405
def test_unregistered_event(self) -> None:
project = self.project # force creation
url = f"/plugins/github/organizations/{project.organization.id}/webhook/"
secret = "b3002c3e321d4b7880360d397db2ccfd"
OrganizationOption.objects.set_value(
organization=project.organization, key="github:webhook_secret", value=secret
)
response = self.client.post(
path=url,
data=PUSH_EVENT_EXAMPLE,
content_type="application/json",
HTTP_X_GITHUB_EVENT="UnregisteredEvent",
HTTP_X_HUB_SIGNATURE="sha1=98196e70369945ffa6b248cf70f7dc5e46dff241",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 204
def test_invalid_signature_event(self) -> None:
project = self.project # force creation
url = f"/plugins/github/organizations/{project.organization.id}/webhook/"
secret = "2d7565c3537847b789d6995dca8d9f84"
OrganizationOption.objects.set_value(
organization=project.organization, key="github:webhook_secret", value=secret
)
response = self.client.post(
path=url,
data=PUSH_EVENT_EXAMPLE,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_HUB_SIGNATURE="sha1=33521abeaaf9a57c2abf486e0ccd54d23cf36fec",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 401
| WebhookTest |
python | run-llama__llama_index | llama-index-integrations/postprocessor/llama-index-postprocessor-contextual-rerank/llama_index/postprocessor/contextual_rerank/base.py | {
"start": 534,
"end": 3933
} | class ____(BaseNodePostprocessor):
"""
Contextual Reranking model.
Args:
model: str = Field(description="Contextual Reranking model name. Default is 'ctxl-rerank-en-v1-instruct'.")
top_n: int = Field(description="Top N nodes to return.")
base_url: Optional[str] = Field(description="Contextual base url.", default=None)
"""
model: str = Field(description="Contextual Reranking model name.")
top_n: int = Field(description="Top N nodes to return.")
base_url: Optional[str] = Field(description="Contextual base url.", default=None)
_client: Any = PrivateAttr()
def __init__(
self,
top_n: int = 2,
model: str = "ctxl-rerank-en-v1-instruct",
api_key: Optional[str] = None,
client: Optional[Any] = None,
base_url: Optional[str] = None,
):
super().__init__(top_n=top_n, model=model)
try:
api_key = api_key or os.environ["CONTEXTUAL_API_KEY"]
except IndexError:
raise ValueError(
"Must pass in contextual api key or "
"specify via CONTEXTUAL_API_KEY environment variable "
)
try:
from contextual import ContextualAI
except ImportError:
raise ImportError(
"Cannot import Contextual client package, please `pip install contextual-client`."
)
if client is not None:
self._client = client
else:
try:
self._client = ContextualAI(api_key=api_key, base_url=base_url)
except Exception as e:
raise ValueError(f"Failed to create Contextual client: {e}")
@classmethod
def class_name(cls) -> str:
return "ContextualRerank"
def _postprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
) -> List[NodeWithScore]:
dispatcher.event(
ReRankStartEvent(
query=query_bundle, nodes=nodes, top_n=self.top_n, model_name=self.model
)
)
if query_bundle is None:
raise ValueError("Missing query bundle in extra info.")
if len(nodes) == 0:
return []
with self.callback_manager.event(
CBEventType.RERANKING,
payload={
EventPayload.NODES: nodes,
EventPayload.MODEL_NAME: self.model,
EventPayload.QUERY_STR: query_bundle.query_str,
EventPayload.TOP_K: self.top_n,
},
) as event:
texts = [
node.node.get_content(metadata_mode=MetadataMode.EMBED)
for node in nodes
]
results = self._client.rerank.create(
model=self.model,
top_n=self.top_n,
query=query_bundle.query_str,
documents=texts,
)
new_nodes = []
for result in results.results:
new_node_with_score = NodeWithScore(
node=nodes[result.index].node, score=result.relevance_score
)
new_nodes.append(new_node_with_score)
event.on_end(payload={EventPayload.NODES: new_nodes})
dispatcher.event(ReRankEndEvent(nodes=new_nodes))
return new_nodes
| ContextualRerank |
python | huggingface__transformers | src/transformers/models/pvt_v2/modeling_pvt_v2.py | {
"start": 3671,
"end": 4584
} | class ____(nn.Module):
"""
Depth-wise (DW) convolution to infuse positional information using zero-padding. Depth-wise convolutions
have an equal number of groups to the number of input channels, meaning one filter per input channel. This
reduces the overall parameters and compute costs since the key purpose of this layer is position encoding.
"""
def __init__(self, config: PvtV2Config, dim: int = 768):
super().__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, hidden_states, height, width):
batch_size, seq_len, num_channels = hidden_states.shape
hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width)
hidden_states = self.dwconv(hidden_states)
hidden_states = hidden_states.flatten(2).transpose(1, 2)
return hidden_states
| PvtV2DepthWiseConv |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 66809,
"end": 67312
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
action: Annotated[
Literal["delete"], Field(description="The action to be performed on the entities.", title="Action")
]
entities: Annotated[
list[str | BulkTaskInstanceBody],
Field(description="A list of entity id/key or entity objects to be deleted.", title="Entities"),
]
action_on_non_existence: BulkActionNotOnExistence | None = "fail"
| BulkDeleteActionBulkTaskInstanceBody |
python | getsentry__sentry | src/sentry/monitors/endpoints/organization_monitor_schedule_sample_data.py | {
"start": 937,
"end": 2817
} | class ____(OrganizationEndpoint):
publish_status = {"GET": ApiPublishStatus.PRIVATE}
owner = ApiOwner.CRONS
def get(self, request: Request, organization: Organization) -> Response:
# Convert query params to a form the validator can use
config_data: dict[str, list | str] = {}
for key, val in request.GET.lists():
if key == "schedule" and len(val) > 1:
config_data[key] = [int(val[0]), val[1]]
else:
config_data[key] = val[0]
validator = SampleScheduleConfigValidator(data=config_data)
if not validator.is_valid():
return self.respond(validator.errors, status=400)
config = validator.validated_data
num_ticks = config.get("num_ticks")
schedule_type = config.get("schedule_type")
schedule = config.get("schedule")
tz = zoneinfo.ZoneInfo(config.get("timezone") or "UTC")
# Align the reference ts to the start of the hour
reference_ts = datetime.now(tz=tz).replace(minute=0, second=0, microsecond=0)
ticks: list[datetime] = []
if schedule_type == ScheduleType.CRONTAB:
schedule_iter = CronSim(schedule, reference_ts)
ticks = [next(schedule_iter) for _ in range(num_ticks)]
elif schedule_type == ScheduleType.INTERVAL:
rule = rrule.rrule(
freq=SCHEDULE_INTERVAL_MAP[cast(IntervalUnit, schedule[1])],
interval=schedule[0],
dtstart=reference_ts,
count=num_ticks,
)
new_date = reference_ts
ticks.append(new_date)
while len(ticks) < num_ticks:
new_date = rule.after(new_date)
ticks.append(new_date)
return Response([int(ts.timestamp()) for ts in ticks])
| OrganizationMonitorScheduleSampleDataEndpoint |
python | yaml__pyyaml | lib/yaml/loader.py | {
"start": 548,
"end": 864
} | class ____(Reader, Scanner, Parser, Composer, FullConstructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream)
Scanner.__init__(self)
Parser.__init__(self)
Composer.__init__(self)
FullConstructor.__init__(self)
Resolver.__init__(self)
| FullLoader |
python | ipython__ipython | IPython/lib/demo.py | {
"start": 22653,
"end": 24502
} | class ____(ClearMixin,IPythonDemo):
pass
def slide(file_path, noclear=False, format_rst=True, formatter="terminal",
style="native", auto_all=False, delimiter='...'):
if noclear:
demo_class = Demo
else:
demo_class = ClearDemo
demo = demo_class(file_path, format_rst=format_rst, formatter=formatter,
style=style, auto_all=auto_all)
while not demo.finished:
demo()
try:
py3compat.input('\n' + delimiter)
except KeyboardInterrupt:
exit(1)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Run python demos')
parser.add_argument('--noclear', '-C', action='store_true',
help='Do not clear terminal on each slide')
parser.add_argument('--rst', '-r', action='store_true',
help='Highlight comments and dostrings as rst')
parser.add_argument('--formatter', '-f', default='terminal',
help='pygments formatter name could be: terminal, '
'terminal256, terminal16m')
parser.add_argument('--style', '-s', default='default',
help='pygments style name')
parser.add_argument('--auto', '-a', action='store_true',
help='Run all blocks automatically without'
'confirmation')
parser.add_argument('--delimiter', '-d', default='...',
help='slides delimiter added after each slide run')
parser.add_argument('file', nargs=1,
help='python demo file')
args = parser.parse_args()
slide(args.file[0], noclear=args.noclear, format_rst=args.rst,
formatter=args.formatter, style=args.style, auto_all=args.auto,
delimiter=args.delimiter)
| ClearIPDemo |
python | PyCQA__pylint | tests/functional/c/ctor_arguments.py | {
"start": 2098,
"end": 2310
} | class ____(Exception):
def __init__(self, val=True):
self.val = val
BuiltinExc(42, 24, badarg=1) # [line-too-long,pointless-exception-statement,too-many-function-args,unexpected-keyword-arg]
| BuiltinExc |
python | pypa__pipenv | pipenv/patched/pip/_internal/utils/misc.py | {
"start": 10844,
"end": 15953
} | class ____(StringIO):
orig_stream: TextIO
@classmethod
def from_stream(cls, orig_stream: TextIO) -> "StreamWrapper":
ret = cls()
ret.orig_stream = orig_stream
return ret
# compileall.compile_dir() needs stdout.encoding to print to stdout
# type ignore is because TextIOBase.encoding is writeable
@property
def encoding(self) -> str: # type: ignore
return self.orig_stream.encoding
# Simulates an enum
def enum(*sequential: Any, **named: Any) -> Type[Any]:
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = {value: key for key, value in enums.items()}
enums["reverse_mapping"] = reverse
return type("Enum", (), enums)
def build_netloc(host: str, port: Optional[int]) -> str:
"""
Build a netloc from a host-port pair
"""
if port is None:
return host
if ":" in host:
# Only wrap host with square brackets when it is IPv6
host = f"[{host}]"
return f"{host}:{port}"
def build_url_from_netloc(netloc: str, scheme: str = "https") -> str:
"""
Build a full URL from a netloc.
"""
if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
# It must be a bare IPv6 address, so wrap it with brackets.
netloc = f"[{netloc}]"
return f"{scheme}://{netloc}"
def parse_netloc(netloc: str) -> Tuple[Optional[str], Optional[int]]:
"""
Return the host-port pair from a netloc.
"""
url = build_url_from_netloc(netloc)
parsed = urllib.parse.urlparse(url)
return parsed.hostname, parsed.port
def split_auth_from_netloc(netloc: str) -> NetlocTuple:
"""
Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)).
"""
if "@" not in netloc:
return netloc, (None, None)
# Split from the right because that's how urllib.parse.urlsplit()
# behaves if more than one @ is present (which can be checked using
# the password attribute of urlsplit()'s return value).
auth, netloc = netloc.rsplit("@", 1)
pw: Optional[str] = None
if ":" in auth:
# Split from the left because that's how urllib.parse.urlsplit()
# behaves if more than one : is present (which again can be checked
# using the password attribute of the return value)
user, pw = auth.split(":", 1)
else:
user, pw = auth, None
user = urllib.parse.unquote(user)
if pw is not None:
pw = urllib.parse.unquote(pw)
return netloc, (user, pw)
def redact_netloc(netloc: str) -> str:
"""
Replace the sensitive data in a netloc with "****", if it exists.
For example:
- "user:pass@example.com" returns "user:****@example.com"
- "accesstoken@example.com" returns "****@example.com"
"""
netloc, (user, password) = split_auth_from_netloc(netloc)
if user is None:
return netloc
if password is None:
user = "****"
password = ""
else:
user = urllib.parse.quote(user)
password = ":****"
return f"{user}{password}@{netloc}"
def _transform_url(
url: str, transform_netloc: Callable[[str], Tuple[Any, ...]]
) -> Tuple[str, NetlocTuple]:
"""Transform and replace netloc in a url.
transform_netloc is a function taking the netloc and returning a
tuple. The first element of this tuple is the new netloc. The
entire tuple is returned.
Returns a tuple containing the transformed url as item 0 and the
original tuple returned by transform_netloc as item 1.
"""
purl = urllib.parse.urlsplit(url)
netloc_tuple = transform_netloc(purl.netloc)
# stripped url
url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
surl = urllib.parse.urlunsplit(url_pieces)
return surl, cast("NetlocTuple", netloc_tuple)
def _get_netloc(netloc: str) -> NetlocTuple:
return split_auth_from_netloc(netloc)
def _redact_netloc(netloc: str) -> Tuple[str]:
return (redact_netloc(netloc),)
def split_auth_netloc_from_url(
url: str,
) -> Tuple[str, str, Tuple[Optional[str], Optional[str]]]:
"""
Parse a url into separate netloc, auth, and url with no auth.
Returns: (url_without_auth, netloc, (username, password))
"""
url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
return url_without_auth, netloc, auth
def remove_auth_from_url(url: str) -> str:
"""Return a copy of url with 'username:password@' removed."""
# username/pass params are passed to subversion through flags
# and are not recognized in the url.
return _transform_url(url, _get_netloc)[0]
def redact_auth_from_url(url: str) -> str:
"""Replace the password in a given url with ****."""
return _transform_url(url, _redact_netloc)[0]
def redact_auth_from_requirement(req: Requirement) -> str:
"""Replace the password in a given requirement url with ****."""
if not req.url:
return str(req)
return str(req).replace(req.url, redact_auth_from_url(req.url))
@dataclass(frozen=True)
| StreamWrapper |
python | spyder-ide__spyder | spyder/utils/snippets/nodes.py | {
"start": 11845,
"end": 12788
} | class ____(VariableSnippetNode):
"""
Node that represents a variable regex transformation snippet.
This node represents the expression ${var/regex/format/options}, where
regex is a PCRE-valid regex expression, format corresponds to a FormatNode
and options is a TextNode containing valid regex options.
"""
KIND = SnippetKind.REGEX
def __init__(self, variable, regex, fmt, options):
VariableSnippetNode.__init__(self, variable)
self.regex = re.compile(regex.text())
self.format = fmt
self.options = options
def text(self):
# FIXME: Implement regex variable placeholder composition once
# microsoft/language-server-protocol#801 is clarified
raise NotImplementedError('Regex variable snippets are '
'not currently implemented')
# -------------------- Regex formatting node classes --------------------------
| RegexNode |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/modules/file_services.py | {
"start": 622,
"end": 1054
} | class ____(SpyderRemoteAPIError):
"""
Exception for errors related to remote file services.
"""
def __init__(self, type, message, url, tracebacks):
self.type = type
self.message = message
self.url = url
self.tracebacks = tracebacks
def __str__(self):
return (
f"(type='{self.type}', message='{self.message}', url='{self.url}')"
)
| RemoteFileServicesError |
python | bokeh__bokeh | src/bokeh/core/property/struct.py | {
"start": 1387,
"end": 1503
} | class ____(Generic[T]):
def __init__(self, type_param: Property[T]):
self.type_param = type_param
| Optional |
python | crytic__slither | slither/core/expressions/new_array.py | {
"start": 179,
"end": 656
} | class ____(Expression):
def __init__(self, array_type: "ArrayType") -> None:
super().__init__()
# pylint: disable=import-outside-toplevel
from slither.core.solidity_types.array_type import ArrayType
assert isinstance(array_type, ArrayType)
self._array_type = array_type
@property
def array_type(self) -> "ArrayType":
return self._array_type
def __str__(self):
return "new " + str(self._array_type)
| NewArray |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/utils/multi.py | {
"start": 3997,
"end": 6436
} | class ____(str):
"""A multi-dimensional partition key stores the partition key for each dimension.
Subclasses the string class to keep partition key type as a string.
Contains additional methods to access the partition key for each dimension.
Creates a string representation of the partition key for each dimension, separated by a pipe (|).
Orders the dimensions by name, to ensure consistent string representation.
"""
dimension_keys: list[PartitionDimensionKey] = []
def __new__(cls, keys_by_dimension: Mapping[str, str]):
check.mapping_param(
keys_by_dimension, "partitions_by_dimension", key_type=str, value_type=str
)
dimension_keys: list[PartitionDimensionKey] = [
PartitionDimensionKey(dimension, keys_by_dimension[dimension])
for dimension in sorted(list(keys_by_dimension.keys()))
]
str_key = super().__new__(
cls,
MULTIPARTITION_KEY_DELIMITER.join(
[dim_key.partition_key for dim_key in dimension_keys]
),
)
str_key.dimension_keys = dimension_keys
return str_key
def __getnewargs__(self): # pyright: ignore[reportIncompatibleMethodOverride]
# When this instance is pickled, replace the argument to __new__ with the
# dimension key mapping instead of the string representation.
return ({dim_key.dimension_name: dim_key.partition_key for dim_key in self.dimension_keys},)
@property
def keys_by_dimension(self) -> Mapping[str, str]:
return {dim_key.dimension_name: dim_key.partition_key for dim_key in self.dimension_keys}
def get_tags_from_multi_partition_key(multi_partition_key: MultiPartitionKey) -> Mapping[str, str]:
check.inst_param(multi_partition_key, "multi_partition_key", MultiPartitionKey)
return {
get_multidimensional_partition_tag(dimension.dimension_name): dimension.partition_key
for dimension in multi_partition_key.dimension_keys
}
def get_multipartition_key_from_tags(tags: Mapping[str, str]) -> str:
partitions_by_dimension: dict[str, str] = {}
for tag in tags:
if tag.startswith(MULTIDIMENSIONAL_PARTITION_PREFIX):
dimension = tag[len(MULTIDIMENSIONAL_PARTITION_PREFIX) :]
partitions_by_dimension[dimension] = tags[tag]
return MultiPartitionKey(partitions_by_dimension)
@record
| MultiPartitionKey |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/tf_method_target.py | {
"start": 1102,
"end": 1841
} | class ____:
"""Binding target for methods replaced by function and defun."""
__slots__ = ("weakrefself_target__", "weakrefself_func__")
def __init__(self, target, original_python_function):
self.weakrefself_target__ = target
self.weakrefself_func__ = weakref.ref(original_python_function)
@property
def target(self):
return self.weakrefself_target__()
@property
def target_class(self):
true_self = self.weakrefself_target__()
if tf_inspect.isclass(true_self):
# Class method
return true_self
else:
return true_self.__class__
def call(self, args, kwargs):
wrapped_fn = self.weakrefself_func__()
return wrapped_fn(self.weakrefself_target__(), *args, **kwargs)
| TfMethodTarget |
python | weaviate__weaviate-python-client | weaviate/collections/classes/generative.py | {
"start": 11315,
"end": 14330
} | class ____(_GenerativeConfigRuntime):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.OPENAI, frozen=True, exclude=True
)
api_version: Optional[str]
base_url: Optional[AnyHttpUrl]
deployment_id: Optional[str]
frequency_penalty: Optional[float]
is_azure: bool
max_tokens: Optional[int]
model: Optional[str]
presence_penalty: Optional[float]
resource_name: Optional[str]
stop: Optional[List[str]]
temperature: Optional[float]
top_p: Optional[float]
verbosity: Optional[Union[OpenAiVerbosity, str]]
reasoning_effort: Optional[Union[OpenAiReasoningEffort, str]]
def _to_grpc(self, opts: _GenerativeConfigRuntimeOptions) -> generative_pb2.GenerativeProvider:
return generative_pb2.GenerativeProvider(
return_metadata=opts.return_metadata,
openai=generative_pb2.GenerativeOpenAI(
api_version=self.api_version,
base_url=_parse_anyhttpurl(self.base_url),
deployment_id=self.deployment_id,
frequency_penalty=self.frequency_penalty,
max_tokens=self.max_tokens,
model=self.model,
presence_penalty=self.presence_penalty,
resource_name=self.resource_name,
stop=_to_text_array(self.stop),
temperature=self.temperature,
top_p=self.top_p,
is_azure=self.is_azure,
images=_to_text_array(opts.images),
image_properties=_to_text_array(opts.image_properties),
verbosity=self.__verbosity(),
reasoning_effort=self.__reasoning_effort(),
),
)
def __verbosity(self):
if self.verbosity is None:
return None
if self.verbosity == "low":
return generative_pb2.GenerativeOpenAI.Verbosity.VERBOSITY_LOW
if self.verbosity == "medium":
return generative_pb2.GenerativeOpenAI.Verbosity.VERBOSITY_MEDIUM
if self.verbosity == "high":
return generative_pb2.GenerativeOpenAI.Verbosity.VERBOSITY_HIGH
raise WeaviateInvalidInputError(f"Invalid verbosity value: {self.verbosity}")
def __reasoning_effort(self):
if self.reasoning_effort is None:
return None
if self.reasoning_effort == "minimal":
return generative_pb2.GenerativeOpenAI.ReasoningEffort.REASONING_EFFORT_MINIMAL
if self.reasoning_effort == "low":
return generative_pb2.GenerativeOpenAI.ReasoningEffort.REASONING_EFFORT_LOW
if self.reasoning_effort == "medium":
return generative_pb2.GenerativeOpenAI.ReasoningEffort.REASONING_EFFORT_MEDIUM
if self.reasoning_effort == "high":
return generative_pb2.GenerativeOpenAI.ReasoningEffort.REASONING_EFFORT_HIGH
raise WeaviateInvalidInputError(f"Invalid reasoning_effort value: {self.reasoning_effort}")
| _GenerativeOpenAI |
python | readthedocs__readthedocs.org | readthedocs/projects/tests/test_build_tasks.py | {
"start": 104319,
"end": 106003
} | class ____(BuildEnvironmentBase):
@mock.patch("readthedocs.doc_builder.director.load_yaml_config")
def test_config_file_exception(self, load_yaml_config):
load_yaml_config.side_effect = ConfigError(
message_id=ConfigError.INVALID_VERSION,
)
self._trigger_update_docs_task()
# This is a known exceptions. We hit the notification API to attach a
# notification to this particular build.
notification_request = self.requests_mock.request_history[-3]
assert notification_request._request.method == "POST"
assert notification_request.path == "/api/v2/notifications/"
assert notification_request.json() == {
"attached_to": f"build/{self.build.pk}",
"message_id": ConfigError.INVALID_VERSION,
"state": "unread",
"dismissable": False,
"news": False,
"format_values": {},
}
build_status_request = self.requests_mock.request_history[-2]
assert build_status_request._request.method == "PATCH"
assert build_status_request.path == "/api/v2/build/1/"
assert build_status_request.json() == {
"id": 1,
"state": "finished",
"commit": "a1b2c3",
"error": "", # We not sending "error" anymore
"success": False,
"builder": mock.ANY,
"task_executed_at": mock.ANY,
"length": 0,
}
revoke_key_request = self.requests_mock.request_history[-1]
assert revoke_key_request._request.method == "POST"
assert revoke_key_request.path == "/api/v2/revoke/"
| TestBuildTaskExceptionHandler |
python | django__django | django/contrib/admindocs/views.py | {
"start": 6302,
"end": 8333
} | class ____(BaseAdminDocsView):
template_name = "admin_doc/view_detail.html"
@staticmethod
def _get_view_func(view):
urlconf = get_urlconf()
if get_resolver(urlconf)._is_callback(view):
mod, func = get_mod_func(view)
try:
# Separate the module and function, e.g.
# 'mymodule.views.myview' -> 'mymodule.views', 'myview').
return getattr(import_module(mod), func)
except ImportError:
# Import may fail because view contains a class name, e.g.
# 'mymodule.views.ViewContainer.my_view', so mod takes the form
# 'mymodule.views.ViewContainer'. Parse it again to separate
# the module and class.
mod, klass = get_mod_func(mod)
return getattr(getattr(import_module(mod), klass), func)
def get_context_data(self, **kwargs):
view = self.kwargs["view"]
view_func = self._get_view_func(view)
if view_func is None:
raise Http404
title, body, metadata = utils.parse_docstring(view_func.__doc__)
title = title and utils.parse_rst(title, "view", _("view:") + view)
body = body and utils.parse_rst(body, "view", _("view:") + view)
for key in metadata:
metadata[key] = utils.parse_rst(metadata[key], "model", _("view:") + view)
return super().get_context_data(
**{
**kwargs,
"name": view,
"summary": strip_p_tags(title),
"body": body,
"meta": metadata,
}
)
def user_has_model_view_permission(user, opts):
"""Based off ModelAdmin.has_view_permission."""
codename_view = get_permission_codename("view", opts)
codename_change = get_permission_codename("change", opts)
return user.has_perm("%s.%s" % (opts.app_label, codename_view)) or user.has_perm(
"%s.%s" % (opts.app_label, codename_change)
)
| ViewDetailView |
python | joke2k__faker | faker/providers/company/en_US/__init__.py | {
"start": 45,
"end": 87
} | class ____(CompanyProvider):
pass
| Provider |
python | pyenv__pyenv | plugins/python-build/scripts/add_miniconda.py | {
"start": 2746,
"end": 3042
} | class ____(type):
def __getattr__(self, name):
"""Generate PyVersion.PYXXX on demand to future-proof it"""
if PyVersion is not None:
return PyVersion(name.lower())
return super(PyVersionMeta,self).__getattr__(self, name)
@dataclass(frozen=True)
| PyVersionMeta |
python | ray-project__ray | python/ray/serve/_private/autoscaling_state.py | {
"start": 35491,
"end": 41502
} | class ____:
"""Manages all things autoscaling related.
Keeps track of request metrics for each application and its deployments,
and decides on the target number of replicas to autoscale to.
"""
def __init__(self):
self._app_autoscaling_states: Dict[
ApplicationName, ApplicationAutoscalingState
] = {}
def register_deployment(
self,
deployment_id: DeploymentID,
info: DeploymentInfo,
curr_target_num_replicas: int,
) -> int:
"""Register autoscaling deployment info."""
assert info.deployment_config.autoscaling_config
app_name = deployment_id.app_name
app_state = self._app_autoscaling_states.setdefault(
app_name, ApplicationAutoscalingState(app_name)
)
logger.info(f"Registering autoscaling state for deployment {deployment_id}")
return app_state.register_deployment(
deployment_id, info, curr_target_num_replicas
)
def deregister_deployment(self, deployment_id: DeploymentID):
"""Remove deployment from tracking."""
app_state = self._app_autoscaling_states.get(deployment_id.app_name)
if app_state:
logger.info(
f"Deregistering autoscaling state for deployment {deployment_id}"
)
app_state.deregister_deployment(deployment_id)
def register_application(
self,
app_name: ApplicationName,
autoscaling_policy: AutoscalingPolicy,
):
app_state = self._app_autoscaling_states.setdefault(
app_name, ApplicationAutoscalingState(app_name)
)
logger.info(f"Registering autoscaling state for application {app_name}")
app_state.register(autoscaling_policy)
def deregister_application(self, app_name: ApplicationName):
"""Remove application from tracking."""
if app_name in self._app_autoscaling_states:
logger.info(f"Deregistering autoscaling state for application {app_name}")
self._app_autoscaling_states.pop(app_name, None)
def _application_has_policy(self, app_name: ApplicationName) -> bool:
return (
app_name in self._app_autoscaling_states
and self._app_autoscaling_states[app_name].has_policy()
)
def get_decision_num_replicas(
self,
app_name: ApplicationName,
deployment_to_target_num_replicas: Dict[DeploymentID, int],
) -> Dict[DeploymentID, int]:
"""
Decide scaling for all deployments in the application.
Args:
app_name: The name of the application.
deployment_to_target_num_replicas: A dictionary of deployment_id to target number of replicas.
Returns:
A dictionary of deployment_id to decision number of replicas.
"""
return self._app_autoscaling_states[app_name].get_decision_num_replicas(
deployment_to_target_num_replicas
)
def should_autoscale_application(self, app_name: ApplicationName):
return app_name in self._app_autoscaling_states
def should_autoscale_deployment(self, deployment_id: DeploymentID):
return (
deployment_id.app_name in self._app_autoscaling_states
and self._app_autoscaling_states[
deployment_id.app_name
].should_autoscale_deployment(deployment_id)
)
def update_running_replica_ids(
self, deployment_id: DeploymentID, running_replicas: List[ReplicaID]
):
app_state = self._app_autoscaling_states.get(deployment_id.app_name)
if app_state:
app_state.update_running_replica_ids(deployment_id, running_replicas)
def on_replica_stopped(self, replica_id: ReplicaID):
app_state = self._app_autoscaling_states.get(replica_id.deployment_id.app_name)
if app_state:
app_state.on_replica_stopped(replica_id)
def get_metrics_for_deployment(
self, deployment_id: DeploymentID
) -> Dict[ReplicaID, List[TimeSeries]]:
if deployment_id.app_name in self._app_autoscaling_states:
return self._app_autoscaling_states[
deployment_id.app_name
].get_replica_metrics_by_deployment_id(deployment_id)
else:
return {}
def get_total_num_requests_for_deployment(
self, deployment_id: DeploymentID
) -> float:
if deployment_id.app_name in self._app_autoscaling_states:
return self._app_autoscaling_states[
deployment_id.app_name
].get_total_num_requests_for_deployment(deployment_id)
else:
return 0
def is_within_bounds(
self, deployment_id: DeploymentID, num_replicas_running_at_target_version: int
) -> bool:
app_state = self._app_autoscaling_states[deployment_id.app_name]
return app_state.is_within_bounds(
deployment_id, num_replicas_running_at_target_version
)
def record_request_metrics_for_replica(
self, replica_metric_report: ReplicaMetricReport
) -> None:
app_state = self._app_autoscaling_states.get(
replica_metric_report.replica_id.deployment_id.app_name
)
if app_state:
app_state.record_request_metrics_for_replica(replica_metric_report)
def record_request_metrics_for_handle(
self,
handle_metric_report: HandleMetricReport,
) -> None:
"""Update request metric for a specific handle."""
app_state = self._app_autoscaling_states.get(
handle_metric_report.deployment_id.app_name
)
if app_state:
app_state.record_request_metrics_for_handle(handle_metric_report)
def drop_stale_handle_metrics(self, alive_serve_actor_ids: Set[str]) -> None:
for app_state in self._app_autoscaling_states.values():
app_state.drop_stale_handle_metrics(alive_serve_actor_ids)
| AutoscalingStateManager |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_reflection.py | {
"start": 13642,
"end": 19446
} | class ____(fixtures.TablesTest):
run_create_tables = "once"
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"quote ' one",
metadata,
Column("id", Integer),
Column("name", String(50)),
Column("data", String(50)),
Column("related_id", Integer),
sa.PrimaryKeyConstraint("id", name="pk quote ' one"),
sa.Index("ix quote ' one", "name"),
sa.UniqueConstraint(
"data",
name="uq quote' one",
),
sa.ForeignKeyConstraint(
["id"], ["related.id"], name="fk quote ' one"
),
sa.CheckConstraint("name != 'foo'", name="ck quote ' one"),
comment=r"""quote ' one comment""",
test_needs_fk=True,
)
if testing.requires.symbol_names_w_double_quote.enabled:
Table(
'quote " two',
metadata,
Column("id", Integer),
Column("name", String(50)),
Column("data", String(50)),
Column("related_id", Integer),
sa.PrimaryKeyConstraint("id", name='pk quote " two'),
sa.Index('ix quote " two', "name"),
sa.UniqueConstraint(
"data",
name='uq quote" two',
),
sa.ForeignKeyConstraint(
["id"], ["related.id"], name='fk quote " two'
),
sa.CheckConstraint("name != 'foo'", name='ck quote " two '),
comment=r"""quote " two comment""",
test_needs_fk=True,
)
Table(
"related",
metadata,
Column("id", Integer, primary_key=True),
Column("related", Integer),
test_needs_fk=True,
)
if testing.requires.view_column_reflection.enabled:
if testing.requires.symbol_names_w_double_quote.enabled:
names = [
"quote ' one",
'quote " two',
]
else:
names = [
"quote ' one",
]
for name in names:
query = "CREATE VIEW %s AS SELECT * FROM %s" % (
config.db.dialect.identifier_preparer.quote(
"view %s" % name
),
config.db.dialect.identifier_preparer.quote(name),
)
event.listen(metadata, "after_create", DDL(query))
event.listen(
metadata,
"before_drop",
DDL(
"DROP VIEW %s"
% config.db.dialect.identifier_preparer.quote(
"view %s" % name
)
),
)
def quote_fixtures(fn):
return testing.combinations(
("quote ' one",),
('quote " two', testing.requires.symbol_names_w_double_quote),
)(fn)
@quote_fixtures
def test_get_table_options(self, name):
insp = inspect(config.db)
if testing.requires.reflect_table_options.enabled:
res = insp.get_table_options(name)
is_true(isinstance(res, dict))
else:
with expect_raises(NotImplementedError):
insp.get_table_options(name)
@quote_fixtures
@testing.requires.view_column_reflection
def test_get_view_definition(self, name):
insp = inspect(config.db)
assert insp.get_view_definition("view %s" % name)
@quote_fixtures
def test_get_columns(self, name):
insp = inspect(config.db)
assert insp.get_columns(name)
@quote_fixtures
def test_get_pk_constraint(self, name):
insp = inspect(config.db)
assert insp.get_pk_constraint(name)
@quote_fixtures
@testing.requires.foreign_key_constraint_reflection
def test_get_foreign_keys(self, name):
insp = inspect(config.db)
assert insp.get_foreign_keys(name)
@quote_fixtures
@testing.requires.index_reflection
def test_get_indexes(self, name):
insp = inspect(config.db)
assert insp.get_indexes(name)
@quote_fixtures
@testing.requires.unique_constraint_reflection
def test_get_unique_constraints(self, name):
insp = inspect(config.db)
assert insp.get_unique_constraints(name)
@quote_fixtures
@testing.requires.comment_reflection
def test_get_table_comment(self, name):
insp = inspect(config.db)
assert insp.get_table_comment(name)
@quote_fixtures
@testing.requires.check_constraint_reflection
def test_get_check_constraints(self, name):
insp = inspect(config.db)
assert insp.get_check_constraints(name)
def _multi_combination(fn):
schema = testing.combinations(
None,
(
lambda: config.test_schema,
testing.requires.schemas,
),
argnames="schema",
)
scope = testing.combinations(
ObjectScope.DEFAULT,
ObjectScope.TEMPORARY,
ObjectScope.ANY,
argnames="scope",
)
kind = testing.combinations(
ObjectKind.TABLE,
ObjectKind.VIEW,
ObjectKind.MATERIALIZED_VIEW,
ObjectKind.ANY,
ObjectKind.ANY_VIEW,
ObjectKind.TABLE | ObjectKind.VIEW,
ObjectKind.TABLE | ObjectKind.MATERIALIZED_VIEW,
argnames="kind",
)
filter_names = testing.combinations(True, False, argnames="use_filter")
return schema(scope(kind(filter_names(fn))))
| QuotedNameArgumentTest |
python | dagster-io__dagster | python_modules/dagster/dagster/components/resolved/model.py | {
"start": 1106,
"end": 1191
} | class ____:
callable: Callable[["ResolutionContext", Any], Any]
@dataclass
| ParentFn |
python | huggingface__transformers | src/transformers/models/deit/modeling_deit.py | {
"start": 18608,
"end": 19604
} | class ____(nn.Module):
def __init__(self, config: DeiTConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.pooler_output_size)
self.activation = ACT2FN[config.pooler_act]
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# 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="""
DeiT Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://huggingface.co/papers/2111.09886).
<Tip>
Note that we provide a script to pre-train this model on custom data in our [examples
directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
</Tip>
"""
)
| DeiTPooler |
python | google__pytype | pytype/overlays/six_overlay.py | {
"start": 137,
"end": 1487
} | class ____(overlay.Overlay):
"""A custom overlay for the 'six' module."""
def __init__(self, ctx):
member_map = {
"add_metaclass": metaclass.AddMetaclass.make,
"with_metaclass": metaclass.WithMetaclass.make,
"string_types": overlay.drop_module(build_string_types),
"integer_types": overlay.drop_module(build_integer_types),
"PY2": build_version_bool(2),
"PY3": build_version_bool(3),
}
ast = ctx.loader.import_name("six")
super().__init__(ctx, "six", member_map, ast)
def build_version_bool(major):
def make(ctx, module):
del module # unused
return ctx.convert.bool_values[ctx.python_version[0] == major]
return make
def build_string_types(ctx):
# six.string_types is defined as a tuple, even though it's only a single value
# in Py3.
# We're following the pyi definition of string_types here, because the real
# value in Py2 is `basestring`, which we don't have available.
classes = [ctx.convert.str_type.to_variable(ctx.root_node)]
return ctx.convert.tuple_to_value(classes)
def build_integer_types(ctx):
# pytype treats `long` as an alias of `int`, so the value of integer_types can
# be represented as just `(int,)` in both Py2 and Py3.
return ctx.convert.tuple_to_value((
ctx.convert.int_type.to_variable(ctx.root_node),
))
| SixOverlay |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_dialect.py | {
"start": 860,
"end": 6060
} | class ____(
ReservedWordFixture, fixtures.TestBase, AssertsCompiledSQL
):
__backend__ = True
__only_on__ = "mysql", "mariadb"
@testing.fixture
def mysql_version_dialect(self, testing_engine):
"""yield a MySQL engine that will simulate a specific version.
patches out various methods to not fail
"""
engine = testing_engine()
_server_version = [None]
with (
mock.patch.object(
engine.dialect,
"_get_server_version_info",
lambda conn: engine.dialect._parse_server_version(
_server_version[0]
),
),
mock.patch.object(
engine.dialect, "_set_mariadb", lambda *arg: None
),
mock.patch.object(
engine.dialect,
"get_isolation_level",
lambda *arg: "REPEATABLE READ",
),
):
def go(server_version):
_server_version[0] = server_version
return engine
yield go
def test_reserved_words_mysql_vs_mariadb(
self, mysql_mariadb_reserved_words
):
"""test #7167 - real backend level
We want to make sure that the "is mariadb" flag as well as the
correct identifier preparer are set up for dialects no matter how they
determine their "is_mariadb" flag.
"""
dialect = testing.db.dialect
expect_mariadb = testing.only_on("mariadb").enabled
table, expected_mysql, expected_mdb = mysql_mariadb_reserved_words
self.assert_compile(
select(table),
expected_mdb if expect_mariadb else expected_mysql,
dialect=dialect,
)
def test_no_show_variables(self):
engine = engines.testing_engine()
def my_execute(self, statement, *args, **kw):
if statement.startswith("SELECT @@"):
statement = "SELECT 1 FROM DUAL WHERE 1=0"
return real_exec(self, statement, *args, **kw)
real_exec = engine._connection_cls.exec_driver_sql
with mock.patch.object(
engine._connection_cls, "exec_driver_sql", my_execute
):
with expect_warnings(
"Could not retrieve SQL_MODE; please ensure the "
"MySQL user has permissions to SHOW VARIABLES"
):
engine.connect()
def test_no_default_isolation_level(self):
engine = engines.testing_engine()
real_isolation_level = testing.db.dialect.get_isolation_level
def fake_isolation_level(connection):
connection = mock.Mock(
cursor=mock.Mock(
return_value=mock.Mock(
fetchone=mock.Mock(return_value=None)
)
)
)
return real_isolation_level(connection)
with mock.patch.object(
engine.dialect, "get_isolation_level", fake_isolation_level
):
with expect_warnings(
"Could not retrieve transaction isolation level for MySQL "
"connection."
):
engine.connect()
@testing.combinations(
"10.5.12-MariaDB", "5.6.49", "5.0.2", argnames="server_version"
)
def test_variable_fetch(self, mysql_version_dialect, server_version):
"""test #7518"""
engine = mysql_version_dialect(server_version)
fetches = []
# the initialize() connection does not seem to use engine-level events.
# not changing that here
@event.listens_for(engine, "do_execute_no_params")
@event.listens_for(engine, "do_execute")
def do_execute_no_params(cursor, statement, *arg):
if statement.startswith("SHOW VARIABLES") or statement.startswith(
"SELECT @@"
):
fetches.append(statement)
return None
engine.connect()
if server_version == "5.0.2":
eq_(
fetches,
[
"SHOW VARIABLES LIKE 'sql_mode'",
"SHOW VARIABLES LIKE 'lower_case_table_names'",
],
)
else:
eq_(
fetches,
["SELECT @@sql_mode", "SELECT @@lower_case_table_names"],
)
def test_autocommit_isolation_level(self):
c = testing.db.connect().execution_options(
isolation_level="AUTOCOMMIT"
)
assert c.exec_driver_sql("SELECT @@autocommit;").scalar()
c.rollback()
c = c.execution_options(isolation_level="READ COMMITTED")
assert not c.exec_driver_sql("SELECT @@autocommit;").scalar()
def test_isolation_level(self):
values = [
"READ UNCOMMITTED",
"READ COMMITTED",
"REPEATABLE READ",
"SERIALIZABLE",
]
for value in values:
c = testing.db.connect().execution_options(isolation_level=value)
eq_(testing.db.dialect.get_isolation_level(c.connection), value)
| BackendDialectTest |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_error.py | {
"start": 2385,
"end": 2614
} | class ____(typing.TypedDict):
my_var: int | str # [unsupported-binary-operation]
# Check dataclasses
def my_decorator(*args, **kwargs):
def wraps(*args, **kwargs):
pass
return wraps
@dataclass
| CustomTypedDict4 |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 98637,
"end": 98933
} | class ____:
xlADORecordset = 7 # from enum XlQueryType
xlDAORecordset = 2 # from enum XlQueryType
xlODBCQuery = 1 # from enum XlQueryType
xlOLEDBQuery = 5 # from enum XlQueryType
xlTextImport = 6 # from enum XlQueryType
xlWebQuery = 4 # from enum XlQueryType
| QueryType |
python | pytorch__pytorch | torch/backends/_nnapi/serializer.py | {
"start": 2685,
"end": 2987
} | class ____:
IMMEDIATE = 0
NUMBERED_BUFFER = 2
NUMBERED_MEMORY = 3
# Scalar types that appear explicitly in models.
# These must be kept in sync with
# AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS.
# TODO: Expose these directly to Python to avoid maintaining this list.
| OperandValueSourceType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.