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 | ray-project__ray | python/ray/_private/serialization.py | {
"start": 1723,
"end": 4776
} | class ____(Exception):
pass
def _object_ref_deserializer(
binary, call_site, owner_address, object_status, tensor_transport_val
):
# NOTE(suquark): This function should be a global function so
# cloudpickle can access it directly. Otherwise cloudpickle
# has to dump the whole function definition, which is inefficient.
# NOTE(swang): Must deserialize the object first before asking
# the core worker to resolve the value. This is to make sure
# that the ref count for the ObjectRef is greater than 0 by the
# time the core worker resolves the value of the object.
obj_ref = ray.ObjectRef(
binary, owner_address, call_site, tensor_transport_val=tensor_transport_val
)
# TODO(edoakes): we should be able to just capture a reference
# to 'self' here instead, but this function is itself pickled
# somewhere, which causes an error.
if owner_address:
worker = ray._private.worker.global_worker
worker.check_connected()
context = worker.get_serialization_context()
outer_id = context.get_outer_object_ref()
# outer_id is None in the case that this ObjectRef was closed
# over in a function or pickled directly using pickle.dumps().
if outer_id is None:
outer_id = ray.ObjectRef.nil()
worker.core_worker.deserialize_and_register_object_ref(
obj_ref.binary(), outer_id, owner_address, object_status
)
return obj_ref
def _gpu_object_ref_deserializer(
binary,
call_site,
owner_address,
object_status,
tensor_transport_val,
gpu_object_meta,
):
"""
Deserialize a GPU object ref. When the GPU object ref is deserialized,
it firstly deserialize the normal object ref, and then add metadata of
the GPU object to the GPU object manager, which will be used to fetch
the GPU object later.
Args:
binary: The binary data of the object ref.
call_site: The call site of the object ref.
owner_address: The owner address of the object ref.
object_status: The object status of the object ref.
tensor_transport_val: The tensor transport value of the GPU object ref.
gpu_object_meta: The GPU object metadata. This is used to fetch the GPU object later.
Returns:
The deserialized GPU object ref.
"""
obj_ref = _object_ref_deserializer(
binary, call_site, owner_address, object_status, tensor_transport_val
)
gpu_object_manager = ray._private.worker.global_worker.gpu_object_manager
gpu_object_manager.add_gpu_object_metadata(obj_ref, gpu_object_meta)
return obj_ref
def _actor_handle_deserializer(serialized_obj, weak_ref):
# If this actor handle was stored in another object, then tell the
# core worker.
context = ray._private.worker.global_worker.get_serialization_context()
outer_id = context.get_outer_object_ref()
return ray.actor.ActorHandle._deserialization_helper(
serialized_obj, weak_ref, outer_id
)
| DeserializationError |
python | numba__numba | numba/tests/npyufunc/test_gufunc.py | {
"start": 565,
"end": 3203
} | class ____(MemoryLeakMixin, TestCase):
target = 'cpu'
def check_matmul_gufunc(self, gufunc):
matrix_ct = 1001
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4)
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5)
C = gufunc(A, B)
Gold = np.matmul(A, B)
np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8)
def test_gufunc(self):
gufunc = GUVectorize(matmulcore, '(m,n),(n,p)->(m,p)',
target=self.target)
gufunc.add((float32[:, :], float32[:, :], float32[:, :]))
gufunc = gufunc.build_ufunc()
self.check_matmul_gufunc(gufunc)
def test_guvectorize_decor(self):
gufunc = guvectorize([void(float32[:,:], float32[:,:], float32[:,:])],
'(m,n),(n,p)->(m,p)',
target=self.target)(matmulcore)
self.check_matmul_gufunc(gufunc)
def test_ufunc_like(self):
# Test problem that the stride of "scalar" gufunc argument not properly
# handled when the actual argument is an array,
# causing the same value (first value) being repeated.
gufunc = GUVectorize(axpy, '(), (), () -> ()', target=self.target)
gufunc.add('(intp, intp, intp, intp[:])')
gufunc = gufunc.build_ufunc()
x = np.arange(10, dtype=np.intp)
out = gufunc(x, x, x)
np.testing.assert_equal(out, x * x + x)
def test_axis(self):
# issue https://github.com/numba/numba/issues/6773
@guvectorize(["f8[:],f8[:]"], "(n)->(n)")
def my_cumsum(x, res):
acc = 0
for i in range(x.shape[0]):
acc += x[i]
res[i] = acc
x = np.ones((20, 30))
# Check regular call
y = my_cumsum(x, axis=0)
expected = np.cumsum(x, axis=0)
np.testing.assert_equal(y, expected)
# Check "out" kw
out_kw = np.zeros_like(y)
my_cumsum(x, out=out_kw, axis=0)
np.testing.assert_equal(out_kw, expected)
def test_docstring(self):
@guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)')
def gufunc(x, y, res):
"docstring for gufunc"
for i in range(x.shape[0]):
res[i] = x[i] + y
self.assertEqual("numba.tests.npyufunc.test_gufunc", gufunc.__module__)
self.assertEqual("gufunc", gufunc.__name__)
self.assertEqual("TestGUFunc.test_docstring.<locals>.gufunc", gufunc.__qualname__)
self.assertEqual("docstring for gufunc", gufunc.__doc__)
| TestGUFunc |
python | viewflow__viewflow | viewflow/workflow/flow/views/mixins.py | {
"start": 3436,
"end": 3642
} | class ____:
def dispatch(self, request, *args, **kwargs):
request.session["vf-pin-location"] = request.get_full_path()
return super().dispatch(request, *args, **kwargs)
| StoreRequestPathMixin |
python | scipy__scipy | scipy/stats/tests/test_hypotests.py | {
"start": 3959,
"end": 8707
} | class ____:
# the expected values of the cdfs are taken from Table 1 in
# Csorgo / Faraway: The Exact and Asymptotic Distribution of
# Cramér-von Mises Statistics, 1996.
@pytest.mark.parametrize('n, x, ref', [
(4, [0.02983, 0.04111, 0.12331, 0.94251], [0.01, 0.05, 0.5, 0.999]),
(10, [0.02657, 0.03830, 0.12068, 0.56643], [0.01, 0.05, 0.5, 0.975]),
(1000, [0.02481, 0.03658, 0.11889, 1.16120], [0.01, 0.05, 0.5, 0.999]),
(None, [0.02480, 0.03656, 0.11888, 1.16204], [0.01, 0.05, 0.5, 0.999]),
])
def test_cdf_ref(self, n, x, ref, xp):
xp_assert_close(_cdf_cvm(xp.asarray(x), n), xp.asarray(ref), atol=1e-4)
def test_cdf_support(self, xp):
# cdf has support on [1/(12*n), n/3]
xp_assert_equal(_cdf_cvm(xp.asarray([1/(12*533), 533/3]), 533),
xp.asarray([0., 1.]))
xp_assert_equal(_cdf_cvm(xp.asarray([1/(12*(27 + 1)), (27 + 1)/3]), 27),
xp.asarray([0., 1.]))
def test_cdf_large_n(self, xp):
# test that asymptotic cdf and cdf for large samples are close
x = xp.asarray([0.02480, 0.03656, 0.11888, 1.16204, 100])
xp_assert_close(_cdf_cvm(x, 10000), _cdf_cvm(x), atol=1e-4)
def test_large_x(self, xp):
# for large values of x and n, the series used to compute the cdf
# converges slowly.
# this leads to bug in R package goftest and MAPLE code that is
# the basis of the implementation in scipy
# note: cdf = 1 for x >= 1000/3 and n = 1000
x = xp.asarray(333.3, dtype=xp.float64)
assert (0.99999 < _cdf_cvm(x, 1000) < 1.0)
assert (0.99999 < _cdf_cvm(x) < 1.0)
def test_low_p(self, xp):
# _cdf_cvm can return values larger than 1. In that case, we just
# return a p-value of zero.
n = 12
res = cramervonmises(xp.ones(n)*0.8, special.ndtr)
assert _cdf_cvm(res.statistic, n, xp=xp) > 1.0
xp_assert_equal(res.pvalue, xp.asarray(0.))
@pytest.mark.skip_xp_backends('jax.numpy', reason='lazy -> no _axis_nan_policy')
@pytest.mark.parametrize('x', [(), [1.5]])
def test_invalid_input(self, x, xp):
with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
res = cramervonmises(xp.asarray(x), special.ndtr)
xp_assert_equal(res.statistic, xp.asarray(xp.nan))
xp_assert_equal(res.pvalue, xp.asarray(xp.nan))
@pytest.mark.parametrize('dtype', [None, 'float32', 'float64'])
def test_values_R(self, dtype, xp):
if is_numpy(xp) and xp.__version__ < "2.0" and dtype == 'float32':
pytest.skip("Pre-NEP 50 doesn't respect dtypes")
dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype)
# compared against R package goftest, version 1.1.1
# library(goftest)
# options(digits=16)
# cvm.test(c(-1.7, 2, 0, 1.3, 4, 0.1, 0.6), "pnorm")
res = cramervonmises(xp.asarray([-1.7, 2, 0, 1.3, 4, 0.1, 0.6], dtype=dtype),
special.ndtr)
xp_assert_close(res.statistic, xp.asarray(0.28815604599198, dtype=dtype))
xp_assert_close(res.pvalue, xp.asarray( 0.1453465252039, dtype=dtype))
# cvm.test(c(-1.7, 2, 0, 1.3, 4, 0.1, 0.6), "pnorm", mean = 3, sd = 1.5)
res = cramervonmises(xp.asarray([-1.7, 2, 0, 1.3, 4, 0.1, 0.6], dtype=dtype),
lambda x: special.ndtr((x - 3)/1.5))
xp_assert_close(res.statistic, xp.asarray(0.94266847977072, dtype=dtype))
xp_assert_close(res.pvalue, xp.asarray(0.002026416728467, dtype=dtype))
# cvm.test(c(1, 2, 5, 1.4, 0.14, 11, 13, 0.9, 7.5), "pexp")
res = cramervonmises(
xp.asarray([1, 2, 5, 1.4, 0.14, 11, 13, 0.9, 7.5], dtype=dtype),
lambda x: -xp.expm1(-x))
xp_assert_close(res.statistic, xp.asarray(0.84218540922393, dtype=dtype))
xp_assert_close(res.pvalue, xp.asarray(0.004433406063014, dtype=dtype))
def test_str_cdf(self, xp):
if not is_numpy(xp):
message = "`cdf` must be a callable if `rvs` is a non-NumPy array."
with pytest.raises(ValueError, match=message):
cramervonmises(xp.asarray([1, 2, 3]), "beta")
return
x, args = np.arange(5), (1.4, 0.7)
ref = cramervonmises(x, distributions.expon.cdf)
res = cramervonmises(x, "expon")
assert_equal((res.statistic, res.pvalue), (ref.statistic, ref.pvalue))
ref = cramervonmises(x, distributions.beta.cdf, args)
res = cramervonmises(x, "beta", args)
assert_equal((res.statistic, res.pvalue), (ref.statistic, ref.pvalue))
@make_xp_test_case(stats.mannwhitneyu)
| TestCvm |
python | huggingface__transformers | tests/models/blenderbot/test_modeling_blenderbot.py | {
"start": 8048,
"end": 11203
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (BlenderbotModel, BlenderbotForConditionalGeneration) if is_torch_available() else ()
pipeline_model_mapping = (
{
"feature-extraction": BlenderbotModel,
"summarization": BlenderbotForConditionalGeneration,
"text-generation": BlenderbotForCausalLM,
"text2text-generation": BlenderbotForConditionalGeneration,
"translation": BlenderbotForConditionalGeneration,
}
if is_torch_available()
else {}
)
is_encoder_decoder = True
test_missing_keys = False
def setUp(self):
self.model_tester = BlenderbotModelTester(self)
self.config_tester = ConfigTester(self, config_class=BlenderbotConfig)
def test_config(self):
self.config_tester.run_common_tests()
def test_save_load_strict(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
self.assertEqual(info["missing_keys"], set())
def test_decoder_model_past_with_large_inputs(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
def test_encoder_decoder_model_standalone(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
@require_torch_fp16
def test_generate_fp16(self):
config, input_dict = self.model_tester.prepare_config_and_inputs()
input_ids = input_dict["input_ids"]
attention_mask = input_ids.ne(1).to(torch_device)
model = BlenderbotForConditionalGeneration(config).eval().to(torch_device)
model.half()
model.generate(input_ids, attention_mask=attention_mask)
model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
def assert_tensors_close(a, b, atol=1e-12, prefix=""):
"""If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if torch.allclose(a, b, atol=atol):
return True
raise Exception
except Exception:
pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
if a.numel() > 100:
msg = f"tensor values are {pct_different:.1%} percent different."
else:
msg = f"{a} != {b}"
if prefix:
msg = prefix + ": " + msg
raise AssertionError(msg)
@unittest.skipUnless(torch_device != "cpu", "3B test too slow on CPU.")
@require_torch
@require_sentencepiece
@require_tokenizers
| BlenderbotModelTest |
python | PyCQA__pyflakes | pyflakes/reporter.py | {
"start": 60,
"end": 3001
} | class ____:
"""
Formats the results of pyflakes checks to users.
"""
def __init__(self, warningStream, errorStream):
"""
Construct a L{Reporter}.
@param warningStream: A file-like object where warnings will be
written to. The stream's C{write} method must accept unicode.
C{sys.stdout} is a good value.
@param errorStream: A file-like object where error output will be
written to. The stream's C{write} method must accept unicode.
C{sys.stderr} is a good value.
"""
self._stdout = warningStream
self._stderr = errorStream
def unexpectedError(self, filename, msg):
"""
An unexpected error occurred trying to process C{filename}.
@param filename: The path to a file that we could not process.
@ptype filename: C{unicode}
@param msg: A message explaining the problem.
@ptype msg: C{unicode}
"""
self._stderr.write(f"{filename}: {msg}\n")
def syntaxError(self, filename, msg, lineno, offset, text):
"""
There was a syntax error in C{filename}.
@param filename: The path to the file with the syntax error.
@ptype filename: C{unicode}
@param msg: An explanation of the syntax error.
@ptype msg: C{unicode}
@param lineno: The line number where the syntax error occurred.
@ptype lineno: C{int}
@param offset: The column on which the syntax error occurred, or None.
@ptype offset: C{int}
@param text: The source code containing the syntax error.
@ptype text: C{unicode}
"""
if text is None:
line = None
else:
line = text.splitlines()[-1]
# lineno might be None if the error was during tokenization
# lineno might be 0 if the error came from stdin
lineno = max(lineno or 0, 1)
if offset is not None:
# some versions of python emit an offset of -1 for certain encoding errors
offset = max(offset, 1)
self._stderr.write('%s:%d:%d: %s\n' %
(filename, lineno, offset, msg))
else:
self._stderr.write('%s:%d: %s\n' % (filename, lineno, msg))
if line is not None:
self._stderr.write(line)
self._stderr.write('\n')
if offset is not None:
self._stderr.write(re.sub(r'\S', ' ', line[:offset - 1]) +
"^\n")
def flake(self, message):
"""
pyflakes found something wrong with the code.
@param: A L{pyflakes.messages.Message}.
"""
self._stdout.write(str(message))
self._stdout.write('\n')
def _makeDefaultReporter():
"""
Make a reporter that can be used when no reporter is specified.
"""
return Reporter(sys.stdout, sys.stderr)
| Reporter |
python | getsentry__sentry | src/sentry/integrations/api/serializers/models/doc_integration.py | {
"start": 557,
"end": 2197
} | class ____(Serializer):
def get_attrs(
self,
item_list: Sequence[DocIntegration],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> dict[DocIntegration, dict[str, Any]]:
# Get associated IntegrationFeatures
doc_feature_attrs = IntegrationFeature.objects.get_by_targets_as_dict(
targets=item_list, target_type=IntegrationTypes.DOC_INTEGRATION
)
# Get associated DocIntegrationAvatar
avatars = DocIntegrationAvatar.objects.filter(doc_integration__in=item_list)
doc_avatar_attrs = {avatar.doc_integration_id: avatar for avatar in avatars}
# Attach both as attrs
return {
item: {
"features": doc_feature_attrs.get(item.id, set()),
"avatar": doc_avatar_attrs.get(item.id),
}
for item in item_list
}
def serialize(
self,
obj: DocIntegration,
attrs: Mapping[str, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> Any:
features = attrs.get("features")
data = {
"name": obj.name,
"slug": obj.slug,
"author": obj.author,
"description": obj.description,
"url": obj.url,
"popularity": obj.popularity,
"isDraft": obj.is_draft,
"features": ([serialize(x, user) for x in features] if features else []),
"avatar": serialize(attrs.get("avatar"), user),
}
if obj.metadata:
data.update(obj.metadata)
return data
| DocIntegrationSerializer |
python | spyder-ide__spyder | spyder/plugins/application/widgets/status.py | {
"start": 814,
"end": 2376
} | class ____(QDialog, SpyderFontsMixin):
CONF_SECTION = "main"
WIDTH = 530
HEIGHT = 620 if WIN else 665
def __init__(self, parent=None):
super().__init__(parent)
# Attributes
self.setWindowFlags(
self.windowFlags() & ~Qt.WindowContextHelpButtonHint
)
self.setFixedWidth(self.WIDTH)
self.setFixedHeight(self.HEIGHT)
self.setWindowTitle(_("Help Spyder"))
self.setWindowIcon(ima.icon("inapp_appeal"))
# Path to the appeal page
appeal_page_path = osp.join(
get_module_source_path("spyder.plugins.application.widgets"),
"appeal_page",
"dark" if is_dark_interface() else "light",
"index.html",
)
from spyder.widgets.browser import WebView
# Create webview to render the appeal message
webview = WebView(self, handle_links=True)
# Set font used in the view
app_font = self.get_font(SpyderFontType.Interface)
webview.set_font(app_font, size_delta=2)
# Load page
webview.load(QUrl.fromLocalFile(appeal_page_path))
# Open links in external browser
webview.page().linkClicked.connect(self._handle_link_clicks)
# Layout
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(webview)
self.setLayout(layout)
def _handle_link_clicks(self, url):
url = str(url.toString())
if url.startswith('http'):
start_file(url)
| InAppAppealDialog |
python | lepture__authlib | tests/flask/test_oauth2/test_client_registration_endpoint_oauth2.py | {
"start": 260,
"end": 7340
} | class ____(_ClientRegistrationEndpoint):
software_statement_alg_values_supported = ["RS256"]
def authenticate_token(self, request):
auth_header = request.headers.get("Authorization")
if auth_header:
request.user_id = 1
return auth_header
def resolve_public_key(self, request):
return read_file_path("rsa_public.pem")
def save_client(self, client_info, client_metadata, request):
client = Client(user_id=request.user_id, **client_info)
client.set_client_metadata(client_metadata)
db.session.add(client)
db.session.commit()
return client
@pytest.fixture
def metadata():
return {}
@pytest.fixture(autouse=True)
def server(server, app, metadata):
class MyClientRegistration(ClientRegistrationEndpoint):
def get_server_metadata(test_client):
return metadata
server.register_endpoint(MyClientRegistration)
@app.route("/create_client", methods=["POST"])
def create_client():
return server.create_endpoint_response("client_registration")
return server
def test_access_denied(test_client):
rv = test_client.post("/create_client", json={})
resp = json.loads(rv.data)
assert resp["error"] == "access_denied"
def test_invalid_request(test_client):
headers = {"Authorization": "bearer abc"}
rv = test_client.post("/create_client", json={}, headers=headers)
resp = json.loads(rv.data)
assert resp["error"] == "invalid_request"
def test_create_client(test_client):
headers = {"Authorization": "bearer abc"}
body = {"client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
def test_software_statement(test_client):
payload = {"software_id": "uuid-123", "client_name": "Authlib"}
s = jwt.encode({"alg": "RS256"}, payload, read_file_path("rsa_private.pem"))
body = {
"software_statement": s.decode("utf-8"),
}
headers = {"Authorization": "bearer abc"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
def test_no_public_key(test_client, server):
class ClientRegistrationEndpoint2(ClientRegistrationEndpoint):
def get_server_metadata(test_client):
return None
def resolve_public_key(self, request):
return None
payload = {"software_id": "uuid-123", "client_name": "Authlib"}
s = jwt.encode({"alg": "RS256"}, payload, read_file_path("rsa_private.pem"))
body = {
"software_statement": s.decode("utf-8"),
}
server._endpoints[ClientRegistrationEndpoint.ENDPOINT_NAME] = [
ClientRegistrationEndpoint2(server)
]
headers = {"Authorization": "bearer abc"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert resp["error"] in "unapproved_software_statement"
def test_scopes_supported(test_client, metadata):
metadata["scopes_supported"] = ["profile", "email"]
headers = {"Authorization": "bearer abc"}
body = {"scope": "profile email", "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
body = {"scope": "profile email address", "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_response_types_supported(test_client, metadata):
metadata["response_types_supported"] = ["code", "code id_token"]
headers = {"Authorization": "bearer abc"}
body = {"response_types": ["code"], "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
# The items order should not matter
# Extension response types MAY contain a space-delimited (%x20) list of
# values, where the order of values does not matter (e.g., response
# type "a b" is the same as "b a").
headers = {"Authorization": "bearer abc"}
body = {"response_types": ["id_token code"], "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
# https://www.rfc-editor.org/rfc/rfc7591.html#section-2
# If omitted, the default is that the client will use only the "code"
# response type.
body = {"client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
body = {"response_types": ["code", "token"], "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_grant_types_supported(test_client, metadata):
metadata["grant_types_supported"] = ["authorization_code", "password"]
headers = {"Authorization": "bearer abc"}
body = {"grant_types": ["password"], "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
# https://www.rfc-editor.org/rfc/rfc7591.html#section-2
# If omitted, the default behavior is that the client will use only
# the "authorization_code" Grant Type.
body = {"client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
body = {"grant_types": ["client_credentials"], "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_token_endpoint_auth_methods_supported(test_client, metadata):
metadata["token_endpoint_auth_methods_supported"] = ["client_secret_basic"]
headers = {"Authorization": "bearer abc"}
body = {
"token_endpoint_auth_method": "client_secret_basic",
"client_name": "Authlib",
}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
body = {"token_endpoint_auth_method": "none", "client_name": "Authlib"}
rv = test_client.post("/create_client", json=body, headers=headers)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
| ClientRegistrationEndpoint |
python | scipy__scipy | scipy/special/_mptestutils.py | {
"start": 454,
"end": 4153
} | class ____:
"""Generate a set of numbers on the real axis, concentrating on
'interesting' regions and covering all orders of magnitude.
"""
def __init__(self, a=-np.inf, b=np.inf, inclusive_a=True, inclusive_b=True):
if a > b:
raise ValueError("a should be less than or equal to b")
if a == -np.inf:
a = -0.5*np.finfo(float).max
if b == np.inf:
b = 0.5*np.finfo(float).max
self.a, self.b = a, b
self.inclusive_a, self.inclusive_b = inclusive_a, inclusive_b
def _positive_values(self, a, b, n):
if a < 0:
raise ValueError("a should be positive")
# Try to put half of the points into a linspace between a and
# 10 the other half in a logspace.
if n % 2 == 0:
nlogpts = n//2
nlinpts = nlogpts
else:
nlogpts = n//2
nlinpts = nlogpts + 1
if a >= 10:
# Outside of linspace range; just return a logspace.
pts = np.logspace(np.log10(a), np.log10(b), n)
elif a > 0 and b < 10:
# Outside of logspace range; just return a linspace
pts = np.linspace(a, b, n)
elif a > 0:
# Linspace between a and 10 and a logspace between 10 and
# b.
linpts = np.linspace(a, 10, nlinpts, endpoint=False)
logpts = np.logspace(1, np.log10(b), nlogpts)
pts = np.hstack((linpts, logpts))
elif a == 0 and b <= 10:
# Linspace between 0 and b and a logspace between 0 and
# the smallest positive point of the linspace
linpts = np.linspace(0, b, nlinpts)
if linpts.size > 1:
right = np.log10(linpts[1])
else:
right = -30
logpts = np.logspace(-30, right, nlogpts, endpoint=False)
pts = np.hstack((logpts, linpts))
else:
# Linspace between 0 and 10, logspace between 0 and the
# smallest positive point of the linspace, and a logspace
# between 10 and b.
if nlogpts % 2 == 0:
nlogpts1 = nlogpts//2
nlogpts2 = nlogpts1
else:
nlogpts1 = nlogpts//2
nlogpts2 = nlogpts1 + 1
linpts = np.linspace(0, 10, nlinpts, endpoint=False)
if linpts.size > 1:
right = np.log10(linpts[1])
else:
right = -30
logpts1 = np.logspace(-30, right, nlogpts1, endpoint=False)
logpts2 = np.logspace(1, np.log10(b), nlogpts2)
pts = np.hstack((logpts1, linpts, logpts2))
return np.sort(pts)
def values(self, n):
"""Return an array containing n numbers."""
a, b = self.a, self.b
if a == b:
return np.zeros(n)
if not self.inclusive_a:
n += 1
if not self.inclusive_b:
n += 1
if n % 2 == 0:
n1 = n//2
n2 = n1
else:
n1 = n//2
n2 = n1 + 1
if a >= 0:
pospts = self._positive_values(a, b, n)
negpts = []
elif b <= 0:
pospts = []
negpts = -self._positive_values(-b, -a, n)
else:
pospts = self._positive_values(0, b, n1)
negpts = -self._positive_values(0, -a, n2 + 1)
# Don't want to get zero twice
negpts = negpts[1:]
pts = np.hstack((negpts[::-1], pospts))
if not self.inclusive_a:
pts = pts[1:]
if not self.inclusive_b:
pts = pts[:-1]
return pts
| Arg |
python | numba__numba | numba/core/types/containers.py | {
"start": 21548,
"end": 23999
} | class ____(Literal, ConstSized, Hashable):
"""A Dictionary of string keys to heterogeneous values (basically a
namedtuple with dict semantics).
"""
class FakeNamedTuple(pySequence):
# This is namedtuple-like and is a workaround for #6518 and #7416.
# This has the couple of namedtuple properties that are used by Numba's
# internals but avoids use of an actual namedtuple as it cannot have
# numeric field names, i.e. `namedtuple('foo', '0 1')` is invalid.
def __init__(self, name, keys):
self.__name__ = name
self._fields = tuple(keys)
super(LiteralStrKeyDict.FakeNamedTuple, self).__init__()
def __len__(self):
return len(self._fields)
def __getitem__(self, key):
return self._fields[key]
mutable = False
def __init__(self, literal_value, value_index=None):
self._literal_init(literal_value)
self.value_index = value_index
strkeys = [x.literal_value for x in literal_value.keys()]
self.tuple_ty = self.FakeNamedTuple("_ntclazz", strkeys)
tys = [x for x in literal_value.values()]
self.types = tuple(tys)
self.count = len(self.types)
self.fields = tuple(self.tuple_ty._fields)
self.instance_class = self.tuple_ty
self.name = "LiteralStrKey[Dict]({})".format(literal_value)
def __unliteral__(self):
return Poison(self)
def unify(self, typingctx, other):
"""
Unify this with the *other* one.
"""
if isinstance(other, LiteralStrKeyDict):
tys = []
for (k1, v1), (k2, v2) in zip(
self.literal_value.items(), other.literal_value.items()
):
if k1 != k2: # keys must be same
break
tys.append(typingctx.unify_pairs(v1, v2))
else:
if all(tys):
d = {k: v for k, v in zip(self.literal_value.keys(), tys)}
return LiteralStrKeyDict(d)
def __len__(self):
return len(self.types)
def __iter__(self):
return iter(self.types)
@property
def key(self):
# use the namedtuple fields not the namedtuple itself as it's created
# locally in the ctor and comparison would always be False.
return self.tuple_ty._fields, self.types, str(self.literal_value)
| LiteralStrKeyDict |
python | ray-project__ray | python/ray/util/client/server/logservicer.py | {
"start": 918,
"end": 2724
} | class ____:
def __init__(self, queue):
self.queue = queue
self.id = str(uuid.uuid4())
def handle(self, data):
logdata = ray_client_pb2.LogData()
logdata.level = -2 if data["is_err"] else -1
logdata.name = "stderr" if data["is_err"] else "stdout"
with io.StringIO() as file:
print_worker_logs(data, file)
logdata.msg = file.getvalue()
self.queue.put(logdata)
def register_global(self):
global_worker_stdstream_dispatcher.add_handler(self.id, self.handle)
def unregister_global(self):
global_worker_stdstream_dispatcher.remove_handler(self.id)
def log_status_change_thread(log_queue, request_iterator):
std_handler = StdStreamHandler(log_queue)
current_handler = None
root_logger = logging.getLogger("ray")
default_level = root_logger.getEffectiveLevel()
try:
for req in request_iterator:
if current_handler is not None:
root_logger.setLevel(default_level)
root_logger.removeHandler(current_handler)
std_handler.unregister_global()
if not req.enabled:
current_handler = None
continue
current_handler = LogstreamHandler(log_queue, req.loglevel)
std_handler.register_global()
root_logger.addHandler(current_handler)
root_logger.setLevel(req.loglevel)
except grpc.RpcError as e:
logger.debug(f"closing log thread " f"grpc error reading request_iterator: {e}")
finally:
if current_handler is not None:
root_logger.setLevel(default_level)
root_logger.removeHandler(current_handler)
std_handler.unregister_global()
log_queue.put(None)
| StdStreamHandler |
python | huggingface__transformers | src/transformers/integrations/executorch.py | {
"start": 37040,
"end": 46286
} | class ____(torch.nn.Module):
def __init__(
self, model, batch_size=1, max_hidden_seq_length=4096, cache_implementation="static", max_cache_length=1024
):
super().__init__()
self.full_model = model
self.encoder = model.get_encoder()
self.config = model.config
self.max_hidden_seq_length = max_hidden_seq_length
self.generation_config = GenerationConfig(
use_cache=True,
max_length=max_cache_length,
cache_implementation=cache_implementation,
cache_config={
"batch_size": batch_size,
"max_cache_len": max_cache_length,
},
)
self.exported_encoder = None
self.exported_decoder = None
def _export_encoder(self, encoder_input_ids):
wrapped_encoder = Seq2SeqLMEncoderExportableModule(self.encoder).to(self.full_model.device).eval()
# Define dynamic sequence length for encoder
seq_len_dim = torch.export.Dim("encoder_seq_length", max=self.max_hidden_seq_length)
# Export the encoder
with torch.no_grad():
exported_encoder = torch.export.export(
wrapped_encoder, (encoder_input_ids,), dynamic_shapes={"input_ids": {1: seq_len_dim}}, strict=True
)
return exported_encoder
def _export_decoder(self, decoder_input_ids, encoder_hidden_states, cache_position):
target_device = self.full_model.device
wrapped_decoder = (
Seq2SeqLMDecoderExportableModuleWithStaticCache(
model=self.full_model,
max_static_cache_length=self.generation_config.cache_config.get("max_cache_len"),
batch_size=self.generation_config.cache_config.get("batch_size"),
)
.to(target_device)
.eval()
)
# Move input tensors to the same device as the wrapped decoder
decoder_input_ids = decoder_input_ids.to(target_device)
encoder_hidden_states = encoder_hidden_states.to(target_device)
cache_position = cache_position.to(target_device)
# Define dynamic dimension for encoder output sequence length
encoder_seq_len_dim = torch.export.Dim("encoder_hidden_seq_length", max=self.max_hidden_seq_length)
# Export the decoder
with torch.no_grad():
exported_decoder = torch.export.export(
wrapped_decoder,
(decoder_input_ids, encoder_hidden_states, cache_position),
dynamic_shapes={
"decoder_input_ids": None,
"encoder_hidden_states": {1: encoder_seq_len_dim},
"cache_position": None,
},
strict=True,
)
return exported_decoder
def export(self, encoder_input_ids=None, decoder_input_ids=None, encoder_hidden_states=None, cache_position=None):
device = self.full_model.device
example_encoder_input_ids = (
encoder_input_ids
if encoder_input_ids is not None
else torch.ones((1, 10), dtype=torch.long, device=device)
)
example_decoder_input_ids = (
decoder_input_ids
if decoder_input_ids is not None
else torch.tensor([[0]], dtype=torch.long, device=device)
) # Start token
example_cache_position = (
cache_position if cache_position is not None else torch.tensor([0], dtype=torch.long, device=device)
)
example_encoder_hidden_states = (
encoder_hidden_states
if encoder_hidden_states is not None
else torch.zeros(
(self.generation_config.cache_config.get("batch_size"), 10, self.config.d_model),
dtype=torch.float32,
device=device,
)
)
self.exported_encoder = self._export_encoder(example_encoder_input_ids)
self.exported_decoder = self._export_decoder(
example_decoder_input_ids, example_encoder_hidden_states, example_cache_position
)
# Return self to allow chaining
return self
def generate(self, prompt_token_ids, max_new_tokens):
with torch.no_grad():
model_device = self.full_model.device
# Move input to the model's device if it's on a different device
if prompt_token_ids.device != model_device:
prompt_token_ids = prompt_token_ids.to(model_device)
# Run encoder
encoder_output = self.exported_encoder.module()(prompt_token_ids)
# Initialize with start token (0 for T5) on the correct device
decoder_input_ids = torch.tensor([[0]], dtype=torch.long, device=model_device)
generated_ids = [0]
# Generate tokens one by one
for i in range(max_new_tokens - 1):
# Run decoder for next token prediction
logits = self.exported_decoder.module()(
decoder_input_ids, encoder_output, torch.tensor([i], dtype=torch.long, device=model_device)
)
# Get next token
next_token = torch.argmax(logits[:, -1, :], dim=-1).item()
generated_ids.append(next_token)
# Update input for next iteration on the correct device
decoder_input_ids = torch.tensor([[next_token]], dtype=torch.long, device=model_device)
# Check if EOS token
if next_token == self.config.eos_token_id:
break
return generated_ids
def export_with_dynamic_cache(
model: PreTrainedModel,
example_input_ids: torch.Tensor | None = None,
example_attention_mask: torch.Tensor | None = None,
):
"""
Export a model with DynamicCache using `torch.export`, ensuring the exported model is compatible with `ExecuTorch`.
Args:
model (`PreTrainedModel`): The pretrained model to be exported.
example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`.
example_attention_mask (`Optional[torch.Tensor]`): Example attention mask used by `torch.export`.
Returns:
Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
"""
if not is_torch_greater_or_equal_than_2_3:
raise ImportError("torch >= 2.3 is required.")
register_dynamic_cache_export_support()
with torch.no_grad():
exported_program = torch.export.export(
model,
(),
{
"input_ids": example_input_ids,
"attention_mask": example_attention_mask,
"past_key_values": DynamicCache(config=model.config),
"use_cache": True,
},
strict=False,
)
return exported_program
def register_dynamic_cache_export_support():
"""
Utilities for `DynamicCache` <> torch.export support
"""
try:
torch.utils._pytree.register_pytree_node(
DynamicCache,
lambda dynamic_cache: torch.utils._pytree._dict_flatten(_get_cache_dict(dynamic_cache)),
_unflatten_dynamic_cache,
serialized_type_name=f"{DynamicCache.__module__}.{DynamicCache.__name__}",
flatten_with_keys_fn=lambda dynamic_cache: torch.utils._pytree._dict_flatten_with_keys(
_get_cache_dict(dynamic_cache)
),
)
# TODO (tmanlaibaatar) This won't be needed in torch 2.7.
torch.fx._pytree.register_pytree_flatten_spec(
DynamicCache,
lambda cache, spec: torch.fx._pytree._dict_flatten_spec(_get_cache_dict(cache), spec),
)
# Catching this in case there are multiple runs for some test runs
except ValueError as e:
if "already registered as pytree node" not in str(e):
raise
def _get_cache_dict(cache: DynamicCache):
"""Convert cache to dictionary format for pytree operations."""
if any(not isinstance(layer, (DynamicLayer, DynamicSlidingWindowLayer)) for layer in cache.layers):
raise RuntimeError("This pytree flattening function should only be applied to DynamicCache")
if not is_torch_greater_or_equal_than_2_6:
logging.warning("DynamicCache + torch.export is tested on torch 2.6.0+ and may not work on earlier versions.")
return {
"key_cache": [layer.keys for layer in cache.layers if layer.keys is not None],
"value_cache": [layer.values for layer in cache.layers if layer.values is not None],
}
def _unflatten_dynamic_cache(values, context: torch.utils._pytree.Context):
dictionary = torch.utils._pytree._dict_unflatten(values, context)
cache = DynamicCache()
# Reconstruct layers from keys and values lists
key_list = dictionary.get("key_cache", [])
value_list = dictionary.get("value_cache", [])
for idx in range(max(len(key_list), len(value_list))):
key = key_list[idx] if idx < len(key_list) else None
value = value_list[idx] if idx < len(value_list) else None
cache.update(key, value, idx)
return cache
| Seq2SeqLMExportableModule |
python | Textualize__textual | tests/input/test_input_mouse.py | {
"start": 446,
"end": 2702
} | class ____(App[None]):
def __init__(self, text):
super().__init__()
self._text = text
def compose(self) -> ComposeResult:
yield Input(self._text)
@pytest.mark.parametrize(
"text, click_at, should_land",
(
# Single-width characters
(TEXT_SINGLE, 0, 0),
(TEXT_SINGLE, 1, 1),
(TEXT_SINGLE, 10, 10),
(TEXT_SINGLE, len(TEXT_SINGLE) - 1, len(TEXT_SINGLE) - 1),
(TEXT_SINGLE, len(TEXT_SINGLE), len(TEXT_SINGLE)),
(TEXT_SINGLE, len(TEXT_SINGLE) + 10, len(TEXT_SINGLE)),
# Double-width characters
(TEXT_DOUBLE, 0, 0),
(TEXT_DOUBLE, 1, 0),
(TEXT_DOUBLE, 2, 1),
(TEXT_DOUBLE, 3, 1),
(TEXT_DOUBLE, 4, 2),
(TEXT_DOUBLE, 5, 2),
(TEXT_DOUBLE, (len(TEXT_DOUBLE) * 2) - 1, len(TEXT_DOUBLE) - 1),
(TEXT_DOUBLE, len(TEXT_DOUBLE) * 2, len(TEXT_DOUBLE)),
(TEXT_DOUBLE, len(TEXT_DOUBLE) * 10, len(TEXT_DOUBLE)),
# Mixed-width characters
(TEXT_MIXED, 0, 0),
(TEXT_MIXED, 1, 1),
(TEXT_MIXED, 2, 1),
(TEXT_MIXED, 3, 2),
(TEXT_MIXED, 4, 2),
(TEXT_MIXED, 5, 3),
(TEXT_MIXED, 13, 9),
(TEXT_MIXED, 14, 9),
(TEXT_MIXED, 15, 10),
(TEXT_MIXED, 60, 10),
),
)
async def test_mouse_clicks_within(text, click_at, should_land):
"""Mouse clicks should result in the cursor going to the right place."""
async with InputApp(text).run_test() as pilot:
# Note the offsets to take into account the decoration around an
# Input.
await pilot.click(Input, Offset(click_at + 3, 1))
await pilot.pause()
assert pilot.app.query_one(Input).cursor_position == should_land
async def test_mouse_click_outwith_moves_cursor_to_nearest_cell():
"""Mouse clicks in the padding or border area should move the cursor as this makes
dragging and selecting text easier."""
async with InputApp(TEXT_SINGLE).run_test() as pilot:
pilot.app.query_one(Input).cursor_position = 3
assert pilot.app.query_one(Input).cursor_position == 3
await pilot.click(Input, Offset(0, 0))
await pilot.pause()
assert pilot.app.query_one(Input).cursor_position == 0
| InputApp |
python | pytest-dev__pytest | src/_pytest/pytester.py | {
"start": 19945,
"end": 20154
} | class ____:
def __init__(self) -> None:
self.__saved = list(sys.path), list(sys.meta_path)
def restore(self) -> None:
sys.path[:], sys.meta_path[:] = self.__saved
@final
| SysPathsSnapshot |
python | django__django | tests/validation/test_validators.py | {
"start": 113,
"end": 1536
} | class ____(ValidationAssertions, SimpleTestCase):
def test_custom_validator_passes_for_correct_value(self):
mtv = ModelToValidate(
number=10,
name="Some Name",
f_with_custom_validator=42,
f_with_iterable_of_validators=42,
)
self.assertIsNone(mtv.full_clean())
def test_custom_validator_raises_error_for_incorrect_value(self):
mtv = ModelToValidate(
number=10,
name="Some Name",
f_with_custom_validator=12,
f_with_iterable_of_validators=42,
)
self.assertFailsValidation(mtv.full_clean, ["f_with_custom_validator"])
self.assertFieldFailsValidationWithMessage(
mtv.full_clean,
"f_with_custom_validator",
["This is not the answer to life, universe and everything!"],
)
def test_field_validators_can_be_any_iterable(self):
mtv = ModelToValidate(
number=10,
name="Some Name",
f_with_custom_validator=42,
f_with_iterable_of_validators=12,
)
self.assertFailsValidation(mtv.full_clean, ["f_with_iterable_of_validators"])
self.assertFieldFailsValidationWithMessage(
mtv.full_clean,
"f_with_iterable_of_validators",
["This is not the answer to life, universe and everything!"],
)
| TestModelsWithValidators |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py | {
"start": 3297,
"end": 3677
} | class ____(graphene.ObjectType):
entries = non_null_list(lambda: GrapheneEvaluationStackEntry)
class Meta:
name = "EvaluationStack"
def __init__(self, stack):
self._stack = stack
super().__init__()
def resolve_entries(self, _):
return map(GrapheneEvaluationStackEntry.from_native_entry, self._stack.entries)
| GrapheneEvaluationStack |
python | django__django | tests/gis_tests/gdal_tests/test_geom.py | {
"start": 446,
"end": 45150
} | class ____(SimpleTestCase, TestDataMixin):
"This tests the OGR Geometry."
def test_geomtype(self):
"Testing OGRGeomType object."
# OGRGeomType should initialize on all these inputs.
OGRGeomType(1)
OGRGeomType(7)
OGRGeomType("point")
OGRGeomType("GeometrycollectioN")
OGRGeomType("LINearrING")
OGRGeomType("Unknown")
# Should throw TypeError on this input
with self.assertRaises(GDALException):
OGRGeomType(23)
with self.assertRaises(GDALException):
OGRGeomType("fooD")
with self.assertRaises(GDALException):
OGRGeomType(4001)
# Equivalence can take strings, ints, and other OGRGeomTypes
self.assertEqual(OGRGeomType(1), OGRGeomType(1))
self.assertEqual(OGRGeomType(7), "GeometryCollection")
self.assertEqual(OGRGeomType("point"), "POINT")
self.assertNotEqual(OGRGeomType("point"), 2)
self.assertEqual(OGRGeomType("unknown"), 0)
self.assertEqual(OGRGeomType(6), "MULtiPolyGON")
self.assertEqual(OGRGeomType(1), OGRGeomType("point"))
self.assertNotEqual(OGRGeomType("POINT"), OGRGeomType(6))
# Testing the Django field name equivalent property.
self.assertEqual("PointField", OGRGeomType("Point").django)
self.assertEqual("GeometryField", OGRGeomType("Geometry").django)
self.assertEqual("GeometryField", OGRGeomType("Unknown").django)
self.assertIsNone(OGRGeomType("none").django)
# 'Geometry' initialization implies an unknown geometry type.
gt = OGRGeomType("Geometry")
self.assertEqual(0, gt.num)
self.assertEqual("Unknown", gt.name)
def test_geom_type_repr(self):
self.assertEqual(repr(OGRGeomType("point")), "<OGRGeomType: Point>")
def test_geomtype_25d(self):
"Testing OGRGeomType object with 25D types."
wkb25bit = OGRGeomType.wkb25bit
self.assertEqual(OGRGeomType(wkb25bit + 1), "Point25D")
self.assertEqual(OGRGeomType("MultiLineString25D"), (5 + wkb25bit))
self.assertEqual(
"GeometryCollectionField", OGRGeomType("GeometryCollection25D").django
)
def test_wkt(self):
"Testing WKT output."
for g in self.geometries.wkt_out:
geom = OGRGeometry(g.wkt)
self.assertEqual(g.wkt, geom.wkt)
def test_ewkt(self):
"Testing EWKT input/output."
for ewkt_val in ("POINT (1 2 3)", "LINEARRING (0 0,1 1,2 1,0 0)"):
# First with ewkt output when no SRID in EWKT
self.assertEqual(ewkt_val, OGRGeometry(ewkt_val).ewkt)
# No test consumption with an SRID specified.
ewkt_val = "SRID=4326;%s" % ewkt_val
geom = OGRGeometry(ewkt_val)
self.assertEqual(ewkt_val, geom.ewkt)
self.assertEqual(4326, geom.srs.srid)
def test_gml(self):
"Testing GML output."
for g in self.geometries.wkt_out:
geom = OGRGeometry(g.wkt)
exp_gml = g.gml
self.assertEqual(exp_gml, geom.gml)
def test_hex(self):
"Testing HEX input/output."
for g in self.geometries.hex_wkt:
geom1 = OGRGeometry(g.wkt)
self.assertEqual(g.hex.encode(), geom1.hex)
# Constructing w/HEX
geom2 = OGRGeometry(g.hex)
self.assertEqual(geom1, geom2)
def test_wkb(self):
"Testing WKB input/output."
for g in self.geometries.hex_wkt:
geom1 = OGRGeometry(g.wkt)
wkb = geom1.wkb
self.assertEqual(wkb.hex().upper(), g.hex)
# Constructing w/WKB.
geom2 = OGRGeometry(wkb)
self.assertEqual(geom1, geom2)
def test_json(self):
"Testing GeoJSON input/output."
for g in self.geometries.json_geoms:
geom = OGRGeometry(g.wkt)
if not hasattr(g, "not_equal"):
# Loading jsons to prevent decimal differences
self.assertEqual(json.loads(g.json), json.loads(geom.json))
self.assertEqual(json.loads(g.json), json.loads(geom.geojson))
self.assertEqual(OGRGeometry(g.wkt), OGRGeometry(geom.json))
# Test input with some garbage content (but valid json) (#15529)
geom = OGRGeometry(
'{"type": "Point", "coordinates": [ 100.0, 0.0 ], "other": "<test>"}'
)
self.assertIsInstance(geom, OGRGeometry)
def test_points(self):
"Testing Point objects."
OGRGeometry("POINT(0 0)")
for p in self.geometries.points:
if not hasattr(p, "z"): # No 3D
pnt = OGRGeometry(p.wkt)
self.assertEqual(1, pnt.geom_type)
self.assertEqual("POINT", pnt.geom_name)
self.assertEqual(p.x, pnt.x)
self.assertEqual(p.y, pnt.y)
self.assertEqual((p.x, p.y), pnt.tuple)
def test_multipoints(self):
"Testing MultiPoint objects."
for mp in self.geometries.multipoints:
mgeom1 = OGRGeometry(mp.wkt) # First one from WKT
self.assertEqual(4, mgeom1.geom_type)
self.assertEqual("MULTIPOINT", mgeom1.geom_name)
mgeom2 = OGRGeometry("MULTIPOINT") # Creating empty multipoint
mgeom3 = OGRGeometry("MULTIPOINT")
for g in mgeom1:
mgeom2.add(g) # adding each point from the multipoints
mgeom3.add(g.wkt) # should take WKT as well
self.assertEqual(mgeom1, mgeom2) # they should equal
self.assertEqual(mgeom1, mgeom3)
self.assertEqual(mp.coords, mgeom2.coords)
self.assertEqual(mp.n_p, mgeom2.point_count)
def test_linestring(self):
"Testing LineString objects."
prev = OGRGeometry("POINT(0 0)")
for ls in self.geometries.linestrings:
linestr = OGRGeometry(ls.wkt)
self.assertEqual(2, linestr.geom_type)
self.assertEqual("LINESTRING", linestr.geom_name)
self.assertEqual(ls.n_p, linestr.point_count)
self.assertEqual(ls.coords, linestr.tuple)
self.assertEqual(linestr, OGRGeometry(ls.wkt))
self.assertNotEqual(linestr, prev)
msg = "Index out of range when accessing points of a line string: %s."
with self.assertRaisesMessage(IndexError, msg % len(linestr)):
linestr.__getitem__(len(linestr))
prev = linestr
# Testing the x, y properties.
x = [tmpx for tmpx, tmpy in ls.coords]
y = [tmpy for tmpx, tmpy in ls.coords]
self.assertEqual(x, linestr.x)
self.assertEqual(y, linestr.y)
def test_multilinestring(self):
"Testing MultiLineString objects."
prev = OGRGeometry("POINT(0 0)")
for mls in self.geometries.multilinestrings:
mlinestr = OGRGeometry(mls.wkt)
self.assertEqual(5, mlinestr.geom_type)
self.assertEqual("MULTILINESTRING", mlinestr.geom_name)
self.assertEqual(mls.n_p, mlinestr.point_count)
self.assertEqual(mls.coords, mlinestr.tuple)
self.assertEqual(mlinestr, OGRGeometry(mls.wkt))
self.assertNotEqual(mlinestr, prev)
prev = mlinestr
for ls in mlinestr:
self.assertEqual(2, ls.geom_type)
self.assertEqual("LINESTRING", ls.geom_name)
msg = "Index out of range when accessing geometry in a collection: %s."
with self.assertRaisesMessage(IndexError, msg % len(mlinestr)):
mlinestr.__getitem__(len(mlinestr))
def test_linearring(self):
"Testing LinearRing objects."
prev = OGRGeometry("POINT(0 0)")
for rr in self.geometries.linearrings:
lr = OGRGeometry(rr.wkt)
# self.assertEqual(101, lr.geom_type.num)
self.assertEqual("LINEARRING", lr.geom_name)
self.assertEqual(rr.n_p, len(lr))
self.assertEqual(lr, OGRGeometry(rr.wkt))
self.assertNotEqual(lr, prev)
prev = lr
def test_polygons(self):
"Testing Polygon objects."
# Testing `from_bbox` class method
bbox = (-180, -90, 180, 90)
p = OGRGeometry.from_bbox(bbox)
self.assertEqual(bbox, p.extent)
prev = OGRGeometry("POINT(0 0)")
for p in self.geometries.polygons:
poly = OGRGeometry(p.wkt)
self.assertEqual(3, poly.geom_type)
self.assertEqual("POLYGON", poly.geom_name)
self.assertEqual(p.n_p, poly.point_count)
self.assertEqual(p.n_i + 1, len(poly))
msg = "Index out of range when accessing rings of a polygon: %s."
with self.assertRaisesMessage(IndexError, msg % len(poly)):
poly.__getitem__(len(poly))
# Testing area & centroid.
self.assertAlmostEqual(p.area, poly.area, 9)
x, y = poly.centroid.tuple
self.assertAlmostEqual(p.centroid[0], x, 9)
self.assertAlmostEqual(p.centroid[1], y, 9)
# Testing equivalence
self.assertEqual(poly, OGRGeometry(p.wkt))
self.assertNotEqual(poly, prev)
if p.ext_ring_cs:
ring = poly[0]
self.assertEqual(p.ext_ring_cs, ring.tuple)
self.assertEqual(p.ext_ring_cs, poly[0].tuple)
self.assertEqual(len(p.ext_ring_cs), ring.point_count)
for r in poly:
self.assertEqual("LINEARRING", r.geom_name)
def test_polygons_templates(self):
# Accessing Polygon attributes in templates should work.
engine = Engine()
template = engine.from_string("{{ polygons.0.wkt }}")
polygons = [OGRGeometry(p.wkt) for p in self.geometries.multipolygons[:2]]
content = template.render(Context({"polygons": polygons}))
self.assertIn("MULTIPOLYGON (((100", content)
def test_closepolygons(self):
"Testing closing Polygon objects."
# Both rings in this geometry are not closed.
poly = OGRGeometry("POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))")
self.assertEqual(8, poly.point_count)
with self.assertRaises(GDALException):
poly.centroid
poly.close_rings()
self.assertEqual(
10, poly.point_count
) # Two closing points should've been added
self.assertEqual(OGRGeometry("POINT(2.5 2.5)"), poly.centroid)
def test_multipolygons(self):
"Testing MultiPolygon objects."
OGRGeometry("POINT(0 0)")
for mp in self.geometries.multipolygons:
mpoly = OGRGeometry(mp.wkt)
self.assertEqual(6, mpoly.geom_type)
self.assertEqual("MULTIPOLYGON", mpoly.geom_name)
if mp.valid:
self.assertEqual(mp.n_p, mpoly.point_count)
self.assertEqual(mp.num_geom, len(mpoly))
msg = "Index out of range when accessing geometry in a collection: %s."
with self.assertRaisesMessage(IndexError, msg % len(mpoly)):
mpoly.__getitem__(len(mpoly))
for p in mpoly:
self.assertEqual("POLYGON", p.geom_name)
self.assertEqual(3, p.geom_type)
self.assertEqual(mpoly.wkt, OGRGeometry(mp.wkt).wkt)
def test_srs(self):
"Testing OGR Geometries with Spatial Reference objects."
for mp in self.geometries.multipolygons:
# Creating a geometry w/spatial reference
sr = SpatialReference("WGS84")
mpoly = OGRGeometry(mp.wkt, sr)
self.assertEqual(sr.wkt, mpoly.srs.wkt)
# Ensuring that SRS is propagated to clones.
klone = mpoly.clone()
self.assertEqual(sr.wkt, klone.srs.wkt)
# Ensuring all children geometries (polygons and their rings) all
# return the assigned spatial reference as well.
for poly in mpoly:
self.assertEqual(sr.wkt, poly.srs.wkt)
for ring in poly:
self.assertEqual(sr.wkt, ring.srs.wkt)
# Ensuring SRS propagate in topological ops.
a = OGRGeometry(self.geometries.topology_geoms[0].wkt_a, sr)
b = OGRGeometry(self.geometries.topology_geoms[0].wkt_b, sr)
diff = a.difference(b)
union = a.union(b)
self.assertEqual(sr.wkt, diff.srs.wkt)
self.assertEqual(sr.srid, union.srs.srid)
# Instantiating w/an integer SRID
mpoly = OGRGeometry(mp.wkt, 4326)
self.assertEqual(4326, mpoly.srid)
mpoly.srs = SpatialReference(4269)
self.assertEqual(4269, mpoly.srid)
self.assertEqual("NAD83", mpoly.srs.name)
# Incrementing through the multipolygon after the spatial reference
# has been re-assigned.
for poly in mpoly:
self.assertEqual(mpoly.srs.wkt, poly.srs.wkt)
poly.srs = 32140
for ring in poly:
# Changing each ring in the polygon
self.assertEqual(32140, ring.srs.srid)
self.assertEqual("NAD83 / Texas South Central", ring.srs.name)
ring.srs = str(SpatialReference(4326)) # back to WGS84
self.assertEqual(4326, ring.srs.srid)
# Using the `srid` property.
ring.srid = 4322
self.assertEqual("WGS 72", ring.srs.name)
self.assertEqual(4322, ring.srid)
# srs/srid may be assigned their own values, even when srs is None.
mpoly = OGRGeometry(mp.wkt, srs=None)
mpoly.srs = mpoly.srs
mpoly.srid = mpoly.srid
def test_srs_transform(self):
"Testing transform()."
orig = OGRGeometry("POINT (-104.609 38.255)", 4326)
trans = OGRGeometry("POINT (992385.4472045 481455.4944650)", 2774)
# Using an srid, a SpatialReference object, and a CoordTransform object
# or transformations.
t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
t1.transform(trans.srid)
t2.transform(SpatialReference("EPSG:2774"))
ct = CoordTransform(SpatialReference("WGS84"), SpatialReference(2774))
t3.transform(ct)
# Testing use of the `clone` keyword.
k1 = orig.clone()
k2 = k1.transform(trans.srid, clone=True)
self.assertEqual(k1, orig)
self.assertNotEqual(k1, k2)
# Different PROJ versions use different transformations, all are
# correct as having a 1 meter accuracy.
prec = -1
for p in (t1, t2, t3, k2):
self.assertAlmostEqual(trans.x, p.x, prec)
self.assertAlmostEqual(trans.y, p.y, prec)
def test_transform_dim(self):
"Testing coordinate dimension is the same on transformed geometries."
ls_orig = OGRGeometry("LINESTRING(-104.609 38.255)", 4326)
ls_trans = OGRGeometry("LINESTRING(992385.4472045 481455.4944650)", 2774)
# Different PROJ versions use different transformations, all are
# correct as having a 1 meter accuracy.
prec = -1
ls_orig.transform(ls_trans.srs)
# Making sure the coordinate dimension is still 2D.
self.assertEqual(2, ls_orig.coord_dim)
self.assertAlmostEqual(ls_trans.x[0], ls_orig.x[0], prec)
self.assertAlmostEqual(ls_trans.y[0], ls_orig.y[0], prec)
def test_difference(self):
"Testing difference()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
d1 = OGRGeometry(self.geometries.diff_geoms[i].wkt)
d2 = a.difference(b)
self.assertTrue(d1.geos.equals(d2.geos))
self.assertTrue(
d1.geos.equals((a - b).geos)
) # __sub__ is difference operator
a -= b # testing __isub__
self.assertTrue(d1.geos.equals(a.geos))
def test_intersection(self):
"Testing intersects() and intersection()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
i1 = OGRGeometry(self.geometries.intersect_geoms[i].wkt)
self.assertTrue(a.intersects(b))
i2 = a.intersection(b)
self.assertTrue(i1.geos.equals(i2.geos))
self.assertTrue(
i1.geos.equals((a & b).geos)
) # __and__ is intersection operator
a &= b # testing __iand__
self.assertTrue(i1.geos.equals(a.geos))
def test_symdifference(self):
"Testing sym_difference()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
d1 = OGRGeometry(self.geometries.sdiff_geoms[i].wkt)
d2 = a.sym_difference(b)
self.assertTrue(d1.geos.equals(d2.geos))
self.assertTrue(
d1.geos.equals((a ^ b).geos)
) # __xor__ is symmetric difference operator
a ^= b # testing __ixor__
self.assertTrue(d1.geos.equals(a.geos))
def test_union(self):
"Testing union()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
u1 = OGRGeometry(self.geometries.union_geoms[i].wkt)
u2 = a.union(b)
self.assertTrue(u1.geos.equals(u2.geos))
self.assertTrue(u1.geos.equals((a | b).geos)) # __or__ is union operator
a |= b # testing __ior__
self.assertTrue(u1.geos.equals(a.geos))
def test_add(self):
"Testing GeometryCollection.add()."
# Can't insert a Point into a MultiPolygon.
mp = OGRGeometry("MultiPolygon")
pnt = OGRGeometry("POINT(5 23)")
with self.assertRaises(GDALException):
mp.add(pnt)
# GeometryCollection.add may take an OGRGeometry (if another collection
# of the same type all child geoms will be added individually) or WKT.
for mp in self.geometries.multipolygons:
mpoly = OGRGeometry(mp.wkt)
mp1 = OGRGeometry("MultiPolygon")
mp2 = OGRGeometry("MultiPolygon")
mp3 = OGRGeometry("MultiPolygon")
for poly in mpoly:
mp1.add(poly) # Adding a geometry at a time
mp2.add(poly.wkt) # Adding WKT
mp3.add(mpoly) # Adding a MultiPolygon's entire contents at once.
for tmp in (mp1, mp2, mp3):
self.assertEqual(mpoly, tmp)
def test_extent(self):
"Testing `extent` property."
# The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
mp = OGRGeometry("MULTIPOINT(5 23, 0 0, 10 50)")
self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
# Testing on the 'real world' Polygon.
poly = OGRGeometry(self.geometries.polygons[3].wkt)
ring = poly.shell
x, y = ring.x, ring.y
xmin, ymin = min(x), min(y)
xmax, ymax = max(x), max(y)
self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
def test_25D(self):
"Testing 2.5D geometries."
pnt_25d = OGRGeometry("POINT(1 2 3)")
self.assertEqual("Point25D", pnt_25d.geom_type.name)
self.assertEqual(3.0, pnt_25d.z)
self.assertEqual(3, pnt_25d.coord_dim)
ls_25d = OGRGeometry("LINESTRING(1 1 1,2 2 2,3 3 3)")
self.assertEqual("LineString25D", ls_25d.geom_type.name)
self.assertEqual([1.0, 2.0, 3.0], ls_25d.z)
self.assertEqual(3, ls_25d.coord_dim)
def test_pickle(self):
"Testing pickle support."
g1 = OGRGeometry("LINESTRING(1 1 1,2 2 2,3 3 3)", "WGS84")
g2 = pickle.loads(pickle.dumps(g1))
self.assertEqual(g1, g2)
self.assertEqual(4326, g2.srs.srid)
self.assertEqual(g1.srs.wkt, g2.srs.wkt)
def test_ogrgeometry_transform_workaround(self):
"Testing coordinate dimensions on geometries after transformation."
# A bug in GDAL versions prior to 1.7 changes the coordinate
# dimension of a geometry after it has been transformed.
# This test ensures that the bug workarounds employed within
# `OGRGeometry.transform` indeed work.
wkt_2d = "MULTILINESTRING ((0 0,1 1,2 2))"
wkt_3d = "MULTILINESTRING ((0 0 0,1 1 1,2 2 2))"
srid = 4326
# For both the 2D and 3D MultiLineString, ensure _both_ the dimension
# of the collection and the component LineString have the expected
# coordinate dimension after transform.
geom = OGRGeometry(wkt_2d, srid)
geom.transform(srid)
self.assertEqual(2, geom.coord_dim)
self.assertEqual(2, geom[0].coord_dim)
self.assertEqual(wkt_2d, geom.wkt)
geom = OGRGeometry(wkt_3d, srid)
geom.transform(srid)
self.assertEqual(3, geom.coord_dim)
self.assertEqual(3, geom[0].coord_dim)
self.assertEqual(wkt_3d, geom.wkt)
# Testing binary predicates, `assertIs` is used to check that bool is
# returned.
def test_equivalence_regression(self):
"Testing equivalence methods with non-OGRGeometry instances."
self.assertIsNotNone(OGRGeometry("POINT(0 0)"))
self.assertNotEqual(OGRGeometry("LINESTRING(0 0, 1 1)"), 3)
def test_contains(self):
self.assertIs(
OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 0)")), True
)
self.assertIs(
OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 1)")), False
)
def test_crosses(self):
self.assertIs(
OGRGeometry("LINESTRING(0 0, 1 1)").crosses(
OGRGeometry("LINESTRING(0 1, 1 0)")
),
True,
)
self.assertIs(
OGRGeometry("LINESTRING(0 0, 0 1)").crosses(
OGRGeometry("LINESTRING(1 0, 1 1)")
),
False,
)
def test_disjoint(self):
self.assertIs(
OGRGeometry("LINESTRING(0 0, 1 1)").disjoint(
OGRGeometry("LINESTRING(0 1, 1 0)")
),
False,
)
self.assertIs(
OGRGeometry("LINESTRING(0 0, 0 1)").disjoint(
OGRGeometry("LINESTRING(1 0, 1 1)")
),
True,
)
def test_equals(self):
self.assertIs(
OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 0)")), True
)
self.assertIs(
OGRGeometry("POINT(0 0)").contains(OGRGeometry("POINT(0 1)")), False
)
def test_intersects(self):
self.assertIs(
OGRGeometry("LINESTRING(0 0, 1 1)").intersects(
OGRGeometry("LINESTRING(0 1, 1 0)")
),
True,
)
self.assertIs(
OGRGeometry("LINESTRING(0 0, 0 1)").intersects(
OGRGeometry("LINESTRING(1 0, 1 1)")
),
False,
)
def test_overlaps(self):
self.assertIs(
OGRGeometry("POLYGON ((0 0, 0 2, 2 2, 2 0, 0 0))").overlaps(
OGRGeometry("POLYGON ((1 1, 1 5, 5 5, 5 1, 1 1))")
),
True,
)
self.assertIs(
OGRGeometry("POINT(0 0)").overlaps(OGRGeometry("POINT(0 1)")), False
)
def test_touches(self):
self.assertIs(
OGRGeometry("POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))").touches(
OGRGeometry("LINESTRING(0 2, 2 0)")
),
True,
)
self.assertIs(
OGRGeometry("POINT(0 0)").touches(OGRGeometry("POINT(0 1)")), False
)
def test_within(self):
self.assertIs(
OGRGeometry("POINT(0.5 0.5)").within(
OGRGeometry("POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))")
),
True,
)
self.assertIs(
OGRGeometry("POINT(0 0)").within(OGRGeometry("POINT(0 1)")), False
)
def test_from_gml(self):
self.assertEqual(
OGRGeometry("POINT(0 0)"),
OGRGeometry.from_gml(
'<gml:Point gml:id="p21" '
'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
' <gml:pos srsDimension="2">0 0</gml:pos>'
"</gml:Point>"
),
)
def test_empty(self):
self.assertIs(OGRGeometry("POINT (0 0)").empty, False)
self.assertIs(OGRGeometry("POINT EMPTY").empty, True)
def test_empty_point_to_geos(self):
p = OGRGeometry("POINT EMPTY", srs=4326)
self.assertEqual(p.geos.ewkt, p.ewkt)
def test_geometry_types(self):
tests = [
("Point", 1, True),
("LineString", 2, True),
("Polygon", 3, True),
("MultiPoint", 4, True),
("Multilinestring", 5, True),
("MultiPolygon", 6, True),
("GeometryCollection", 7, True),
("CircularString", 8, True),
("CompoundCurve", 9, True),
("CurvePolygon", 10, True),
("MultiCurve", 11, True),
("MultiSurface", 12, True),
# 13 (Curve) and 14 (Surface) are abstract types.
("PolyhedralSurface", 15, False),
("TIN", 16, False),
("Triangle", 17, False),
("Linearring", 2, True),
# Types 1 - 7 with Z dimension have 2.5D enums.
("Point Z", -2147483647, True), # 1001
("LineString Z", -2147483646, True), # 1002
("Polygon Z", -2147483645, True), # 1003
("MultiPoint Z", -2147483644, True), # 1004
("Multilinestring Z", -2147483643, True), # 1005
("MultiPolygon Z", -2147483642, True), # 1006
("GeometryCollection Z", -2147483641, True), # 1007
("CircularString Z", 1008, True),
("CompoundCurve Z", 1009, True),
("CurvePolygon Z", 1010, True),
("MultiCurve Z", 1011, True),
("MultiSurface Z", 1012, True),
("PolyhedralSurface Z", 1015, False),
("TIN Z", 1016, False),
("Triangle Z", 1017, False),
("Point M", 2001, True),
("LineString M", 2002, True),
("Polygon M", 2003, True),
("MultiPoint M", 2004, True),
("MultiLineString M", 2005, True),
("MultiPolygon M", 2006, True),
("GeometryCollection M", 2007, True),
("CircularString M", 2008, True),
("CompoundCurve M", 2009, True),
("CurvePolygon M", 2010, True),
("MultiCurve M", 2011, True),
("MultiSurface M", 2012, True),
("PolyhedralSurface M", 2015, False),
("TIN M", 2016, False),
("Triangle M", 2017, False),
("Point ZM", 3001, True),
("LineString ZM", 3002, True),
("Polygon ZM", 3003, True),
("MultiPoint ZM", 3004, True),
("MultiLineString ZM", 3005, True),
("MultiPolygon ZM", 3006, True),
("GeometryCollection ZM", 3007, True),
("CircularString ZM", 3008, True),
("CompoundCurve ZM", 3009, True),
("CurvePolygon ZM", 3010, True),
("MultiCurve ZM", 3011, True),
("MultiSurface ZM", 3012, True),
("PolyhedralSurface ZM", 3015, False),
("TIN ZM", 3016, False),
("Triangle ZM", 3017, False),
]
for test in tests:
geom_type, num, supported = test
with self.subTest(geom_type=geom_type, num=num, supported=supported):
if supported:
g = OGRGeometry(f"{geom_type} EMPTY")
self.assertEqual(g.geom_type.num, num)
else:
type_ = geom_type.replace(" ", "")
msg = f"Unsupported geometry type: {type_}"
with self.assertRaisesMessage(TypeError, msg):
OGRGeometry(f"{geom_type} EMPTY")
def test_is_3d_and_set_3d(self):
geom = OGRGeometry("POINT (1 2)")
self.assertIs(geom.is_3d, False)
geom.set_3d(True)
self.assertIs(geom.is_3d, True)
self.assertEqual(geom.wkt, "POINT (1 2 0)")
geom.set_3d(False)
self.assertIs(geom.is_3d, False)
self.assertEqual(geom.wkt, "POINT (1 2)")
msg = "Input to 'set_3d' must be a boolean, got 'None'"
with self.assertRaisesMessage(ValueError, msg):
geom.set_3d(None)
def test_wkt_and_wkb_output(self):
tests = [
# 2D
("POINT (1 2)", "0101000000000000000000f03f0000000000000040"),
(
"LINESTRING (30 10,10 30)",
"0102000000020000000000000000003e400000000000002"
"44000000000000024400000000000003e40",
),
(
"POLYGON ((30 10,40 40,20 40,30 10))",
"010300000001000000040000000000000000003e400000000000002440000000000000"
"44400000000000004440000000000000344000000000000044400000000000003e4000"
"00000000002440",
),
(
"MULTIPOINT (10 40,40 30)",
"0104000000020000000101000000000000000000244000000000000044400101000000"
"00000000000044400000000000003e40",
),
(
"MULTILINESTRING ((10 10,20 20),(40 40,30 30,40 20))",
"0105000000020000000102000000020000000000000000002440000000000000244000"
"0000000000344000000000000034400102000000030000000000000000004440000000"
"00000044400000000000003e400000000000003e400000000000004440000000000000"
"3440",
),
(
"MULTIPOLYGON (((30 20,45 40,10 40,30 20)),((15 5,40 10,10 20,15 5)))",
"010600000002000000010300000001000000040000000000000000003e400000000000"
"0034400000000000804640000000000000444000000000000024400000000000004440"
"0000000000003e40000000000000344001030000000100000004000000000000000000"
"2e40000000000000144000000000000044400000000000002440000000000000244000"
"000000000034400000000000002e400000000000001440",
),
(
"GEOMETRYCOLLECTION (POINT (40 10))",
"010700000001000000010100000000000000000044400000000000002440",
),
# 3D
(
"POINT (1 2 3)",
"0101000080000000000000f03f00000000000000400000000000000840",
),
(
"LINESTRING (30 10 3,10 30 3)",
"0102000080020000000000000000003e40000000000000244000000000000008400000"
"0000000024400000000000003e400000000000000840",
),
(
"POLYGON ((30 10 3,40 40 3,30 10 3))",
"010300008001000000030000000000000000003e400000000000002440000000000000"
"08400000000000004440000000000000444000000000000008400000000000003e4000"
"000000000024400000000000000840",
),
(
"MULTIPOINT (10 40 3,40 30 3)",
"0104000080020000000101000080000000000000244000000000000044400000000000"
"000840010100008000000000000044400000000000003e400000000000000840",
),
(
"MULTILINESTRING ((10 10 3,20 20 3))",
"0105000080010000000102000080020000000000000000002440000000000000244000"
"00000000000840000000000000344000000000000034400000000000000840",
),
(
"MULTIPOLYGON (((30 20 3,45 40 3,30 20 3)))",
"010600008001000000010300008001000000030000000000000000003e400000000000"
"0034400000000000000840000000000080464000000000000044400000000000000840"
"0000000000003e4000000000000034400000000000000840",
),
(
"GEOMETRYCOLLECTION (POINT (40 10 3))",
"0107000080010000000101000080000000000000444000000000000024400000000000"
"000840",
),
]
for geom, wkb in tests:
with self.subTest(geom=geom):
g = OGRGeometry(geom)
self.assertEqual(g.wkt, geom)
self.assertEqual(g.wkb.hex(), wkb)
def test_measure_is_measure_and_set_measure(self):
geom = OGRGeometry("POINT (1 2 3)")
self.assertIs(geom.is_measured, False)
geom.set_measured(True)
self.assertIs(geom.is_measured, True)
self.assertEqual(geom.wkt, "POINT ZM (1 2 3 0)")
geom.set_measured(False)
self.assertIs(geom.is_measured, False)
self.assertEqual(geom.wkt, "POINT (1 2 3)")
msg = "Input to 'set_measured' must be a boolean, got 'None'"
with self.assertRaisesMessage(ValueError, msg):
geom.set_measured(None)
def test_point_m_coordinate(self):
geom = OGRGeometry("POINT ZM (1 2 3 4)")
self.assertEqual(geom.m, 4)
geom = OGRGeometry("POINT (1 2 3 4)")
self.assertEqual(geom.m, 4)
geom = OGRGeometry("POINT M (1 2 3)")
self.assertEqual(geom.m, 3)
geom = OGRGeometry("POINT Z (1 2 3)")
self.assertEqual(geom.m, None)
def test_point_m_tuple(self):
geom = OGRGeometry("POINT ZM (1 2 3 4)")
self.assertEqual(geom.tuple, (geom.x, geom.y, geom.z, geom.m))
geom = OGRGeometry("POINT M (1 2 3)")
self.assertEqual(geom.tuple, (geom.x, geom.y, geom.m))
geom = OGRGeometry("POINT Z (1 2 3)")
self.assertEqual(geom.tuple, (geom.x, geom.y, geom.z))
geom = OGRGeometry("POINT (1 2 3)")
self.assertEqual(geom.tuple, (geom.x, geom.y, geom.z))
def test_point_m_wkt_wkb(self):
wkt = "POINT ZM (1 2 3 4)"
geom = OGRGeometry(wkt)
self.assertEqual(geom.wkt, wkt)
self.assertEqual(
geom.wkb.hex(),
"01b90b0000000000000000f03f00000000000000"
"4000000000000008400000000000001040",
)
wkt = "POINT M (1 2 3)"
geom = OGRGeometry(wkt)
self.assertEqual(geom.wkt, wkt)
self.assertEqual(
geom.wkb.hex(),
"01d1070000000000000000f03f00000000000000400000000000000840",
)
def test_point_m_dimension_types(self):
geom = OGRGeometry("POINT ZM (1 2 3 4)")
self.assertEqual(geom.geom_type.name, "PointZM")
self.assertEqual(geom.geom_type.num, 3001)
geom = OGRGeometry("POINT M (1 2 3)")
self.assertEqual(geom.geom_type.name, "PointM")
self.assertEqual(geom.geom_type.num, 2001)
def test_point_m_dimension_geos(self):
"""GEOSGeometry does not yet support the M dimension."""
geom = OGRGeometry("POINT ZM (1 2 3 4)")
self.assertEqual(geom.geos.wkt, "POINT Z (1 2 3)")
geom = OGRGeometry("POINT M (1 2 3)")
self.assertEqual(geom.geos.wkt, "POINT (1 2)")
def test_centroid(self):
point = OGRGeometry("POINT (1 2 3)")
self.assertEqual(point.centroid.wkt, "POINT (1 2)")
linestring = OGRGeometry("LINESTRING (0 0 0, 1 1 1, 2 2 2)")
self.assertEqual(linestring.centroid.wkt, "POINT (1 1)")
polygon = OGRGeometry("POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))")
self.assertEqual(polygon.centroid.wkt, "POINT (5 5)")
multipoint = OGRGeometry("MULTIPOINT (0 0,10 10)")
self.assertEqual(multipoint.centroid.wkt, "POINT (5 5)")
multilinestring = OGRGeometry(
"MULTILINESTRING ((0 0,0 10,0 20),(10 0,10 10,10 20))"
)
self.assertEqual(multilinestring.centroid.wkt, "POINT (5 10)")
multipolygon = OGRGeometry(
"MULTIPOLYGON(((0 0, 10 0, 10 10, 0 10, 0 0)),"
"((20 20, 20 30, 30 30, 30 20, 20 20)))"
)
self.assertEqual(multipolygon.centroid.wkt, "POINT (15 15)")
geometrycollection = OGRGeometry(
"GEOMETRYCOLLECTION (POINT (110 260),LINESTRING (110 0,110 60))"
)
self.assertEqual(geometrycollection.centroid.wkt, "POINT (110 30)")
def test_linestring_m_dimension(self):
geom = OGRGeometry("LINESTRING(0 1 2 10, 1 2 3 11, 2 3 4 12)")
self.assertIs(geom.is_measured, True)
self.assertEqual(geom.m, [10.0, 11.0, 12.0])
self.assertEqual(geom[0], (0.0, 1.0, 2.0, 10.0))
geom = OGRGeometry("LINESTRING M (0 1 10, 1 2 11)")
self.assertIs(geom.is_measured, True)
self.assertEqual(geom.m, [10.0, 11.0])
self.assertEqual(geom[0], (0.0, 1.0, 10.0))
geom.set_measured(False)
self.assertIs(geom.is_measured, False)
self.assertIs(geom.m, None)
def test_polygon_m_dimension(self):
geom = OGRGeometry("POLYGON Z ((0 0 0, 10 0 0, 10 10 0, 0 10 0, 0 0 0))")
self.assertIs(geom.is_measured, False)
self.assertEqual(
geom.shell.wkt, "LINEARRING (0 0 0,10 0 0,10 10 0,0 10 0,0 0 0)"
)
geom = OGRGeometry("POLYGON M ((0 0 0, 10 0 0, 10 10 0, 0 10 0, 0 0 0))")
self.assertIs(geom.is_measured, True)
self.assertEqual(
geom.shell.wkt, "LINEARRING M (0 0 0,10 0 0,10 10 0,0 10 0,0 0 0)"
)
geom = OGRGeometry(
"POLYGON ZM ((0 0 0 1, 10 0 0 1, 10 10 0 1, 0 10 0 1, 0 0 0 1))"
)
self.assertIs(geom.is_measured, True)
self.assertEqual(
geom.shell.wkt,
"LINEARRING ZM (0 0 0 1,10 0 0 1,10 10 0 1,0 10 0 1,0 0 0 1)",
)
geom.set_measured(False)
self.assertEqual(geom.wkt, "POLYGON ((0 0 0,10 0 0,10 10 0,0 10 0,0 0 0))")
self.assertEqual(
geom.shell.wkt, "LINEARRING (0 0 0,10 0 0,10 10 0,0 10 0,0 0 0)"
)
def test_multi_geometries_m_dimension(self):
tests = [
"MULTIPOINT M ((10 40 10), (40 30 10), (20 20 10))",
"MULTIPOINT ZM ((10 40 0 10), (40 30 1 10), (20 20 1 10))",
"MULTILINESTRING M ((10 10 1, 20 20 2),(40 40 1, 30 30 2))",
"MULTILINESTRING ZM ((10 10 0 1, 20 20 0 2),(40 40 1, 30 30 0 2))",
(
"MULTIPOLYGON ZM (((30 20 1 0, 45 40 1 0, 30 20 1 0)),"
"((15 5 0 0, 40 10 0 0, 15 5 0 0)))"
),
(
"GEOMETRYCOLLECTION M (POINT M (40 10 0),"
"LINESTRING M (10 10 0, 20 20 0, 10 40 0))"
),
(
"GEOMETRYCOLLECTION ZM (POINT ZM (40 10 0 1),"
"LINESTRING ZM (10 10 1 0, 20 20 1 0, 10 40 1 0))"
),
]
for geom_input in tests:
with self.subTest(geom_input=geom_input):
geom = OGRGeometry(geom_input)
self.assertIs(geom.is_measured, True)
def test_has_curve(self):
for geom in self.geometries.curved_geoms:
with self.subTest(wkt=geom.wkt):
geom = OGRGeometry(geom.wkt)
self.assertIs(geom.has_curve, True)
msg = f"GEOS does not support {geom.__class__.__qualname__}."
with self.assertRaisesMessage(GEOSException, msg):
geom.geos
geom = OGRGeometry("POINT (0 1)")
self.assertIs(geom.has_curve, False)
def test_get_linear_geometry(self):
geom = OGRGeometry("CIRCULARSTRING (-0.797 0.466,-0.481 0.62,-0.419 0.473)")
linear = geom.get_linear_geometry()
self.assertEqual(linear.geom_name, "LINESTRING")
self.assertIs(linear.has_curve, False)
def test_get_linear_geometry_no_conversion_possible(self):
wkt = "POINT (0 0)"
geom = OGRGeometry(wkt)
geom2 = geom.get_linear_geometry()
self.assertEqual(geom2.wkt, wkt)
def test_get_curve_geometry(self):
linear_string = OGRGeometry(
"LINESTRING (-0.797 0.466,-0.797500910583869 0.479079607685707,"
"-0.797096828208069 0.49216256476959,-0.795789684575482 0.505186328593822,"
"-0.793585728444384 0.518088639471983,-0.79049549575663 0.530807818319715,"
"-0.786533759270668 0.543283061509385,-0.781719457941079 0.555454731539925,"
"-0.776075606381369 0.567264642132187,-0.769629184843353 0.578656336386302,"
"-0.76241101023902 0.589575356672327,-0.754455588821145 0.599969504963013,"
"-0.745800951227352 0.609789092364991,-0.736488470675795 0.618987176654798,"
"-0.726562665181888 0.627519786684672,-0.716070984741265 0.635346132585369,"
"-0.705063584496685 0.642428800760598,-0.693593084972889 0.648733932741749,"
"-0.681714320525941 0.654231387047048,-0.669484077209319 0.658894883272069,"
"-0.656960821309923 0.662702127722269,-0.644204419852031 0.665634919987354,"
"-0.631275854404748 0.667679239947688,-0.618236929561618 0.668825314797118,"
"-0.60514997748578 0.669067665761503,-0.592077559933017 0.66840513428977,"
"-0.579082169177269 0.666840887592428,-0.566225929268313 0.664382403500809,"
"-0.553570299049824 0.661041434719465,-0.541175778357228 0.656833952642756,"
"-0.529101618800212 0.651780071004197,-0.5174055405123 0.645903949723276,"
"-0.506143456221622 0.639233679409784,-0.495369203961872 0.631801147077652,"
"-0.485134289701335 0.623641883709865,-0.475487641120239 0.614794894404014,"
"-0.46647537371355 0.605302471909454,-0.458140570337321 0.595209994448282,"
"-0.450523075252448 0.58456570878613,-0.443659303650563 0.573420499590156,"
"-0.437582067572208 0.561827646176397,-0.432320419050072 0.549842567809747,"
"-0.427899511226613 0.537522558773986,-0.424340478110267 0.524926514478182,"
"-0.421660333544978 0.512114649909193,-0.419871889876113 0.499148211775737,"
"-0.418983696701434 0.486089185720561,-0.419 0.473)"
)
curve = linear_string.get_curve_geometry()
self.assertEqual(curve.geom_name, "CIRCULARSTRING")
self.assertEqual(
curve.wkt,
"CIRCULARSTRING (-0.797 0.466,-0.618236929561618 "
"0.668825314797118,-0.419 0.473)",
)
def test_get_curve_geometry_no_conversion_possible(self):
geom = OGRGeometry("LINESTRING (0 0, 1 0, 2 0)")
geom2 = geom.get_curve_geometry()
self.assertEqual(geom2.wkt, geom.wkt)
def test_curved_geometries(self):
for geom in self.geometries.curved_geoms:
with self.subTest(wkt=geom.wkt, geom_name=geom.name):
g = OGRGeometry(geom.wkt)
self.assertEqual(geom.name, g.geom_type.name)
self.assertEqual(geom.num, g.geom_type.num)
msg = f"GEOS does not support {g.__class__.__qualname__}."
with self.assertRaisesMessage(GEOSException, msg):
g.geos
def test_circularstring_has_linestring_features(self):
geom = OGRGeometry("CIRCULARSTRING ZM (1 5 0 1, 6 2 0 2, 7 3 0 3)")
self.assertIsInstance(geom, CircularString)
self.assertEqual(geom.x, [1, 6, 7])
self.assertEqual(geom.y, [5, 2, 3])
self.assertEqual(geom.z, [0, 0, 0])
self.assertEqual(geom.m, [1, 2, 3])
self.assertEqual(
geom.tuple,
((1.0, 5.0, 0.0, 1.0), (6.0, 2.0, 0.0, 2.0), (7.0, 3.0, 0.0, 3.0)),
)
self.assertEqual(geom[0], (1, 5, 0, 1))
self.assertEqual(len(geom), 3)
def test_curvepolygon_has_polygon_features(self):
geom = OGRGeometry(
"CURVEPOLYGON ZM (CIRCULARSTRING ZM (0 0 0 0, 4 0 0 0, 4 4 0 0, 0 4 0 0, "
"0 0 0 0), (1 1 0 0, 3 3 0 0, 3 1 0 0, 1 1 0 0))"
)
self.assertIsInstance(geom, CurvePolygon)
self.assertIsInstance(geom.shell, CircularString)
| OGRGeomTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_base_aws.py | {
"start": 47279,
"end": 51755
} | class ____: # ptlint: disable=invalid-name
def test_do_nothing_on_non_exception(self):
result = _retryable_test(lambda: 42)
assert result == 42
@mock.patch("time.sleep", return_value=0)
def test_retry_on_exception(self, _):
quota_retry = {
"stop_after_delay": 2,
"multiplier": 1,
"min": 1,
"max": 10,
}
custom_fn = ThrowErrorUntilCount(
count=2,
quota_retry=quota_retry,
)
result = _retryable_test(custom_fn)
assert custom_fn.counter == 2
assert result
def test_no_retry_on_exception(self):
quota_retry = {
"stop_after_delay": 2,
"multiplier": 1,
"min": 1,
"max": 10,
}
custom_fn = ThrowErrorUntilCount(
count=2,
quota_retry=quota_retry,
)
with pytest.raises(RuntimeError, match="Fake Unexpected Error"):
_non_retryable_test(custom_fn)
def test_raise_exception_when_no_retry_args(self):
custom_fn = ThrowErrorUntilCount(count=2, quota_retry=None)
with pytest.raises(RuntimeError, match="Fake Unexpected Error"):
_retryable_test(custom_fn)
def test_raise_no_creds_default_credentials_strategy(tmp_path_factory, monkeypatch):
"""Test raise an error if no credentials provided and default boto3 strategy unable to get creds."""
for env_key in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_SECURITY_TOKEN"):
# Delete aws credentials environment variables
monkeypatch.delenv(env_key, raising=False)
hook = AwsBaseHook(aws_conn_id=None, client_type="sts")
with pytest.raises(NoCredentialsError) as credential_error:
# Call AWS STS API method GetCallerIdentity
# which should return result in case of valid credentials
hook.conn.get_caller_identity()
assert str(credential_error.value) == "Unable to locate credentials"
TEST_WAITER_CONFIG_LOCATION = Path(__file__).parents[1].joinpath("waiters/test.json")
@mock.patch.object(AwsGenericHook, "waiter_path", new_callable=PropertyMock)
def test_waiter_config_params_not_provided(waiter_path_mock: MagicMock, caplog):
waiter_path_mock.return_value = TEST_WAITER_CONFIG_LOCATION
hook = AwsBaseHook(client_type="mwaa") # needs to be a real client type
with pytest.raises(AirflowException) as ae:
hook.get_waiter("wait_for_test")
# should warn about missing param
assert "PARAM_1" in str(ae.value)
@mock.patch.object(AwsGenericHook, "waiter_path", new_callable=PropertyMock)
def test_waiter_config_no_params_needed(waiter_path_mock: MagicMock, caplog):
waiter_path_mock.return_value = TEST_WAITER_CONFIG_LOCATION
hook = AwsBaseHook(client_type="mwaa") # needs to be a real client type
with caplog.at_level("WARN"):
hook.get_waiter("other_wait")
# other waiters in the json need params, but not this one, so we shouldn't warn about it.
assert len(caplog.text) == 0
@mock.patch.object(AwsGenericHook, "waiter_path", new_callable=PropertyMock)
def test_waiter_config_with_parameters_specified(waiter_path_mock: MagicMock):
waiter_path_mock.return_value = TEST_WAITER_CONFIG_LOCATION
hook = AwsBaseHook(client_type="mwaa") # needs to be a real client type
waiter = hook.get_waiter("wait_for_test", {"PARAM_1": "hello", "PARAM_2": "world"})
assert waiter.config.acceptors[0].argument == "'hello' == 'world'"
@mock.patch.object(AwsGenericHook, "waiter_path", new_callable=PropertyMock)
def test_waiter_config_param_wrong_format(waiter_path_mock: MagicMock):
waiter_path_mock.return_value = TEST_WAITER_CONFIG_LOCATION
hook = AwsBaseHook(client_type="mwaa") # needs to be a real client type
with pytest.raises(jinja2.TemplateSyntaxError):
hook.get_waiter("bad_param_wait")
@mock.patch.object(AwsGenericHook, "waiter_path", new_callable=PropertyMock)
def test_custom_waiter_with_resource_type(waiter_path_mock: MagicMock):
waiter_path_mock.return_value = TEST_WAITER_CONFIG_LOCATION
hook = AwsBaseHook(resource_type="dynamodb") # needs to be a real client type
with mock.patch("airflow.providers.amazon.aws.waiters.base_waiter.BaseBotoWaiter") as BaseBotoWaiter:
hook.get_waiter("other_wait")
assert isinstance(BaseBotoWaiter.call_args.kwargs["client"], botocore.client.BaseClient)
| TestRetryDecorator |
python | huggingface__transformers | src/transformers/models/qwen3_vl/configuration_qwen3_vl.py | {
"start": 2509,
"end": 8829
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen3VLTextModel`]. It is used to instantiate a
Qwen3-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of
Qwen3-VL-4B-Instruct [Qwen/Qwen3-VL-4B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-4B-Instruct).
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 151936):
Vocabulary size of the Qwen3VL model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`Qwen3VLModel`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 22016):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 32):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
head_dim (`int`, *optional*, defaults to 128):
The dimension of the head. If not specified, will default to `hidden_size // num_attention_heads`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 128000):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether the model's input and output word embeddings should be tied.
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
```python
>>> from transformers import Qwen3VLTextModel, Qwen3VLTextConfig
>>> # Initializing a Qwen3VL style configuration
>>> configuration = Qwen3VLTextConfig()
>>> # Initializing a model from the Qwen3-VL-7B style configuration
>>> model = Qwen3VLTextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "qwen3_vl_text"
base_config_key = "text_config"
default_theta = 500000.0
def __init__(
self,
vocab_size: Optional[int] = 151936,
hidden_size: Optional[int] = 4096,
intermediate_size: Optional[int] = 22016,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = 32,
head_dim: Optional[int] = 128,
hidden_act: Optional[str] = "silu",
max_position_embeddings: Optional[int] = 128000,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[float] = 1e-6,
use_cache: Optional[bool] = True,
tie_word_embeddings: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
attention_bias: Optional[bool] = False,
attention_dropout: Optional[float] = 0.0,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.head_dim = head_dim
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.rope_parameters = rope_parameters
super().__init__(
tie_word_embeddings=tie_word_embeddings,
ignore_keys_at_rope_validation={"mrope_section", "mrope_interleaved"},
**kwargs,
)
| Qwen3VLTextConfig |
python | pytorch__pytorch | test/dynamo/test_backward_higher_order_ops.py | {
"start": 4268,
"end": 5880
} | class ____(torch.nn.Module):
def forward(self, L_inputs_ : list, s69: "Sym(s21)", L_sizes_0_: "f32[0, s21]"):
l_inputs_ = L_inputs_
l_sizes_0_ = L_sizes_0_
getitem: "f32[s21]" = l_inputs_[0]
getitem_1: "f32[s21]" = l_inputs_[1]
getitem_2: "f32[s21]" = l_inputs_[2]; l_inputs_ = None
size: "Sym(s21)" = l_sizes_0_.size(1); l_sizes_0_ = None
validate_outputs = torch__dynamo_compiled_autograd_ops_validate_outputs([getitem], [((None, None, device(type='cpu'), 6, 0, None), [size], False, 6)]); getitem = size = None
getitem_9: "f32[s21]" = validate_outputs[0]; validate_outputs = None
call_aot_bwd_prologue = torch__dynamo_compiled_autograd_call_aot_bwd_prologue((), [], getitem_9); getitem_9 = None
aot1_tangents_1: "f32[s21]" = call_aot_bwd_prologue[0]; call_aot_bwd_prologue = None
accumulate_grad = torch__dynamo_compiled_autograd_ops_AccumulateGrad([aot1_tangents_1], getitem_1, None, False); getitem_1 = None
getitem_11: "f32[s21]" = accumulate_grad[0]; accumulate_grad = None
result: "f32[s21]" = aot1_tangents_1 * aot1_tangents_1; aot1_tangents_1 = None
accumulate_grad_1 = torch__dynamo_compiled_autograd_ops_AccumulateGrad([result], getitem_2, None, False); result = getitem_2 = None
getitem_12: "f32[s21]" = accumulate_grad_1[0]; accumulate_grad_1 = None
return (getitem_11, getitem_12)
""",
)
elif backend == "inductor":
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | kamyu104__LeetCode-Solutions | Python/decode-the-message.py | {
"start": 73,
"end": 600
} | class ____(object):
def decodeMessage(self, key, message):
"""
:type key: str
:type message: str
:rtype: str
"""
f = lambda x: ord(x)-ord('a')
lookup = [-1]*26
i = 0
for x in itertools.imap(f, key):
if x < 0 or lookup[x] != -1:
continue
lookup[x] = i
i += 1
return "".join(itertools.imap(lambda x: chr(ord('a')+x), (lookup[x] if x >= 0 else x for x in itertools.imap(f, message))))
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_header_image22.py | {
"start": 315,
"end": 1050
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("header_image22.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
worksheet1.set_paper(9)
worksheet1.vertical_dpi = 200
worksheet1.set_header("&L&G", {"image_left": self.image_dir + "blue.png"})
worksheet2 = workbook.add_worksheet()
worksheet2.insert_image(0, 0, self.image_dir + "red.png")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | django-compressor__django-compressor | compressor/tests/test_base.py | {
"start": 16307,
"end": 17429
} | class ____(SimpleTestCase):
def setUp(self):
self.js = """\
<script src="/static/js/one.js" type="text/javascript"></script>
<script src="/static/js/two.js" type="text/javascript" async></script>
<script src="/static/js/three.js" type="text/javascript" defer></script>
<script type="text/javascript">obj.value = "value";</script>
<script src="/static/js/one.js" type="text/javascript" async></script>
<script src="/static/js/two.js" type="text/javascript" async></script>
<script src="/static/js/three.js" type="text/javascript"></script>"""
def test_js_output(self):
def extract_attr(tag):
if tag.has_attr("async"):
return "async"
if tag.has_attr("defer"):
return "defer"
js_node = JsCompressor("js", self.js)
output = [None, "async", "defer", None, "async", None]
scripts = make_soup(js_node.output()).find_all("script")
attrs = [extract_attr(s) for s in scripts]
self.assertEqual(output, attrs)
| JsAsyncDeferTestCase |
python | huggingface__transformers | src/transformers/models/xcodec/configuration_xcodec.py | {
"start": 926,
"end": 7952
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of an [`XcodecModel`]. It is used to instantiate a
Xcodec model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the
[Manel/X-Codec](https://huggingface.co/Manel/X-Codec) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
target_bandwidths (`List[float]`, *optional*, defaults to `[0.5, 1, 1.5, 2, 4]`):
The range of different bandwidths (in kbps) the model can encode audio with.
sample_rate (`int`, *optional*, defaults to 16000):
The sampling rate at which the audio waveform should be digitalized, in hertz (Hz).
kernel_size (`int`, *optional*, defaults to 3):
Kernel size for the initial semantic convolution.
channel_ratios (`List[float]`, *optional*, defaults to `[1, 1]`):
Expansion factors for the number of output channels in each semantic block.
strides (`List[int]`, *optional*, defaults to `[1, 1]`):
Strides for each semantic encoder block.
block_dilations (`List[int]`, *optional*, defaults to `[1, 1]`):
Dilation factors for the residual units in semantic blocks.
unit_kernel_size (`int`, *optional*, defaults to 3):
Kernel size inside each ResidualUnit in semantic blocks.
codebook_size (`int`, *optional*, defaults to 1024):
Number of entries in each residual quantizer's codebook.
codebook_dim (`int`, *optional*):
Dimensionality of each codebook vector. Defaults to sum of hidden size of acoustic and semantic models.
initializer_range (`float`, *optional*, defaults to 0.02):
Standard deviation of the truncated normal initializer for all weight matrices.
acoustic_model_config (`Union[Dict, DacConfig]`, *optional*):
An instance of the configuration for the acoustic (DAC) model.
semantic_model_config (`Union[Dict, HubertConfig, WavLMConfig]`, *optional*):
An instance of the configuration object for the semantic (HuBERT) model.
Example:
```python
>>> from transformers import XcodecModel, XcodecConfig
>>> # Initializing configuration
>>> configuration = XcodecConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = XcodecModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "xcodec"
sub_configs = {
"acoustic_model_config": DacConfig,
"semantic_model_config": AutoConfig,
}
def __init__(
self,
target_bandwidths: Optional[list[float]] = None,
sample_rate: int = 16000,
kernel_size: int = 3,
channel_ratios: list[float] = [1, 1],
strides: list[int] = [1, 1],
block_dilations: list[int] = [1, 1],
unit_kernel_size: int = 3,
codebook_size: int = 1024,
codebook_dim: Optional[int] = None,
initializer_range: float = 0.02,
acoustic_model_config: Optional[Union[dict, DacConfig]] = None,
semantic_model_config: Optional[Union[dict, HubertConfig]] = None,
**kwargs,
):
if acoustic_model_config is None:
self.acoustic_model_config = DacConfig(
encoder_hidden_size=64,
# NOTE: original DAC uses [2, 4, 8, 8] `downsampling ratios`, namely reverse of `upsampling_ratios`
# (not sure if intentional by Xcodec but we keep it)
downsampling_ratios=[8, 5, 4, 2],
decoder_hidden_size=1024,
upsampling_ratios=[8, 5, 4, 2],
hidden_size=256,
)
elif isinstance(acoustic_model_config, dict):
self.acoustic_model_config = DacConfig(**acoustic_model_config)
elif isinstance(acoustic_model_config, DacConfig):
self.acoustic_model_config = acoustic_model_config
else:
raise ValueError(
f"acoustic_model_config must be a dict or DacConfig instance, but got {type(acoustic_model_config)}"
)
if semantic_model_config is None:
self.semantic_model_config = HubertConfig()
elif isinstance(semantic_model_config, dict):
if "_name_or_path" in semantic_model_config:
# If the config is a path, load it using AutoConfig
self.semantic_model_config = AutoConfig.from_pretrained(semantic_model_config["_name_or_path"])
else:
# assume HubertConfig as probably created from scratch
logger.warning(
"Could not determine semantic model type from config architecture. Defaulting to `HubertConfig`."
)
self.semantic_model_config = HubertConfig(**semantic_model_config)
elif isinstance(semantic_model_config, WavLMConfig) or isinstance(semantic_model_config, HubertConfig):
self.semantic_model_config = semantic_model_config
else:
raise ValueError(
f"semantic_model_config must be a dict, HubertConfig, or WavLMConfig instance, but got {type(semantic_model_config)}"
)
if target_bandwidths is None:
target_bandwidths = [0.5, 1, 1.5, 2, 4]
self.target_bandwidths = target_bandwidths
self.sample_rate = sample_rate
self.kernel_size = kernel_size
self.channel_ratios = channel_ratios
self.strides = strides
self.block_dilations = block_dilations
self.unit_kernel_size = unit_kernel_size
self.codebook_size = codebook_size
self.initializer_range = initializer_range
if codebook_dim is None:
codebook_dim = self.acoustic_model_config.hidden_size + self.semantic_model_config.hidden_size
self.codebook_dim = codebook_dim
super().__init__(**kwargs)
@property
def frame_rate(self) -> int:
return math.ceil(self.sample_rate / self.hop_length)
@property
def semantic_hidden_size(self) -> int:
return self.semantic_model_config.hidden_size
@property
def hop_length(self) -> int:
return int(np.prod(self.acoustic_model_config.downsampling_ratios))
@property
def codebook_nbits(self) -> int:
return math.ceil(math.log2(self.codebook_size))
@property
def hidden_size(self) -> int:
return self.acoustic_model_config.hidden_size + self.semantic_model_config.hidden_size
@property
def num_quantizers(self) -> int:
return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * self.codebook_nbits))
__all__ = ["XcodecConfig"]
| XcodecConfig |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams1.py | {
"start": 1418,
"end": 1590
} | class ____:
def method1[T](self, v: ClassI1) -> None: ...
# This should generate an error because ClassJ is
def method2[T](self, v: ClassI3) -> None: ...
| ClassI2 |
python | ethereum__web3.py | tests/core/method-class/test_method.py | {
"start": 10031,
"end": 10713
} | class ____(Module):
method = Method(
"eth_method",
mungers=[keywords],
request_formatters=return_exception_raising_formatter,
)
@pytest.fixture
def dummy_w3():
return Web3(EthereumTesterProvider(), modules={"fake": FakeModule})
def test_munger_class_method_access_raises_friendly_error():
with pytest.raises(TypeError, match="Direct calls to methods are not supported"):
FakeModule.method(1, 2)
def test_munger_arguments_by_keyword(dummy_w3):
with pytest.raises(Success):
dummy_w3.fake.method(keyword_one=1, keyword_two="latest")
with pytest.raises(Success):
dummy_w3.fake.method(1, keyword_two=2)
| FakeModule |
python | pytorch__pytorch | test/dynamo/test_functions.py | {
"start": 81737,
"end": 82998
} | class ____(torch.nn.Module):
def forward(self, s9: "Sym(s9)", L_lambda0_keywords_y_: "f32[s9, s9]"):
l_lambda0_keywords_y_ = L_lambda0_keywords_y_
mul: "f32[s9, s9]" = l_lambda0_keywords_y_ * l_lambda0_keywords_y_
mul_1: "f32[s9, s9]" = l_lambda0_keywords_y_ * l_lambda0_keywords_y_; l_lambda0_keywords_y_ = None
mul_2: "f32[s9, s9]" = torch.mul(mul, mul_1); mul = mul_1 = None
return (mul_2,)
""",
)
def test_partials_graph_break_reconstruct_mix(self):
def fn(udf_mul_0, udf_add_1, x):
lambda0 = functools.partial(udf_mul_0, y=x)
lambda1 = functools.partial(udf_add_1, x)
print("break")
return torch.mul(lambda0(x), lambda1(x))
backend = EagerAndRecordGraphs()
cnts = CompileCounterWithBackend(backend)
x = torch.randn(2, 2)
dynamo_result = torch.compile(fn, backend=cnts)(udf_mul, udf_add, x)
eager_result = fn(udf_mul, udf_add, x)
self.assertEqual(eager_result, dynamo_result)
if torch._dynamo.config.assume_static_by_default:
self.assertExpectedInline(
normalize_gm(backend.graphs[0].print_readable(print_output=False)),
"""\
| GraphModule |
python | ray-project__ray | python/ray/_private/runtime_env/agent/runtime_env_agent.py | {
"start": 6659,
"end": 26193
} | class ____:
"""An RPC server to create and delete runtime envs.
Attributes:
dashboard_agent: The DashboardAgent object contains global config.
"""
def __init__(
self,
runtime_env_dir,
logging_params,
gcs_client: GcsClient,
temp_dir,
address,
runtime_env_agent_port,
):
super().__init__()
self._logger = default_logger
self._logging_params = logging_params
self._logger = setup_component_logger(
logger_name=default_logger.name, **self._logging_params
)
# Don't propagate logs to the root logger, because these logs
# might contain sensitive information. Instead, these logs should
# be confined to the runtime env agent log file `self.LOG_FILENAME`.
self._logger.propagate = False
self._logger.info("Starting runtime env agent at pid %s", os.getpid())
self._logger.info(f"Parent raylet pid is {os.environ.get('RAY_RAYLET_PID')}")
self._runtime_env_dir = runtime_env_dir
self._per_job_logger_cache = dict()
# Cache the results of creating envs to avoid repeatedly calling into
# conda and other slow calls.
self._env_cache: Dict[str, CreatedEnvResult] = dict()
# Maps a serialized runtime env to a lock that is used
# to prevent multiple concurrent installs of the same env.
self._env_locks: Dict[str, asyncio.Lock] = dict()
self._gcs_client = gcs_client
self._pip_plugin = PipPlugin(self._runtime_env_dir)
self._uv_plugin = UvPlugin(self._runtime_env_dir)
self._conda_plugin = CondaPlugin(self._runtime_env_dir)
self._py_modules_plugin = PyModulesPlugin(
self._runtime_env_dir, self._gcs_client
)
self._py_executable_plugin = PyExecutablePlugin()
self._java_jars_plugin = JavaJarsPlugin(self._runtime_env_dir, self._gcs_client)
self._working_dir_plugin = WorkingDirPlugin(
self._runtime_env_dir, self._gcs_client
)
self._container_plugin = ContainerPlugin(temp_dir)
# TODO(jonathan-anyscale): change the plugin to ProfilerPlugin
# and unify with nsight and other profilers.
self._nsight_plugin = NsightPlugin(self._runtime_env_dir)
self._rocprof_sys_plugin = RocProfSysPlugin(self._runtime_env_dir)
self._image_uri_plugin = get_image_uri_plugin_cls()(temp_dir)
# TODO(architkulkarni): "base plugins" and third-party plugins should all go
# through the same code path. We should never need to refer to
# self._xxx_plugin, we should just iterate through self._plugins.
self._base_plugins: List[RuntimeEnvPlugin] = [
self._working_dir_plugin,
self._uv_plugin,
self._pip_plugin,
self._conda_plugin,
self._py_modules_plugin,
self._py_executable_plugin,
self._java_jars_plugin,
self._container_plugin,
self._nsight_plugin,
self._rocprof_sys_plugin,
self._image_uri_plugin,
]
self._plugin_manager = RuntimeEnvPluginManager()
for plugin in self._base_plugins:
self._plugin_manager.add_plugin(plugin)
self._reference_table = ReferenceTable(
self.uris_parser,
self.unused_uris_processor,
self.unused_runtime_env_processor,
)
self._logger.info(
"Listening to address %s, port %d", address, runtime_env_agent_port
)
try:
self._node_ip = ray.util.get_node_ip_address()
self._node_prefix = f"[Node {self._node_ip}] "
except Exception as e:
self._logger.warning(f"Failed to get node IP address, using fallback: {e}")
self._node_prefix = "[Node unknown] "
def uris_parser(self, runtime_env: RuntimeEnv):
result = list()
for name, plugin_setup_context in self._plugin_manager.plugins.items():
plugin = plugin_setup_context.class_instance
uris = plugin.get_uris(runtime_env)
for uri in uris:
result.append((uri, UriType(name)))
return result
def unused_uris_processor(self, unused_uris: List[Tuple[str, UriType]]) -> None:
for uri, uri_type in unused_uris:
self._plugin_manager.plugins[str(uri_type)].uri_cache.mark_unused(uri)
def unused_runtime_env_processor(self, unused_runtime_env: str) -> None:
def delete_runtime_env():
del self._env_cache[unused_runtime_env]
self._logger.info(
"Runtime env %s removed from env-level cache.", unused_runtime_env
)
if unused_runtime_env in self._env_cache:
if not self._env_cache[unused_runtime_env].success:
loop = get_or_create_event_loop()
# Cache the bad runtime env result by ttl seconds.
loop.call_later(
runtime_env_consts.BAD_RUNTIME_ENV_CACHE_TTL_SECONDS,
delete_runtime_env,
)
else:
delete_runtime_env()
def get_or_create_logger(self, job_id: bytes, log_files: List[str]):
job_id = job_id.decode()
if job_id not in self._per_job_logger_cache:
params = self._logging_params.copy()
params["filename"] = [f"runtime_env_setup-{job_id}.log", *log_files]
params["logger_name"] = f"runtime_env_{job_id}"
params["propagate"] = False
per_job_logger = setup_component_logger(**params)
self._per_job_logger_cache[job_id] = per_job_logger
return self._per_job_logger_cache[job_id]
async def GetOrCreateRuntimeEnv(self, request):
self._logger.debug(
f"Got request from {request.source_process} to increase "
"reference for runtime env: "
f"{request.serialized_runtime_env}."
)
async def _setup_runtime_env(
runtime_env: RuntimeEnv,
runtime_env_config: RuntimeEnvConfig,
):
log_files = runtime_env_config.get("log_files", [])
# Use a separate logger for each job.
per_job_logger = self.get_or_create_logger(request.job_id, log_files)
context = RuntimeEnvContext(env_vars=runtime_env.env_vars())
# Warn about unrecognized fields in the runtime env.
for name, _ in runtime_env.plugins():
if name not in self._plugin_manager.plugins:
per_job_logger.warning(
f"runtime_env field {name} is not recognized by "
"Ray and will be ignored. In the future, unrecognized "
"fields in the runtime_env will raise an exception."
)
# Creates each runtime env URI by their priority. `working_dir` is special
# because it needs to be created before other plugins. All other plugins are
# created in the priority order (smaller priority value -> earlier to
# create), with a special environment variable being set to the working dir.
# ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}
# First create working dir...
working_dir_ctx = self._plugin_manager.plugins[WorkingDirPlugin.name]
await create_for_plugin_if_needed(
runtime_env,
working_dir_ctx.class_instance,
working_dir_ctx.uri_cache,
context,
per_job_logger,
)
# Then within the working dir, create the other plugins.
working_dir_uri_or_none = runtime_env.working_dir_uri()
with self._working_dir_plugin.with_working_dir_env(working_dir_uri_or_none):
"""Run setup for each plugin unless it has already been cached."""
for (
plugin_setup_context
) in self._plugin_manager.sorted_plugin_setup_contexts():
plugin = plugin_setup_context.class_instance
if plugin.name != WorkingDirPlugin.name:
uri_cache = plugin_setup_context.uri_cache
await create_for_plugin_if_needed(
runtime_env, plugin, uri_cache, context, per_job_logger
)
return context
async def _create_runtime_env_with_retry(
runtime_env,
setup_timeout_seconds,
runtime_env_config: RuntimeEnvConfig,
) -> Tuple[bool, str, str]:
"""Create runtime env with retry times. This function won't raise exceptions.
Args:
runtime_env: The instance of RuntimeEnv class.
setup_timeout_seconds: The timeout of runtime environment creation for
each attempt.
runtime_env_config: The configuration for the runtime environment.
Returns:
Tuple[bool, str, str]: A tuple containing:
- result (bool): Whether the creation was successful
- runtime_env_context (str): The serialized context if successful, None otherwise
- error_message (str): Error message if failed, None otherwise
"""
self._logger.info(
f"Creating runtime env: {serialized_env} with timeout "
f"{setup_timeout_seconds} seconds."
)
num_retries = runtime_env_consts.RUNTIME_ENV_RETRY_TIMES
error_message = None
serialized_context = None
for i in range(num_retries):
# Only sleep when retrying.
if i != 0:
await asyncio.sleep(
runtime_env_consts.RUNTIME_ENV_RETRY_INTERVAL_MS / 1000
)
try:
runtime_env_setup_task = _setup_runtime_env(
runtime_env, runtime_env_config
)
runtime_env_context = await asyncio.wait_for(
runtime_env_setup_task, timeout=setup_timeout_seconds
)
serialized_context = runtime_env_context.serialize()
error_message = None
break
except Exception as e:
err_msg = f"Failed to create runtime env {serialized_env}."
self._logger.exception(err_msg)
error_message = "".join(
traceback.format_exception(type(e), e, e.__traceback__)
)
if isinstance(e, asyncio.TimeoutError):
hint = (
f"Failed to install runtime_env within the "
f"timeout of {setup_timeout_seconds} seconds. Consider "
"increasing the timeout in the runtime_env config. "
"For example: \n"
' runtime_env={"config": {"setup_timeout_seconds":'
" 1800}, ...}\n"
"If not provided, the default timeout is "
f"{DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS} seconds. "
)
error_message = hint + error_message
if error_message:
self._logger.error(
"runtime_env creation failed %d times, giving up.",
num_retries,
)
return False, None, error_message
else:
self._logger.info(
"Successfully created runtime env: %s, context: %s",
serialized_env,
serialized_context,
)
return True, serialized_context, None
try:
serialized_env = request.serialized_runtime_env
runtime_env = RuntimeEnv.deserialize(serialized_env)
except Exception as e:
self._logger.exception(
"[Increase] Failed to parse runtime env: " f"{serialized_env}"
)
error_message = "".join(
traceback.format_exception(type(e), e, e.__traceback__)
)
return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply(
status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED,
error_message=f"{self._node_prefix}{error_message}",
)
# Increase reference
self._reference_table.increase_reference(
runtime_env, serialized_env, request.source_process
)
if serialized_env not in self._env_locks:
# async lock to prevent the same env being concurrently installed
self._env_locks[serialized_env] = asyncio.Lock()
async with self._env_locks[serialized_env]:
if serialized_env in self._env_cache:
serialized_context = self._env_cache[serialized_env]
result = self._env_cache[serialized_env]
if result.success:
context = result.result
self._logger.info(
"Runtime env already created "
f"successfully. Env: {serialized_env}, "
f"context: {context}"
)
return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply(
status=runtime_env_agent_pb2.AGENT_RPC_STATUS_OK,
serialized_runtime_env_context=context,
)
else:
error_message = result.result
self._logger.info(
"Runtime env already failed. "
f"Env: {serialized_env}, "
f"err: {error_message}"
)
# Recover the reference.
self._reference_table.decrease_reference(
runtime_env, serialized_env, request.source_process
)
return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply(
status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED,
error_message=f"{self._node_prefix}{error_message}",
)
if SLEEP_FOR_TESTING_S:
self._logger.info(f"Sleeping for {SLEEP_FOR_TESTING_S}s.")
time.sleep(int(SLEEP_FOR_TESTING_S))
runtime_env_config = RuntimeEnvConfig.from_proto(request.runtime_env_config)
# accroding to the document of `asyncio.wait_for`,
# None means disable timeout logic
setup_timeout_seconds = (
None
if runtime_env_config["setup_timeout_seconds"] == -1
else runtime_env_config["setup_timeout_seconds"]
)
start = time.perf_counter()
(
successful,
serialized_context,
error_message,
) = await _create_runtime_env_with_retry(
runtime_env,
setup_timeout_seconds,
runtime_env_config,
)
creation_time_ms = int(round((time.perf_counter() - start) * 1000, 0))
if not successful:
# Recover the reference.
self._reference_table.decrease_reference(
runtime_env, serialized_env, request.source_process
)
# Add the result to env cache.
self._env_cache[serialized_env] = CreatedEnvResult(
successful,
serialized_context if successful else error_message,
creation_time_ms,
)
# Reply the RPC
return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply(
status=runtime_env_agent_pb2.AGENT_RPC_STATUS_OK
if successful
else runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED,
serialized_runtime_env_context=serialized_context,
error_message=f"{self._node_prefix}{error_message}"
if not successful
else "",
)
async def DeleteRuntimeEnvIfPossible(self, request):
self._logger.info(
f"Got request from {request.source_process} to decrease "
"reference for runtime env: "
f"{request.serialized_runtime_env}."
)
try:
runtime_env = RuntimeEnv.deserialize(request.serialized_runtime_env)
except Exception as e:
self._logger.exception(
"[Decrease] Failed to parse runtime env: "
f"{request.serialized_runtime_env}"
)
error_message = "".join(
traceback.format_exception(type(e), e, e.__traceback__)
)
return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply(
status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED,
error_message=f"{self._node_prefix}{error_message}",
)
try:
self._reference_table.decrease_reference(
runtime_env, request.serialized_runtime_env, request.source_process
)
except Exception as e:
return runtime_env_agent_pb2.DeleteRuntimeEnvIfPossibleReply(
status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED,
error_message=f"{self._node_prefix}Failed to decrement reference for runtime env for {str(e)}",
)
return runtime_env_agent_pb2.DeleteRuntimeEnvIfPossibleReply(
status=runtime_env_agent_pb2.AGENT_RPC_STATUS_OK
)
async def GetRuntimeEnvsInfo(self, request):
"""Return the runtime env information of the node."""
# TODO(sang): Currently, it only includes runtime_env information.
# We should include the URI information which includes,
# URIs
# Caller
# Ref counts
# Cache information
# Metrics (creation time & success)
# Deleted URIs
limit = request.limit if request.HasField("limit") else -1
runtime_env_states = defaultdict(ProtoRuntimeEnvState)
runtime_env_refs = self._reference_table.runtime_env_refs
for runtime_env, ref_cnt in runtime_env_refs.items():
runtime_env_states[runtime_env].runtime_env = runtime_env
runtime_env_states[runtime_env].ref_cnt = ref_cnt
for runtime_env, result in self._env_cache.items():
runtime_env_states[runtime_env].runtime_env = runtime_env
runtime_env_states[runtime_env].success = result.success
if not result.success:
runtime_env_states[runtime_env].error = result.result
runtime_env_states[runtime_env].creation_time_ms = result.creation_time_ms
reply = runtime_env_agent_pb2.GetRuntimeEnvsInfoReply()
count = 0
for runtime_env_state in runtime_env_states.values():
if limit != -1 and count >= limit:
break
count += 1
reply.runtime_env_states.append(runtime_env_state)
reply.total = len(runtime_env_states)
return reply
| RuntimeEnvAgent |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 35363,
"end": 35548
} | class ____(AutoSchema):
"""A dummy AutoSchema subclass"""
pass
@override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'})
| CustomViewInspector |
python | spyder-ide__spyder | spyder/plugins/history/widgets.py | {
"start": 1352,
"end": 10472
} | class ____(PluginMainWidget):
"""
History plugin main widget.
"""
# Signals
sig_focus_changed = Signal()
"""
This signal is emitted when the focus of the code editor storing history
changes.
"""
def __init__(self, name, plugin, parent):
super().__init__(name, plugin, parent)
# Attributes
self.editors = []
self.filenames = []
self.tabwidget = None
self.dockviewer = None
self.wrap_action = None
self.linenumbers_action = None
self.filenames = []
self.font = None
# Widgets
self.tabwidget = Tabs(self)
self.find_widget = FindReplace(self)
# Setup
self.tabwidget.setStyleSheet(self._tabs_stylesheet)
self.find_widget.hide()
# Layout
layout = QVBoxLayout()
layout.setSpacing(0)
# TODO: Move this to the tab container directly
if sys.platform == 'darwin':
tab_container = QWidget(self)
tab_container.setObjectName('tab-container')
tab_layout = QVBoxLayout(tab_container)
tab_layout.setContentsMargins(0, 0, 0, 0)
tab_layout.addWidget(self.tabwidget)
layout.addWidget(tab_container)
else:
layout.addWidget(self.tabwidget)
layout.addWidget(self.find_widget)
self.setLayout(layout)
# Signals
self.tabwidget.currentChanged.connect(self.refresh)
self.tabwidget.move_data.connect(self.move_tab)
# --- PluginMainWidget API
# ------------------------------------------------------------------------
def get_title(self):
return _('History')
def get_focus_widget(self):
return self.tabwidget.currentWidget()
def setup(self):
# Actions
self.wrap_action = self.create_action(
HistoryWidgetActions.ToggleWrap,
text=_("Wrap lines"),
toggled=True,
initial=self.get_conf('wrap'),
option='wrap'
)
self.linenumbers_action = self.create_action(
HistoryWidgetActions.ToggleLineNumbers,
text=_("Show line numbers"),
toggled=True,
initial=self.get_conf('line_numbers'),
option='line_numbers'
)
# Menu
menu = self.get_options_menu()
for item in [self.wrap_action, self.linenumbers_action]:
self.add_item_to_menu(
item,
menu=menu,
section=HistoryWidgetOptionsMenuSections.Main,
)
def update_actions(self):
pass
@on_conf_change(option='wrap')
def on_wrap_update(self, value):
for editor in self.editors:
editor.toggle_wrap_mode(value)
@on_conf_change(option='line_numbers')
def on_line_numbers_update(self, value):
for editor in self.editors:
editor.toggle_line_numbers(value)
@on_conf_change(section='appearance', option=['selected', 'ui_theme'])
def on_color_scheme_change(self, option, value):
if option == 'ui_theme':
value = self.get_conf('selected', section='appearance')
for editor in self.editors:
editor.set_color_scheme(value)
# --- Public API
# ------------------------------------------------------------------------
def update_font(self, font, color_scheme):
"""
Update font of the code editor.
Parameters
----------
font: QFont
Font object.
color_scheme: str
Name of the color scheme to use.
"""
self.color_scheme = color_scheme
self.font = font
for editor in self.editors:
editor.set_font(font)
editor.set_color_scheme(color_scheme)
def move_tab(self, index_from, index_to):
"""
Move tab.
Parameters
----------
index_from: int
Move tab from this index.
index_to: int
Move tab to this index.
Notes
-----
Tabs themselves have already been moved by the history.tabwidget.
"""
filename = self.filenames.pop(index_from)
editor = self.editors.pop(index_from)
self.filenames.insert(index_to, filename)
self.editors.insert(index_to, editor)
def get_filename_text(self, filename):
"""
Read and return content from filename.
Parameters
----------
filename: str
The file path to read.
Returns
-------
str
Content of the filename.
"""
# Avoid a possible error when reading the history file
try:
text, _ = encoding.read(filename)
except (IOError, OSError):
text = "# Previous history could not be read from disk, sorry\n\n"
text = normalize_eols(text)
linebreaks = [m.start() for m in re.finditer('\n', text)]
if len(linebreaks) > MAX_LINES:
text = text[linebreaks[-MAX_LINES - 1] + 1:]
# Avoid an error when trying to write the trimmed text to disk.
# See spyder-ide/spyder#9093.
try:
encoding.write(text, filename)
except (IOError, OSError):
pass
return text
def add_history(self, filename):
"""
Create a history tab for `filename`.
Parameters
----------
filename: str
History filename.
"""
filename = encoding.to_unicode_from_fs(filename)
if filename in self.filenames:
return
# Widgets
editor = SimpleCodeEditor(self)
# Setup
language = 'py' if osp.splitext(filename)[1] == '.py' else 'bat'
editor.setup_editor(
linenumbers=self.get_conf('line_numbers'),
language=language,
color_scheme=self.get_conf('selected', section='appearance'),
font=self.font,
wrap=self.get_conf('wrap'),
)
editor.setReadOnly(True)
editor.set_text(self.get_filename_text(filename))
editor.set_cursor_position('eof')
self.find_widget.set_editor(editor)
index = self.tabwidget.addTab(editor, osp.basename(filename))
self.filenames.append(filename)
self.editors.append(editor)
self.tabwidget.setCurrentIndex(index)
self.tabwidget.setTabToolTip(index, filename)
# Hide close button
tab_bar = self.tabwidget.tabBar()
tab_bar.setTabButton(index, tab_bar.close_btn_side, None)
# Signals
editor.sig_focus_changed.connect(self.sig_focus_changed)
@Slot(str, str)
def append_to_history(self, filename, command):
"""
Append command to history tab.
Parameters
----------
filename: str
History file.
command: str
Command to append to history file.
"""
if not isinstance(filename, str): # filename is a QString
filename = str(filename.toUtf8())
index = self.filenames.index(filename)
command = str(command)
self.editors[index].append(command)
if self.get_conf('go_to_eof'):
self.editors[index].set_cursor_position('eof')
self.tabwidget.setCurrentIndex(index)
def refresh(self):
"""Refresh widget and update find widget on current editor."""
if self.tabwidget.count():
editor = self.tabwidget.currentWidget()
else:
editor = None
self.find_widget.set_editor(editor)
@property
def _tabs_stylesheet(self):
"""
Change style of tabs because we don't have a close button here.
"""
tabs_stylesheet = PANES_TABBAR_STYLESHEET.get_copy()
css = tabs_stylesheet.get_stylesheet()
margin_top = PANES_TABBAR_STYLESHEET.TOP_MARGIN.split('px')[0]
if WIN:
padding = '8px 10px'
elif MAC:
padding = '6px 10px 7px 10px'
else:
padding = '6px 10px'
css['QTabBar::tab'].setValues(
marginTop=f'{margin_top}px',
padding=f'{padding}',
)
for state in ['selected', 'selected:hover', 'hover']:
css[f'QTabBar::tab:{state}'].setValues(
padding=f'{padding}',
)
css['QTabWidget::pane'].setValues(
border='1px',
)
css['QTabWidget::left-corner'].setValues(
left='-1px',
right='-1px'
)
return str(tabs_stylesheet)
def test():
"""Run history widget."""
from spyder.utils.qthelpers import qapplication
from unittest.mock import MagicMock
plugin_mock = MagicMock()
plugin_mock.CONF_SECTION = 'historylog'
app = qapplication(test_time=8)
widget = HistoryWidget('historylog', plugin_mock, None)
widget._setup()
widget.setup()
widget.show()
sys.exit(app.exec_())
if __name__ == '__main__':
test()
| HistoryWidget |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_issue_metrics.py | {
"start": 979,
"end": 7323
} | class ____(OrganizationEndpoint):
owner = ApiOwner.REPLAY
publish_status = {"GET": ApiPublishStatus.PRIVATE}
def get(self, request: Request, organization: Organization) -> Response:
"""Stats bucketed by time."""
environments = [e.id for e in get_environments(request, organization)]
projects = self.get_projects(request, organization)
start, end = get_date_range_from_params(request.GET)
issue_category = request.GET.get("category", "issue")
if issue_category not in ["issue", "feedback"]:
raise ParseError("Invalid issue category. Valid options are 'issue' and 'feedback'.")
type_filter = (
~Q(type=FeedbackGroup.type_id)
if issue_category == "issue"
else Q(type=FeedbackGroup.type_id)
)
try:
interval_s = int(request.GET["interval"]) // 1000
if interval_s == 0:
raise ParseError("Interval must be greater than 1000 milliseconds.")
interval = timedelta(seconds=interval_s)
except KeyError:
# Defaulting for now. Probably better to compute some known interval. I.e. if we're
# close to an hour round up to an hour to ensure the best visual experience.
#
# Or maybe we require this field and ignore all these problems.
interval_s = 3600
interval = timedelta(seconds=interval_s)
except ValueError:
raise ParseError("Could not parse interval value.")
# This step validates our maximum granularity. Without this we could see unbounded
# cardinality in our queries. Our maximum granularity is 200 which is more than enough to
# accommodate common aggregation intervals.
#
# Max granularity estimates for a given range (rounded to understandable intervals):
# - One week range -> one hour interval.
# - One day range -> ten minute interval.
# - One hour range -> twenty second interval.
number_of_buckets = (end - start).total_seconds() // interval.total_seconds()
if number_of_buckets > 200:
raise ParseError("The specified granularity is too precise. Increase your interval.")
def gen_ts(
qs,
group_by: list[str],
date_column_name: str,
axis: str,
):
qs = make_timeseries_query(
qs,
projects,
environments,
type_filter,
group_by,
interval,
date_column_name,
start,
end,
)
grouped_counter: collections.defaultdict[str, int] = collections.defaultdict(int)
grouped_series: dict[str, list[TimeSeries]] = collections.defaultdict(list)
for row in qs:
grouping = [row[g] for g in group_by]
key = "||||".join(grouping)
grouped_counter[key] += row["value"]
grouped_series[key].append({"timestamp": row["timestamp"], "value": row["value"]})
# Group the smallest series into the "other" bucket.
if len(grouped_series) > 4:
keys = [v[0] for v in nlargest(5, grouped_counter.items(), key=lambda i: i[0])]
new_grouped_series: dict[str, list[TimeSeries]] = {}
other_series: collections.defaultdict[float, float] = collections.defaultdict(float)
for key, series in grouped_series.items():
if key in keys:
new_grouped_series[key] = series
else:
for s in series:
other_series[s["timestamp"]] += s["value"]
if other_series:
new_grouped_series["other"] = list(
map(
lambda i: {"timestamp": i[0], "value": i[1]},
sorted(list(other_series.items()), key=lambda i: i[0]),
)
)
else:
new_grouped_series = grouped_series
# Return a default empty state if nothing found.
if len(new_grouped_series) == 0:
return [
make_timeseries_result(
axis=axis,
group=[],
start=start,
end=end,
interval=interval,
is_other=False,
order=0,
values=[],
)
]
return [
make_timeseries_result(
axis=axis,
group=key.split("||||") if key else [],
start=start,
end=end,
interval=interval,
is_other=key == "other",
order=i,
values=series,
)
for i, (key, series) in enumerate(new_grouped_series.items())
]
return Response(
{
"timeseries": chain(
gen_ts(
Group.objects,
axis="new_issues_count",
date_column_name="first_seen",
group_by=[],
),
gen_ts(
Group.objects.filter(status=GroupStatus.RESOLVED),
axis="resolved_issues_count",
date_column_name="resolved_at",
group_by=[],
),
gen_ts(
Group.objects.filter(first_release__isnull=False),
axis="new_issues_count_by_release",
date_column_name="first_seen",
group_by=["first_release__version"],
),
),
"meta": {
"dataset": "issues",
"end": end.timestamp(),
"start": start.timestamp(),
},
},
status=200,
)
| OrganizationIssueMetricsEndpoint |
python | pypa__pipenv | pipenv/patched/pip/_internal/metadata/pkg_resources.py | {
"start": 1224,
"end": 2359
} | class ____:
"""IMetadataProvider that reads metadata files from a dictionary.
This also maps metadata decoding exceptions to our internal exception type.
"""
def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:
self._metadata = metadata
self._wheel_name = wheel_name
def has_metadata(self, name: str) -> bool:
return name in self._metadata
def get_metadata(self, name: str) -> str:
try:
return self._metadata[name].decode()
except UnicodeDecodeError as e:
# Augment the default error with the origin of the file.
raise UnsupportedWheel(
f"Error decoding metadata for {self._wheel_name}: {e} in {name} file"
)
def get_metadata_lines(self, name: str) -> Iterable[str]:
return pkg_resources.yield_lines(self.get_metadata(name))
def metadata_isdir(self, name: str) -> bool:
return False
def metadata_listdir(self, name: str) -> List[str]:
return []
def run_script(self, script_name: str, namespace: str) -> None:
pass
| InMemoryMetadata |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 159375,
"end": 162378
} | class ____(TestCase):
@_no_tracing
def test_basic(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
if IS_PYPY:
x.resize((5, 5), refcheck=False)
else:
x.resize((5, 5))
assert_array_equal(
x.ravel()[:9], np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).ravel()
)
assert_array_equal(x[9:].ravel(), 0)
@skip(reason="how to find if someone is referencing an array")
def test_check_reference(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
y = x
assert_raises(ValueError, x.resize, (5, 1))
del y # avoid pyflakes unused variable warning.
@_no_tracing
def test_int_shape(self):
x = np.eye(3)
if IS_PYPY:
x.resize(3, refcheck=False)
else:
x.resize(3)
assert_array_equal(x, np.eye(3)[0, :])
def test_none_shape(self):
x = np.eye(3)
x.resize(None)
assert_array_equal(x, np.eye(3))
x.resize()
assert_array_equal(x, np.eye(3))
def test_0d_shape(self):
# to it multiple times to test it does not break alloc cache gh-9216
for _ in range(10):
x = np.empty((1,))
x.resize(())
assert_equal(x.shape, ())
assert_equal(x.size, 1)
x = np.empty(())
x.resize((1,))
assert_equal(x.shape, (1,))
assert_equal(x.size, 1)
def test_invalid_arguments(self):
assert_raises(TypeError, np.eye(3).resize, "hi")
assert_raises(ValueError, np.eye(3).resize, -1)
assert_raises(TypeError, np.eye(3).resize, order=1)
assert_raises((NotImplementedError, TypeError), np.eye(3).resize, refcheck="hi")
@_no_tracing
def test_freeform_shape(self):
x = np.eye(3)
if IS_PYPY:
x.resize(3, 2, 1, refcheck=False)
else:
x.resize(3, 2, 1)
assert_(x.shape == (3, 2, 1))
@_no_tracing
def test_zeros_appended(self):
x = np.eye(3)
if IS_PYPY:
x.resize(2, 3, 3, refcheck=False)
else:
x.resize(2, 3, 3)
assert_array_equal(x[0], np.eye(3))
assert_array_equal(x[1], np.zeros((3, 3)))
def test_empty_view(self):
# check that sizes containing a zero don't trigger a reallocate for
# already empty arrays
x = np.zeros((10, 0), int)
x_view = x[...]
x_view.resize((0, 10))
x_view.resize((0, 100))
@skip(reason="ignore weakrefs for ndarray.resize")
def test_check_weakref(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
xref = weakref.ref(x)
assert_raises(ValueError, x.resize, (5, 1))
del xref # avoid pyflakes unused variable warning.
def _mean(a, **args):
return a.mean(**args)
def _var(a, **args):
return a.var(**args)
def _std(a, **args):
return a.std(**args)
@instantiate_parametrized_tests
| TestResize |
python | sympy__sympy | sympy/physics/quantum/constants.py | {
"start": 442,
"end": 1420
} | class ____(NumberSymbol, metaclass=Singleton):
"""Reduced Plank's constant in numerical and symbolic form [1]_.
Examples
========
>>> from sympy.physics.quantum.constants import hbar
>>> hbar.evalf()
1.05457162000000e-34
References
==========
.. [1] https://en.wikipedia.org/wiki/Planck_constant
"""
is_real = True
is_positive = True
is_negative = False
is_irrational = True
__slots__ = ()
def _as_mpf_val(self, prec):
return mlib.from_float(1.05457162e-34, prec)
def _sympyrepr(self, printer, *args):
return 'HBar()'
def _sympystr(self, printer, *args):
return 'hbar'
def _pretty(self, printer, *args):
if printer._use_unicode:
return prettyForm('\N{PLANCK CONSTANT OVER TWO PI}')
return prettyForm('hbar')
def _latex(self, printer, *args):
return r'\hbar'
# Create an instance for everyone to use.
hbar = HBar()
| HBar |
python | django__django | tests/serializers/models/data.py | {
"start": 1404,
"end": 1481
} | class ____(models.Model):
data = models.IntegerField(null=True)
| IntegerData |
python | realpython__materials | python-class/robot.py | {
"start": 814,
"end": 1166
} | class ____:
def __init__(self):
self.position = 0
def move_up(self, distance=1):
self.position += distance
print(f"Moving arm {distance} cm up...")
def move_down(self, distance=1):
self.position -= distance
print(f"Moving arm {distance} cm down...")
def weld(self):
print("Welding...")
| Arm |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-s3/source_s3/source_files_abstract/spec.py | {
"start": 1344,
"end": 5317
} | class ____(BaseModel):
dataset: str = Field(
pattern=r"^([A-Za-z0-9-_]+)$",
description="The name of the stream you would like this source to output. Can contain letters, numbers, or underscores.",
order=0,
title="Output Stream Name",
)
path_pattern: str = Field(
title="Pattern of files to replicate",
description="A regular expression which tells the connector which files to replicate. All files which match this pattern will be "
'replicated. Use | to separate multiple patterns. See <a href="https://facelessuser.github.io/wcmatch/glob/" target="_'
'blank">this page</a> to understand pattern syntax (GLOBSTAR and SPLIT flags are enabled). '
"Use pattern <strong>**</strong> to pick up all files.",
examples=["**", "myFolder/myTableFiles/*.csv|myFolder/myOtherTableFiles/*.csv"],
order=10,
)
format: Union[CsvFormat, ParquetFormat, AvroFormat, JsonlFormat] = Field(
default="csv", title="File Format", description="The format of the files you'd like to replicate", order=20
)
user_schema: str = Field(
title="Manually enforced data schema",
alias="schema",
default="{}",
description="Optionally provide a schema to enforce, as a valid JSON string. Ensure this is a mapping of "
'<strong>{ "column" : "type" }</strong>, where types are valid '
'<a href="https://json-schema.org/understanding-json-schema/reference/type.html" target="_blank">JSON Schema '
"datatypes</a>. Leave as {} to auto-infer the schema.",
examples=['{"column_1": "number", "column_2": "string", "column_3": "array", "column_4": "object", "column_5": "boolean"}'],
order=30,
)
@staticmethod
def change_format_to_oneOf(schema: dict) -> dict:
props_to_change = ["format"]
for prop in props_to_change:
schema["properties"][prop]["type"] = "object"
if "oneOf" in schema["properties"][prop]:
continue
schema["properties"][prop]["oneOf"] = schema["properties"][prop].pop("anyOf")
return schema
@staticmethod
def remove_enum_allOf(schema: dict) -> dict:
"""
allOfs are not supported by the UI, but pydantic is automatically writing them for enums.
Unpack them into the root
"""
objects_to_check = schema["properties"]["format"]["oneOf"]
for object in objects_to_check:
for key in object["properties"]:
property = object["properties"][key]
if "allOf" in property and "enum" in property["allOf"][0]:
property["enum"] = property["allOf"][0]["enum"]
property.pop("allOf")
return schema
@staticmethod
def check_provider_added(schema: dict) -> None:
if "provider" not in schema["properties"]:
raise RuntimeError("You must add the 'provider' property in your child spec class")
@staticmethod
def resolve_refs(schema: dict) -> dict:
json_schema_ref_resolver = RefResolver.from_schema(schema)
str_schema = json.dumps(schema)
for ref_block in re.findall(r'{"\$ref": "#\/definitions\/.+?(?="})"}', str_schema):
ref = json.loads(ref_block)["$ref"]
str_schema = str_schema.replace(ref_block, json.dumps(json_schema_ref_resolver.resolve(ref)[1]))
pyschema: dict = json.loads(str_schema)
del pyschema["definitions"]
return pyschema
@classmethod
def schema(cls, *args: Any, **kwargs: Any) -> Dict[str, Any]:
"""we're overriding the schema classmethod to enable some post-processing"""
schema = super().schema(*args, **kwargs)
cls.check_provider_added(schema)
schema = cls.change_format_to_oneOf(schema)
schema = cls.resolve_refs(schema)
schema = cls.remove_enum_allOf(schema)
return schema
| SourceFilesAbstractSpec |
python | tensorflow__tensorflow | tensorflow/python/distribute/values.py | {
"start": 59362,
"end": 60800
} | class ____(object):
"""Policy defining synchronization and aggregation of a distributed variable.
Given `synchronization` and `aggregation` parameters set on a `tf.Variable`
during variable creation within `tf.distribute` scope, `tf.distribute` creates
an appropriate policy object and assigns it to the distributed variable. All
variable operations are delegated to the respective policy object.
"""
def __init__(self, aggregation):
self._aggregation = aggregation
def value(self):
raise NotImplementedError(
"VariablePolicy.value should be overridden by sub-classes. "
f"Type name is {type(self)}"
)
def _is_mirrored(self):
raise NotImplementedError(
"VariablePolicy._is_mirrored should be overridden by sub-classes. "
f"Type name is {type(self)}"
)
def _as_graph_element(self, _):
raise NotImplementedError(
"VariablePolicy._as_graph_element should be overridden by sub-classes. "
f"Type name is {type(self)}"
)
def _get_cross_replica(self, var):
raise NotImplementedError(
"VariablePolicy._get_cross_replica should be overridden by"
f" sub-classes. Type name is {type(self)}"
)
def _update_replica(self, var, update_fn, value, **kwargs):
raise NotImplementedError(
"VariablePolicy._update_replica should be overridden by sub-classes. "
f"Type name is {type(self)}"
)
| VariablePolicy |
python | ray-project__ray | python/ray/tune/search/searcher.py | {
"start": 15583,
"end": 21389
} | class ____(Searcher):
"""A wrapper algorithm for limiting the number of concurrent trials.
Certain Searchers have their own internal logic for limiting
the number of concurrent trials. If such a Searcher is passed to a
``ConcurrencyLimiter``, the ``max_concurrent`` of the
``ConcurrencyLimiter`` will override the ``max_concurrent`` value
of the Searcher. The ``ConcurrencyLimiter`` will then let the
Searcher's internal logic take over.
Args:
searcher: Searcher object that the
ConcurrencyLimiter will manage.
max_concurrent: Maximum concurrent samples from the underlying
searcher.
batch: Whether to wait for all concurrent samples
to finish before updating the underlying searcher.
Example:
.. code-block:: python
from ray.tune.search import ConcurrencyLimiter
search_alg = HyperOptSearch(metric="accuracy")
search_alg = ConcurrencyLimiter(search_alg, max_concurrent=2)
tuner = tune.Tuner(
trainable_function,
tune_config=tune.TuneConfig(
search_alg=search_alg
),
)
tuner.fit()
"""
def __init__(self, searcher: Searcher, max_concurrent: int, batch: bool = False):
assert type(max_concurrent) is int and max_concurrent > 0
self.searcher = searcher
self.max_concurrent = max_concurrent
self.batch = batch
self.live_trials = set()
self.num_unfinished_live_trials = 0
self.cached_results = {}
self._limit_concurrency = True
if not isinstance(searcher, Searcher):
raise RuntimeError(
f"The `ConcurrencyLimiter` only works with `Searcher` "
f"objects (got {type(searcher)}). Please try to pass "
f"`max_concurrent` to the search generator directly."
)
self._set_searcher_max_concurrency()
super(ConcurrencyLimiter, self).__init__(
metric=self.searcher.metric, mode=self.searcher.mode
)
def _set_searcher_max_concurrency(self):
# If the searcher has special logic for handling max concurrency,
# we do not do anything inside the ConcurrencyLimiter
self._limit_concurrency = not self.searcher.set_max_concurrency(
self.max_concurrent
)
def set_max_concurrency(self, max_concurrent: int) -> bool:
# Determine if this behavior is acceptable, or if it should
# raise an exception.
self.max_concurrent = max_concurrent
return True
def set_search_properties(
self, metric: Optional[str], mode: Optional[str], config: Dict, **spec
) -> bool:
self._set_searcher_max_concurrency()
return _set_search_properties_backwards_compatible(
self.searcher.set_search_properties, metric, mode, config, **spec
)
def suggest(self, trial_id: str) -> Optional[Dict]:
if not self._limit_concurrency:
return self.searcher.suggest(trial_id)
assert (
trial_id not in self.live_trials
), f"Trial ID {trial_id} must be unique: already found in set."
if len(self.live_trials) >= self.max_concurrent:
logger.debug(
f"Not providing a suggestion for {trial_id} due to "
"concurrency limit: %s/%s.",
len(self.live_trials),
self.max_concurrent,
)
return
suggestion = self.searcher.suggest(trial_id)
if suggestion not in (None, Searcher.FINISHED):
self.live_trials.add(trial_id)
self.num_unfinished_live_trials += 1
return suggestion
def on_trial_complete(
self, trial_id: str, result: Optional[Dict] = None, error: bool = False
):
if not self._limit_concurrency:
return self.searcher.on_trial_complete(trial_id, result=result, error=error)
if trial_id not in self.live_trials:
return
elif self.batch:
self.cached_results[trial_id] = (result, error)
self.num_unfinished_live_trials -= 1
if self.num_unfinished_live_trials <= 0:
# Update the underlying searcher once the
# full batch is completed.
for trial_id, (result, error) in self.cached_results.items():
self.searcher.on_trial_complete(
trial_id, result=result, error=error
)
self.live_trials.remove(trial_id)
self.cached_results = {}
self.num_unfinished_live_trials = 0
else:
return
else:
self.searcher.on_trial_complete(trial_id, result=result, error=error)
self.live_trials.remove(trial_id)
self.num_unfinished_live_trials -= 1
def on_trial_result(self, trial_id: str, result: Dict) -> None:
self.searcher.on_trial_result(trial_id, result)
def add_evaluated_point(
self,
parameters: Dict,
value: float,
error: bool = False,
pruned: bool = False,
intermediate_values: Optional[List[float]] = None,
):
return self.searcher.add_evaluated_point(
parameters, value, error, pruned, intermediate_values
)
def get_state(self) -> Dict:
state = self.__dict__.copy()
del state["searcher"]
return copy.deepcopy(state)
def set_state(self, state: Dict):
self.__dict__.update(state)
def save(self, checkpoint_path: str):
self.searcher.save(checkpoint_path)
def restore(self, checkpoint_path: str):
self.searcher.restore(checkpoint_path)
| ConcurrencyLimiter |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_math.py | {
"start": 9449,
"end": 108032
} | class ____(__TestCase):
def ftest(self, name, got, expected, ulp_tol=5, abs_tol=0.0):
"""Compare arguments expected and got, as floats, if either
is a float, using a tolerance expressed in multiples of
ulp(expected) or absolutely, whichever is greater.
As a convenience, when neither argument is a float, and for
non-finite floats, exact equality is demanded. Also, nan==nan
in this function.
"""
failure = result_check(expected, got, ulp_tol, abs_tol)
if failure is not None:
self.fail("{}: {}".format(name, failure))
def testConstants(self):
# Ref: Abramowitz & Stegun (Dover, 1965)
self.ftest('pi', math.pi, 3.141592653589793238462643)
self.ftest('e', math.e, 2.718281828459045235360287)
self.assertEqual(math.tau, 2*math.pi)
def testAcos(self):
self.assertRaises(TypeError, math.acos)
self.ftest('acos(-1)', math.acos(-1), math.pi)
self.ftest('acos(0)', math.acos(0), math.pi/2)
self.ftest('acos(1)', math.acos(1), 0)
self.assertRaises(ValueError, math.acos, INF)
self.assertRaises(ValueError, math.acos, NINF)
self.assertRaises(ValueError, math.acos, 1 + eps)
self.assertRaises(ValueError, math.acos, -1 - eps)
self.assertTrue(math.isnan(math.acos(NAN)))
def testAcosh(self):
self.assertRaises(TypeError, math.acosh)
self.ftest('acosh(1)', math.acosh(1), 0)
self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
self.assertRaises(ValueError, math.acosh, 0)
self.assertRaises(ValueError, math.acosh, -1)
self.assertEqual(math.acosh(INF), INF)
self.assertRaises(ValueError, math.acosh, NINF)
self.assertTrue(math.isnan(math.acosh(NAN)))
def testAsin(self):
self.assertRaises(TypeError, math.asin)
self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
self.ftest('asin(0)', math.asin(0), 0)
self.ftest('asin(1)', math.asin(1), math.pi/2)
self.assertRaises(ValueError, math.asin, INF)
self.assertRaises(ValueError, math.asin, NINF)
self.assertRaises(ValueError, math.asin, 1 + eps)
self.assertRaises(ValueError, math.asin, -1 - eps)
self.assertTrue(math.isnan(math.asin(NAN)))
def testAsinh(self):
self.assertRaises(TypeError, math.asinh)
self.ftest('asinh(0)', math.asinh(0), 0)
self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
self.assertEqual(math.asinh(INF), INF)
self.assertEqual(math.asinh(NINF), NINF)
self.assertTrue(math.isnan(math.asinh(NAN)))
def testAtan(self):
self.assertRaises(TypeError, math.atan)
self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
self.ftest('atan(0)', math.atan(0), 0)
self.ftest('atan(1)', math.atan(1), math.pi/4)
self.ftest('atan(inf)', math.atan(INF), math.pi/2)
self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
self.assertTrue(math.isnan(math.atan(NAN)))
def testAtanh(self):
self.assertRaises(TypeError, math.atan)
self.ftest('atanh(0)', math.atanh(0), 0)
self.ftest('atanh(0.5)', math.atanh(0.5), 0.54930614433405489)
self.ftest('atanh(-0.5)', math.atanh(-0.5), -0.54930614433405489)
self.assertRaises(ValueError, math.atanh, 1)
self.assertRaises(ValueError, math.atanh, -1)
self.assertRaises(ValueError, math.atanh, INF)
self.assertRaises(ValueError, math.atanh, NINF)
self.assertTrue(math.isnan(math.atanh(NAN)))
def testAtan2(self):
self.assertRaises(TypeError, math.atan2)
self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)
self.ftest('atan2(1, -1)', math.atan2(1, -1), 3*math.pi/4)
# math.atan2(0, x)
self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
self.assertEqual(math.atan2(0., 0.), 0.)
self.assertEqual(math.atan2(0., 2.3), 0.)
self.assertEqual(math.atan2(0., INF), 0.)
self.assertTrue(math.isnan(math.atan2(0., NAN)))
# math.atan2(-0, x)
self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
self.assertEqual(math.atan2(-0., 0.), -0.)
self.assertEqual(math.atan2(-0., 2.3), -0.)
self.assertEqual(math.atan2(-0., INF), -0.)
self.assertTrue(math.isnan(math.atan2(-0., NAN)))
# math.atan2(INF, x)
self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
self.assertTrue(math.isnan(math.atan2(INF, NAN)))
# math.atan2(NINF, x)
self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
# math.atan2(+finite, x)
self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
self.assertEqual(math.atan2(2.3, INF), 0.)
self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
# math.atan2(-finite, x)
self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
self.assertEqual(math.atan2(-2.3, INF), -0.)
self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
# math.atan2(NAN, x)
self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
self.assertTrue(math.isnan(math.atan2(NAN, INF)))
self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
def testCbrt(self):
self.assertRaises(TypeError, math.cbrt)
self.ftest('cbrt(0)', math.cbrt(0), 0)
self.ftest('cbrt(1)', math.cbrt(1), 1)
self.ftest('cbrt(8)', math.cbrt(8), 2)
self.ftest('cbrt(0.0)', math.cbrt(0.0), 0.0)
self.ftest('cbrt(-0.0)', math.cbrt(-0.0), -0.0)
self.ftest('cbrt(1.2)', math.cbrt(1.2), 1.062658569182611)
self.ftest('cbrt(-2.6)', math.cbrt(-2.6), -1.375068867074141)
self.ftest('cbrt(27)', math.cbrt(27), 3)
self.ftest('cbrt(-1)', math.cbrt(-1), -1)
self.ftest('cbrt(-27)', math.cbrt(-27), -3)
self.assertEqual(math.cbrt(INF), INF)
self.assertEqual(math.cbrt(NINF), NINF)
self.assertTrue(math.isnan(math.cbrt(NAN)))
def testCeil(self):
self.assertRaises(TypeError, math.ceil)
self.assertEqual(int, type(math.ceil(0.5)))
self.assertEqual(math.ceil(0.5), 1)
self.assertEqual(math.ceil(1.0), 1)
self.assertEqual(math.ceil(1.5), 2)
self.assertEqual(math.ceil(-0.5), 0)
self.assertEqual(math.ceil(-1.0), -1)
self.assertEqual(math.ceil(-1.5), -1)
self.assertEqual(math.ceil(0.0), 0)
self.assertEqual(math.ceil(-0.0), 0)
#self.assertEqual(math.ceil(INF), INF)
#self.assertEqual(math.ceil(NINF), NINF)
#self.assertTrue(math.isnan(math.ceil(NAN)))
with torch._dynamo.error_on_graph_break(False):
class TestCeil:
def __ceil__(self):
return 42
class FloatCeil(float):
def __ceil__(self):
return 42
class TestNoCeil:
pass
class TestBadCeil:
__ceil__ = BadDescr()
self.assertEqual(math.ceil(TestCeil()), 42)
self.assertEqual(math.ceil(FloatCeil()), 42)
self.assertEqual(math.ceil(FloatLike(42.5)), 43)
self.assertRaises(TypeError, math.ceil, TestNoCeil())
self.assertRaises(ValueError, math.ceil, TestBadCeil())
t = TestNoCeil()
t.__ceil__ = lambda *args: args
self.assertRaises(TypeError, math.ceil, t)
self.assertRaises(TypeError, math.ceil, t, 0)
self.assertEqual(math.ceil(FloatLike(+1.0)), +1.0)
self.assertEqual(math.ceil(FloatLike(-1.0)), -1.0)
@requires_IEEE_754
def testCopysign(self):
self.assertEqual(math.copysign(1, 42), 1.0)
self.assertEqual(math.copysign(0., 42), 0.0)
self.assertEqual(math.copysign(1., -42), -1.0)
self.assertEqual(math.copysign(3, 0.), 3.0)
self.assertEqual(math.copysign(4., -0.), -4.0)
self.assertRaises(TypeError, math.copysign)
# copysign should let us distinguish signs of zeros
self.assertEqual(math.copysign(1., 0.), 1.)
self.assertEqual(math.copysign(1., -0.), -1.)
self.assertEqual(math.copysign(INF, 0.), INF)
self.assertEqual(math.copysign(INF, -0.), NINF)
self.assertEqual(math.copysign(NINF, 0.), INF)
self.assertEqual(math.copysign(NINF, -0.), NINF)
# and of infinities
self.assertEqual(math.copysign(1., INF), 1.)
self.assertEqual(math.copysign(1., NINF), -1.)
self.assertEqual(math.copysign(INF, INF), INF)
self.assertEqual(math.copysign(INF, NINF), NINF)
self.assertEqual(math.copysign(NINF, INF), INF)
self.assertEqual(math.copysign(NINF, NINF), NINF)
self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
self.assertTrue(math.isnan(math.copysign(NAN, INF)))
self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
# copysign(INF, NAN) may be INF or it may be NINF, since
# we don't know whether the sign bit of NAN is set on any
# given platform.
self.assertTrue(math.isinf(math.copysign(INF, NAN)))
# similarly, copysign(2., NAN) could be 2. or -2.
self.assertEqual(abs(math.copysign(2., NAN)), 2.)
def testCos(self):
self.assertRaises(TypeError, math.cos)
self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=math.ulp(1))
self.ftest('cos(0)', math.cos(0), 1)
self.ftest('cos(pi/2)', math.cos(math.pi/2), 0, abs_tol=math.ulp(1))
self.ftest('cos(pi)', math.cos(math.pi), -1)
try:
self.assertTrue(math.isnan(math.cos(INF)))
self.assertTrue(math.isnan(math.cos(NINF)))
except ValueError:
self.assertRaises(ValueError, math.cos, INF)
self.assertRaises(ValueError, math.cos, NINF)
self.assertTrue(math.isnan(math.cos(NAN)))
@unittest.skipIf(sys.platform == 'win32' and platform.machine() in ('ARM', 'ARM64'),
"Windows UCRT is off by 2 ULP this test requires accuracy within 1 ULP")
def testCosh(self):
self.assertRaises(TypeError, math.cosh)
self.ftest('cosh(0)', math.cosh(0), 1)
self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
self.assertEqual(math.cosh(INF), INF)
self.assertEqual(math.cosh(NINF), INF)
self.assertTrue(math.isnan(math.cosh(NAN)))
def testDegrees(self):
self.assertRaises(TypeError, math.degrees)
self.ftest('degrees(pi)', math.degrees(math.pi), 180.0)
self.ftest('degrees(pi/2)', math.degrees(math.pi/2), 90.0)
self.ftest('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0)
self.ftest('degrees(0)', math.degrees(0), 0)
def testExp(self):
self.assertRaises(TypeError, math.exp)
self.ftest('exp(-1)', math.exp(-1), 1/math.e)
self.ftest('exp(0)', math.exp(0), 1)
self.ftest('exp(1)', math.exp(1), math.e)
self.assertEqual(math.exp(INF), INF)
self.assertEqual(math.exp(NINF), 0.)
self.assertTrue(math.isnan(math.exp(NAN)))
self.assertRaises(OverflowError, math.exp, 1000000)
def testExp2(self):
self.assertRaises(TypeError, math.exp2)
self.ftest('exp2(-1)', math.exp2(-1), 0.5)
self.ftest('exp2(0)', math.exp2(0), 1)
self.ftest('exp2(1)', math.exp2(1), 2)
self.ftest('exp2(2.3)', math.exp2(2.3), 4.924577653379665)
self.assertEqual(math.exp2(INF), INF)
self.assertEqual(math.exp2(NINF), 0.)
self.assertTrue(math.isnan(math.exp2(NAN)))
self.assertRaises(OverflowError, math.exp2, 1000000)
def testFabs(self):
self.assertRaises(TypeError, math.fabs)
self.ftest('fabs(-1)', math.fabs(-1), 1)
self.ftest('fabs(0)', math.fabs(0), 0)
self.ftest('fabs(1)', math.fabs(1), 1)
@skipIfTorchDynamo("infinite loop")
def testFactorial(self):
self.assertEqual(math.factorial(0), 1)
total = 1
for i in range(1, 1000):
total *= i
self.assertEqual(math.factorial(i), total)
self.assertEqual(math.factorial(i), py_factorial(i))
self.assertRaises(ValueError, math.factorial, -1)
self.assertRaises(ValueError, math.factorial, -10**100)
def testFactorialNonIntegers(self):
self.assertRaises(TypeError, math.factorial, 5.0)
self.assertRaises(TypeError, math.factorial, 5.2)
self.assertRaises(TypeError, math.factorial, -1.0)
self.assertRaises(TypeError, math.factorial, -1e100)
self.assertRaises(TypeError, math.factorial, decimal.Decimal('5'))
self.assertRaises(TypeError, math.factorial, decimal.Decimal('5.2'))
self.assertRaises(TypeError, math.factorial, "5")
# Other implementations may place different upper bounds.
@support.cpython_only
def testFactorialHugeInputs(self):
# Currently raises OverflowError for inputs that are too large
# to fit into a C long.
self.assertRaises(OverflowError, math.factorial, 10**100)
self.assertRaises(TypeError, math.factorial, 1e100)
def testFloor(self):
self.assertRaises(TypeError, math.floor)
self.assertEqual(int, type(math.floor(0.5)))
self.assertEqual(math.floor(0.5), 0)
self.assertEqual(math.floor(1.0), 1)
self.assertEqual(math.floor(1.5), 1)
self.assertEqual(math.floor(-0.5), -1)
self.assertEqual(math.floor(-1.0), -1)
self.assertEqual(math.floor(-1.5), -2)
#self.assertEqual(math.ceil(INF), INF)
#self.assertEqual(math.ceil(NINF), NINF)
#self.assertTrue(math.isnan(math.floor(NAN)))
with torch._dynamo.error_on_graph_break(False):
class TestFloor:
def __floor__(self):
return 42
class FloatFloor(float):
def __floor__(self):
return 42
class TestNoFloor:
pass
class TestBadFloor:
__floor__ = BadDescr()
self.assertEqual(math.floor(TestFloor()), 42)
self.assertEqual(math.floor(FloatFloor()), 42)
self.assertEqual(math.floor(FloatLike(41.9)), 41)
self.assertRaises(TypeError, math.floor, TestNoFloor())
self.assertRaises(ValueError, math.floor, TestBadFloor())
t = TestNoFloor()
t.__floor__ = lambda *args: args
self.assertRaises(TypeError, math.floor, t)
self.assertRaises(TypeError, math.floor, t, 0)
self.assertEqual(math.floor(FloatLike(+1.0)), +1.0)
self.assertEqual(math.floor(FloatLike(-1.0)), -1.0)
def testFmod(self):
self.assertRaises(TypeError, math.fmod)
self.ftest('fmod(10, 1)', math.fmod(10, 1), 0.0)
self.ftest('fmod(10, 0.5)', math.fmod(10, 0.5), 0.0)
self.ftest('fmod(10, 1.5)', math.fmod(10, 1.5), 1.0)
self.ftest('fmod(-10, 1)', math.fmod(-10, 1), -0.0)
self.ftest('fmod(-10, 0.5)', math.fmod(-10, 0.5), -0.0)
self.ftest('fmod(-10, 1.5)', math.fmod(-10, 1.5), -1.0)
self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
self.assertTrue(math.isnan(math.fmod(1., NAN)))
self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
self.assertRaises(ValueError, math.fmod, 1., 0.)
self.assertRaises(ValueError, math.fmod, INF, 1.)
self.assertRaises(ValueError, math.fmod, NINF, 1.)
self.assertRaises(ValueError, math.fmod, INF, 0.)
self.assertEqual(math.fmod(3.0, INF), 3.0)
self.assertEqual(math.fmod(-3.0, INF), -3.0)
self.assertEqual(math.fmod(3.0, NINF), 3.0)
self.assertEqual(math.fmod(-3.0, NINF), -3.0)
self.assertEqual(math.fmod(0.0, 3.0), 0.0)
self.assertEqual(math.fmod(0.0, NINF), 0.0)
self.assertRaises(ValueError, math.fmod, INF, INF)
def testFrexp(self):
self.assertRaises(TypeError, math.frexp)
def testfrexp(name, result, expected):
(mant, exp), (emant, eexp) = result, expected
if abs(mant-emant) > eps or exp != eexp:
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
testfrexp('frexp(0)', math.frexp(0), (0, 0))
testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
self.assertEqual(math.frexp(INF)[0], INF)
self.assertEqual(math.frexp(NINF)[0], NINF)
self.assertTrue(math.isnan(math.frexp(NAN)[0]))
@requires_IEEE_754
@unittest.skipIf(HAVE_DOUBLE_ROUNDING,
"fsum is not exact on machines with double rounding")
def testFsum(self):
# math.fsum relies on exact rounding for correct operation.
# There's a known problem with IA32 floating-point that causes
# inexact rounding in some situations, and will cause the
# math.fsum tests below to fail; see issue #2937. On non IEEE
# 754 platforms, and on IEEE 754 platforms that exhibit the
# problem described in issue #2937, we simply skip the whole
# test.
# Python version of math.fsum, for comparison. Uses a
# different algorithm based on frexp, ldexp and integer
# arithmetic.
from sys import float_info
mant_dig = float_info.mant_dig
etiny = float_info.min_exp - mant_dig
def msum(iterable):
"""Full precision summation. Compute sum(iterable) without any
intermediate accumulation of error. Based on the 'lsum' function
at https://code.activestate.com/recipes/393090-binary-floating-point-summation-accurate-to-full-p/
"""
tmant, texp = 0, 0
for x in iterable:
mant, exp = math.frexp(x)
mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
if texp > exp:
tmant <<= texp-exp
texp = exp
else:
mant <<= exp-texp
tmant += mant
# Round tmant * 2**texp to a float. The original recipe
# used float(str(tmant)) * 2.0**texp for this, but that's
# a little unsafe because str -> float conversion can't be
# relied upon to do correct rounding on all platforms.
tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
if tail > 0:
h = 1 << (tail-1)
tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
texp += tail
return math.ldexp(tmant, texp)
test_values = [
([], 0.0),
([0.0], 0.0),
([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100),
([1e100, 1.0, -1e100, 1e-100, 1e50, -1, -1e50], 1e-100),
([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0),
([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0),
([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0),
([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0),
([1./n for n in range(1, 1001)],
float.fromhex('0x1.df11f45f4e61ap+2')),
([(-1.)**n/n for n in range(1, 1001)],
float.fromhex('-0x1.62a2af1bd3624p-1')),
([1e16, 1., 1e-16], 10000000000000002.0),
([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0),
# exercise code for resizing partials array
([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] +
[-2.**1022],
float.fromhex('0x1.5555555555555p+970')),
]
# Telescoping sum, with exact differences (due to Sterbenz)
terms = [1.7**i for i in range(1001)]
test_values.append((
[terms[i+1] - terms[i] for i in range(1000)] + [-terms[1000]],
-terms[0]
))
for i, (vals, expected) in enumerate(test_values):
try:
actual = math.fsum(vals)
except OverflowError:
self.fail("test %d failed: got OverflowError, expected %r "
"for math.fsum(%.100r)" % (i, expected, vals))
except ValueError:
self.fail("test %d failed: got ValueError, expected %r "
"for math.fsum(%.100r)" % (i, expected, vals))
self.assertEqual(actual, expected)
from random import random, gauss, shuffle
for j in range(1000):
vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
s = 0
for i in range(200):
v = gauss(0, random()) ** 7 - s
s += v
vals.append(v)
shuffle(vals)
s = msum(vals)
self.assertEqual(msum(vals), math.fsum(vals))
self.assertEqual(math.fsum([1.0, math.inf]), math.inf)
self.assertTrue(math.isnan(math.fsum([math.nan, 1.0])))
self.assertEqual(math.fsum([1e100, FloatLike(1.0), -1e100, 1e-100,
1e50, FloatLike(-1.0), -1e50]), 1e-100)
self.assertRaises(OverflowError, math.fsum, [1e+308, 1e+308])
self.assertRaises(ValueError, math.fsum, [math.inf, -math.inf])
self.assertRaises(TypeError, math.fsum, ['spam'])
self.assertRaises(TypeError, math.fsum, 1)
self.assertRaises(OverflowError, math.fsum, [10**1000])
def bad_iter():
yield 1.0
raise ZeroDivisionError
self.assertRaises(ZeroDivisionError, math.fsum, bad_iter())
def testGcd(self):
gcd = math.gcd
self.assertEqual(gcd(0, 0), 0)
self.assertEqual(gcd(1, 0), 1)
self.assertEqual(gcd(-1, 0), 1)
self.assertEqual(gcd(0, 1), 1)
self.assertEqual(gcd(0, -1), 1)
self.assertEqual(gcd(7, 1), 1)
self.assertEqual(gcd(7, -1), 1)
self.assertEqual(gcd(-23, 15), 1)
self.assertEqual(gcd(120, 84), 12)
self.assertEqual(gcd(84, -120), 12)
self.assertEqual(gcd(1216342683557601535506311712,
436522681849110124616458784), 32)
x = 434610456570399902378880679233098819019853229470286994367836600566
y = 1064502245825115327754847244914921553977
for c in (652560,
576559230871654959816130551884856912003141446781646602790216406874):
a = x * c
b = y * c
self.assertEqual(gcd(a, b), c)
self.assertEqual(gcd(b, a), c)
self.assertEqual(gcd(-a, b), c)
self.assertEqual(gcd(b, -a), c)
self.assertEqual(gcd(a, -b), c)
self.assertEqual(gcd(-b, a), c)
self.assertEqual(gcd(-a, -b), c)
self.assertEqual(gcd(-b, -a), c)
self.assertEqual(gcd(), 0)
self.assertEqual(gcd(120), 120)
self.assertEqual(gcd(-120), 120)
self.assertEqual(gcd(120, 84, 102), 6)
self.assertEqual(gcd(120, 1, 84), 1)
self.assertRaises(TypeError, gcd, 120.0)
self.assertRaises(TypeError, gcd, 120.0, 84)
self.assertRaises(TypeError, gcd, 120, 84.0)
self.assertRaises(TypeError, gcd, 120, 1, 84.0)
self.assertEqual(gcd(MyIndexable(120), MyIndexable(84)), 12)
def testHypot(self):
from decimal import Decimal
from fractions import Fraction
hypot = math.hypot
# Test different numbers of arguments (from zero to five)
# against a straightforward pure python implementation
args = math.e, math.pi, math.sqrt(2.0), math.gamma(3.5), math.sin(2.1)
for i in range(len(args)+1):
self.assertAlmostEqual(
hypot(*args[:i]),
math.sqrt(sum(s**2 for s in args[:i]))
)
# Test allowable types (those with __float__)
self.assertEqual(hypot(12.0, 5.0), 13.0)
self.assertEqual(hypot(12, 5), 13)
self.assertEqual(hypot(0.75, -1), 1.25)
self.assertEqual(hypot(-1, 0.75), 1.25)
self.assertEqual(hypot(0.75, FloatLike(-1.)), 1.25)
self.assertEqual(hypot(FloatLike(-1.), 0.75), 1.25)
self.assertEqual(hypot(Decimal(12), Decimal(5)), 13)
self.assertEqual(hypot(Fraction(12, 32), Fraction(5, 32)), Fraction(13, 32))
self.assertEqual(hypot(True, False, True, True, True), 2.0)
# Test corner cases
self.assertEqual(hypot(0.0, 0.0), 0.0) # Max input is zero
self.assertEqual(hypot(-10.5), 10.5) # Negative input
self.assertEqual(hypot(), 0.0) # Negative input
self.assertEqual(1.0,
math.copysign(1.0, hypot(-0.0)) # Convert negative zero to positive zero
)
self.assertEqual( # Handling of moving max to the end
hypot(1.5, 1.5, 0.5),
hypot(1.5, 0.5, 1.5),
)
# Test handling of bad arguments
with self.assertRaises(TypeError): # Reject keyword args
hypot(x=1)
with self.assertRaises(TypeError): # Reject values without __float__
hypot(1.1, 'string', 2.2)
int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
with self.assertRaises((ValueError, OverflowError)):
hypot(1, int_too_big_for_float)
# Any infinity gives positive infinity.
self.assertEqual(hypot(INF), INF)
self.assertEqual(hypot(0, INF), INF)
self.assertEqual(hypot(10, INF), INF)
self.assertEqual(hypot(-10, INF), INF)
self.assertEqual(hypot(NAN, INF), INF)
self.assertEqual(hypot(INF, NAN), INF)
self.assertEqual(hypot(NINF, NAN), INF)
self.assertEqual(hypot(NAN, NINF), INF)
self.assertEqual(hypot(-INF, INF), INF)
self.assertEqual(hypot(-INF, -INF), INF)
self.assertEqual(hypot(10, -INF), INF)
# If no infinity, any NaN gives a NaN.
self.assertTrue(math.isnan(hypot(NAN)))
self.assertTrue(math.isnan(hypot(0, NAN)))
self.assertTrue(math.isnan(hypot(NAN, 10)))
self.assertTrue(math.isnan(hypot(10, NAN)))
self.assertTrue(math.isnan(hypot(NAN, NAN)))
self.assertTrue(math.isnan(hypot(NAN)))
# Verify scaling for extremely large values
fourthmax = FLOAT_MAX / 4.0
for n in range(32):
self.assertTrue(math.isclose(hypot(*([fourthmax]*n)),
fourthmax * math.sqrt(n)))
# Verify scaling for extremely small values
for exp in range(32):
scale = FLOAT_MIN / 2.0 ** exp
self.assertEqual(math.hypot(4*scale, 3*scale), 5*scale)
self.assertRaises(TypeError, math.hypot, *([1.0]*18), 'spam')
@requires_IEEE_754
@unittest.skipIf(HAVE_DOUBLE_ROUNDING,
"hypot() loses accuracy on machines with double rounding")
def testHypotAccuracy(self):
# Verify improved accuracy in cases that were known to be inaccurate.
#
# The new algorithm's accuracy depends on IEEE 754 arithmetic
# guarantees, on having the usual ROUND HALF EVEN rounding mode, on
# the system not having double rounding due to extended precision,
# and on the compiler maintaining the specified order of operations.
#
# This test is known to succeed on most of our builds. If it fails
# some build, we either need to add another skipIf if the cause is
# identifiable; otherwise, we can remove this test entirely.
hypot = math.hypot
Decimal = decimal.Decimal
high_precision = decimal.Context(prec=500)
for hx, hy in [
# Cases with a 1 ulp error in Python 3.7 compiled with Clang
('0x1.10e89518dca48p+29', '0x1.1970f7565b7efp+30'),
('0x1.10106eb4b44a2p+29', '0x1.ef0596cdc97f8p+29'),
('0x1.459c058e20bb7p+30', '0x1.993ca009b9178p+29'),
('0x1.378371ae67c0cp+30', '0x1.fbe6619854b4cp+29'),
('0x1.f4cd0574fb97ap+29', '0x1.50fe31669340ep+30'),
('0x1.494b2cdd3d446p+29', '0x1.212a5367b4c7cp+29'),
('0x1.f84e649f1e46dp+29', '0x1.1fa56bef8eec4p+30'),
('0x1.2e817edd3d6fap+30', '0x1.eb0814f1e9602p+29'),
('0x1.0d3a6e3d04245p+29', '0x1.32a62fea52352p+30'),
('0x1.888e19611bfc5p+29', '0x1.52b8e70b24353p+29'),
# Cases with 2 ulp error in Python 3.8
('0x1.538816d48a13fp+29', '0x1.7967c5ca43e16p+29'),
('0x1.57b47b7234530p+29', '0x1.74e2c7040e772p+29'),
('0x1.821b685e9b168p+30', '0x1.677dc1c1e3dc6p+29'),
('0x1.9e8247f67097bp+29', '0x1.24bd2dc4f4baep+29'),
('0x1.b73b59e0cb5f9p+29', '0x1.da899ab784a97p+28'),
('0x1.94a8d2842a7cfp+30', '0x1.326a51d4d8d8ap+30'),
('0x1.e930b9cd99035p+29', '0x1.5a1030e18dff9p+30'),
('0x1.1592bbb0e4690p+29', '0x1.a9c337b33fb9ap+29'),
('0x1.1243a50751fd4p+29', '0x1.a5a10175622d9p+29'),
('0x1.57a8596e74722p+30', '0x1.42d1af9d04da9p+30'),
# Cases with 1 ulp error in version fff3c28052e6b0
('0x1.ee7dbd9565899p+29', '0x1.7ab4d6fc6e4b4p+29'),
('0x1.5c6bfbec5c4dcp+30', '0x1.02511184b4970p+30'),
('0x1.59dcebba995cap+30', '0x1.50ca7e7c38854p+29'),
('0x1.768cdd94cf5aap+29', '0x1.9cfdc5571d38ep+29'),
('0x1.dcf137d60262ep+29', '0x1.1101621990b3ep+30'),
('0x1.3a2d006e288b0p+30', '0x1.e9a240914326cp+29'),
('0x1.62a32f7f53c61p+29', '0x1.47eb6cd72684fp+29'),
('0x1.d3bcb60748ef2p+29', '0x1.3f13c4056312cp+30'),
('0x1.282bdb82f17f3p+30', '0x1.640ba4c4eed3ap+30'),
('0x1.89d8c423ea0c6p+29', '0x1.d35dcfe902bc3p+29'),
]:
x = float.fromhex(hx)
y = float.fromhex(hy)
with self.subTest(hx=hx, hy=hy, x=x, y=y):
with decimal.localcontext(high_precision):
z = float((Decimal(x)**2 + Decimal(y)**2).sqrt())
self.assertEqual(hypot(x, y), z)
def testDist(self):
from decimal import Decimal as D
from fractions import Fraction as F
dist = math.dist
sqrt = math.sqrt
# Simple exact cases
self.assertEqual(dist((1.0, 2.0, 3.0), (4.0, 2.0, -1.0)), 5.0)
self.assertEqual(dist((1, 2, 3), (4, 2, -1)), 5.0)
# Test different numbers of arguments (from zero to nine)
# against a straightforward pure python implementation
for i in range(9):
for j in range(5):
p = tuple(random.uniform(-5, 5) for k in range(i))
q = tuple(random.uniform(-5, 5) for k in range(i))
self.assertAlmostEqual(
dist(p, q),
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
)
# Test non-tuple inputs
self.assertEqual(dist([1.0, 2.0, 3.0], [4.0, 2.0, -1.0]), 5.0)
self.assertEqual(dist(iter([1.0, 2.0, 3.0]), iter([4.0, 2.0, -1.0])), 5.0)
# Test allowable types (those with __float__)
self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0)
self.assertEqual(dist((14, 1), (2, -4)), 13)
self.assertEqual(dist((FloatLike(14.), 1), (2, -4)), 13)
self.assertEqual(dist((11, 1), (FloatLike(-1.), -4)), 13)
self.assertEqual(dist((14, FloatLike(-1.)), (2, -6)), 13)
self.assertEqual(dist((14, -1), (2, -6)), 13)
self.assertEqual(dist((D(14), D(1)), (D(2), D(-4))), D(13))
self.assertEqual(dist((F(14, 32), F(1, 32)), (F(2, 32), F(-4, 32))),
F(13, 32))
self.assertEqual(dist((True, True, False, False, True, True),
(True, False, True, False, False, False)),
2.0)
# Test corner cases
self.assertEqual(dist((13.25, 12.5, -3.25),
(13.25, 12.5, -3.25)),
0.0) # Distance with self is zero
self.assertEqual(dist((), ()), 0.0) # Zero-dimensional case
self.assertEqual(1.0, # Convert negative zero to positive zero
math.copysign(1.0, dist((-0.0,), (0.0,)))
)
self.assertEqual(1.0, # Convert negative zero to positive zero
math.copysign(1.0, dist((0.0,), (-0.0,)))
)
self.assertEqual( # Handling of moving max to the end
dist((1.5, 1.5, 0.5), (0, 0, 0)),
dist((1.5, 0.5, 1.5), (0, 0, 0))
)
# Verify tuple subclasses are allowed
with torch._dynamo.error_on_graph_break(False):
class T(tuple):
pass
self.assertEqual(dist(T((1, 2, 3)), ((4, 2, -1))), 5.0)
# Test handling of bad arguments
with self.assertRaises(TypeError): # Reject keyword args
dist(p=(1, 2, 3), q=(4, 5, 6))
with self.assertRaises(TypeError): # Too few args
dist((1, 2, 3))
with self.assertRaises(TypeError): # Too many args
dist((1, 2, 3), (4, 5, 6), (7, 8, 9))
with self.assertRaises(TypeError): # Scalars not allowed
dist(1, 2)
with self.assertRaises(TypeError): # Reject values without __float__
dist((1.1, 'string', 2.2), (1, 2, 3))
with self.assertRaises(ValueError): # Check dimension agree
dist((1, 2, 3, 4), (5, 6, 7))
with self.assertRaises(ValueError): # Check dimension agree
dist((1, 2, 3), (4, 5, 6, 7))
with self.assertRaises(TypeError):
dist((1,)*17 + ("spam",), (1,)*18)
with self.assertRaises(TypeError): # Rejects invalid types
dist("abc", "xyz")
int_too_big_for_float = 10 ** (sys.float_info.max_10_exp + 5)
with self.assertRaises((ValueError, OverflowError)):
dist((1, int_too_big_for_float), (2, 3))
with self.assertRaises((ValueError, OverflowError)):
dist((2, 3), (1, int_too_big_for_float))
with self.assertRaises(TypeError):
dist((1,), 2)
with self.assertRaises(TypeError):
dist([1], 2)
with torch._dynamo.error_on_graph_break(False):
class BadFloat:
__float__ = BadDescr()
with self.assertRaises(ValueError):
dist([1], [BadFloat()])
# Verify that the one dimensional case is equivalent to abs()
for i in range(20):
p, q = random.random(), random.random()
self.assertEqual(dist((p,), (q,)), abs(p - q))
# Test special values
values = [NINF, -10.5, -0.0, 0.0, 10.5, INF, NAN]
for p in itertools.product(values, repeat=3):
for q in itertools.product(values, repeat=3):
diffs = [px - qx for px, qx in zip(p, q)]
if any(map(math.isinf, diffs)):
# Any infinite difference gives positive infinity.
self.assertEqual(dist(p, q), INF)
elif any(map(math.isnan, diffs)):
# If no infinity, any NaN gives a NaN.
self.assertTrue(math.isnan(dist(p, q)))
# Verify scaling for extremely large values
fourthmax = FLOAT_MAX / 4.0
for n in range(32):
p = (fourthmax,) * n
q = (0.0,) * n
self.assertTrue(math.isclose(dist(p, q), fourthmax * math.sqrt(n)))
self.assertTrue(math.isclose(dist(q, p), fourthmax * math.sqrt(n)))
# Verify scaling for extremely small values
for exp in range(32):
scale = FLOAT_MIN / 2.0 ** exp
p = (4*scale, 3*scale)
q = (0.0, 0.0)
self.assertEqual(math.dist(p, q), 5*scale)
self.assertEqual(math.dist(q, p), 5*scale)
def test_math_dist_leak(self):
# gh-98897: Check for error handling does not leak memory
with self.assertRaises(ValueError):
math.dist([1, 2], [3, 4, 5])
@slowTest
def testIsqrt(self):
# Test a variety of inputs, large and small.
test_values = (
list(range(1000))
+ list(range(10**6 - 1000, 10**6 + 1000))
+ [2**e + i for e in range(60, 200) for i in range(-40, 40)]
+ [3**9999, 10**5001]
)
for value in test_values:
with self.subTest(value=value):
s = math.isqrt(value)
self.assertIs(type(s), int)
self.assertLessEqual(s*s, value)
self.assertLess(value, (s+1)*(s+1))
# Negative values
with self.assertRaises(ValueError):
math.isqrt(-1)
# Integer-like things
s = math.isqrt(True)
self.assertIs(type(s), int)
self.assertEqual(s, 1)
s = math.isqrt(False)
self.assertIs(type(s), int)
self.assertEqual(s, 0)
with torch._dynamo.error_on_graph_break(False):
class IntegerLike(object):
def __init__(self, value):
self.value = value
def __index__(self):
return self.value
s = math.isqrt(IntegerLike(1729))
self.assertIs(type(s), int)
self.assertEqual(s, 41)
with self.assertRaises(ValueError):
math.isqrt(IntegerLike(-3))
# Non-integer-like things
bad_values = [
3.5, "a string", decimal.Decimal("3.5"), 3.5j,
100.0, -4.0,
]
for value in bad_values:
with self.subTest(value=value):
with self.assertRaises(TypeError):
math.isqrt(value)
def test_lcm(self):
lcm = math.lcm
self.assertEqual(lcm(0, 0), 0)
self.assertEqual(lcm(1, 0), 0)
self.assertEqual(lcm(-1, 0), 0)
self.assertEqual(lcm(0, 1), 0)
self.assertEqual(lcm(0, -1), 0)
self.assertEqual(lcm(7, 1), 7)
self.assertEqual(lcm(7, -1), 7)
self.assertEqual(lcm(-23, 15), 345)
self.assertEqual(lcm(120, 84), 840)
self.assertEqual(lcm(84, -120), 840)
self.assertEqual(lcm(1216342683557601535506311712,
436522681849110124616458784),
16592536571065866494401400422922201534178938447014944)
x = 43461045657039990237
y = 10645022458251153277
for c in (652560,
57655923087165495981):
a = x * c
b = y * c
d = x * y * c
self.assertEqual(lcm(a, b), d)
self.assertEqual(lcm(b, a), d)
self.assertEqual(lcm(-a, b), d)
self.assertEqual(lcm(b, -a), d)
self.assertEqual(lcm(a, -b), d)
self.assertEqual(lcm(-b, a), d)
self.assertEqual(lcm(-a, -b), d)
self.assertEqual(lcm(-b, -a), d)
self.assertEqual(lcm(), 1)
self.assertEqual(lcm(120), 120)
self.assertEqual(lcm(-120), 120)
self.assertEqual(lcm(120, 84, 102), 14280)
self.assertEqual(lcm(120, 0, 84), 0)
self.assertRaises(TypeError, lcm, 120.0)
self.assertRaises(TypeError, lcm, 120.0, 84)
self.assertRaises(TypeError, lcm, 120, 84.0)
self.assertRaises(TypeError, lcm, 120, 0, 84.0)
self.assertEqual(lcm(MyIndexable(120), MyIndexable(84)), 840)
def testLdexp(self):
self.assertRaises(TypeError, math.ldexp)
self.assertRaises(TypeError, math.ldexp, 2.0, 1.1)
self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
self.assertEqual(math.ldexp(1., -1000000), 0.)
self.assertEqual(math.ldexp(-1., -1000000), -0.)
self.assertEqual(math.ldexp(INF, 30), INF)
self.assertEqual(math.ldexp(NINF, -213), NINF)
self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
# large second argument
for n in [10**5, 10**10, 10**20, 10**40]:
self.assertEqual(math.ldexp(INF, -n), INF)
self.assertEqual(math.ldexp(NINF, -n), NINF)
self.assertEqual(math.ldexp(1., -n), 0.)
self.assertEqual(math.ldexp(-1., -n), -0.)
self.assertEqual(math.ldexp(0., -n), 0.)
self.assertEqual(math.ldexp(-0., -n), -0.)
self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
self.assertRaises(OverflowError, math.ldexp, 1., n)
self.assertRaises(OverflowError, math.ldexp, -1., n)
self.assertEqual(math.ldexp(0., n), 0.)
self.assertEqual(math.ldexp(-0., n), -0.)
self.assertEqual(math.ldexp(INF, n), INF)
self.assertEqual(math.ldexp(NINF, n), NINF)
self.assertTrue(math.isnan(math.ldexp(NAN, n)))
def testLog(self):
self.assertRaises(TypeError, math.log)
self.assertRaises(TypeError, math.log, 1, 2, 3)
self.ftest('log(1/e)', math.log(1/math.e), -1)
self.ftest('log(1)', math.log(1), 0)
self.ftest('log(e)', math.log(math.e), 1)
self.ftest('log(32,2)', math.log(32,2), 5)
self.ftest('log(10**40, 10)', math.log(10**40, 10), 40)
self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
self.ftest('log(10**1000)', math.log(10**1000),
2302.5850929940457)
self.assertRaises(ValueError, math.log, -1.5)
self.assertRaises(ValueError, math.log, -10**1000)
self.assertRaises(ValueError, math.log, 10, -10)
self.assertRaises(ValueError, math.log, NINF)
self.assertEqual(math.log(INF), INF)
self.assertTrue(math.isnan(math.log(NAN)))
def testLog1p(self):
self.assertRaises(TypeError, math.log1p)
for n in [2, 2**90, 2**300]:
self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
self.assertRaises(ValueError, math.log1p, -1)
self.assertEqual(math.log1p(INF), INF)
@skipIfTorchDynamo("Infinite loop")
@requires_IEEE_754
def testLog2(self):
self.assertRaises(TypeError, math.log2)
# Check some integer values
self.assertEqual(math.log2(1), 0.0)
self.assertEqual(math.log2(2), 1.0)
self.assertEqual(math.log2(4), 2.0)
# Large integer values
self.assertEqual(math.log2(2**1023), 1023.0)
self.assertEqual(math.log2(2**1024), 1024.0)
self.assertEqual(math.log2(2**2000), 2000.0)
self.assertRaises(ValueError, math.log2, -1.5)
self.assertRaises(ValueError, math.log2, NINF)
self.assertTrue(math.isnan(math.log2(NAN)))
@skipIfTorchDynamo("Infinite loop")
@requires_IEEE_754
# log2() is not accurate enough on Mac OS X Tiger (10.4)
@support.requires_mac_ver(10, 5)
def testLog2Exact(self):
# Check that we get exact equality for log2 of powers of 2.
actual = [math.log2(math.ldexp(1.0, n)) for n in range(-1074, 1024)]
expected = [float(n) for n in range(-1074, 1024)]
self.assertEqual(actual, expected)
def testLog10(self):
self.assertRaises(TypeError, math.log10)
self.ftest('log10(0.1)', math.log10(0.1), -1)
self.ftest('log10(1)', math.log10(1), 0)
self.ftest('log10(10)', math.log10(10), 1)
self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0)
self.assertRaises(ValueError, math.log10, -1.5)
self.assertRaises(ValueError, math.log10, -10**1000)
self.assertRaises(ValueError, math.log10, NINF)
self.assertEqual(math.log(INF), INF)
self.assertTrue(math.isnan(math.log10(NAN)))
def testSumProd(self):
sumprod = math.sumprod
Decimal = decimal.Decimal
Fraction = fractions.Fraction
# Core functionality
self.assertEqual(sumprod(iter([10, 20, 30]), (1, 2, 3)), 140)
self.assertEqual(sumprod([1.5, 2.5], [3.5, 4.5]), 16.5)
self.assertEqual(sumprod([], []), 0)
self.assertEqual(sumprod([-1], [1.]), -1)
self.assertEqual(sumprod([1.], [-1]), -1)
# Type preservation and coercion
for v in [
(10, 20, 30),
(1.5, -2.5),
(Fraction(3, 5), Fraction(4, 5)),
(Decimal(3.5), Decimal(4.5)),
(2.5, 10), # float/int
(2.5, Fraction(3, 5)), # float/fraction
(25, Fraction(3, 5)), # int/fraction
(25, Decimal(4.5)), # int/decimal
]:
for p, q in [(v, v), (v, v[::-1])]:
with self.subTest(p=p, q=q):
expected = sum(p_i * q_i for p_i, q_i in zip(p, q, strict=True))
actual = sumprod(p, q)
self.assertEqual(expected, actual)
self.assertEqual(type(expected), type(actual))
# Bad arguments
self.assertRaises(TypeError, sumprod) # No args
self.assertRaises(TypeError, sumprod, []) # One arg
self.assertRaises(TypeError, sumprod, [], [], []) # Three args
self.assertRaises(TypeError, sumprod, None, [10]) # Non-iterable
self.assertRaises(TypeError, sumprod, [10], None) # Non-iterable
self.assertRaises(TypeError, sumprod, ['x'], [1.0])
# Uneven lengths
self.assertRaises(ValueError, sumprod, [10, 20], [30])
self.assertRaises(ValueError, sumprod, [10], [20, 30])
# Overflows
self.assertEqual(sumprod([10**20], [1]), 10**20)
self.assertEqual(sumprod([1], [10**20]), 10**20)
self.assertEqual(sumprod([10**10], [10**10]), 10**20)
self.assertEqual(sumprod([10**7]*10**5, [10**7]*10**5), 10**19)
self.assertRaises(OverflowError, sumprod, [10**1000], [1.0])
self.assertRaises(OverflowError, sumprod, [1.0], [10**1000])
# Error in iterator
def raise_after(n):
for i in range(n):
yield i
raise RuntimeError
with self.assertRaises(RuntimeError):
sumprod(range(10), raise_after(5))
with self.assertRaises(RuntimeError):
sumprod(raise_after(5), range(10))
from test_iter import BasicIterClass
self.assertEqual(sumprod(BasicIterClass(1), [1]), 0)
self.assertEqual(sumprod([1], BasicIterClass(1)), 0)
# Error in multiplication
with torch._dynamo.error_on_graph_break(False):
class BadMultiply:
def __mul__(self, other):
raise RuntimeError
def __rmul__(self, other):
raise RuntimeError
with self.assertRaises(RuntimeError):
sumprod([10, BadMultiply(), 30], [1, 2, 3])
with self.assertRaises(RuntimeError):
sumprod([1, 2, 3], [10, BadMultiply(), 30])
# Error in addition
with self.assertRaises(TypeError):
sumprod(['abc', 3], [5, 10])
with self.assertRaises(TypeError):
sumprod([5, 10], ['abc', 3])
# Special values should give the same as the pure python recipe
self.assertEqual(sumprod([10.1, math.inf], [20.2, 30.3]), math.inf)
self.assertEqual(sumprod([10.1, math.inf], [math.inf, 30.3]), math.inf)
self.assertEqual(sumprod([10.1, math.inf], [math.inf, math.inf]), math.inf)
self.assertEqual(sumprod([10.1, -math.inf], [20.2, 30.3]), -math.inf)
self.assertTrue(math.isnan(sumprod([10.1, math.inf], [-math.inf, math.inf])))
self.assertTrue(math.isnan(sumprod([10.1, math.nan], [20.2, 30.3])))
self.assertTrue(math.isnan(sumprod([10.1, math.inf], [math.nan, 30.3])))
self.assertTrue(math.isnan(sumprod([10.1, math.inf], [20.3, math.nan])))
# Error cases that arose during development
args = ((-5, -5, 10), (1.5, 4611686018427387904, 2305843009213693952))
self.assertEqual(sumprod(*args), 0.0)
@requires_IEEE_754
@unittest.skipIf(HAVE_DOUBLE_ROUNDING,
"sumprod() accuracy not guaranteed on machines with double rounding")
@support.cpython_only # Other implementations may choose a different algorithm
def test_sumprod_accuracy(self):
sumprod = math.sumprod
self.assertEqual(sumprod([0.1] * 10, [1]*10), 1.0)
self.assertEqual(sumprod([0.1] * 20, [True, False] * 10), 1.0)
self.assertEqual(sumprod([True, False] * 10, [0.1] * 20), 1.0)
self.assertEqual(sumprod([1.0, 10E100, 1.0, -10E100], [1.0]*4), 2.0)
@support.requires_resource('cpu')
def test_sumprod_stress(self):
sumprod = math.sumprod
product = itertools.product
Decimal = decimal.Decimal
Fraction = fractions.Fraction
with torch._dynamo.error_on_graph_break(False):
class Int(int):
def __add__(self, other):
return Int(int(self) + int(other))
def __mul__(self, other):
return Int(int(self) * int(other))
__radd__ = __add__
__rmul__ = __mul__
def __repr__(self):
return f'Int({int(self)})'
class Flt(float):
def __add__(self, other):
return Int(int(self) + int(other))
def __mul__(self, other):
return Int(int(self) * int(other))
__radd__ = __add__
__rmul__ = __mul__
def __repr__(self):
return f'Flt({int(self)})'
def baseline_sumprod(p, q):
"""This defines the target behavior including exceptions and special values.
However, it is subject to rounding errors, so float inputs should be exactly
representable with only a few bits.
"""
total = 0
for p_i, q_i in zip(p, q, strict=True):
total += p_i * q_i
return total
def run(func, *args):
"Make comparing functions easier. Returns error status, type, and result."
try:
result = func(*args)
except (AssertionError, NameError):
raise
except Exception as e:
return type(e), None, 'None'
return None, type(result), repr(result)
pools = [
(-5, 10, -2**20, 2**31, 2**40, 2**61, 2**62, 2**80, 1.5, Int(7)),
(5.25, -3.5, 4.75, 11.25, 400.5, 0.046875, 0.25, -1.0, -0.078125),
(-19.0*2**500, 11*2**1000, -3*2**1500, 17*2*333,
5.25, -3.25, -3.0*2**(-333), 3, 2**513),
(3.75, 2.5, -1.5, float('inf'), -float('inf'), float('NaN'), 14,
9, 3+4j, Flt(13), 0.0),
(13.25, -4.25, Decimal('10.5'), Decimal('-2.25'), Fraction(13, 8),
Fraction(-11, 16), 4.75 + 0.125j, 97, -41, Int(3)),
(Decimal('6.125'), Decimal('12.375'), Decimal('-2.75'), Decimal(0),
Decimal('Inf'), -Decimal('Inf'), Decimal('NaN'), 12, 13.5),
(-2.0 ** -1000, 11*2**1000, 3, 7, -37*2**32, -2*2**-537, -2*2**-538,
2*2**-513),
(-7 * 2.0 ** -510, 5 * 2.0 ** -520, 17, -19.0, -6.25),
(11.25, -3.75, -0.625, 23.375, True, False, 7, Int(5)),
]
for pool in pools:
for size in range(4):
for args1 in product(pool, repeat=size):
for args2 in product(pool, repeat=size):
args = (args1, args2)
self.assertEqual(
run(baseline_sumprod, *args),
run(sumprod, *args),
args,
)
@requires_IEEE_754
@unittest.skipIf(HAVE_DOUBLE_ROUNDING,
"sumprod() accuracy not guaranteed on machines with double rounding")
@support.cpython_only # Other implementations may choose a different algorithm
@support.requires_resource('cpu')
def test_sumprod_extended_precision_accuracy(self):
import operator
from fractions import Fraction
from itertools import starmap
from collections import namedtuple
from math import log2, exp2, fabs
from random import choices, uniform, shuffle
from statistics import median
DotExample = namedtuple('DotExample', ('x', 'y', 'target_sumprod', 'condition'))
def DotExact(x, y):
vec1 = map(Fraction, x)
vec2 = map(Fraction, y)
return sum(starmap(operator.mul, zip(vec1, vec2, strict=True)))
def Condition(x, y):
return 2.0 * DotExact(map(abs, x), map(abs, y)) / abs(DotExact(x, y))
def linspace(lo, hi, n):
width = (hi - lo) / (n - 1)
return [lo + width * i for i in range(n)]
def GenDot(n, c):
""" Algorithm 6.1 (GenDot) works as follows. The condition number (5.7) of
the dot product xT y is proportional to the degree of cancellation. In
order to achieve a prescribed cancellation, we generate the first half of
the vectors x and y randomly within a large exponent range. This range is
chosen according to the anticipated condition number. The second half of x
and y is then constructed choosing xi randomly with decreasing exponent,
and calculating yi such that some cancellation occurs. Finally, we permute
the vectors x, y randomly and calculate the achieved condition number.
"""
assert n >= 6
n2 = n // 2
x = [0.0] * n
y = [0.0] * n
b = log2(c)
# First half with exponents from 0 to |_b/2_| and random ints in between
e = choices(range(int(b/2)), k=n2)
e[0] = int(b / 2) + 1
e[-1] = 0.0
x[:n2] = [uniform(-1.0, 1.0) * exp2(p) for p in e]
y[:n2] = [uniform(-1.0, 1.0) * exp2(p) for p in e]
# Second half
e = list(map(round, linspace(b/2, 0.0 , n-n2)))
for i in range(n2, n):
x[i] = uniform(-1.0, 1.0) * exp2(e[i - n2])
y[i] = (uniform(-1.0, 1.0) * exp2(e[i - n2]) - DotExact(x, y)) / x[i]
# Shuffle
pairs = list(zip(x, y))
shuffle(pairs)
x, y = zip(*pairs)
return DotExample(x, y, DotExact(x, y), Condition(x, y))
def RelativeError(res, ex):
x, y, target_sumprod, condition = ex
n = DotExact(list(x) + [-res], list(y) + [1])
return fabs(n / target_sumprod)
def Trial(dotfunc, c, n):
ex = GenDot(10, c)
res = dotfunc(ex.x, ex.y)
return RelativeError(res, ex)
times = 1000 # Number of trials
n = 20 # Length of vectors
c = 1e30 # Target condition number
# If the following test fails, it means that the C math library
# implementation of fma() is not compliant with the C99 standard
# and is inaccurate. To solve this problem, make a new build
# with the symbol UNRELIABLE_FMA defined. That will enable a
# slower but accurate code path that avoids the fma() call.
relative_err = median(Trial(math.sumprod, c, n) for i in range(times))
self.assertLess(relative_err, 1e-16)
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def testPow(self):
self.assertRaises(TypeError, math.pow)
self.ftest('pow(0,1)', math.pow(0,1), 0)
self.ftest('pow(1,0)', math.pow(1,0), 1)
self.ftest('pow(2,1)', math.pow(2,1), 2)
self.ftest('pow(2,-1)', math.pow(2,-1), 0.5)
self.assertEqual(math.pow(INF, 1), INF)
self.assertEqual(math.pow(NINF, 1), NINF)
self.assertEqual((math.pow(1, INF)), 1.)
self.assertEqual((math.pow(1, NINF)), 1.)
self.assertTrue(math.isnan(math.pow(NAN, 1)))
self.assertTrue(math.isnan(math.pow(2, NAN)))
self.assertTrue(math.isnan(math.pow(0, NAN)))
self.assertEqual(math.pow(1, NAN), 1)
self.assertRaises(OverflowError, math.pow, 1e+100, 1e+100)
# pow(0., x)
self.assertEqual(math.pow(0., INF), 0.)
self.assertEqual(math.pow(0., 3.), 0.)
self.assertEqual(math.pow(0., 2.3), 0.)
self.assertEqual(math.pow(0., 2.), 0.)
self.assertEqual(math.pow(0., 0.), 1.)
self.assertEqual(math.pow(0., -0.), 1.)
self.assertRaises(ValueError, math.pow, 0., -2.)
self.assertRaises(ValueError, math.pow, 0., -2.3)
self.assertRaises(ValueError, math.pow, 0., -3.)
self.assertEqual(math.pow(0., NINF), INF)
self.assertTrue(math.isnan(math.pow(0., NAN)))
# pow(INF, x)
self.assertEqual(math.pow(INF, INF), INF)
self.assertEqual(math.pow(INF, 3.), INF)
self.assertEqual(math.pow(INF, 2.3), INF)
self.assertEqual(math.pow(INF, 2.), INF)
self.assertEqual(math.pow(INF, 0.), 1.)
self.assertEqual(math.pow(INF, -0.), 1.)
self.assertEqual(math.pow(INF, -2.), 0.)
self.assertEqual(math.pow(INF, -2.3), 0.)
self.assertEqual(math.pow(INF, -3.), 0.)
self.assertEqual(math.pow(INF, NINF), 0.)
self.assertTrue(math.isnan(math.pow(INF, NAN)))
# pow(-0., x)
self.assertEqual(math.pow(-0., INF), 0.)
self.assertEqual(math.pow(-0., 3.), -0.)
self.assertEqual(math.pow(-0., 2.3), 0.)
self.assertEqual(math.pow(-0., 2.), 0.)
self.assertEqual(math.pow(-0., 0.), 1.)
self.assertEqual(math.pow(-0., -0.), 1.)
self.assertRaises(ValueError, math.pow, -0., -2.)
self.assertRaises(ValueError, math.pow, -0., -2.3)
self.assertRaises(ValueError, math.pow, -0., -3.)
self.assertEqual(math.pow(-0., NINF), INF)
self.assertTrue(math.isnan(math.pow(-0., NAN)))
# pow(NINF, x)
self.assertEqual(math.pow(NINF, INF), INF)
self.assertEqual(math.pow(NINF, 3.), NINF)
self.assertEqual(math.pow(NINF, 2.3), INF)
self.assertEqual(math.pow(NINF, 2.), INF)
self.assertEqual(math.pow(NINF, 0.), 1.)
self.assertEqual(math.pow(NINF, -0.), 1.)
self.assertEqual(math.pow(NINF, -2.), 0.)
self.assertEqual(math.pow(NINF, -2.3), 0.)
self.assertEqual(math.pow(NINF, -3.), -0.)
self.assertEqual(math.pow(NINF, NINF), 0.)
self.assertTrue(math.isnan(math.pow(NINF, NAN)))
# pow(-1, x)
self.assertEqual(math.pow(-1., INF), 1.)
self.assertEqual(math.pow(-1., 3.), -1.)
self.assertRaises(ValueError, math.pow, -1., 2.3)
self.assertEqual(math.pow(-1., 2.), 1.)
self.assertEqual(math.pow(-1., 0.), 1.)
self.assertEqual(math.pow(-1., -0.), 1.)
self.assertEqual(math.pow(-1., -2.), 1.)
self.assertRaises(ValueError, math.pow, -1., -2.3)
self.assertEqual(math.pow(-1., -3.), -1.)
self.assertEqual(math.pow(-1., NINF), 1.)
self.assertTrue(math.isnan(math.pow(-1., NAN)))
# pow(1, x)
self.assertEqual(math.pow(1., INF), 1.)
self.assertEqual(math.pow(1., 3.), 1.)
self.assertEqual(math.pow(1., 2.3), 1.)
self.assertEqual(math.pow(1., 2.), 1.)
self.assertEqual(math.pow(1., 0.), 1.)
self.assertEqual(math.pow(1., -0.), 1.)
self.assertEqual(math.pow(1., -2.), 1.)
self.assertEqual(math.pow(1., -2.3), 1.)
self.assertEqual(math.pow(1., -3.), 1.)
self.assertEqual(math.pow(1., NINF), 1.)
self.assertEqual(math.pow(1., NAN), 1.)
# pow(x, 0) should be 1 for any x
self.assertEqual(math.pow(2.3, 0.), 1.)
self.assertEqual(math.pow(-2.3, 0.), 1.)
self.assertEqual(math.pow(NAN, 0.), 1.)
self.assertEqual(math.pow(2.3, -0.), 1.)
self.assertEqual(math.pow(-2.3, -0.), 1.)
self.assertEqual(math.pow(NAN, -0.), 1.)
# pow(x, y) is invalid if x is negative and y is not integral
self.assertRaises(ValueError, math.pow, -1., 2.3)
self.assertRaises(ValueError, math.pow, -15., -3.1)
# pow(x, NINF)
self.assertEqual(math.pow(1.9, NINF), 0.)
self.assertEqual(math.pow(1.1, NINF), 0.)
self.assertEqual(math.pow(0.9, NINF), INF)
self.assertEqual(math.pow(0.1, NINF), INF)
self.assertEqual(math.pow(-0.1, NINF), INF)
self.assertEqual(math.pow(-0.9, NINF), INF)
self.assertEqual(math.pow(-1.1, NINF), 0.)
self.assertEqual(math.pow(-1.9, NINF), 0.)
# pow(x, INF)
self.assertEqual(math.pow(1.9, INF), INF)
self.assertEqual(math.pow(1.1, INF), INF)
self.assertEqual(math.pow(0.9, INF), 0.)
self.assertEqual(math.pow(0.1, INF), 0.)
self.assertEqual(math.pow(-0.1, INF), 0.)
self.assertEqual(math.pow(-0.9, INF), 0.)
self.assertEqual(math.pow(-1.1, INF), INF)
self.assertEqual(math.pow(-1.9, INF), INF)
# pow(x, y) should work for x negative, y an integer
self.ftest('(-2.)**3.', math.pow(-2.0, 3.0), -8.0)
self.ftest('(-2.)**2.', math.pow(-2.0, 2.0), 4.0)
self.ftest('(-2.)**1.', math.pow(-2.0, 1.0), -2.0)
self.ftest('(-2.)**0.', math.pow(-2.0, 0.0), 1.0)
self.ftest('(-2.)**-0.', math.pow(-2.0, -0.0), 1.0)
self.ftest('(-2.)**-1.', math.pow(-2.0, -1.0), -0.5)
self.ftest('(-2.)**-2.', math.pow(-2.0, -2.0), 0.25)
self.ftest('(-2.)**-3.', math.pow(-2.0, -3.0), -0.125)
self.assertRaises(ValueError, math.pow, -2.0, -0.5)
self.assertRaises(ValueError, math.pow, -2.0, 0.5)
# the following tests have been commented out since they don't
# really belong here: the implementation of ** for floats is
# independent of the implementation of math.pow
#self.assertEqual(1**NAN, 1)
#self.assertEqual(1**INF, 1)
#self.assertEqual(1**NINF, 1)
#self.assertEqual(1**0, 1)
#self.assertEqual(1.**NAN, 1)
#self.assertEqual(1.**INF, 1)
#self.assertEqual(1.**NINF, 1)
#self.assertEqual(1.**0, 1)
def testRadians(self):
self.assertRaises(TypeError, math.radians)
self.ftest('radians(180)', math.radians(180), math.pi)
self.ftest('radians(90)', math.radians(90), math.pi/2)
self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
self.ftest('radians(0)', math.radians(0), 0)
@requires_IEEE_754
def testRemainder(self):
from fractions import Fraction
def validate_spec(x, y, r):
"""
Check that r matches remainder(x, y) according to the IEEE 754
specification. Assumes that x, y and r are finite and y is nonzero.
"""
fx, fy, fr = Fraction(x), Fraction(y), Fraction(r)
# r should not exceed y/2 in absolute value
self.assertLessEqual(abs(fr), abs(fy/2))
# x - r should be an exact integer multiple of y
n = (fx - fr) / fy
self.assertEqual(n, int(n))
if abs(fr) == abs(fy/2):
# If |r| == |y/2|, n should be even.
self.assertEqual(n/2, int(n/2))
# triples (x, y, remainder(x, y)) in hexadecimal form.
testcases = [
# Remainders modulo 1, showing the ties-to-even behaviour.
'-4.0 1 -0.0',
'-3.8 1 0.8',
'-3.0 1 -0.0',
'-2.8 1 -0.8',
'-2.0 1 -0.0',
'-1.8 1 0.8',
'-1.0 1 -0.0',
'-0.8 1 -0.8',
'-0.0 1 -0.0',
' 0.0 1 0.0',
' 0.8 1 0.8',
' 1.0 1 0.0',
' 1.8 1 -0.8',
' 2.0 1 0.0',
' 2.8 1 0.8',
' 3.0 1 0.0',
' 3.8 1 -0.8',
' 4.0 1 0.0',
# Reductions modulo 2*pi
'0x0.0p+0 0x1.921fb54442d18p+2 0x0.0p+0',
'0x1.921fb54442d18p+0 0x1.921fb54442d18p+2 0x1.921fb54442d18p+0',
'0x1.921fb54442d17p+1 0x1.921fb54442d18p+2 0x1.921fb54442d17p+1',
'0x1.921fb54442d18p+1 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
'0x1.921fb54442d19p+1 0x1.921fb54442d18p+2 -0x1.921fb54442d17p+1',
'0x1.921fb54442d17p+2 0x1.921fb54442d18p+2 -0x0.0000000000001p+2',
'0x1.921fb54442d18p+2 0x1.921fb54442d18p+2 0x0p0',
'0x1.921fb54442d19p+2 0x1.921fb54442d18p+2 0x0.0000000000001p+2',
'0x1.2d97c7f3321d1p+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
'0x1.2d97c7f3321d2p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d18p+1',
'0x1.2d97c7f3321d3p+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
'0x1.921fb54442d17p+3 0x1.921fb54442d18p+2 -0x0.0000000000001p+3',
'0x1.921fb54442d18p+3 0x1.921fb54442d18p+2 0x0p0',
'0x1.921fb54442d19p+3 0x1.921fb54442d18p+2 0x0.0000000000001p+3',
'0x1.f6a7a2955385dp+3 0x1.921fb54442d18p+2 0x1.921fb54442d14p+1',
'0x1.f6a7a2955385ep+3 0x1.921fb54442d18p+2 0x1.921fb54442d18p+1',
'0x1.f6a7a2955385fp+3 0x1.921fb54442d18p+2 -0x1.921fb54442d14p+1',
'0x1.1475cc9eedf00p+5 0x1.921fb54442d18p+2 0x1.921fb54442d10p+1',
'0x1.1475cc9eedf01p+5 0x1.921fb54442d18p+2 -0x1.921fb54442d10p+1',
# Symmetry with respect to signs.
' 1 0.c 0.4',
'-1 0.c -0.4',
' 1 -0.c 0.4',
'-1 -0.c -0.4',
' 1.4 0.c -0.4',
'-1.4 0.c 0.4',
' 1.4 -0.c -0.4',
'-1.4 -0.c 0.4',
# Huge modulus, to check that the underlying algorithm doesn't
# rely on 2.0 * modulus being representable.
'0x1.dp+1023 0x1.4p+1023 0x0.9p+1023',
'0x1.ep+1023 0x1.4p+1023 -0x0.ap+1023',
'0x1.fp+1023 0x1.4p+1023 -0x0.9p+1023',
]
for case in testcases:
with self.subTest(case=case):
x_hex, y_hex, expected_hex = case.split()
x = float.fromhex(x_hex)
y = float.fromhex(y_hex)
expected = float.fromhex(expected_hex)
validate_spec(x, y, expected)
actual = math.remainder(x, y)
# Cheap way of checking that the floats are
# as identical as we need them to be.
self.assertEqual(actual.hex(), expected.hex())
# Test tiny subnormal modulus: there's potential for
# getting the implementation wrong here (for example,
# by assuming that modulus/2 is exactly representable).
tiny = float.fromhex('1p-1074') # min +ve subnormal
for n in range(-25, 25):
if n == 0:
continue
y = n * tiny
for m in range(100):
x = m * tiny
actual = math.remainder(x, y)
validate_spec(x, y, actual)
actual = math.remainder(-x, y)
validate_spec(-x, y, actual)
# Special values.
# NaNs should propagate as usual.
for value in [NAN, 0.0, -0.0, 2.0, -2.3, NINF, INF]:
self.assertIsNaN(math.remainder(NAN, value))
self.assertIsNaN(math.remainder(value, NAN))
# remainder(x, inf) is x, for non-nan non-infinite x.
for value in [-2.3, -0.0, 0.0, 2.3]:
self.assertEqual(math.remainder(value, INF), value)
self.assertEqual(math.remainder(value, NINF), value)
# remainder(x, 0) and remainder(infinity, x) for non-NaN x are invalid
# operations according to IEEE 754-2008 7.2(f), and should raise.
for value in [NINF, -2.3, -0.0, 0.0, 2.3, INF]:
with self.assertRaises(ValueError):
math.remainder(INF, value)
with self.assertRaises(ValueError):
math.remainder(NINF, value)
with self.assertRaises(ValueError):
math.remainder(value, 0.0)
with self.assertRaises(ValueError):
math.remainder(value, -0.0)
def testSin(self):
self.assertRaises(TypeError, math.sin)
self.ftest('sin(0)', math.sin(0), 0)
self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
try:
self.assertTrue(math.isnan(math.sin(INF)))
self.assertTrue(math.isnan(math.sin(NINF)))
except ValueError:
self.assertRaises(ValueError, math.sin, INF)
self.assertRaises(ValueError, math.sin, NINF)
self.assertTrue(math.isnan(math.sin(NAN)))
def testSinh(self):
self.assertRaises(TypeError, math.sinh)
self.ftest('sinh(0)', math.sinh(0), 0)
self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
self.assertEqual(math.sinh(INF), INF)
self.assertEqual(math.sinh(NINF), NINF)
self.assertTrue(math.isnan(math.sinh(NAN)))
def testSqrt(self):
self.assertRaises(TypeError, math.sqrt)
self.ftest('sqrt(0)', math.sqrt(0), 0)
self.ftest('sqrt(0)', math.sqrt(0.0), 0.0)
self.ftest('sqrt(2.5)', math.sqrt(2.5), 1.5811388300841898)
self.ftest('sqrt(0.25)', math.sqrt(0.25), 0.5)
self.ftest('sqrt(25.25)', math.sqrt(25.25), 5.024937810560445)
self.ftest('sqrt(1)', math.sqrt(1), 1)
self.ftest('sqrt(4)', math.sqrt(4), 2)
self.assertEqual(math.sqrt(INF), INF)
self.assertRaises(ValueError, math.sqrt, -1)
self.assertRaises(ValueError, math.sqrt, NINF)
self.assertTrue(math.isnan(math.sqrt(NAN)))
def testTan(self):
self.assertRaises(TypeError, math.tan)
self.ftest('tan(0)', math.tan(0), 0)
self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
try:
self.assertTrue(math.isnan(math.tan(INF)))
self.assertTrue(math.isnan(math.tan(NINF)))
except ValueError:
self.assertRaises(ValueError, math.tan, INF)
self.assertRaises(ValueError, math.tan, NINF)
self.assertTrue(math.isnan(math.tan(NAN)))
def testTanh(self):
self.assertRaises(TypeError, math.tanh)
self.ftest('tanh(0)', math.tanh(0), 0)
self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
abs_tol=math.ulp(1))
self.ftest('tanh(inf)', math.tanh(INF), 1)
self.ftest('tanh(-inf)', math.tanh(NINF), -1)
self.assertTrue(math.isnan(math.tanh(NAN)))
@requires_IEEE_754
def testTanhSign(self):
# check that tanh(-0.) == -0. on IEEE 754 systems
self.assertEqual(math.tanh(-0.), -0.)
self.assertEqual(math.copysign(1., math.tanh(-0.)),
math.copysign(1., -0.))
def test_trunc(self):
self.assertEqual(math.trunc(1), 1)
self.assertEqual(math.trunc(-1), -1)
self.assertEqual(type(math.trunc(1)), int)
self.assertEqual(type(math.trunc(1.5)), int)
self.assertEqual(math.trunc(1.5), 1)
self.assertEqual(math.trunc(-1.5), -1)
self.assertEqual(math.trunc(1.999999), 1)
self.assertEqual(math.trunc(-1.999999), -1)
self.assertEqual(math.trunc(-0.999999), -0)
self.assertEqual(math.trunc(-100.999), -100)
with torch._dynamo.error_on_graph_break(False):
class TestTrunc:
def __trunc__(self):
return 23
class FloatTrunc(float):
def __trunc__(self):
return 23
class TestNoTrunc:
pass
class TestBadTrunc:
__trunc__ = BadDescr()
self.assertEqual(math.trunc(TestTrunc()), 23)
self.assertEqual(math.trunc(FloatTrunc()), 23)
self.assertRaises(TypeError, math.trunc)
self.assertRaises(TypeError, math.trunc, 1, 2)
self.assertRaises(TypeError, math.trunc, FloatLike(23.5))
self.assertRaises(TypeError, math.trunc, TestNoTrunc())
self.assertRaises(ValueError, math.trunc, TestBadTrunc())
def testIsfinite(self):
self.assertTrue(math.isfinite(0.0))
self.assertTrue(math.isfinite(-0.0))
self.assertTrue(math.isfinite(1.0))
self.assertTrue(math.isfinite(-1.0))
self.assertFalse(math.isfinite(float("nan")))
self.assertFalse(math.isfinite(float("inf")))
self.assertFalse(math.isfinite(float("-inf")))
def testIsnan(self):
self.assertTrue(math.isnan(float("nan")))
self.assertTrue(math.isnan(float("-nan")))
self.assertTrue(math.isnan(float("inf") * 0.))
self.assertFalse(math.isnan(float("inf")))
self.assertFalse(math.isnan(0.))
self.assertFalse(math.isnan(1.))
def testIsinf(self):
self.assertTrue(math.isinf(float("inf")))
self.assertTrue(math.isinf(float("-inf")))
self.assertTrue(math.isinf(1E400))
self.assertTrue(math.isinf(-1E400))
self.assertFalse(math.isinf(float("nan")))
self.assertFalse(math.isinf(0.))
self.assertFalse(math.isinf(1.))
def test_nan_constant(self):
# `math.nan` must be a quiet NaN with positive sign bit
self.assertTrue(math.isnan(math.nan))
self.assertEqual(math.copysign(1., math.nan), 1.)
def test_inf_constant(self):
self.assertTrue(math.isinf(math.inf))
self.assertGreater(math.inf, 0.0)
self.assertEqual(math.inf, float("inf"))
self.assertEqual(-math.inf, float("-inf"))
# RED_FLAG 16-Oct-2000 Tim
# While 2.0 is more consistent about exceptions than previous releases, it
# still fails this part of the test on some platforms. For now, we only
# *run* test_exceptions() in verbose mode, so that this isn't normally
# tested.
@unittest.skipUnless(verbose, 'requires verbose mode')
def test_exceptions(self):
try:
x = math.exp(-1000000000)
except:
# mathmodule.c is failing to weed out underflows from libm, or
# we've got an fp format with huge dynamic range
self.fail("underflowing exp() should not have raised "
"an exception")
if x != 0:
self.fail("underflowing exp() should have returned 0")
# If this fails, probably using a strict IEEE-754 conforming libm, and x
# is +Inf afterwards. But Python wants overflows detected by default.
try:
x = math.exp(1000000000)
except OverflowError:
pass
else:
self.fail("overflowing exp() didn't trigger OverflowError")
# If this fails, it could be a puzzle. One odd possibility is that
# mathmodule.c's macros are getting confused while comparing
# Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE
# as a result (and so raising OverflowError instead).
try:
x = math.sqrt(-1.0)
except ValueError:
pass
else:
self.fail("sqrt(-1) didn't raise ValueError")
@requires_IEEE_754
def test_testfile(self):
# Some tests need to be skipped on ancient OS X versions.
# See issue #27953.
SKIP_ON_TIGER = {'tan0064'}
osx_version = None
if sys.platform == 'darwin':
version_txt = platform.mac_ver()[0]
try:
osx_version = tuple(map(int, version_txt.split('.')))
except ValueError:
pass
fail_fmt = "{}: {}({!r}): {}"
failures = []
for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file):
# Skip if either the input or result is complex
if ai != 0.0 or ei != 0.0:
continue
if fn in ['rect', 'polar']:
# no real versions of rect, polar
continue
# Skip certain tests on OS X 10.4.
if osx_version is not None and osx_version < (10, 5):
if id in SKIP_ON_TIGER:
continue
func = getattr(math, fn)
if 'invalid' in flags or 'divide-by-zero' in flags:
er = 'ValueError'
elif 'overflow' in flags:
er = 'OverflowError'
try:
result = func(ar)
except ValueError:
result = 'ValueError'
except OverflowError:
result = 'OverflowError'
# C99+ says for math.h's sqrt: If the argument is +∞ or ±0, it is
# returned, unmodified. On another hand, for csqrt: If z is ±0+0i,
# the result is +0+0i. Lets correct zero sign of er to follow
# first convention.
if id in ['sqrt0002', 'sqrt0003', 'sqrt1001', 'sqrt1023']:
er = math.copysign(er, ar)
# Default tolerances
ulp_tol, abs_tol = 5, 0.0
failure = result_check(er, result, ulp_tol, abs_tol)
if failure is None:
continue
msg = fail_fmt.format(id, fn, ar, failure)
failures.append(msg)
if failures:
self.fail('Failures in test_testfile:\n ' +
'\n '.join(failures))
@requires_IEEE_754
def test_mtestfile(self):
fail_fmt = "{}: {}({!r}): {}"
failures = []
for id, fn, arg, expected, flags in parse_mtestfile(math_testcases):
func = getattr(math, fn)
if 'invalid' in flags or 'divide-by-zero' in flags:
expected = 'ValueError'
elif 'overflow' in flags:
expected = 'OverflowError'
try:
got = func(arg)
except ValueError:
got = 'ValueError'
except OverflowError:
got = 'OverflowError'
# Default tolerances
ulp_tol, abs_tol = 5, 0.0
# Exceptions to the defaults
if fn == 'gamma':
# Experimental results on one platform gave
# an accuracy of <= 10 ulps across the entire float
# domain. We weaken that to require 20 ulp accuracy.
ulp_tol = 20
elif fn == 'lgamma':
# we use a weaker accuracy test for lgamma;
# lgamma only achieves an absolute error of
# a few multiples of the machine accuracy, in
# general.
abs_tol = 1e-15
elif fn == 'erfc' and arg >= 0.0:
# erfc has less-than-ideal accuracy for large
# arguments (x ~ 25 or so), mainly due to the
# error involved in computing exp(-x*x).
#
# Observed between CPython and mpmath at 25 dp:
# x < 0 : err <= 2 ulp
# 0 <= x < 1 : err <= 10 ulp
# 1 <= x < 10 : err <= 100 ulp
# 10 <= x < 20 : err <= 300 ulp
# 20 <= x : < 600 ulp
#
if arg < 1.0:
ulp_tol = 10
elif arg < 10.0:
ulp_tol = 100
else:
ulp_tol = 1000
failure = result_check(expected, got, ulp_tol, abs_tol)
if failure is None:
continue
msg = fail_fmt.format(id, fn, arg, failure)
failures.append(msg)
if failures:
self.fail('Failures in test_mtestfile:\n ' +
'\n '.join(failures))
def test_prod(self):
from fractions import Fraction as F
prod = math.prod
self.assertEqual(prod([]), 1)
self.assertEqual(prod([], start=5), 5)
self.assertEqual(prod(list(range(2,8))), 5040)
self.assertEqual(prod(iter(list(range(2,8)))), 5040)
self.assertEqual(prod(range(1, 10), start=10), 3628800)
self.assertEqual(prod([1, 2, 3, 4, 5]), 120)
self.assertEqual(prod([1.0, 2.0, 3.0, 4.0, 5.0]), 120.0)
self.assertEqual(prod([1, 2, 3, 4.0, 5.0]), 120.0)
self.assertEqual(prod([1.0, 2.0, 3.0, 4, 5]), 120.0)
self.assertEqual(prod([1., F(3, 2)]), 1.5)
# Error in multiplication
with torch._dynamo.error_on_graph_break(False):
class BadMultiply:
def __rmul__(self, other):
raise RuntimeError
with self.assertRaises(RuntimeError):
prod([10., BadMultiply()])
# Test overflow in fast-path for integers
self.assertEqual(prod([1, 1, 2**32, 1, 1]), 2**32)
# Test overflow in fast-path for floats
self.assertEqual(prod([1.0, 1.0, 2**32, 1, 1]), float(2**32))
self.assertRaises(TypeError, prod)
self.assertRaises(TypeError, prod, 42)
self.assertRaises(TypeError, prod, ['a', 'b', 'c'])
self.assertRaises(TypeError, prod, ['a', 'b', 'c'], start='')
self.assertRaises(TypeError, prod, [b'a', b'c'], start=b'')
values = [bytearray(b'a'), bytearray(b'b')]
self.assertRaises(TypeError, prod, values, start=bytearray(b''))
self.assertRaises(TypeError, prod, [[1], [2], [3]])
self.assertRaises(TypeError, prod, [{2:3}])
self.assertRaises(TypeError, prod, [{2:3}]*2, start={2:3})
self.assertRaises(TypeError, prod, [[1], [2], [3]], start=[])
# Some odd cases
self.assertEqual(prod([2, 3], start='ab'), 'abababababab')
self.assertEqual(prod([2, 3], start=[1, 2]), [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])
self.assertEqual(prod([], start={2: 3}), {2:3})
with self.assertRaises(TypeError):
prod([10, 20], 1) # start is a keyword-only argument
self.assertEqual(prod([0, 1, 2, 3]), 0)
self.assertEqual(prod([1, 0, 2, 3]), 0)
self.assertEqual(prod([1, 2, 3, 0]), 0)
def _naive_prod(iterable, start=1):
for elem in iterable:
start *= elem
return start
# Big integers
iterable = range(1, 10000)
self.assertEqual(prod(iterable), _naive_prod(iterable))
iterable = range(-10000, -1)
self.assertEqual(prod(iterable), _naive_prod(iterable))
iterable = range(-1000, 1000)
self.assertEqual(prod(iterable), 0)
# Big floats
iterable = [float(x) for x in range(1, 1000)]
self.assertEqual(prod(iterable), _naive_prod(iterable))
iterable = [float(x) for x in range(-1000, -1)]
self.assertEqual(prod(iterable), _naive_prod(iterable))
iterable = [float(x) for x in range(-1000, 1000)]
self.assertIsNaN(prod(iterable))
# Float tests
self.assertIsNaN(prod([1, 2, 3, float("nan"), 2, 3]))
self.assertIsNaN(prod([1, 0, float("nan"), 2, 3]))
self.assertIsNaN(prod([1, float("nan"), 0, 3]))
self.assertIsNaN(prod([1, float("inf"), float("nan"),3]))
self.assertIsNaN(prod([1, float("-inf"), float("nan"),3]))
self.assertIsNaN(prod([1, float("nan"), float("inf"),3]))
self.assertIsNaN(prod([1, float("nan"), float("-inf"),3]))
self.assertEqual(prod([1, 2, 3, float('inf'),-3,4]), float('-inf'))
self.assertEqual(prod([1, 2, 3, float('-inf'),-3,4]), float('inf'))
self.assertIsNaN(prod([1,2,0,float('inf'), -3, 4]))
self.assertIsNaN(prod([1,2,0,float('-inf'), -3, 4]))
self.assertIsNaN(prod([1, 2, 3, float('inf'), -3, 0, 3]))
self.assertIsNaN(prod([1, 2, 3, float('-inf'), -3, 0, 2]))
# Type preservation
self.assertEqual(type(prod([1, 2, 3, 4, 5, 6])), int)
self.assertEqual(type(prod([1, 2.0, 3, 4, 5, 6])), float)
self.assertEqual(type(prod(range(1, 10000))), int)
self.assertEqual(type(prod(range(1, 10000), start=1.0)), float)
self.assertEqual(type(prod([1, decimal.Decimal(2.0), 3, 4, 5, 6])),
decimal.Decimal)
@skipIfTorchDynamo("Infinite loop")
def testPerm(self):
perm = math.perm
factorial = math.factorial
# Test if factorial definition is satisfied
for n in range(500):
for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)):
self.assertEqual(perm(n, k),
factorial(n) // factorial(n - k))
# Test for Pascal's identity
for n in range(1, 100):
for k in range(1, n):
self.assertEqual(perm(n, k), perm(n - 1, k - 1) * k + perm(n - 1, k))
# Test corner cases
for n in range(1, 100):
self.assertEqual(perm(n, 0), 1)
self.assertEqual(perm(n, 1), n)
self.assertEqual(perm(n, n), factorial(n))
# Test one argument form
for n in range(20):
self.assertEqual(perm(n), factorial(n))
self.assertEqual(perm(n, None), factorial(n))
# Raises TypeError if any argument is non-integer or argument count is
# not 1 or 2
self.assertRaises(TypeError, perm, 10, 1.0)
self.assertRaises(TypeError, perm, 10, decimal.Decimal(1.0))
self.assertRaises(TypeError, perm, 10, "1")
self.assertRaises(TypeError, perm, 10.0, 1)
self.assertRaises(TypeError, perm, decimal.Decimal(10.0), 1)
self.assertRaises(TypeError, perm, "10", 1)
self.assertRaises(TypeError, perm)
self.assertRaises(TypeError, perm, 10, 1, 3)
self.assertRaises(TypeError, perm)
# Raises Value error if not k or n are negative numbers
self.assertRaises(ValueError, perm, -1, 1)
self.assertRaises(ValueError, perm, -2**1000, 1)
self.assertRaises(ValueError, perm, 1, -1)
self.assertRaises(ValueError, perm, 1, -2**1000)
# Returns zero if k is greater than n
self.assertEqual(perm(1, 2), 0)
self.assertEqual(perm(1, 2**1000), 0)
n = 2**1000
self.assertEqual(perm(n, 0), 1)
self.assertEqual(perm(n, 1), n)
self.assertEqual(perm(n, 2), n * (n-1))
if support.check_impl_detail(cpython=True):
self.assertRaises(OverflowError, perm, n, n)
for n, k in (True, True), (True, False), (False, False):
self.assertEqual(perm(n, k), 1)
self.assertIs(type(perm(n, k)), int)
self.assertEqual(perm(IntSubclass(5), IntSubclass(2)), 20)
self.assertEqual(perm(MyIndexable(5), MyIndexable(2)), 20)
for k in range(3):
self.assertIs(type(perm(IntSubclass(5), IntSubclass(k))), int)
self.assertIs(type(perm(MyIndexable(5), MyIndexable(k))), int)
@skipIfTorchDynamo("infinite loop")
def testComb(self):
comb = math.comb
factorial = math.factorial
# Test if factorial definition is satisfied
for n in range(500):
for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)):
self.assertEqual(comb(n, k), factorial(n)
// (factorial(k) * factorial(n - k)))
# Test for Pascal's identity
for n in range(1, 100):
for k in range(1, n):
self.assertEqual(comb(n, k), comb(n - 1, k - 1) + comb(n - 1, k))
# Test corner cases
for n in range(100):
self.assertEqual(comb(n, 0), 1)
self.assertEqual(comb(n, n), 1)
for n in range(1, 100):
self.assertEqual(comb(n, 1), n)
self.assertEqual(comb(n, n - 1), n)
# Test Symmetry
for n in range(100):
for k in range(n // 2):
self.assertEqual(comb(n, k), comb(n, n - k))
# Raises TypeError if any argument is non-integer or argument count is
# not 2
self.assertRaises(TypeError, comb, 10, 1.0)
self.assertRaises(TypeError, comb, 10, decimal.Decimal(1.0))
self.assertRaises(TypeError, comb, 10, "1")
self.assertRaises(TypeError, comb, 10.0, 1)
self.assertRaises(TypeError, comb, decimal.Decimal(10.0), 1)
self.assertRaises(TypeError, comb, "10", 1)
self.assertRaises(TypeError, comb, 10)
self.assertRaises(TypeError, comb, 10, 1, 3)
self.assertRaises(TypeError, comb)
# Raises Value error if not k or n are negative numbers
self.assertRaises(ValueError, comb, -1, 1)
self.assertRaises(ValueError, comb, -2**1000, 1)
self.assertRaises(ValueError, comb, 1, -1)
self.assertRaises(ValueError, comb, 1, -2**1000)
# Returns zero if k is greater than n
self.assertEqual(comb(1, 2), 0)
self.assertEqual(comb(1, 2**1000), 0)
n = 2**1000
self.assertEqual(comb(n, 0), 1)
self.assertEqual(comb(n, 1), n)
self.assertEqual(comb(n, 2), n * (n-1) // 2)
self.assertEqual(comb(n, n), 1)
self.assertEqual(comb(n, n-1), n)
self.assertEqual(comb(n, n-2), n * (n-1) // 2)
if support.check_impl_detail(cpython=True):
self.assertRaises(OverflowError, comb, n, n//2)
for n, k in (True, True), (True, False), (False, False):
self.assertEqual(comb(n, k), 1)
self.assertIs(type(comb(n, k)), int)
self.assertEqual(comb(IntSubclass(5), IntSubclass(2)), 10)
self.assertEqual(comb(MyIndexable(5), MyIndexable(2)), 10)
for k in range(3):
self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int)
self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int)
@requires_IEEE_754
def test_nextafter(self):
# around 2^52 and 2^63
self.assertEqual(math.nextafter(4503599627370496.0, -INF),
4503599627370495.5)
self.assertEqual(math.nextafter(4503599627370496.0, INF),
4503599627370497.0)
self.assertEqual(math.nextafter(9223372036854775808.0, 0.0),
9223372036854774784.0)
self.assertEqual(math.nextafter(-9223372036854775808.0, 0.0),
-9223372036854774784.0)
# around 1.0
self.assertEqual(math.nextafter(1.0, -INF),
float.fromhex('0x1.fffffffffffffp-1'))
self.assertEqual(math.nextafter(1.0, INF),
float.fromhex('0x1.0000000000001p+0'))
self.assertEqual(math.nextafter(1.0, -INF, steps=1),
float.fromhex('0x1.fffffffffffffp-1'))
self.assertEqual(math.nextafter(1.0, INF, steps=1),
float.fromhex('0x1.0000000000001p+0'))
self.assertEqual(math.nextafter(1.0, -INF, steps=3),
float.fromhex('0x1.ffffffffffffdp-1'))
self.assertEqual(math.nextafter(1.0, INF, steps=3),
float.fromhex('0x1.0000000000003p+0'))
# x == y: y is returned
for steps in range(1, 5):
self.assertEqual(math.nextafter(2.0, 2.0, steps=steps), 2.0)
self.assertEqualSign(math.nextafter(-0.0, +0.0, steps=steps), +0.0)
self.assertEqualSign(math.nextafter(+0.0, -0.0, steps=steps), -0.0)
# around 0.0
smallest_subnormal = sys.float_info.min * sys.float_info.epsilon
self.assertEqual(math.nextafter(+0.0, INF), smallest_subnormal)
self.assertEqual(math.nextafter(-0.0, INF), smallest_subnormal)
self.assertEqual(math.nextafter(+0.0, -INF), -smallest_subnormal)
self.assertEqual(math.nextafter(-0.0, -INF), -smallest_subnormal)
self.assertEqualSign(math.nextafter(smallest_subnormal, +0.0), +0.0)
self.assertEqualSign(math.nextafter(-smallest_subnormal, +0.0), -0.0)
self.assertEqualSign(math.nextafter(smallest_subnormal, -0.0), +0.0)
self.assertEqualSign(math.nextafter(-smallest_subnormal, -0.0), -0.0)
# around infinity
largest_normal = sys.float_info.max
self.assertEqual(math.nextafter(INF, 0.0), largest_normal)
self.assertEqual(math.nextafter(-INF, 0.0), -largest_normal)
self.assertEqual(math.nextafter(largest_normal, INF), INF)
self.assertEqual(math.nextafter(-largest_normal, -INF), -INF)
# NaN
self.assertIsNaN(math.nextafter(NAN, 1.0))
self.assertIsNaN(math.nextafter(1.0, NAN))
self.assertIsNaN(math.nextafter(NAN, NAN))
self.assertEqual(1.0, math.nextafter(1.0, INF, steps=0))
with self.assertRaises(ValueError):
math.nextafter(1.0, INF, steps=-1)
@unittest.skip("flaky test under torch dynamo") # works on pytest and crashes on unittest
@requires_IEEE_754
def test_ulp(self):
self.assertEqual(math.ulp(1.0), sys.float_info.epsilon)
# use int ** int rather than float ** int to not rely on pow() accuracy
self.assertEqual(math.ulp(2 ** 52), 1.0)
self.assertEqual(math.ulp(2 ** 53), 2.0)
self.assertEqual(math.ulp(2 ** 64), 4096.0)
# min and max
self.assertEqual(math.ulp(0.0),
sys.float_info.min * sys.float_info.epsilon)
self.assertEqual(math.ulp(FLOAT_MAX),
FLOAT_MAX - math.nextafter(FLOAT_MAX, -INF))
# special cases
self.assertEqual(math.ulp(INF), INF)
self.assertIsNaN(math.ulp(math.nan))
# negative number: ulp(-x) == ulp(x)
for x in (0.0, 1.0, 2 ** 52, 2 ** 64, INF):
with self.subTest(x=x):
self.assertEqual(math.ulp(-x), math.ulp(x))
def test_issue39871(self):
# A SystemError should not be raised if the first arg to atan2(),
# copysign(), or remainder() cannot be converted to a float.
with torch._dynamo.error_on_graph_break(False):
class F:
def __float__(self):
self.converted = True
1/0
for func in math.atan2, math.copysign, math.remainder:
y = F()
with self.assertRaises(TypeError):
func("not a number", y)
# There should not have been any attempt to convert the second
# argument to a float.
self.assertFalse(getattr(y, "converted", False))
def test_input_exceptions(self):
self.assertRaises(TypeError, math.exp, "spam")
self.assertRaises(TypeError, math.erf, "spam")
self.assertRaises(TypeError, math.atan2, "spam", 1.0)
self.assertRaises(TypeError, math.atan2, 1.0, "spam")
self.assertRaises(TypeError, math.atan2, 1.0)
self.assertRaises(TypeError, math.atan2, 1.0, 2.0, 3.0)
# Custom assertions.
def assertIsNaN(self, value):
if not math.isnan(value):
self.fail("Expected a NaN, got {!r}.".format(value))
def assertEqualSign(self, x, y):
"""Similar to assertEqual(), but compare also the sign with copysign().
Function useful to compare signed zeros.
"""
self.assertEqual(x, y)
self.assertEqual(math.copysign(1.0, x), math.copysign(1.0, y))
| MathTests |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 88775,
"end": 90944
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
"""test op() in conjunction with join conditions"""
run_create_tables = run_deletes = None
__dialect__ = "default"
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column("foo", String(50)),
)
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("foo", String(50)),
)
def test_join_on_custom_op_legacy_is_comparison(self):
class A(BasicEntity):
pass
class B(BasicEntity):
pass
self.mapper_registry.map_imperatively(
A,
self.tables.a,
properties={
"bs": relationship(
B,
primaryjoin=self.tables.a.c.foo.op(
"&*", is_comparison=True
)(foreign(self.tables.b.c.foo)),
viewonly=True,
)
},
)
self.mapper_registry.map_imperatively(B, self.tables.b)
self.assert_compile(
fixture_session().query(A).join(A.bs),
"SELECT a.id AS a_id, a.foo AS a_foo "
"FROM a JOIN b ON a.foo &* b.foo",
)
def test_join_on_custom_bool_op(self):
class A(BasicEntity):
pass
class B(BasicEntity):
pass
self.mapper_registry.map_imperatively(
A,
self.tables.a,
properties={
"bs": relationship(
B,
primaryjoin=self.tables.a.c.foo.bool_op("&*")(
foreign(self.tables.b.c.foo)
),
viewonly=True,
)
},
)
self.mapper_registry.map_imperatively(B, self.tables.b)
self.assert_compile(
fixture_session().query(A).join(A.bs),
"SELECT a.id AS a_id, a.foo AS a_foo "
"FROM a JOIN b ON a.foo &* b.foo",
)
| CustomOperatorTest |
python | automl__auto-sklearn | autosklearn/pipeline/components/base.py | {
"start": 10478,
"end": 14830
} | class ____(object):
def __init__(
self,
dataset_properties,
feat_type: Optional[FEAT_TYPE_TYPE] = None,
random_state=None,
):
"""
Parameters
----------
dataset_properties : dict
Describes the dataset to work on, this can change the
configuration space constructed by auto-sklearn. Mandatory
properties are:
* target_type: classification or regression
Optional properties are:
* multiclass: whether the dataset is a multiclass classification
dataset.
* multilabel: whether the dataset is a multilabel classification
dataset
"""
# Since all calls to get_hyperparameter_search_space will be done by the
# pipeline on construction, it is not necessary to construct a
# configuration space at this location!
# self.configuration = self.get_hyperparameter_search_space(
# dataset_properties).get_default_configuration()
self.random_state = random_state
# Since the pipeline will initialize the hyperparameters, it is not
# necessary to do this upon the construction of this object
# self.set_hyperparameters(self.configuration)
self.choice = None
def get_components(cls):
raise NotImplementedError()
def get_available_components(
self, dataset_properties=None, include=None, exclude=None
):
if dataset_properties is None:
dataset_properties = {}
if include is not None and exclude is not None:
raise ValueError(
"The argument include and exclude cannot be used together."
)
available_comp = self.get_components()
if include is not None:
for incl in include:
if incl not in available_comp:
raise ValueError(
"Trying to include unknown component: " "%s" % incl
)
components_dict = OrderedDict()
for name in available_comp:
if include is not None and name not in include:
continue
elif exclude is not None and name in exclude:
continue
if "sparse" in dataset_properties and dataset_properties["sparse"]:
# In case the dataset is sparse, ignore
# components that do not handle sparse data
# Auto-sklearn uses SPARSE constant as a mechanism
# to indicate whether a component can handle sparse data.
# If SPARSE is not in the input properties of the component, it
# means SPARSE is not a valid input to this component, so filter it out
if SPARSE not in available_comp[name].get_properties()["input"]:
continue
components_dict[name] = available_comp[name]
return components_dict
def set_hyperparameters(
self,
configuration,
feat_type: Optional[FEAT_TYPE_TYPE] = None,
init_params=None,
):
new_params = {}
params = configuration.get_dictionary()
choice = params["__choice__"]
del params["__choice__"]
for param, value in params.items():
param = param.replace(choice, "").replace(":", "")
new_params[param] = value
if init_params is not None:
for param, value in init_params.items():
param = param.replace(choice, "").replace(":", "")
new_params[param] = value
new_params["random_state"] = self.random_state
self.new_params = new_params
self.choice = self.get_components()[choice](**new_params)
return self
def get_hyperparameter_search_space(
self,
feat_type: FEAT_TYPE_TYPE,
dataset_properties=None,
default=None,
include=None,
exclude=None,
):
raise NotImplementedError()
def fit(self, X, y, **kwargs):
# Allows to use check_is_fitted on the choice object
self.fitted_ = True
if kwargs is None:
kwargs = {}
return self.choice.fit(X, y, **kwargs)
def predict(self, X):
return self.choice.predict(X)
| AutoSklearnChoice |
python | pypa__warehouse | tests/unit/events/test_models.py | {
"start": 208,
"end": 1023
} | class ____:
@pytest.mark.parametrize(
("test_input", "expected"),
[
({}, ""),
(
{"city": "new york", "country_code": "us", "region": "ny"},
"New York, NY, US",
),
(
{"city": "new york", "country_code": "us"},
"New York, US",
),
({"city": "new york", "region": "ny"}, "New York, NY"),
({"region": "ny", "country_code": "us"}, "NY, US"),
({"country_name": "United States"}, "United States"),
],
)
def test_display_output(self, test_input, expected):
"""Create a GeoIPInfo object and test the display method."""
dataklazz = GeoIPInfo(**test_input)
assert dataklazz.display() == expected
| TestGeoIPInfo |
python | tensorflow__tensorflow | tensorflow/python/training/gradient_descent_test.py | {
"start": 1268,
"end": 13619
} | class ____(test.TestCase):
def testBasic(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
var0 = variables.Variable([1.0, 2.0], dtype=dtype)
var1 = variables.Variable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
optimizer = gradient_descent.GradientDescentOptimizer(3.0)
sgd_op = optimizer.apply_gradients(
zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0, 4.0], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1],
self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01],
self.evaluate(var1))
self.assertEqual(0, len(optimizer.variables()))
def testBasicResourceVariable(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype)
var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
sgd_op = gradient_descent.GradientDescentOptimizer(3.0).apply_gradients(
zip([grads0, grads1], [var0, var1]))
# TODO(apassos) calling initialize_resources on all resources here
# doesn't work because the sessions and graph are reused across unit
# tests and this would mean trying to reinitialize variables. Figure out
# a long-term solution for this.
resources.initialize_resources([var0, var1]).run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0, 4.0], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1],
self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01],
self.evaluate(var1))
def testBasicCallableParams(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype)
var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
lr = lambda: 3.0
sgd_op = gradient_descent.GradientDescentOptimizer(lr).apply_gradients(
zip([grads0, grads1], [var0, var1]))
# TODO(apassos) calling initialize_resources on all resources here
# doesn't work because the sessions and graph are reused across unit
# tests and this would mean trying to reinitialize variables. Figure out
# a long-term solution for this.
resources.initialize_resources([var0, var1]).run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0, 4.0], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1],
self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01],
self.evaluate(var1))
def testMinimizeResourceVariable(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
var1 = resource_variable_ops.ResourceVariable([3.0], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(var0, x) + var1
loss = pred * pred
sgd_op = gradient_descent.GradientDescentOptimizer(1.0).minimize(loss)
# TODO(apassos) calling initialize_resources on all resources here
# doesn't work because the sessions and graph are reused across unit
# tests and this would mean trying to reinitialize variables. Figure out
# a long-term solution for this.
resources.initialize_resources([var0, var1]).run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
np_pred = 1.0 * 4.0 + 2.0 * 5.0 + 3.0
np_grad = 2 * np_pred
self.assertAllCloseAccordingToType(
[[1.0 - np_grad * 4.0, 2.0 - np_grad * 5.0]], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0 - np_grad], self.evaluate(var1))
def testMinimizeSparseResourceVariable(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
var1 = resource_variable_ops.ResourceVariable([3.0], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
pred += var1
loss = pred * pred
sgd_op = gradient_descent.GradientDescentOptimizer(1.0).minimize(loss)
# TODO(apassos) calling initialize_resources on all resources here
# doesn't work because the sessions and graph are reused across unit
# tests and this would mean trying to reinitialize variables. Figure out
# a long-term solution for this.
self.evaluate(variables.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
np_pred = 1.0 * 4.0 + 2.0 * 5.0 + 3.0
np_grad = 2 * np_pred
self.assertAllCloseAccordingToType(
[[1.0 - np_grad * 4.0, 2.0 - np_grad * 5.0]], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0 - np_grad], self.evaluate(var1))
def testTensorLearningRate(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
var0 = variables.Variable([1.0, 2.0], dtype=dtype)
var1 = variables.Variable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
lrate = constant_op.constant(3.0)
sgd_op = gradient_descent.GradientDescentOptimizer(
lrate).apply_gradients(zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0, 4.0], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1],
self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01],
self.evaluate(var1))
def testGradWrtRef(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
opt = gradient_descent.GradientDescentOptimizer(3.0)
values = [1.0, 3.0]
vars_ = [variables.Variable([v], dtype=dtype) for v in values]
grads_and_vars = opt.compute_gradients(vars_[0] + vars_[1], vars_)
self.evaluate(variables.global_variables_initializer())
for grad, _ in grads_and_vars:
self.assertAllCloseAccordingToType([1.0], self.evaluate(grad))
def testWithGlobalStep(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
global_step = variables.Variable(0, trainable=False)
var0 = variables.Variable([1.0, 2.0], dtype=dtype)
var1 = variables.Variable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
sgd_op = gradient_descent.GradientDescentOptimizer(3.0).apply_gradients(
zip([grads0, grads1], [var0, var1]), global_step=global_step)
self.evaluate(variables.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0, 4.0], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params and global_step
self.assertAllCloseAccordingToType([1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1],
self.evaluate(var0))
self.assertAllCloseAccordingToType([3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01],
self.evaluate(var1))
self.assertAllCloseAccordingToType(1, self.evaluate(global_step))
def testSparseBasic(self):
for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:
# train.GradientDescentOptimizer is V1 only API.
with ops.Graph().as_default(), self.cached_session():
var0 = variables.Variable([[1.0], [2.0]], dtype=dtype)
var1 = variables.Variable([[3.0], [4.0]], dtype=dtype)
grads0 = indexed_slices.IndexedSlices(
constant_op.constant(
[0.1], shape=[1, 1], dtype=dtype),
constant_op.constant([0]),
constant_op.constant([2, 1]))
grads1 = indexed_slices.IndexedSlices(
constant_op.constant(
[0.01], shape=[1, 1], dtype=dtype),
constant_op.constant([1]),
constant_op.constant([2, 1]))
sgd_op = gradient_descent.GradientDescentOptimizer(3.0).apply_gradients(
zip([grads0, grads1], [var0, var1]))
self.evaluate(variables.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0], [2.0]], self.evaluate(var0))
self.assertAllCloseAccordingToType([[3.0], [4.0]], self.evaluate(var1))
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType([[1.0 - 3.0 * 0.1], [2.0]],
self.evaluate(var0))
self.assertAllCloseAccordingToType([[3.0], [4.0 - 3.0 * 0.01]],
self.evaluate(var1))
if __name__ == "__main__":
test.main()
| GradientDescentOptimizerTest |
python | getsentry__sentry | src/sentry/integrations/api/endpoints/organization_coding_agents.py | {
"start": 1711,
"end": 4144
} | class ____(OrganizationEndpoint):
owner = ApiOwner.ML_AI
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
"POST": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (OrganizationEventPermission,)
def get(self, request: Request, organization: Organization) -> Response:
"""Get all available coding agent integrations for the organization."""
if not features.has("organizations:seer-coding-agent-integrations", organization):
return Response({"detail": "Feature not available"}, status=404)
integrations = integration_service.get_integrations(
organization_id=organization.id,
providers=get_coding_agent_providers(),
status=ObjectStatus.ACTIVE,
)
integrations_data = [
{
"id": str(integration.id),
"name": integration.name,
"provider": integration.provider,
}
for integration in integrations
]
logger.info(
"coding_agent.list_integrations",
extra={"organization_id": organization.id, "count": len(integrations_data)},
)
return self.respond({"integrations": integrations_data})
def post(self, request: Request, organization: Organization) -> Response:
"""Launch a coding agent."""
serializer = OrganizationCodingAgentLaunchSerializer(data=request.data)
if not serializer.is_valid():
raise ValidationError(serializer.errors)
validated = serializer.validated_data
run_id = validated["run_id"]
integration_id = validated["integration_id"]
trigger_source = validated["trigger_source"]
instruction = validated.get("instruction")
results = launch_coding_agents_for_run(
organization_id=organization.id,
integration_id=integration_id,
run_id=run_id,
trigger_source=trigger_source,
instruction=instruction,
)
successes = results["successes"]
failures = results["failures"]
response_data: LaunchResponse = {
"success": True,
"launched_count": len(successes),
"failed_count": len(failures),
}
if failures:
response_data["failures"] = failures
return self.respond(response_data)
| OrganizationCodingAgentsEndpoint |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/spec_cache.py | {
"start": 274,
"end": 712
} | class ____(str, Enum):
OSS = "oss"
CLOUD = "cloud"
@classmethod
def _missing_(cls, value):
"""Returns the registry from the string value. (case insensitive)"""
value = value.lower()
for member in cls:
if member.lower() == value:
return member
return None
SPEC_FILE_NAMES = {Registries.OSS: "spec.json", Registries.CLOUD: "spec.cloud.json"}
@dataclass
| Registries |
python | django__django | tests/queries/models.py | {
"start": 16906,
"end": 17027
} | class ____(models.Model):
schools = models.ManyToManyField(School)
friends = models.ManyToManyField("self")
| Teacher |
python | nedbat__coveragepy | coverage/types.py | {
"start": 5459,
"end": 5600
} | class ____(Protocol):
"""Anything that can be written to."""
def write(self, msg: str) -> None:
"""Write a message."""
| TWritable |
python | getsentry__sentry | src/sentry/apidocs/parameters.py | {
"start": 30431,
"end": 30690
} | class ____:
DISCOVER_SAVED_QUERY_ID = OpenApiParameter(
name="query_id",
location="path",
required=True,
type=int,
description="""The ID of the Discover query you'd like to retrieve.""",
)
| DiscoverSavedQueryParams |
python | celery__celery | t/unit/backends/test_mongodb.py | {
"start": 25876,
"end": 26367
} | class ____:
def test_encode(self, mongo_backend_factory, serializer, encoded_into):
backend = mongo_backend_factory(serializer=serializer)
assert isinstance(backend.encode(10), encoded_into)
def test_encode_decode(self, mongo_backend_factory, serializer,
encoded_into):
backend = mongo_backend_factory(serializer=serializer)
decoded = backend.decode(backend.encode(12))
assert decoded == 12
| test_MongoBackend_no_mock |
python | ray-project__ray | rllib/core/models/configs.py | {
"start": 35383,
"end": 37097
} | class ____(_MLPConfig):
"""Configuration for an MLP that acts as an encoder.
See _MLPConfig for usage details.
Example:
.. testcode::
# Configuration:
config = MLPEncoderConfig(
input_dims=[4], # must be 1D tensor
hidden_layer_dims=[16],
hidden_layer_activation="relu",
hidden_layer_use_layernorm=False,
output_layer_dim=None, # maybe None or an int
)
model = config.build(framework="torch")
# Resulting stack in pseudocode:
# Linear(4, 16, bias=True)
# ReLU()
Example:
.. testcode::
# Configuration:
config = MLPEncoderConfig(
input_dims=[2],
hidden_layer_dims=[8, 8],
hidden_layer_activation="silu",
hidden_layer_use_layernorm=True,
hidden_layer_use_bias=False,
output_layer_dim=4,
output_layer_activation="tanh",
output_layer_use_bias=False,
)
model = config.build(framework="tf2")
# Resulting stack in pseudocode:
# Linear(2, 8, bias=False)
# LayerNorm((8,)) # layernorm always before activation
# SiLU()
# Linear(8, 8, bias=False)
# LayerNorm((8,)) # layernorm always before activation
# SiLU()
# Linear(8, 4, bias=False)
# Tanh()
"""
@_framework_implemented()
def build(self, framework: str = "torch") -> "Encoder":
self._validate(framework)
if framework == "torch":
from ray.rllib.core.models.torch.encoder import TorchMLPEncoder
return TorchMLPEncoder(self)
@ExperimentalAPI
@dataclass
| MLPEncoderConfig |
python | pyqtgraph__pyqtgraph | pyqtgraph/opengl/items/GLMeshItem.py | {
"start": 361,
"end": 544
} | class ____(enum.Flag):
POSITION = enum.auto()
NORMAL = enum.auto()
COLOR = enum.auto()
FACES = enum.auto()
EDGE_VERTS = enum.auto()
EDGES = enum.auto()
| DirtyFlag |
python | qdrant__qdrant-client | qdrant_client/http/api/points_api.py | {
"start": 23372,
"end": 30391
} | class ____(_PointsApi):
def batch_update(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
update_operations: m.UpdateOperations = None,
) -> m.InlineResponse20014:
"""
Apply a series of update operations for points, vectors and payloads
"""
return self._build_for_batch_update(
collection_name=collection_name,
wait=wait,
ordering=ordering,
update_operations=update_operations,
)
def clear_payload(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
points_selector: m.PointsSelector = None,
) -> m.InlineResponse2005:
"""
Remove all payload for specified points
"""
return self._build_for_clear_payload(
collection_name=collection_name,
wait=wait,
ordering=ordering,
points_selector=points_selector,
)
def count_points(
self,
collection_name: str,
consistency: m.ReadConsistency = None,
timeout: int = None,
count_request: m.CountRequest = None,
) -> m.InlineResponse20019:
"""
Count points which matches given filtering condition
"""
return self._build_for_count_points(
collection_name=collection_name,
consistency=consistency,
timeout=timeout,
count_request=count_request,
)
def delete_payload(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
delete_payload: m.DeletePayload = None,
) -> m.InlineResponse2005:
"""
Delete specified key payload for points
"""
return self._build_for_delete_payload(
collection_name=collection_name,
wait=wait,
ordering=ordering,
delete_payload=delete_payload,
)
def delete_points(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
points_selector: m.PointsSelector = None,
) -> m.InlineResponse2005:
"""
Delete points
"""
return self._build_for_delete_points(
collection_name=collection_name,
wait=wait,
ordering=ordering,
points_selector=points_selector,
)
def delete_vectors(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
delete_vectors: m.DeleteVectors = None,
) -> m.InlineResponse2005:
"""
Delete named vectors from the given points.
"""
return self._build_for_delete_vectors(
collection_name=collection_name,
wait=wait,
ordering=ordering,
delete_vectors=delete_vectors,
)
def facet(
self,
collection_name: str,
consistency: m.ReadConsistency = None,
timeout: int = None,
facet_request: m.FacetRequest = None,
) -> m.InlineResponse20020:
"""
Count points that satisfy the given filter for each unique value of a payload key.
"""
return self._build_for_facet(
collection_name=collection_name,
consistency=consistency,
timeout=timeout,
facet_request=facet_request,
)
def get_point(
self,
collection_name: str,
id: m.ExtendedPointId,
consistency: m.ReadConsistency = None,
) -> m.InlineResponse20012:
"""
Retrieve full information of single point by id
"""
return self._build_for_get_point(
collection_name=collection_name,
id=id,
consistency=consistency,
)
def get_points(
self,
collection_name: str,
consistency: m.ReadConsistency = None,
timeout: int = None,
point_request: m.PointRequest = None,
) -> m.InlineResponse20013:
"""
Retrieve multiple points by specified IDs
"""
return self._build_for_get_points(
collection_name=collection_name,
consistency=consistency,
timeout=timeout,
point_request=point_request,
)
def overwrite_payload(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
set_payload: m.SetPayload = None,
) -> m.InlineResponse2005:
"""
Replace full payload of points with new one
"""
return self._build_for_overwrite_payload(
collection_name=collection_name,
wait=wait,
ordering=ordering,
set_payload=set_payload,
)
def scroll_points(
self,
collection_name: str,
consistency: m.ReadConsistency = None,
timeout: int = None,
scroll_request: m.ScrollRequest = None,
) -> m.InlineResponse20015:
"""
Scroll request - paginate over all points which matches given filtering condition
"""
return self._build_for_scroll_points(
collection_name=collection_name,
consistency=consistency,
timeout=timeout,
scroll_request=scroll_request,
)
def set_payload(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
set_payload: m.SetPayload = None,
) -> m.InlineResponse2005:
"""
Set payload values for points
"""
return self._build_for_set_payload(
collection_name=collection_name,
wait=wait,
ordering=ordering,
set_payload=set_payload,
)
def update_vectors(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
update_vectors: m.UpdateVectors = None,
) -> m.InlineResponse2005:
"""
Update specified named vectors on points, keep unspecified vectors intact.
"""
return self._build_for_update_vectors(
collection_name=collection_name,
wait=wait,
ordering=ordering,
update_vectors=update_vectors,
)
def upsert_points(
self,
collection_name: str,
wait: bool = None,
ordering: WriteOrdering = None,
point_insert_operations: m.PointInsertOperations = None,
) -> m.InlineResponse2005:
"""
Perform insert + updates on points. If point with given ID already exists - it will be overwritten.
"""
return self._build_for_upsert_points(
collection_name=collection_name,
wait=wait,
ordering=ordering,
point_insert_operations=point_insert_operations,
)
| SyncPointsApi |
python | kamyu104__LeetCode-Solutions | Python/design-compressed-string-iterator.py | {
"start": 41,
"end": 788
} | class ____(object):
def __init__(self, compressedString):
"""
:type compressedString: str
"""
self.__result = re.findall(r"([a-zA-Z])(\d+)", compressedString)
self.__index, self.__num, self.__ch = 0, 0, ' '
def next(self):
"""
:rtype: str
"""
if not self.hasNext():
return ' '
if self.__num == 0:
self.__ch = self.__result[self.__index][0]
self.__num = int(self.__result[self.__index][1])
self.__index += 1
self.__num -= 1
return self.__ch
def hasNext(self):
"""
:rtype: bool
"""
return self.__index != len(self.__result) or self.__num != 0
| StringIterator |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datastore.py | {
"start": 14885,
"end": 17286
} | class ____(GoogleCloudBaseOperator):
"""
Commit a transaction, optionally creating, deleting or modifying some entities.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDatastoreCommitOperator`
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/commit
:param body: the body of the commit request.
:param project_id: Google Cloud project ID against which to make the request.
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"body",
"impersonation_chain",
)
operator_extra_links = (CloudDatastoreEntitiesLink(),)
def __init__(
self,
*,
body: dict[str, Any],
project_id: str = PROVIDE_PROJECT_ID,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.body = body
self.gcp_conn_id = gcp_conn_id
self.project_id = project_id
self.impersonation_chain = impersonation_chain
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"project_id": self.project_id,
}
def execute(self, context: Context) -> dict:
hook = DatastoreHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
response = hook.commit(
body=self.body,
project_id=self.project_id,
)
CloudDatastoreEntitiesLink.persist(context=context)
return response
| CloudDatastoreCommitOperator |
python | pandas-dev__pandas | pandas/tests/extension/base/index.py | {
"start": 86,
"end": 518
} | class ____:
"""Tests for Index object backed by an ExtensionArray"""
def test_index_from_array(self, data):
idx = pd.Index(data)
assert data.dtype == idx.dtype
def test_index_from_listlike_with_dtype(self, data):
idx = pd.Index(data, dtype=data.dtype)
assert idx.dtype == data.dtype
idx = pd.Index(list(data), dtype=data.dtype)
assert idx.dtype == data.dtype
| BaseIndexTests |
python | dagster-io__dagster | examples/project_fully_featured/project_fully_featured/resources/parquet_io_manager.py | {
"start": 2608,
"end": 2799
} | class ____(PartitionedParquetIOManager):
base_path: str = get_system_temp_directory()
@property
def _base_path(self):
return self.base_path
| LocalPartitionedParquetIOManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1043700,
"end": 1044178
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UpdateRepositoryRuleset"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "ruleset")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
ruleset = sgqlc.types.Field("RepositoryRuleset", graphql_name="ruleset")
"""The newly created Ruleset."""
| UpdateRepositoryRulesetPayload |
python | encode__starlette | starlette/requests.py | {
"start": 6993,
"end": 11700
} | class ____(HTTPConnection):
_form: FormData | None
def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send):
super().__init__(scope)
assert scope["type"] == "http"
self._receive = receive
self._send = send
self._stream_consumed = False
self._is_disconnected = False
self._form = None
@property
def method(self) -> str:
return cast(str, self.scope["method"])
@property
def receive(self) -> Receive:
return self._receive
async def stream(self) -> AsyncGenerator[bytes, None]:
if hasattr(self, "_body"):
yield self._body
yield b""
return
if self._stream_consumed:
raise RuntimeError("Stream consumed")
while not self._stream_consumed:
message = await self._receive()
if message["type"] == "http.request":
body = message.get("body", b"")
if not message.get("more_body", False):
self._stream_consumed = True
if body:
yield body
elif message["type"] == "http.disconnect": # pragma: no branch
self._is_disconnected = True
raise ClientDisconnect()
yield b""
async def body(self) -> bytes:
if not hasattr(self, "_body"):
chunks: list[bytes] = []
async for chunk in self.stream():
chunks.append(chunk)
self._body = b"".join(chunks)
return self._body
async def json(self) -> Any:
if not hasattr(self, "_json"): # pragma: no branch
body = await self.body()
self._json = json.loads(body)
return self._json
async def _get_form(
self,
*,
max_files: int | float = 1000,
max_fields: int | float = 1000,
max_part_size: int = 1024 * 1024,
) -> FormData:
if self._form is None: # pragma: no branch
assert parse_options_header is not None, (
"The `python-multipart` library must be installed to use form parsing."
)
content_type_header = self.headers.get("Content-Type")
content_type: bytes
content_type, _ = parse_options_header(content_type_header)
if content_type == b"multipart/form-data":
try:
multipart_parser = MultiPartParser(
self.headers,
self.stream(),
max_files=max_files,
max_fields=max_fields,
max_part_size=max_part_size,
)
self._form = await multipart_parser.parse()
except MultiPartException as exc:
if "app" in self.scope:
raise HTTPException(status_code=400, detail=exc.message)
raise exc
elif content_type == b"application/x-www-form-urlencoded":
form_parser = FormParser(self.headers, self.stream())
self._form = await form_parser.parse()
else:
self._form = FormData()
return self._form
def form(
self,
*,
max_files: int | float = 1000,
max_fields: int | float = 1000,
max_part_size: int = 1024 * 1024,
) -> AwaitableOrContextManager[FormData]:
return AwaitableOrContextManagerWrapper(
self._get_form(max_files=max_files, max_fields=max_fields, max_part_size=max_part_size)
)
async def close(self) -> None:
if self._form is not None: # pragma: no branch
await self._form.close()
async def is_disconnected(self) -> bool:
if not self._is_disconnected:
message: Message = {}
# If message isn't immediately available, move on
with anyio.CancelScope() as cs:
cs.cancel()
message = await self._receive()
if message.get("type") == "http.disconnect":
self._is_disconnected = True
return self._is_disconnected
async def send_push_promise(self, path: str) -> None:
if "http.response.push" in self.scope.get("extensions", {}):
raw_headers: list[tuple[bytes, bytes]] = []
for name in SERVER_PUSH_HEADERS_TO_COPY:
for value in self.headers.getlist(name):
raw_headers.append((name.encode("latin-1"), value.encode("latin-1")))
await self._send({"type": "http.response.push", "path": path, "headers": raw_headers})
| Request |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/type_api.py | {
"start": 52181,
"end": 54693
} | class ____(TypeEngineMixin):
"""Mixin for base types that emulate the behavior of a DB-native type.
An :class:`.Emulated` type will use an available database type
in conjunction with Python-side routines and/or database constraints
in order to approximate the behavior of a database type that is provided
natively by some backends. When a native-providing backend is in
use, the native version of the type is used. This native version
should include the :class:`.NativeForEmulated` mixin to allow it to be
distinguished from :class:`.Emulated`.
Current examples of :class:`.Emulated` are: :class:`.Interval`,
:class:`.Enum`, :class:`.Boolean`.
"""
native: bool
def adapt_to_emulated(
self,
impltype: Type[Union[TypeEngine[Any], TypeEngineMixin]],
**kw: Any,
) -> TypeEngine[Any]:
"""Given an impl class, adapt this type to the impl assuming
"emulated".
The impl should also be an "emulated" version of this type,
most likely the same class as this type itself.
e.g.: sqltypes.Enum adapts to the Enum class.
"""
return super().adapt(impltype, **kw)
@overload
def adapt(self, cls: Type[_TE], **kw: Any) -> _TE: ...
@overload
def adapt(
self, cls: Type[TypeEngineMixin], **kw: Any
) -> TypeEngine[Any]: ...
def adapt(
self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
) -> TypeEngine[Any]:
if _is_native_for_emulated(cls):
if self.native:
# native support requested, dialect gave us a native
# implementor, pass control over to it
return cls.adapt_emulated_to_native(self, **kw)
else:
# non-native support, let the native implementor
# decide also, at the moment this is just to help debugging
# as only the default logic is implemented.
return cls.adapt_native_to_emulated(self, **kw)
else:
# this would be, both classes are Enum, or both classes
# are postgresql.ENUM
if issubclass(cls, self.__class__):
return self.adapt_to_emulated(cls, **kw)
else:
return super().adapt(cls, **kw)
def _is_native_for_emulated(
typ: Type[Union[TypeEngine[Any], TypeEngineMixin]],
) -> TypeGuard[Type[NativeForEmulated]]:
return hasattr(typ, "adapt_emulated_to_native")
| Emulated |
python | huggingface__transformers | src/transformers/models/glm4_moe/modeling_glm4_moe.py | {
"start": 14344,
"end": 15071
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
Glm4MoeRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
| Glm4MoeRMSNorm |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 5725,
"end": 5883
} | class ____(ParentI):
def f(self):
super = 1
__class__ = 3
builtins.super(ChildI5, self).f() # no __class__ in the local scope
| ChildI5 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 21358,
"end": 21781
} | class ____(sgqlc.types.Enum):
"""Properties by which Enterprise Server user account connections can
be ordered.
Enumeration Choices:
* `LOGIN`: Order user accounts by login
* `REMOTE_CREATED_AT`: Order user accounts by creation time on the
Enterprise Server installation
"""
__schema__ = github_schema
__choices__ = ("LOGIN", "REMOTE_CREATED_AT")
| EnterpriseServerUserAccountOrderField |
python | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 43367,
"end": 43972
} | class ____(forms.ModelForm):
"""
Project feature form for dynamic admin choices.
This form converts the CharField into a ChoiceField on display. The
underlying driver won't attempt to do validation on the choices, and so we
can dynamically populate this list.
"""
feature_id = forms.ChoiceField()
class Meta:
model = Feature
fields = ["projects", "feature_id", "default_true", "future_default_true"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["feature_id"].choices = Feature.FEATURES
| FeatureForm |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol52.py | {
"start": 209,
"end": 277
} | class ____:
def __init__(self, *, p1: int, p2: str) -> None: ...
| A |
python | getsentry__sentry | tests/sentry/core/endpoints/test_project_key_stats.py | {
"start": 336,
"end": 6393
} | class ____(OutcomesSnubaTest, SnubaTestCase, APITestCase):
def setUp(self) -> None:
super().setUp()
self.project = self.create_project()
self.key = ProjectKey.objects.create(project=self.project)
self.login_as(user=self.user)
self.path = f"/api/0/projects/{self.project.organization.slug}/{self.project.slug}/keys/{self.key.public_key}/stats/"
@pytest.mark.skip(reason="flakey: https://github.com/getsentry/sentry/issues/54520")
def test_simple(self) -> None:
# This outcome should not be included.
other_key = ProjectKey.objects.create(project=self.project)
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(hours=1),
"project_id": self.project.id,
"key_id": other_key.id,
"outcome": Outcome.ACCEPTED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 100,
},
1,
)
# These outcomes should be included.
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(hours=1),
"project_id": self.project.id,
"key_id": self.key.id,
"outcome": Outcome.ACCEPTED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 1,
},
2,
)
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(hours=1),
"project_id": self.project.id,
"key_id": self.key.id,
"outcome": Outcome.FILTERED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 1,
},
1,
)
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(hours=1),
"key_id": self.key.id,
"project_id": self.project.id,
"outcome": Outcome.RATE_LIMITED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 1,
},
5,
)
response = self.client.get(self.path)
assert response.status_code == 200, response.content
# Find the bucket with data.
# The index of this bucket can shift when we run tests at UTC midnight
result = [bucket for bucket in response.data if bucket["total"] > 0][0]
assert isinstance(result["ts"], int)
assert result["total"] == 8, response.data
assert result["filtered"] == 1, response.data
assert result["dropped"] == 5, response.data
assert result["accepted"] == 2, response.data
@pytest.mark.skip(reason="flakey: https://github.com/getsentry/sentry/issues/46402")
def test_ignore_discard(self) -> None:
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(hours=1),
"project_id": self.project.id,
"key_id": self.key.id,
"outcome": Outcome.ACCEPTED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 1,
},
2,
)
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(hours=1),
"project_id": self.project.id,
"key_id": self.key.id,
"outcome": Outcome.CLIENT_DISCARD,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 10,
},
1,
)
response = self.client.get(self.path)
assert response.status_code == 200, response.content
result = [bucket for bucket in response.data if bucket["total"] > 0][0]
assert result["total"] == 2, response.data
assert result["filtered"] == 0, response.data
def test_invalid_parameters(self) -> None:
url = self.path + "?resolution=2d"
response = self.client.get(url)
assert response.status_code == 400
@pytest.mark.skip(reason="flakey: https://github.com/getsentry/sentry/issues/46402")
def test_date_conditions(self) -> None:
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(hours=1),
"project_id": self.project.id,
"key_id": self.key.id,
"outcome": Outcome.ACCEPTED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 1,
},
2,
)
self.store_outcomes(
{
"org_id": self.organization.id,
"timestamp": before_now(days=10),
"project_id": self.project.id,
"key_id": self.key.id,
"outcome": Outcome.ACCEPTED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 10,
},
1,
)
response = self.client.get(
self.path,
data={
"since": int(before_now(days=1).timestamp()),
"until": int(before_now().timestamp()),
},
)
assert response.status_code == 200, response.content
result = [bucket for bucket in response.data if bucket["total"] > 0][0]
assert isinstance(result["ts"], int)
assert result["total"] == 2, response.data
assert result["filtered"] == 0, response.data
assert result["dropped"] == 0, response.data
assert result["accepted"] == 2, response.data
assert len(response.data) == 2
| ProjectKeyStatsTest |
python | kubernetes-client__python | kubernetes/client/models/v1_resource_rule.py | {
"start": 383,
"end": 7224
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_groups': 'list[str]',
'resource_names': 'list[str]',
'resources': 'list[str]',
'verbs': 'list[str]'
}
attribute_map = {
'api_groups': 'apiGroups',
'resource_names': 'resourceNames',
'resources': 'resources',
'verbs': 'verbs'
}
def __init__(self, api_groups=None, resource_names=None, resources=None, verbs=None, local_vars_configuration=None): # noqa: E501
"""V1ResourceRule - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_groups = None
self._resource_names = None
self._resources = None
self._verbs = None
self.discriminator = None
if api_groups is not None:
self.api_groups = api_groups
if resource_names is not None:
self.resource_names = resource_names
if resources is not None:
self.resources = resources
self.verbs = verbs
@property
def api_groups(self):
"""Gets the api_groups of this V1ResourceRule. # noqa: E501
APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"*\" means all. # noqa: E501
:return: The api_groups of this V1ResourceRule. # noqa: E501
:rtype: list[str]
"""
return self._api_groups
@api_groups.setter
def api_groups(self, api_groups):
"""Sets the api_groups of this V1ResourceRule.
APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"*\" means all. # noqa: E501
:param api_groups: The api_groups of this V1ResourceRule. # noqa: E501
:type: list[str]
"""
self._api_groups = api_groups
@property
def resource_names(self):
"""Gets the resource_names of this V1ResourceRule. # noqa: E501
ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. \"*\" means all. # noqa: E501
:return: The resource_names of this V1ResourceRule. # noqa: E501
:rtype: list[str]
"""
return self._resource_names
@resource_names.setter
def resource_names(self, resource_names):
"""Sets the resource_names of this V1ResourceRule.
ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. \"*\" means all. # noqa: E501
:param resource_names: The resource_names of this V1ResourceRule. # noqa: E501
:type: list[str]
"""
self._resource_names = resource_names
@property
def resources(self):
"""Gets the resources of this V1ResourceRule. # noqa: E501
Resources is a list of resources this rule applies to. \"*\" means all in the specified apiGroups. \"*/foo\" represents the subresource 'foo' for all resources in the specified apiGroups. # noqa: E501
:return: The resources of this V1ResourceRule. # noqa: E501
:rtype: list[str]
"""
return self._resources
@resources.setter
def resources(self, resources):
"""Sets the resources of this V1ResourceRule.
Resources is a list of resources this rule applies to. \"*\" means all in the specified apiGroups. \"*/foo\" represents the subresource 'foo' for all resources in the specified apiGroups. # noqa: E501
:param resources: The resources of this V1ResourceRule. # noqa: E501
:type: list[str]
"""
self._resources = resources
@property
def verbs(self):
"""Gets the verbs of this V1ResourceRule. # noqa: E501
Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy. \"*\" means all. # noqa: E501
:return: The verbs of this V1ResourceRule. # noqa: E501
:rtype: list[str]
"""
return self._verbs
@verbs.setter
def verbs(self, verbs):
"""Sets the verbs of this V1ResourceRule.
Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy. \"*\" means all. # noqa: E501
:param verbs: The verbs of this V1ResourceRule. # noqa: E501
:type: list[str]
"""
if self.local_vars_configuration.client_side_validation and verbs is None: # noqa: E501
raise ValueError("Invalid value for `verbs`, must not be `None`") # noqa: E501
self._verbs = verbs
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1ResourceRule):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1ResourceRule):
return True
return self.to_dict() != other.to_dict()
| V1ResourceRule |
python | great-expectations__great_expectations | tests/integration/fixtures/partition_and_sample_data/partitioner_test_cases_and_fixtures.py | {
"start": 7915,
"end": 8325
} | class ____:
table_domain_test_case: (
bool # Use "MetricDomainTypes" when column-pair and multicolumn test cases are developed.
)
num_expected_batch_definitions: int
num_expected_rows_in_first_batch_definition: int
add_batch_definition_method_name: str
add_batch_definition_kwargs: dict
expected_column_values: List[Any] = field(default_factory=list)
| TaxiPartitioningTestCase |
python | gevent__gevent | src/greentest/3.14/test_urllib.py | {
"start": 72219,
"end": 73276
} | class ____(unittest.TestCase):
"""Unit tests for urllib.request.Request."""
def test_default_values(self):
Request = urllib.request.Request
request = Request("http://www.python.org")
self.assertEqual(request.get_method(), 'GET')
request = Request("http://www.python.org", {})
self.assertEqual(request.get_method(), 'POST')
def test_with_method_arg(self):
Request = urllib.request.Request
request = Request("http://www.python.org", method='HEAD')
self.assertEqual(request.method, 'HEAD')
self.assertEqual(request.get_method(), 'HEAD')
request = Request("http://www.python.org", {}, method='HEAD')
self.assertEqual(request.method, 'HEAD')
self.assertEqual(request.get_method(), 'HEAD')
request = Request("http://www.python.org", method='GET')
self.assertEqual(request.get_method(), 'GET')
request.method = 'HEAD'
self.assertEqual(request.get_method(), 'HEAD')
if __name__ == '__main__':
unittest.main()
| RequestTests |
python | crytic__slither | slither/detectors/operations/unchecked_low_level_return_values.py | {
"start": 478,
"end": 3103
} | class ____(AbstractDetector):
"""
If the return value of a low-level call is not checked, it might lead to losing ether
"""
ARGUMENT = "unchecked-lowlevel"
HELP = "Unchecked low-level calls"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-low-level-calls"
WIKI_TITLE = "Unchecked low-level calls"
WIKI_DESCRIPTION = "The return value of a low-level call is not checked."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract MyConc{
function my_func(address payable dst) public payable{
dst.call.value(msg.value)("");
}
}
```
The return value of the low-level call is not checked, so if the call fails, the Ether will be locked in the contract.
If the low level is used to prevent blocking operations, consider logging failed calls.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Ensure that the return value of a low-level call is checked or logged."
@staticmethod
def detect_unused_return_values(f: FunctionContract) -> List[Node]:
"""
Return the nodes where the return value of a call is unused
Args:
f (Function)
Returns:
list(Node)
"""
values_returned = []
nodes_origin = {}
for n in f.nodes:
for ir in n.irs:
if isinstance(ir, LowLevelCall):
# if a return value is stored in a state variable, it's ok
if ir.lvalue and not isinstance(ir.lvalue, StateVariable):
values_returned.append(ir.lvalue)
nodes_origin[ir.lvalue] = ir
for read in ir.read:
if read in values_returned:
values_returned.remove(read)
return [nodes_origin[value].node for value in values_returned]
def _detect(self) -> List[Output]:
"""Detect low level calls where the success value is not checked"""
results = []
for c in self.compilation_unit.contracts_derived:
for f in c.functions_and_modifiers:
unused_return = UncheckedLowLevel.detect_unused_return_values(f)
if unused_return:
for node in unused_return:
info: DETECTOR_INFO = [f, " ignores return value by ", node, "\n"]
res = self.generate_result(info)
results.append(res)
return results
| UncheckedLowLevel |
python | django__django | django/db/models/expressions.py | {
"start": 68314,
"end": 72414
} | class ____(SQLiteNumericMixin, Expression):
template = "%(expression)s OVER (%(window)s)"
# Although the main expression may either be an aggregate or an
# expression with an aggregate function, the GROUP BY that will
# be introduced in the query as a result is not desired.
contains_aggregate = False
contains_over_clause = True
def __init__(
self,
expression,
partition_by=None,
order_by=None,
frame=None,
output_field=None,
):
self.partition_by = partition_by
self.order_by = order_by
self.frame = frame
if not getattr(expression, "window_compatible", False):
raise ValueError(
"Expression '%s' isn't compatible with OVER clauses."
% expression.__class__.__name__
)
if self.partition_by is not None:
if not isinstance(self.partition_by, (tuple, list)):
self.partition_by = (self.partition_by,)
self.partition_by = ExpressionList(*self.partition_by)
self.order_by = OrderByList.from_param("Window.order_by", self.order_by)
super().__init__(output_field=output_field)
self.source_expression = self._parse_expressions(expression)[0]
def _resolve_output_field(self):
return self.source_expression.output_field
def get_source_expressions(self):
return [self.source_expression, self.partition_by, self.order_by, self.frame]
def set_source_expressions(self, exprs):
self.source_expression, self.partition_by, self.order_by, self.frame = exprs
def as_sql(self, compiler, connection, template=None):
connection.ops.check_expression_support(self)
if not connection.features.supports_over_clause:
raise NotSupportedError("This backend does not support window expressions.")
expr_sql, params = compiler.compile(self.source_expression)
window_sql, window_params = [], ()
if self.partition_by is not None:
sql_expr, sql_params = self.partition_by.as_sql(
compiler=compiler,
connection=connection,
template="PARTITION BY %(expressions)s",
)
window_sql.append(sql_expr)
window_params += tuple(sql_params)
if self.order_by is not None:
order_sql, order_params = compiler.compile(self.order_by)
window_sql.append(order_sql)
window_params += tuple(order_params)
if self.frame:
frame_sql, frame_params = compiler.compile(self.frame)
window_sql.append(frame_sql)
window_params += tuple(frame_params)
template = template or self.template
return (
template % {"expression": expr_sql, "window": " ".join(window_sql).strip()},
(*params, *window_params),
)
def as_sqlite(self, compiler, connection):
if isinstance(self.output_field, fields.DecimalField):
# Casting to numeric must be outside of the window expression.
copy = self.copy()
source_expressions = copy.get_source_expressions()
source_expressions[0].output_field = fields.FloatField()
copy.set_source_expressions(source_expressions)
return super(Window, copy).as_sqlite(compiler, connection)
return self.as_sql(compiler, connection)
def __str__(self):
return "{} OVER ({}{}{})".format(
str(self.source_expression),
"PARTITION BY " + str(self.partition_by) if self.partition_by else "",
str(self.order_by or ""),
str(self.frame or ""),
)
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self)
def get_group_by_cols(self):
group_by_cols = []
if self.partition_by:
group_by_cols.extend(self.partition_by.get_group_by_cols())
if self.order_by is not None:
group_by_cols.extend(self.order_by.get_group_by_cols())
return group_by_cols
| Window |
python | walkccc__LeetCode | solutions/3090. Maximum Length Substring With Two Occurrences/3090.py | {
"start": 0,
"end": 288
} | class ____:
def maximumLengthSubstring(self, s: str) -> int:
ans = 0
count = collections.Counter()
l = 0
for r, c in enumerate(s):
count[c] += 1
while count[c] > 2:
count[s[l]] -= 1
l += 1
ans = max(ans, r - l + 1)
return ans
| Solution |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 8669,
"end": 11823
} | class ____:
def setup_method(self):
class ExampleSerializer(serializers.BaseSerializer):
def to_representation(self, obj):
return {
'id': obj['id'],
'email': obj['name'] + '@' + obj['domain']
}
def to_internal_value(self, data):
name, domain = str(data['email']).split('@')
return {
'id': int(data['id']),
'name': name,
'domain': domain,
}
self.Serializer = ExampleSerializer
def test_abstract_methods_raise_proper_errors(self):
serializer = serializers.BaseSerializer()
with pytest.raises(NotImplementedError):
serializer.to_internal_value(None)
with pytest.raises(NotImplementedError):
serializer.to_representation(None)
with pytest.raises(NotImplementedError):
serializer.update(None, None)
with pytest.raises(NotImplementedError):
serializer.create(None)
def test_access_to_data_attribute_before_validation_raises_error(self):
serializer = serializers.BaseSerializer(data={'foo': 'bar'})
with pytest.raises(AssertionError):
serializer.data
def test_access_to_errors_attribute_before_validation_raises_error(self):
serializer = serializers.BaseSerializer(data={'foo': 'bar'})
with pytest.raises(AssertionError):
serializer.errors
def test_access_to_validated_data_attribute_before_validation_raises_error(self):
serializer = serializers.BaseSerializer(data={'foo': 'bar'})
with pytest.raises(AssertionError):
serializer.validated_data
def test_serialize_instance(self):
instance = {'id': 1, 'name': 'tom', 'domain': 'example.com'}
serializer = self.Serializer(instance)
assert serializer.data == {'id': 1, 'email': 'tom@example.com'}
def test_serialize_list(self):
instances = [
{'id': 1, 'name': 'tom', 'domain': 'example.com'},
{'id': 2, 'name': 'ann', 'domain': 'example.com'},
]
serializer = self.Serializer(instances, many=True)
assert serializer.data == [
{'id': 1, 'email': 'tom@example.com'},
{'id': 2, 'email': 'ann@example.com'}
]
def test_validate_data(self):
data = {'id': 1, 'email': 'tom@example.com'}
serializer = self.Serializer(data=data)
assert serializer.is_valid()
assert serializer.validated_data == {
'id': 1,
'name': 'tom',
'domain': 'example.com'
}
def test_validate_list(self):
data = [
{'id': 1, 'email': 'tom@example.com'},
{'id': 2, 'email': 'ann@example.com'},
]
serializer = self.Serializer(data=data, many=True)
assert serializer.is_valid()
assert serializer.validated_data == [
{'id': 1, 'name': 'tom', 'domain': 'example.com'},
{'id': 2, 'name': 'ann', 'domain': 'example.com'}
]
| TestBaseSerializer |
python | openai__openai-python | src/openai/_legacy_response.py | {
"start": 12817,
"end": 16237
} | class ____:
response: httpx.Response
def __init__(self, response: httpx.Response) -> None:
self.response = response
@property
def content(self) -> bytes:
return self.response.content
@property
def text(self) -> str:
return self.response.text
@property
def encoding(self) -> str | None:
return self.response.encoding
@property
def charset_encoding(self) -> str | None:
return self.response.charset_encoding
def json(self, **kwargs: Any) -> Any:
return self.response.json(**kwargs)
def read(self) -> bytes:
return self.response.read()
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
return self.response.iter_bytes(chunk_size)
def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
return self.response.iter_text(chunk_size)
def iter_lines(self) -> Iterator[str]:
return self.response.iter_lines()
def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]:
return self.response.iter_raw(chunk_size)
def write_to_file(
self,
file: str | os.PathLike[str],
) -> None:
"""Write the output to the given file.
Accepts a filename or any path-like object, e.g. pathlib.Path
Note: if you want to stream the data to the file instead of writing
all at once then you should use `.with_streaming_response` when making
the API request, e.g. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')`
"""
with open(file, mode="wb") as f:
for data in self.response.iter_bytes():
f.write(data)
@deprecated(
"Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead"
)
def stream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
with open(file, mode="wb") as f:
for data in self.response.iter_bytes(chunk_size):
f.write(data)
def close(self) -> None:
return self.response.close()
async def aread(self) -> bytes:
return await self.response.aread()
async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
return self.response.aiter_bytes(chunk_size)
async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
return self.response.aiter_text(chunk_size)
async def aiter_lines(self) -> AsyncIterator[str]:
return self.response.aiter_lines()
async def aiter_raw(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
return self.response.aiter_raw(chunk_size)
@deprecated(
"Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead"
)
async def astream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
path = anyio.Path(file)
async with await path.open(mode="wb") as f:
async for data in self.response.aiter_bytes(chunk_size):
await f.write(data)
async def aclose(self) -> None:
return await self.response.aclose()
| HttpxBinaryResponseContent |
python | pytorch__pytorch | test/inductor/test_loop_ordering.py | {
"start": 6987,
"end": 22825
} | class ____(TestCase):
device = GPU_TYPE
def do_acc_test(self, f, *args, cast_fp8=True):
expect = f(*args)
actual = torch.compile(f)(*args)
if cast_fp8:
def _cast(x):
if isinstance(x, torch.Tensor) and x.dtype in (
torch.float8_e5m2,
torch.float8_e4m3fn,
):
return x.to(torch.float32)
return x
# Workaround the issue that call allclose on fp8 tensor triggers error
# RuntimeError: "mul_cuda" not implemented for 'Float8_e4m3fn'
expect = tree_map(_cast, expect)
actual = tree_map(_cast, actual)
self.assertTrue(same(expect, actual, tol=1e-3))
def setUp(self):
super().setUp()
metrics.reset()
def test_for_reordering_reindex(self):
"""
ComputedBuffer.iter_reoredering_reindex can cause some fusion
opportunitiies being skipped.
In this test case, Inductor generates 2 triton kernels before.
By removing ComputedBuffer.iter_reoredering_reindex, we can fuse those
two kernels into a single one.
"""
def f(x, y):
"""
Add a matmul since inductor may force layout for output.
"""
return (x.sum(dim=-1) + 1) @ y
A, B = 20, 30
# Make the first 2 dimension not able to merge on purpose so that
# ComputedBuffer.iter_reoredering_reindex will be updated.
x = rand_strided([A, A, B], [B, B * A + 300, 1], device=GPU_TYPE)
y = torch.randn(A, A)
self.do_acc_test(f, x, y)
self.assertEqual(1, metrics.generated_kernel_count)
expected_num_bytes = 0
expected_num_bytes += A * A * B + A * A # for the fused reduction
expected_num_bytes += A * A * 3 # for matmul
expected_num_bytes *= x.itemsize
self.assertEqual(expected_num_bytes, metrics.num_bytes_accessed)
def test_apbt_realize(self):
M = 1024
N = 2048
def f(x, y):
"""
There will be 2 kernels being generated without loop ordering after fusion:
https://gist.github.com/shunting314/44df83f71de2c110232c50ac6638ed69
"""
x = realize(x * 2)
y = realize(y * 3)
return x + y
x = torch.randn(M, N)
y = torch.randn(N, M).t()
self.do_acc_test(f, x, y)
self.assertEqual(1, metrics.generated_kernel_count)
def test_sum_and_t(self):
N = 1024
def f(x):
return x.sum(dim=-1), x.t().contiguous()
x = torch.randn(N, N * 2)
self.do_acc_test(f, x)
self.assertEqual(1, metrics.generated_kernel_count)
def test_pw_outer_red(self):
def f(x):
x = realize(x + 1)
return x.sum(dim=[0, 1])
# make the first 2 dimension small so we don't split the reduction
x = torch.randn(2, 4, 512)
self.do_acc_test(f, x)
self.assertEqual(1, metrics.generated_kernel_count)
def test_pw_outer_red_2(self):
"""
The pointwise kernel is a fused kernel
"""
def f(x):
x = realize(x + 1)
x = realize(x - 2)
x = realize(x * 3)
return x.sum(dim=[0, 1])
# make the first 2 dimension small so we don't split the reduction
x = torch.randn(2, 4, 512)
self.do_acc_test(f, x)
self.assertEqual(1, metrics.generated_kernel_count)
@inductor_config.patch(split_reductions=False)
def test_different_reduction_order(self):
"""
We should not reorder loops in this case. Since reordering loops does
not help!
"""
def f(x):
return x.sum(dim=0), x.sum(dim=1)
x = torch.randn(1024, 2048)
self.do_acc_test(f, x)
self.assertEqual(2, metrics.generated_kernel_count)
self.assertEqual(0, metrics.num_loop_reordering)
def test_keep_fake_dep(self):
"""
In this model, there are fake dependencies (StarDep) between Scatter
and a following mutation kernel that computes the gradients of
the embedding tables.
When we do loop reordering for the mutation kernel, we re-analyze
the node's dependencies. But the analysis result does not contains
those fake dependencies. Have to add them back manually.
"""
V = 2048
hidden_size = 64
max_seqlen = 512
batch_size = 8
class Model(nn.Module):
def __init__(self):
super().__init__()
self.word_embeddings = nn.Embedding(V, hidden_size)
self.position_embeddings = nn.Embedding(max_seqlen, hidden_size)
self.layer_norm = nn.LayerNorm(hidden_size)
def forward(self, input_ids, labels, position_ids):
emb = self.word_embeddings(input_ids) + self.position_embeddings(
position_ids
)
return self.layer_norm(emb)
m = Model()
@torch.compile
def f(*args):
m(*args).sum().backward()
input_ids = torch.randint(0, V, (batch_size, max_seqlen))
labels = torch.randint(0, V, (batch_size, max_seqlen))
position_ids = torch.arange(max_seqlen)[None, :]
# Make sure this line does not raise exceptions. If we miss
# fake dependencies after loop reordering, we may get exception that
# some buffer is used before being defined.
f(input_ids, labels, position_ids)
def test_different_broadcast_shapes(self):
def f(x, y, c):
return x + c, y + c
x = torch.randn(4, 256, 1024)
y = torch.randn(2, 512, 1024)
c = torch.randn(1024)
self.do_acc_test(f, x, y, c)
# The two kernels are not fused due to c is broadcasted
self.assertEqual(2, metrics.generated_kernel_count)
def test_view(self):
"""
Passing this test relies that we compare normalized MemoryDep.
Normlaization here means merging contiguous loops.
To make loop reordering work, we don't merge loops when creating
SchedulerNode. Thus we need explicitly normalize MemoryDep when
we check if two MemeoryDep matches.
"""
def f(x):
y = x.sin()
x = realize(x.view(10, 10))
return x, y
x = torch.randn(100)
self.do_acc_test(f, x)
self.assertEqual(1, metrics.generated_kernel_count)
@unittest.skipIf(not PLATFORM_SUPPORTS_FP8, "FP8 requires H100+ and MI300+")
def test_fp8_cast_and_t(self):
"""
This test repros the not able to fuses issue in
https://github.com/pytorch/pytorch/issues/130015
for fp8 cast and transpose
"""
def f(x, scale):
x = x * scale
x = x.clamp(-1 * E4M3_MAX_POS, E4M3_MAX_POS)
x = x.to(torch.float8_e4m3fn)
x_t = x.t().contiguous().t()
return x, x_t
x = torch.randn(4096, 4096, dtype=torch.bfloat16)
scale = torch.Tensor([10.0]).to(GPU_TYPE)
E4M3_MAX_POS = torch.finfo(torch.float8_e4m3fn).max
self.do_acc_test(f, x, scale)
self.assertEqual(1, metrics.generated_kernel_count)
@unittest.skipIf(not PLATFORM_SUPPORTS_FP8, "FP8 requires H100+ and MI300+")
def test_fp8_pattern_2(self):
"""
This test repros the fp8 fusion relation issue here:
https://github.com/pytorch/pytorch/issues/133242
"""
ref_dtype = torch.bfloat16
M, K = 4096, 4096
input_tensor = torch.randn(
M, K, device=GPU_TYPE, dtype=ref_dtype, requires_grad=False
)
scale = torch.Tensor([10.0]).to(GPU_TYPE)
E4M3_MAX_POS = torch.finfo(torch.float8_e4m3fn).max
def test_pattern2(tensor_x_inp, scale_x):
tensor_x = tensor_x_inp * scale_x
tensor_x = tensor_x.clamp(min=-1 * E4M3_MAX_POS, max=E4M3_MAX_POS)
tensor_fp8 = tensor_x.to(torch.float8_e4m3fn)
tensor_x_t = (tensor_x_inp * scale_x).t()
tensor_x_t = tensor_x_t.clamp(min=-1 * E4M3_MAX_POS, max=E4M3_MAX_POS)
tensor_fp8_t = tensor_x_t.to(torch.float8_e4m3fn)
tensor_fp8_t = tensor_fp8_t.contiguous().t()
return (tensor_fp8, tensor_fp8_t)
test_pattern = torch.compile(test_pattern2)
tensor_fp8, tensor_fp8_t = test_pattern(input_tensor, scale)
self.assertEqual(1, metrics.generated_kernel_count)
expected_numbytes = scale.nbytes # scalar
expected_numbytes += input_tensor.nbytes # input
expected_numbytes += tensor_fp8.nbytes + tensor_fp8_t.nbytes # output
self.assertEqual(expected_numbytes, metrics.num_bytes_accessed)
def test_outer_dimension_softmax(self):
"""
This test repros the not able to fuse problem for outer dimension
softmax reported here: https://github.com/pytorch/pytorch/issues/93718
Perf data on h100:
- without loop ordering after fusion 0.564 ms
- with loop ordering after fusion 0.302 ms
This is 1.87x speedup.
"""
x = torch.randn(32, 2**21, device=GPU_TYPE)
def f(x):
return F.softmax(x, dim=0)
self.do_acc_test(f, x)
self.assertEqual(1, metrics.generated_kernel_count)
def test_outer_dimension_sum_fuse_with_pw(self):
"""
Test the fusion of an outer dimension sum with a followed pointwise.
Perf data on h100:
- without loop ordering after fusion 0.436 ms
- with loop ordering after fusion 0.260 ms
This is 1.68x speedup.
"""
x = torch.randn(32, 2**21, device=GPU_TYPE)
def f(x):
return x.sum(dim=0, keepdim=True) + x
self.do_acc_test(f, x)
self.assertEqual(1, metrics.generated_kernel_count)
if DO_PERF_TEST:
from triton.testing import do_bench
optf = torch.compile(f)
print(f"ms={do_bench(lambda: optf(x))}")
# Disable split reduction to make it easier to calculate the expected
# number of bytes accessed. In this case, split reduction does not
# help perf much.
@inductor_config.patch(split_reductions=False)
def test_fuse_reduction_with_tiled_pw(self):
def f(x):
y = torch.sum(torch.sum(x, dim=-1))
z = x / 10.0
z_t = z.t().contiguous().t()
return y, z, z_t
# use this input sizes to test for perf
if DO_PERF_TEST:
M, N = 1024 * 32, 1024 * 8
else:
M, N = 200, 100
x = torch.randn(M, N, device=GPU_TYPE)
actual = f(x)
opt_f = torch.compile(f)
expected = opt_f(x)
self.assertTrue(same(actual, expected, tol=1e-3))
# We should fuse the first sum with the two pointwise.
# Overall we read x once for all these three kernels and write
# out 2 buffers with the same size as x.
# This should be sort of 'optimal' for this workload.
expected_numbytes = x.nbytes * 3
# A small amount of extra memory access for:
# - store output for the first reduction
# - load input for the second reduction
# - store output for the second reduction
expected_numbytes += (M * 2 + 1) * x.itemsize
print(expected_numbytes)
self.assertEqual(expected_numbytes, metrics.num_bytes_accessed)
if DO_PERF_TEST:
from triton.testing import do_bench
ms = do_bench(lambda: opt_f(x))
print(f"{ms=:.3f}")
@inductor_config.patch(
{
"max_autotune": True,
"max_autotune_gemm_backends": "TRITON",
"test_configs.max_mm_configs": 4,
}
)
@skipUnless(HAS_GPU and is_big_gpu(), "Need big gpu for max-autotune")
def test_interaction_with_triton_template(self):
"""
Make sure the dependency prefix for TritonTempalate and its
prologue match.
"""
@torch.compile
def f(x, y):
return (x.expand([1, y.shape[0]]) + 1) @ y
x = torch.randn([1, 1], device=GPU_TYPE)
y = torch.randn([64, 128], device=GPU_TYPE)
out, code = run_and_get_code(f, x, y)
# well when benchmark_kernel flag is on, we have one more .run
# call in the benchmarking code.
FileCheck().check("def call(").check_count(
".run(", 1 + int(inductor_config.benchmark_kernel), exactly=True
).run(code[0])
@inductor_config.patch(
{
"max_autotune": True,
"max_autotune_gemm_backends": "TRITON",
"test_configs.max_mm_configs": 4,
}
)
@skipUnless(HAS_GPU and is_big_gpu(), "Need big gpu for max-autotune")
def test_interaction_with_multi_template(self):
"""
Skip MultiTemplateBuffer during loop reordering
"""
@torch.compile
def f(x, y):
return (x @ y), x + 1
N = 2
x = torch.randn([N, N], device=GPU_TYPE, dtype=torch.bfloat16)
y = torch.randn([N, N], device=GPU_TYPE, dtype=torch.bfloat16)
out, code = run_and_get_code(f, x, y)
# didn't fuse due to small savings
FileCheck().check_count("@triton.jit", 2, exactly=True).run(code[0])
def test_fuse_with_scalar_shared_memory(self):
"""
Make sure if we can fuse two nodes sharing a scalar before,
we can still do it with LOAF applied.
This is not really a big deal. But some tests rely on this and
less number of kernels has some small benefits.
"""
@torch.compile
def f(x):
return torch.mean(x)
x = torch.randn([5, 5], device=GPU_TYPE)
out, code = run_and_get_code(f, x)
FileCheck().check_count("@triton.jit", 1, exactly=True).run(code[0])
def test_3dred_pw_2d_outer_red(self):
"""
Test a pattern as follows. We have a 3d contiguous tensor [m, n, k] as input.
1. do reduction on the k dimension and get a [m, n] tensor
2. do a pointwise operation on this [m, n] tensor (and realize the computation)
3. do a outer reduction on the output of step 2 on the m dimension.
Each of these step generate a kernel before fusion.
Without any loop reorder, kernel 1 and kernel 2 will get fused. And kernel 3 will be separeate.
But if we reorder the loop for kernel 2, then kernel 2 will get fused with kernel 3.
And the fused kernel-2-3 can not be fused with kernel 1.
The older version of LOAF algorithm will do reorder in this case. But there is no real
benefits. There are even some slight downsides
1. the original fusion without loop reordering is more natural
2. fusion kernel 1 with kernel 2 may help precision when the output of kernel 1 is in low precision.
By fusion kernel 1 and kernel 2, the pointwise operation will operate on fp32 precision thanks
to fusion.
"""
M, N, K = 64, 64, 64
def f(x):
x = x.sum(dim=-1)
x = x + 1 # can be more complex like sigmoid or other ops
return x, x.sum(dim=0)
x = torch.randn(M, N, K, device=GPU_TYPE)
self.do_acc_test(f, x)
self.assertEqual(0, metrics.num_loop_reordering)
@inductor_config.patch(
{
"triton.unique_kernel_names": True,
"loop_ordering_after_fusion": True,
"triton.max_tiles": 3,
"triton.coalesce_tiling_analysis": True,
}
)
@instantiate_parametrized_tests
| LoopOrderingTest |
python | scrapy__scrapy | tests/AsyncCrawlerProcess/twisted_reactor_custom_settings.py | {
"start": 63,
"end": 336
} | class ____(scrapy.Spider):
name = "asyncio_reactor"
custom_settings = {
"TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor",
}
process = AsyncCrawlerProcess()
process.crawl(AsyncioReactorSpider)
process.start()
| AsyncioReactorSpider |
python | great-expectations__great_expectations | great_expectations/core/serializer.py | {
"start": 1709,
"end": 2189
} | class ____(AbstractConfigSerializer):
@override
def serialize(self, obj: AbstractConfig) -> dict:
"""Serialize to Python dictionary.
This is typically the default implementation used in can be overridden in subclasses.
Args:
obj: Object to serialize.
Returns:
Representation of object as a Python dictionary using the defined Marshmallow schema.
"""
return self.schema.dump(obj)
| DictConfigSerializer |
python | kubernetes-client__python | kubernetes/client/models/v1_device_request_allocation_result.py | {
"start": 383,
"end": 17477
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'admin_access': 'bool',
'binding_conditions': 'list[str]',
'binding_failure_conditions': 'list[str]',
'consumed_capacity': 'dict(str, str)',
'device': 'str',
'driver': 'str',
'pool': 'str',
'request': 'str',
'share_id': 'str',
'tolerations': 'list[V1DeviceToleration]'
}
attribute_map = {
'admin_access': 'adminAccess',
'binding_conditions': 'bindingConditions',
'binding_failure_conditions': 'bindingFailureConditions',
'consumed_capacity': 'consumedCapacity',
'device': 'device',
'driver': 'driver',
'pool': 'pool',
'request': 'request',
'share_id': 'shareID',
'tolerations': 'tolerations'
}
def __init__(self, admin_access=None, binding_conditions=None, binding_failure_conditions=None, consumed_capacity=None, device=None, driver=None, pool=None, request=None, share_id=None, tolerations=None, local_vars_configuration=None): # noqa: E501
"""V1DeviceRequestAllocationResult - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._admin_access = None
self._binding_conditions = None
self._binding_failure_conditions = None
self._consumed_capacity = None
self._device = None
self._driver = None
self._pool = None
self._request = None
self._share_id = None
self._tolerations = None
self.discriminator = None
if admin_access is not None:
self.admin_access = admin_access
if binding_conditions is not None:
self.binding_conditions = binding_conditions
if binding_failure_conditions is not None:
self.binding_failure_conditions = binding_failure_conditions
if consumed_capacity is not None:
self.consumed_capacity = consumed_capacity
self.device = device
self.driver = driver
self.pool = pool
self.request = request
if share_id is not None:
self.share_id = share_id
if tolerations is not None:
self.tolerations = tolerations
@property
def admin_access(self):
"""Gets the admin_access of this V1DeviceRequestAllocationResult. # noqa: E501
AdminAccess indicates that this device was allocated for administrative access. See the corresponding request field for a definition of mode. This is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled. # noqa: E501
:return: The admin_access of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: bool
"""
return self._admin_access
@admin_access.setter
def admin_access(self, admin_access):
"""Sets the admin_access of this V1DeviceRequestAllocationResult.
AdminAccess indicates that this device was allocated for administrative access. See the corresponding request field for a definition of mode. This is an alpha field and requires enabling the DRAAdminAccess feature gate. Admin access is disabled if this field is unset or set to false, otherwise it is enabled. # noqa: E501
:param admin_access: The admin_access of this V1DeviceRequestAllocationResult. # noqa: E501
:type: bool
"""
self._admin_access = admin_access
@property
def binding_conditions(self):
"""Gets the binding_conditions of this V1DeviceRequestAllocationResult. # noqa: E501
BindingConditions contains a copy of the BindingConditions from the corresponding ResourceSlice at the time of allocation. This is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates. # noqa: E501
:return: The binding_conditions of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: list[str]
"""
return self._binding_conditions
@binding_conditions.setter
def binding_conditions(self, binding_conditions):
"""Sets the binding_conditions of this V1DeviceRequestAllocationResult.
BindingConditions contains a copy of the BindingConditions from the corresponding ResourceSlice at the time of allocation. This is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates. # noqa: E501
:param binding_conditions: The binding_conditions of this V1DeviceRequestAllocationResult. # noqa: E501
:type: list[str]
"""
self._binding_conditions = binding_conditions
@property
def binding_failure_conditions(self):
"""Gets the binding_failure_conditions of this V1DeviceRequestAllocationResult. # noqa: E501
BindingFailureConditions contains a copy of the BindingFailureConditions from the corresponding ResourceSlice at the time of allocation. This is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates. # noqa: E501
:return: The binding_failure_conditions of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: list[str]
"""
return self._binding_failure_conditions
@binding_failure_conditions.setter
def binding_failure_conditions(self, binding_failure_conditions):
"""Sets the binding_failure_conditions of this V1DeviceRequestAllocationResult.
BindingFailureConditions contains a copy of the BindingFailureConditions from the corresponding ResourceSlice at the time of allocation. This is an alpha field and requires enabling the DRADeviceBindingConditions and DRAResourceClaimDeviceStatus feature gates. # noqa: E501
:param binding_failure_conditions: The binding_failure_conditions of this V1DeviceRequestAllocationResult. # noqa: E501
:type: list[str]
"""
self._binding_failure_conditions = binding_failure_conditions
@property
def consumed_capacity(self):
"""Gets the consumed_capacity of this V1DeviceRequestAllocationResult. # noqa: E501
ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. The consumed amount may differ from the requested amount: it is rounded up to the nearest valid value based on the device’s requestPolicy if applicable (i.e., may not be less than the requested amount). The total consumed capacity for each device must not exceed the DeviceCapacity's Value. This field is populated only for devices that allow multiple allocations. All capacity entries are included, even if the consumed amount is zero. # noqa: E501
:return: The consumed_capacity of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: dict(str, str)
"""
return self._consumed_capacity
@consumed_capacity.setter
def consumed_capacity(self, consumed_capacity):
"""Sets the consumed_capacity of this V1DeviceRequestAllocationResult.
ConsumedCapacity tracks the amount of capacity consumed per device as part of the claim request. The consumed amount may differ from the requested amount: it is rounded up to the nearest valid value based on the device’s requestPolicy if applicable (i.e., may not be less than the requested amount). The total consumed capacity for each device must not exceed the DeviceCapacity's Value. This field is populated only for devices that allow multiple allocations. All capacity entries are included, even if the consumed amount is zero. # noqa: E501
:param consumed_capacity: The consumed_capacity of this V1DeviceRequestAllocationResult. # noqa: E501
:type: dict(str, str)
"""
self._consumed_capacity = consumed_capacity
@property
def device(self):
"""Gets the device of this V1DeviceRequestAllocationResult. # noqa: E501
Device references one device instance via its name in the driver's resource pool. It must be a DNS label. # noqa: E501
:return: The device of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: str
"""
return self._device
@device.setter
def device(self, device):
"""Sets the device of this V1DeviceRequestAllocationResult.
Device references one device instance via its name in the driver's resource pool. It must be a DNS label. # noqa: E501
:param device: The device of this V1DeviceRequestAllocationResult. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and device is None: # noqa: E501
raise ValueError("Invalid value for `device`, must not be `None`") # noqa: E501
self._device = device
@property
def driver(self):
"""Gets the driver of this V1DeviceRequestAllocationResult. # noqa: E501
Driver specifies the name of the DRA driver whose kubelet plugin should be invoked to process the allocation once the claim is needed on a node. Must be a DNS subdomain and should end with a DNS domain owned by the vendor of the driver. # noqa: E501
:return: The driver of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: str
"""
return self._driver
@driver.setter
def driver(self, driver):
"""Sets the driver of this V1DeviceRequestAllocationResult.
Driver specifies the name of the DRA driver whose kubelet plugin should be invoked to process the allocation once the claim is needed on a node. Must be a DNS subdomain and should end with a DNS domain owned by the vendor of the driver. # noqa: E501
:param driver: The driver of this V1DeviceRequestAllocationResult. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and driver is None: # noqa: E501
raise ValueError("Invalid value for `driver`, must not be `None`") # noqa: E501
self._driver = driver
@property
def pool(self):
"""Gets the pool of this V1DeviceRequestAllocationResult. # noqa: E501
This name together with the driver name and the device name field identify which device was allocated (`<driver name>/<pool name>/<device name>`). Must not be longer than 253 characters and may contain one or more DNS sub-domains separated by slashes. # noqa: E501
:return: The pool of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: str
"""
return self._pool
@pool.setter
def pool(self, pool):
"""Sets the pool of this V1DeviceRequestAllocationResult.
This name together with the driver name and the device name field identify which device was allocated (`<driver name>/<pool name>/<device name>`). Must not be longer than 253 characters and may contain one or more DNS sub-domains separated by slashes. # noqa: E501
:param pool: The pool of this V1DeviceRequestAllocationResult. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and pool is None: # noqa: E501
raise ValueError("Invalid value for `pool`, must not be `None`") # noqa: E501
self._pool = pool
@property
def request(self):
"""Gets the request of this V1DeviceRequestAllocationResult. # noqa: E501
Request is the name of the request in the claim which caused this device to be allocated. If it references a subrequest in the firstAvailable list on a DeviceRequest, this field must include both the name of the main request and the subrequest using the format <main request>/<subrequest>. Multiple devices may have been allocated per request. # noqa: E501
:return: The request of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: str
"""
return self._request
@request.setter
def request(self, request):
"""Sets the request of this V1DeviceRequestAllocationResult.
Request is the name of the request in the claim which caused this device to be allocated. If it references a subrequest in the firstAvailable list on a DeviceRequest, this field must include both the name of the main request and the subrequest using the format <main request>/<subrequest>. Multiple devices may have been allocated per request. # noqa: E501
:param request: The request of this V1DeviceRequestAllocationResult. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and request is None: # noqa: E501
raise ValueError("Invalid value for `request`, must not be `None`") # noqa: E501
self._request = request
@property
def share_id(self):
"""Gets the share_id of this V1DeviceRequestAllocationResult. # noqa: E501
ShareID uniquely identifies an individual allocation share of the device, used when the device supports multiple simultaneous allocations. It serves as an additional map key to differentiate concurrent shares of the same device. # noqa: E501
:return: The share_id of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: str
"""
return self._share_id
@share_id.setter
def share_id(self, share_id):
"""Sets the share_id of this V1DeviceRequestAllocationResult.
ShareID uniquely identifies an individual allocation share of the device, used when the device supports multiple simultaneous allocations. It serves as an additional map key to differentiate concurrent shares of the same device. # noqa: E501
:param share_id: The share_id of this V1DeviceRequestAllocationResult. # noqa: E501
:type: str
"""
self._share_id = share_id
@property
def tolerations(self):
"""Gets the tolerations of this V1DeviceRequestAllocationResult. # noqa: E501
A copy of all tolerations specified in the request at the time when the device got allocated. The maximum number of tolerations is 16. This is an alpha field and requires enabling the DRADeviceTaints feature gate. # noqa: E501
:return: The tolerations of this V1DeviceRequestAllocationResult. # noqa: E501
:rtype: list[V1DeviceToleration]
"""
return self._tolerations
@tolerations.setter
def tolerations(self, tolerations):
"""Sets the tolerations of this V1DeviceRequestAllocationResult.
A copy of all tolerations specified in the request at the time when the device got allocated. The maximum number of tolerations is 16. This is an alpha field and requires enabling the DRADeviceTaints feature gate. # noqa: E501
:param tolerations: The tolerations of this V1DeviceRequestAllocationResult. # noqa: E501
:type: list[V1DeviceToleration]
"""
self._tolerations = tolerations
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1DeviceRequestAllocationResult):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1DeviceRequestAllocationResult):
return True
return self.to_dict() != other.to_dict()
| V1DeviceRequestAllocationResult |
python | davidhalter__jedi | jedi/inference/helpers.py | {
"start": 4321,
"end": 5943
} | class ____(Exception):
pass
@contextmanager
def reraise_getitem_errors(*exception_classes):
try:
yield
except exception_classes as e:
raise SimpleGetItemNotFound(e)
def parse_dotted_names(nodes, is_import_from, until_node=None):
level = 0
names = []
for node in nodes[1:]:
if node in ('.', '...'):
if not names:
level += len(node.value)
elif node.type == 'dotted_name':
for n in node.children[::2]:
names.append(n)
if n is until_node:
break
else:
continue
break
elif node.type == 'name':
names.append(node)
if node is until_node:
break
elif node == ',':
if not is_import_from:
names = []
else:
# Here if the keyword `import` comes along it stops checking
# for names.
break
return level, names
def values_from_qualified_names(inference_state, *names):
return inference_state.import_module(names[:-1]).py__getattribute__(names[-1])
def is_big_annoying_library(context):
string_names = context.get_root_context().string_names
if string_names is None:
return False
# Especially pandas and tensorflow are huge complicated Python libraries
# that get even slower than they already are when Jedi tries to undrstand
# dynamic features like decorators, ifs and other stuff.
return string_names[0] in ('pandas', 'numpy', 'tensorflow', 'matplotlib')
| SimpleGetItemNotFound |
python | gevent__gevent | src/gevent/_config.py | {
"start": 11308,
"end": 11547
} | class ____(ImportableSetting, Setting):
name = 'format_context'
# using pprint.pformat can override custom __repr__ methods on dict/list
# subclasses, which can be a security concern
default = 'pprint.saferepr'
| FormatContext |
python | PyCQA__pylint | tests/functional/n/no/no_member_assign_same_line.py | {
"start": 164,
"end": 280
} | class ____:
"""Member defined in superclass."""
def __init__(self):
self.member = True
| ClassWithMember |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 20807,
"end": 22886
} | class ____(SingleContinuousDistribution):
_argnames = ('k',)
@staticmethod
def check(k):
_value_check(k > 0, "Number of degrees of freedom (k) must be positive.")
_value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.")
set = Interval(0, oo)
def pdf(self, x):
return 2**(1 - self.k/2)*x**(self.k - 1)*exp(-x**2/2)/gamma(self.k/2)
def _characteristic_function(self, t):
k = self.k
part_1 = hyper((k/2,), (S.Half,), -t**2/2)
part_2 = I*t*sqrt(2)*gamma((k+1)/2)/gamma(k/2)
part_3 = hyper(((k+1)/2,), (Rational(3, 2),), -t**2/2)
return part_1 + part_2*part_3
def _moment_generating_function(self, t):
k = self.k
part_1 = hyper((k / 2,), (S.Half,), t ** 2 / 2)
part_2 = t * sqrt(2) * gamma((k + 1) / 2) / gamma(k / 2)
part_3 = hyper(((k + 1) / 2,), (S(3) / 2,), t ** 2 / 2)
return part_1 + part_2 * part_3
def Chi(name, k):
r"""
Create a continuous random variable with a Chi distribution.
The density of the Chi distribution is given by
.. math::
f(x) := \frac{2^{1-k/2}x^{k-1}e^{-x^2/2}}{\Gamma(k/2)}
with :math:`x \geq 0`.
Parameters
==========
k : Positive integer, The number of degrees of freedom
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import Chi, density, E
>>> from sympy import Symbol, simplify
>>> k = Symbol("k", integer=True)
>>> z = Symbol("z")
>>> X = Chi("x", k)
>>> density(X)(z)
2**(1 - k/2)*z**(k - 1)*exp(-z**2/2)/gamma(k/2)
>>> simplify(E(X))
sqrt(2)*gamma(k/2 + 1/2)/gamma(k/2)
References
==========
.. [1] https://en.wikipedia.org/wiki/Chi_distribution
.. [2] https://mathworld.wolfram.com/ChiDistribution.html
"""
return rv(name, ChiDistribution, (k,))
#-------------------------------------------------------------------------------
# Non-central Chi distribution -------------------------------------------------
| ChiDistribution |
python | django__django | django/core/management/commands/loaddata.py | {
"start": 15600,
"end": 16008
} | class ____(zipfile.ZipFile):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if len(self.namelist()) != 1:
raise ValueError("Zip-compressed fixtures must contain one file.")
def read(self):
return zipfile.ZipFile.read(self, self.namelist()[0])
def humanize(dirname):
return "'%s'" % dirname if dirname else "absolute path"
| SingleZipReader |
python | django-crispy-forms__django-crispy-forms | crispy_forms/layout.py | {
"start": 11057,
"end": 13301
} | class ____(BaseInput):
"""
Used to create a button descriptor for the {% crispy %} template tag.
Attributes
----------
template: str
The default template which this Layout Object will be rendered
with.
field_classes: str
CSS classes to be applied to the ``<input>``.
input_type: str
The ``type`` attribute of the ``<input>``.
Parameters
----------
name : str
The name attribute of the button.
value : str
The value attribute of the button.
css_id : str, optional
A custom DOM id for the layout object. If not provided the name
argument is slugified and turned into the id for the submit button.
By default None.
css_class : str, optional
Additional CSS classes to be applied to the ``<input>``. By default
None.
template : str, optional
Overrides the default template, if provided. By default None.
**kwargs : dict, optional
Additional attributes are passed to `flatatt` and converted into
key="value", pairs. These attributes are added to the ``<input>``.
Examples
--------
Note: ``form`` arg to ``render()`` is not required for ``BaseInput``
inherited objects.
>>> button = Button('Button 1', 'Press Me!')
>>> button.render("", "", Context())
'<input type="button" name="button-1" value="Press Me!" '
'class="btn" id="button-id-button-1"/>'
>>> button = Button('Button 1', 'Press Me!', css_id="custom-id",
css_class="custom class", my_attr=True, data="my-data")
>>> button.render("", "", Context())
'<input type="button" name="button-1" value="Press Me!" '
'class="btn custom class" id="custom-id" data="my-data" my-attr/>'
Usually you will not call the render method on the object directly. Instead
add it to your ``Layout`` manually or use the `add_input` method::
class ExampleForm(forms.Form):
[...]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.add_input(Button('Button 1', 'Press Me!'))
"""
input_type = "button"
field_classes = "btn"
| Button |
python | ray-project__ray | python/ray/_private/gcs_pubsub.py | {
"start": 7433,
"end": 8474
} | class ____(_AioSubscriber):
def __init__(
self,
worker_id: bytes = None,
address: str = None,
channel: grpc.Channel = None,
):
super().__init__(pubsub_pb2.GCS_ACTOR_CHANNEL, worker_id, address, channel)
@property
def queue_size(self):
return len(self._queue)
async def poll(
self, batch_size, timeout=None
) -> List[Tuple[bytes, gcs_pb2.ActorTableData]]:
"""Polls for new actor message.
Returns:
A list of tuples of binary actor ID and actor table data.
"""
await self._poll(timeout=timeout)
return self._pop_actors(self._queue, batch_size=batch_size)
@staticmethod
def _pop_actors(queue, batch_size):
if len(queue) == 0:
return []
popped = 0
msgs = []
while len(queue) > 0 and popped < batch_size:
msg = queue.popleft()
msgs.append((msg.key_id, msg.actor_message))
popped += 1
return msgs
| GcsAioActorSubscriber |
python | explosion__spaCy | spacy/pipeline/entityruler.py | {
"start": 805,
"end": 20268
} | class ____(Pipe):
"""The EntityRuler lets you add spans to the `Doc.ents` using token-based
rules or exact phrase matches. It can be combined with the statistical
`EntityRecognizer` to boost accuracy, or used on its own to implement a
purely rule-based entity recognition system. After initialization, the
component is typically added to the pipeline using `nlp.add_pipe`.
DOCS: https://spacy.io/api/entityruler
USAGE: https://spacy.io/usage/rule-based-matching#entityruler
"""
def __init__(
self,
nlp: Language,
name: str = "entity_ruler",
*,
phrase_matcher_attr: Optional[Union[int, str]] = None,
matcher_fuzzy_compare: Callable = levenshtein_compare,
validate: bool = False,
overwrite_ents: bool = False,
ent_id_sep: str = DEFAULT_ENT_ID_SEP,
patterns: Optional[List[PatternType]] = None,
scorer: Optional[Callable] = entity_ruler_score,
) -> None:
"""Initialize the entity ruler. If patterns are supplied here, they
need to be a list of dictionaries with a `"label"` and `"pattern"`
key. A pattern can either be a token pattern (list) or a phrase pattern
(string). For example: `{'label': 'ORG', 'pattern': 'Apple'}`.
nlp (Language): The shared nlp object to pass the vocab to the matchers
and process phrase patterns.
name (str): Instance name of the current pipeline component. Typically
passed in automatically from the factory when the component is
added. Used to disable the current entity ruler while creating
phrase patterns with the nlp object.
phrase_matcher_attr (int / str): Token attribute to match on, passed
to the internal PhraseMatcher as `attr`.
matcher_fuzzy_compare (Callable): The fuzzy comparison method for the
internal Matcher. Defaults to
spacy.matcher.levenshtein.levenshtein_compare.
validate (bool): Whether patterns should be validated, passed to
Matcher and PhraseMatcher as `validate`
patterns (iterable): Optional patterns to load in.
overwrite_ents (bool): If existing entities are present, e.g. entities
added by the model, overwrite them by matches if necessary.
ent_id_sep (str): Separator used internally for entity IDs.
scorer (Optional[Callable]): The scoring method. Defaults to
spacy.scorer.get_ner_prf.
DOCS: https://spacy.io/api/entityruler#init
"""
self.nlp = nlp
self.name = name
self.overwrite = overwrite_ents
self.token_patterns = defaultdict(list) # type: ignore
self.phrase_patterns = defaultdict(list) # type: ignore
self._validate = validate
self.matcher_fuzzy_compare = matcher_fuzzy_compare
self.matcher = Matcher(
nlp.vocab, validate=validate, fuzzy_compare=self.matcher_fuzzy_compare
)
self.phrase_matcher_attr = phrase_matcher_attr
self.phrase_matcher = PhraseMatcher(
nlp.vocab, attr=self.phrase_matcher_attr, validate=validate
)
self.ent_id_sep = ent_id_sep
self._ent_ids = defaultdict(tuple) # type: ignore
if patterns is not None:
self.add_patterns(patterns)
self.scorer = scorer
def __len__(self) -> int:
"""The number of all patterns added to the entity ruler."""
n_token_patterns = sum(len(p) for p in self.token_patterns.values())
n_phrase_patterns = sum(len(p) for p in self.phrase_patterns.values())
return n_token_patterns + n_phrase_patterns
def __contains__(self, label: str) -> bool:
"""Whether a label is present in the patterns."""
return label in self.token_patterns or label in self.phrase_patterns
def __call__(self, doc: Doc) -> Doc:
"""Find matches in document and add them as entities.
doc (Doc): The Doc object in the pipeline.
RETURNS (Doc): The Doc with added entities, if available.
DOCS: https://spacy.io/api/entityruler#call
"""
error_handler = self.get_error_handler()
try:
matches = self.match(doc)
self.set_annotations(doc, matches)
return doc
except Exception as e:
return error_handler(self.name, self, [doc], e)
def match(self, doc: Doc):
self._require_patterns()
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="\\[W036")
matches = list(self.matcher(doc)) + list(self.phrase_matcher(doc))
final_matches = set(
[(m_id, start, end) for m_id, start, end in matches if start != end]
)
get_sort_key = lambda m: (m[2] - m[1], -m[1])
final_matches = sorted(final_matches, key=get_sort_key, reverse=True)
return final_matches
def set_annotations(self, doc, matches):
"""Modify the document in place"""
entities = list(doc.ents)
new_entities = []
seen_tokens = set()
for match_id, start, end in matches:
if any(t.ent_type for t in doc[start:end]) and not self.overwrite:
continue
# check for end - 1 here because boundaries are inclusive
if start not in seen_tokens and end - 1 not in seen_tokens:
if match_id in self._ent_ids:
label, ent_id = self._ent_ids[match_id]
span = Span(doc, start, end, label=label, span_id=ent_id)
else:
span = Span(doc, start, end, label=match_id)
new_entities.append(span)
entities = [
e for e in entities if not (e.start < end and e.end > start)
]
seen_tokens.update(range(start, end))
doc.ents = entities + new_entities
@property
def labels(self) -> Tuple[str, ...]:
"""All labels present in the match patterns.
RETURNS (set): The string labels.
DOCS: https://spacy.io/api/entityruler#labels
"""
keys = set(self.token_patterns.keys())
keys.update(self.phrase_patterns.keys())
all_labels = set()
for l in keys:
if self.ent_id_sep in l:
label, _ = self._split_label(l)
all_labels.add(label)
else:
all_labels.add(l)
return tuple(sorted(all_labels))
def initialize(
self,
get_examples: Callable[[], Iterable[Example]],
*,
nlp: Optional[Language] = None,
patterns: Optional[Sequence[PatternType]] = None,
):
"""Initialize the pipe for training.
get_examples (Callable[[], Iterable[Example]]): Function that
returns a representative sample of gold-standard Example objects.
nlp (Language): The current nlp object the component is part of.
patterns Optional[Iterable[PatternType]]: The list of patterns.
DOCS: https://spacy.io/api/entityruler#initialize
"""
self.clear()
if patterns:
self.add_patterns(patterns) # type: ignore[arg-type]
@property
def ent_ids(self) -> Tuple[Optional[str], ...]:
"""All entity ids present in the match patterns `id` properties
RETURNS (set): The string entity ids.
DOCS: https://spacy.io/api/entityruler#ent_ids
"""
keys = set(self.token_patterns.keys())
keys.update(self.phrase_patterns.keys())
all_ent_ids = set()
for l in keys:
if self.ent_id_sep in l:
_, ent_id = self._split_label(l)
all_ent_ids.add(ent_id)
return tuple(all_ent_ids)
@property
def patterns(self) -> List[PatternType]:
"""Get all patterns that were added to the entity ruler.
RETURNS (list): The original patterns, one dictionary per pattern.
DOCS: https://spacy.io/api/entityruler#patterns
"""
all_patterns = []
for label, patterns in self.token_patterns.items():
for pattern in patterns:
ent_label, ent_id = self._split_label(label)
p = {"label": ent_label, "pattern": pattern}
if ent_id:
p["id"] = ent_id
all_patterns.append(p)
for label, patterns in self.phrase_patterns.items():
for pattern in patterns:
ent_label, ent_id = self._split_label(label)
p = {"label": ent_label, "pattern": pattern.text}
if ent_id:
p["id"] = ent_id
all_patterns.append(p)
return all_patterns
def add_patterns(self, patterns: List[PatternType]) -> None:
"""Add patterns to the entity ruler. A pattern can either be a token
pattern (list of dicts) or a phrase pattern (string). For example:
{'label': 'ORG', 'pattern': 'Apple'}
{'label': 'GPE', 'pattern': [{'lower': 'san'}, {'lower': 'francisco'}]}
patterns (list): The patterns to add.
DOCS: https://spacy.io/api/entityruler#add_patterns
"""
# disable the nlp components after this one in case they hadn't been initialized / deserialised yet
try:
current_index = -1
for i, (name, pipe) in enumerate(self.nlp.pipeline):
if self == pipe:
current_index = i
break
subsequent_pipes = [pipe for pipe in self.nlp.pipe_names[current_index:]]
except ValueError:
subsequent_pipes = []
with self.nlp.select_pipes(disable=subsequent_pipes):
token_patterns = []
phrase_pattern_labels = []
phrase_pattern_texts = []
phrase_pattern_ids = []
for entry in patterns:
if isinstance(entry["pattern"], str):
phrase_pattern_labels.append(entry["label"])
phrase_pattern_texts.append(entry["pattern"])
phrase_pattern_ids.append(entry.get("id"))
elif isinstance(entry["pattern"], list):
token_patterns.append(entry)
phrase_patterns = []
for label, pattern, ent_id in zip(
phrase_pattern_labels,
self.nlp.pipe(phrase_pattern_texts),
phrase_pattern_ids,
):
phrase_pattern = {"label": label, "pattern": pattern}
if ent_id:
phrase_pattern["id"] = ent_id
phrase_patterns.append(phrase_pattern)
for entry in token_patterns + phrase_patterns: # type: ignore[operator]
label = entry["label"] # type: ignore
if "id" in entry:
ent_label = label
label = self._create_label(label, entry["id"])
key = self.matcher._normalize_key(label)
self._ent_ids[key] = (ent_label, entry["id"])
pattern = entry["pattern"] # type: ignore
if isinstance(pattern, Doc):
self.phrase_patterns[label].append(pattern)
self.phrase_matcher.add(label, [pattern]) # type: ignore
elif isinstance(pattern, list):
self.token_patterns[label].append(pattern)
self.matcher.add(label, [pattern])
else:
raise ValueError(Errors.E097.format(pattern=pattern))
def clear(self) -> None:
"""Reset all patterns."""
self.token_patterns = defaultdict(list)
self.phrase_patterns = defaultdict(list)
self._ent_ids = defaultdict(tuple)
self.matcher = Matcher(
self.nlp.vocab,
validate=self._validate,
fuzzy_compare=self.matcher_fuzzy_compare,
)
self.phrase_matcher = PhraseMatcher(
self.nlp.vocab, attr=self.phrase_matcher_attr, validate=self._validate
)
def remove(self, ent_id: str) -> None:
"""Remove a pattern by its ent_id if a pattern with this ent_id was added before
ent_id (str): id of the pattern to be removed
RETURNS: None
DOCS: https://spacy.io/api/entityruler#remove
"""
label_id_pairs = [
(label, eid) for (label, eid) in self._ent_ids.values() if eid == ent_id
]
if not label_id_pairs:
raise ValueError(
Errors.E1024.format(attr_type="ID", label=ent_id, component=self.name)
)
created_labels = [
self._create_label(label, eid) for (label, eid) in label_id_pairs
]
# remove the patterns from self.phrase_patterns
self.phrase_patterns = defaultdict(
list,
{
label: val
for (label, val) in self.phrase_patterns.items()
if label not in created_labels
},
)
# remove the patterns from self.token_pattern
self.token_patterns = defaultdict(
list,
{
label: val
for (label, val) in self.token_patterns.items()
if label not in created_labels
},
)
# remove the patterns from self.token_pattern
for label in created_labels:
if label in self.phrase_matcher:
self.phrase_matcher.remove(label)
else:
self.matcher.remove(label)
def _require_patterns(self) -> None:
"""Raise a warning if this component has no patterns defined."""
if len(self) == 0:
warnings.warn(Warnings.W036.format(name=self.name))
def _split_label(self, label: str) -> Tuple[str, Optional[str]]:
"""Split Entity label into ent_label and ent_id if it contains self.ent_id_sep
label (str): The value of label in a pattern entry
RETURNS (tuple): ent_label, ent_id
"""
if self.ent_id_sep in label:
ent_label, ent_id = label.rsplit(self.ent_id_sep, 1)
else:
ent_label = label
ent_id = None # type: ignore
return ent_label, ent_id
def _create_label(self, label: Any, ent_id: Any) -> str:
"""Join Entity label with ent_id if the pattern has an `id` attribute
If ent_id is not a string, the label is returned as is.
label (str): The label to set for ent.label_
ent_id (str): The label
RETURNS (str): The ent_label joined with configured `ent_id_sep`
"""
if isinstance(ent_id, str):
label = f"{label}{self.ent_id_sep}{ent_id}"
return label
def from_bytes(
self, patterns_bytes: bytes, *, exclude: Iterable[str] = SimpleFrozenList()
) -> "EntityRuler":
"""Load the entity ruler from a bytestring.
patterns_bytes (bytes): The bytestring to load.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://spacy.io/api/entityruler#from_bytes
"""
cfg = srsly.msgpack_loads(patterns_bytes)
self.clear()
if isinstance(cfg, dict):
self.add_patterns(cfg.get("patterns", cfg))
self.overwrite = cfg.get("overwrite", False)
self.phrase_matcher_attr = cfg.get("phrase_matcher_attr", None)
self.phrase_matcher = PhraseMatcher(
self.nlp.vocab,
attr=self.phrase_matcher_attr,
)
self.ent_id_sep = cfg.get("ent_id_sep", DEFAULT_ENT_ID_SEP)
else:
self.add_patterns(cfg)
return self
def to_bytes(self, *, exclude: Iterable[str] = SimpleFrozenList()) -> bytes:
"""Serialize the entity ruler patterns to a bytestring.
RETURNS (bytes): The serialized patterns.
DOCS: https://spacy.io/api/entityruler#to_bytes
"""
serial = {
"overwrite": self.overwrite,
"ent_id_sep": self.ent_id_sep,
"phrase_matcher_attr": self.phrase_matcher_attr,
"patterns": self.patterns,
}
return srsly.msgpack_dumps(serial)
def from_disk(
self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList()
) -> "EntityRuler":
"""Load the entity ruler from a file. Expects a file containing
newline-delimited JSON (JSONL) with one entry per line.
path (str / Path): The JSONL file to load.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://spacy.io/api/entityruler#from_disk
"""
path = ensure_path(path)
self.clear()
depr_patterns_path = path.with_suffix(".jsonl")
if path.suffix == ".jsonl": # user provides a jsonl
if path.is_file:
patterns = srsly.read_jsonl(path)
self.add_patterns(patterns)
else:
raise ValueError(Errors.E1023.format(path=path))
elif depr_patterns_path.is_file():
patterns = srsly.read_jsonl(depr_patterns_path)
self.add_patterns(patterns)
elif path.is_dir(): # path is a valid directory
cfg = {}
deserializers_patterns = {
"patterns": lambda p: self.add_patterns(
srsly.read_jsonl(p.with_suffix(".jsonl"))
)
}
deserializers_cfg = {"cfg": lambda p: cfg.update(srsly.read_json(p))}
from_disk(path, deserializers_cfg, {})
self.overwrite = cfg.get("overwrite", False)
self.phrase_matcher_attr = cfg.get("phrase_matcher_attr")
self.ent_id_sep = cfg.get("ent_id_sep", DEFAULT_ENT_ID_SEP)
self.phrase_matcher = PhraseMatcher(
self.nlp.vocab, attr=self.phrase_matcher_attr
)
from_disk(path, deserializers_patterns, {})
else: # path is not a valid directory or file
raise ValueError(Errors.E146.format(path=path))
return self
def to_disk(
self, path: Union[str, Path], *, exclude: Iterable[str] = SimpleFrozenList()
) -> None:
"""Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (str / Path): The JSONL file to save.
DOCS: https://spacy.io/api/entityruler#to_disk
"""
path = ensure_path(path)
cfg = {
"overwrite": self.overwrite,
"phrase_matcher_attr": self.phrase_matcher_attr,
"ent_id_sep": self.ent_id_sep,
}
serializers = {
"patterns": lambda p: srsly.write_jsonl(
p.with_suffix(".jsonl"), self.patterns
),
"cfg": lambda p: srsly.write_json(p, cfg),
}
if path.suffix == ".jsonl": # user wants to save only JSONL
srsly.write_jsonl(path, self.patterns)
else:
to_disk(path, serializers, {})
# Setup backwards compatibility hook for factories
def __getattr__(name):
if name == "make_entity_ruler":
module = importlib.import_module("spacy.pipeline.factories")
return module.make_entity_ruler
raise AttributeError(f"module {__name__} has no attribute {name}")
| EntityRuler |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/tokenize_stage.py | {
"start": 2213,
"end": 3809
} | class ____(StatefulStageUDF):
def __init__(
self,
data_column: str,
expected_input_keys: List[str],
model: str,
):
"""
Initialize the DetokenizeUDF.
Args:
data_column: The data column name.
expected_input_keys: The expected input keys of the stage.
model: The model to use for the chat template.
"""
from transformers import AutoTokenizer
super().__init__(data_column, expected_input_keys)
model_path = download_model_files(
model_id=model,
mirror_config=None,
download_model=NodeModelDownloadable.TOKENIZER_ONLY,
download_extra_files=False,
)
self.tokenizer = get_cached_tokenizer(
AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
)
)
async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]:
"""
Detokenize the given batch.
Args:
batch: A list of rows to send.
Yields:
A generator of rows with the detokenized prompt.
"""
for row, generated_text in zip(
batch,
self.tokenizer.batch_decode(
[row["generated_tokens"] for row in batch],
skip_special_tokens=True,
),
):
yield {
self.IDX_IN_BATCH_COLUMN: row[self.IDX_IN_BATCH_COLUMN],
"generated_text": generated_text,
}
| DetokenizeUDF |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 75379,
"end": 76200
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.fc1 = torch.nn.Linear(5, 8).to(dtype=torch.float)
self.layer_norm = torch.nn.LayerNorm(8)
self.group_norm = torch.nn.GroupNorm(2, 8)
self.instance_norm1d = torch.nn.InstanceNorm1d(8)
self.instance_norm2d = torch.nn.InstanceNorm2d(8)
self.instance_norm3d = torch.nn.InstanceNorm3d(8)
def forward(self, x):
x = self.quant(x)
x = self.fc1(x)
x = self.layer_norm(x)
x = self.group_norm(x.unsqueeze(-1).repeat(1, 1, 3))
x = self.instance_norm1d(x)
x = self.instance_norm2d(x.unsqueeze(-1))
x = self.instance_norm3d(x.unsqueeze(-1))
return x
| NormalizationTestModel |
python | marshmallow-code__marshmallow | tests/test_utils.py | {
"start": 474,
"end": 1142
} | class ____(dict):
def __init__(self, x, y):
super().__init__({"x": x})
self.y = y
@pytest.mark.parametrize(
"obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}]
)
def test_get_value_from_object(obj):
assert utils.get_value(obj, "x") == 24
assert utils.get_value(obj, "y") == 42
def test_get_value_from_namedtuple_with_default():
p = PointNT(x=42, y=None)
# Default is only returned if key is not found
assert utils.get_value(p, "z", default=123) == 123
# since 'y' is an attribute, None is returned instead of the default
assert utils.get_value(p, "y", default=123) is None
| PointDict |
python | openai__openai-python | src/openai/types/beta/realtime/session.py | {
"start": 390,
"end": 700
} | class ____(BaseModel):
type: Optional[Literal["near_field", "far_field"]] = None
"""Type of noise reduction.
`near_field` is for close-talking microphones such as headphones, `far_field` is
for far-field microphones such as laptop or conference room microphones.
"""
| InputAudioNoiseReduction |
python | graphql-python__graphene | graphene/types/tests/test_scalar.py | {
"start": 3136,
"end": 4624
} | class ____:
def test_query(self):
"""
Test that a normal query works.
"""
value = 2**31
result = schema.execute("{ optional { bigInt(input: %s) } }" % value)
assert not result.errors
assert result.data == {"optional": {"bigInt": value}}
def test_optional_input(self):
"""
Test that we can provide a null value to an optional input
"""
result = schema.execute("{ optional { bigInt(input: null) } }")
assert not result.errors
assert result.data == {"optional": {"bigInt": None}}
def test_invalid_input(self):
"""
Test that if an invalid type is provided we get an error
"""
result = schema.execute('{ optional { bigInt(input: "20") } }')
assert result.errors
assert len(result.errors) == 1
assert (
result.errors[0].message == "Expected value of type 'BigInt', found \"20\"."
)
result = schema.execute('{ optional { bigInt(input: "a") } }')
assert result.errors
assert len(result.errors) == 1
assert (
result.errors[0].message == "Expected value of type 'BigInt', found \"a\"."
)
result = schema.execute("{ optional { bigInt(input: true) } }")
assert result.errors
assert len(result.errors) == 1
assert (
result.errors[0].message == "Expected value of type 'BigInt', found true."
)
| TestBigInt |
python | sympy__sympy | sympy/core/function.py | {
"start": 11775,
"end": 27393
} | class ____(Application, Expr):
r"""
Base class for applied mathematical functions.
It also serves as a constructor for undefined function classes.
See the :ref:`custom-functions` guide for details on how to subclass
``Function`` and what methods can be defined.
Examples
========
**Undefined Functions**
To create an undefined function, pass a string of the function name to
``Function``.
>>> from sympy import Function, Symbol
>>> x = Symbol('x')
>>> f = Function('f')
>>> g = Function('g')(x)
>>> f
f
>>> f(x)
f(x)
>>> g
g(x)
>>> f(x).diff(x)
Derivative(f(x), x)
>>> g.diff(x)
Derivative(g(x), x)
Assumptions can be passed to ``Function`` the same as with a
:class:`~.Symbol`. Alternatively, you can use a ``Symbol`` with
assumptions for the function name and the function will inherit the name
and assumptions associated with the ``Symbol``:
>>> f_real = Function('f', real=True)
>>> f_real(x).is_real
True
>>> f_real_inherit = Function(Symbol('f', real=True))
>>> f_real_inherit(x).is_real
True
Note that assumptions on a function are unrelated to the assumptions on
the variables it is called on. If you want to add a relationship, subclass
``Function`` and define custom assumptions handler methods. See the
:ref:`custom-functions-assumptions` section of the :ref:`custom-functions`
guide for more details.
**Custom Function Subclasses**
The :ref:`custom-functions` guide has several
:ref:`custom-functions-complete-examples` of how to subclass ``Function``
to create a custom function.
"""
@property
def _diff_wrt(self):
return False
@cacheit
def __new__(cls, *args, **options) -> type[AppliedUndef]: # type: ignore
# Handle calls like Function('f')
if cls is Function:
return UndefinedFunction(*args, **options) # type: ignore
else:
return cls._new_(*args, **options) # type: ignore
@classmethod
def _new_(cls, *args, **options) -> Expr:
n = len(args)
if not cls._valid_nargs(n):
# XXX: exception message must be in exactly this format to
# make it work with NumPy's functions like vectorize(). See,
# for example, https://github.com/numpy/numpy/issues/1697.
# The ideal solution would be just to attach metadata to
# the exception and change NumPy to take advantage of this.
temp = ('%(name)s takes %(qual)s %(args)s '
'argument%(plural)s (%(given)s given)')
raise TypeError(temp % {
'name': cls,
'qual': 'exactly' if len(cls.nargs) == 1 else 'at least',
'args': min(cls.nargs),
'plural': 's'*(min(cls.nargs) != 1),
'given': n})
evaluate = options.get('evaluate', global_parameters.evaluate)
result = super().__new__(cls, *args, **options)
if evaluate and isinstance(result, cls) and result.args:
_should_evalf = [cls._should_evalf(a) for a in result.args]
pr2 = min(_should_evalf)
if pr2 > 0:
pr = max(_should_evalf)
result = result.evalf(prec_to_dps(pr))
return _sympify(result)
@classmethod
def _should_evalf(cls, arg):
"""
Decide if the function should automatically evalf().
Explanation
===========
By default (in this implementation), this happens if (and only if) the
ARG is a floating point number (including complex numbers).
This function is used by __new__.
Returns the precision to evalf to, or -1 if it should not evalf.
"""
if arg.is_Float:
return arg._prec
if not arg.is_Add:
return -1
m = pure_complex(arg)
if m is None:
return -1
# the elements of m are of type Number, so have a _prec
return max(m[0]._prec, m[1]._prec)
@classmethod
def class_key(cls):
from sympy.sets.fancysets import Naturals0
funcs = {
'exp': 10,
'log': 11,
'sin': 20,
'cos': 21,
'tan': 22,
'cot': 23,
'sinh': 30,
'cosh': 31,
'tanh': 32,
'coth': 33,
'conjugate': 40,
're': 41,
'im': 42,
'arg': 43,
}
name = cls.__name__
try:
i = funcs[name]
except KeyError:
i = 0 if isinstance(cls.nargs, Naturals0) else 10000
return 4, i, name
def _eval_evalf(self, prec):
def _get_mpmath_func(fname):
"""Lookup mpmath function based on name"""
if isinstance(self, AppliedUndef):
# Shouldn't lookup in mpmath but might have ._imp_
return None
if not hasattr(mpmath, fname):
fname = MPMATH_TRANSLATIONS.get(fname, None)
if fname is None:
return None
return getattr(mpmath, fname)
_eval_mpmath = getattr(self, '_eval_mpmath', None)
if _eval_mpmath is None:
func = _get_mpmath_func(self.func.__name__)
args = self.args
else:
func, args = _eval_mpmath()
# Fall-back evaluation
if func is None:
imp = getattr(self, '_imp_', None)
if imp is None:
return None
try:
return Float(imp(*[i.evalf(prec) for i in self.args]), prec)
except (TypeError, ValueError):
return None
# Convert all args to mpf or mpc
# Convert the arguments to *higher* precision than requested for the
# final result.
# XXX + 5 is a guess, it is similar to what is used in evalf.py. Should
# we be more intelligent about it?
try:
args = [arg._to_mpmath(prec + 5) for arg in args]
def bad(m):
from mpmath import mpf, mpc
# the precision of an mpf value is the last element
# if that is 1 (and m[1] is not 1 which would indicate a
# power of 2), then the eval failed; so check that none of
# the arguments failed to compute to a finite precision.
# Note: An mpc value has two parts, the re and imag tuple;
# check each of those parts, too. Anything else is allowed to
# pass
if isinstance(m, mpf):
m = m._mpf_
return m[1] !=1 and m[-1] == 1
elif isinstance(m, mpc):
m, n = m._mpc_
return m[1] !=1 and m[-1] == 1 and \
n[1] !=1 and n[-1] == 1
else:
return False
if any(bad(a) for a in args):
raise ValueError # one or more args failed to compute with significance
except ValueError:
return
with mpmath.workprec(prec):
v = func(*args)
return Expr._from_mpmath(v, prec)
def _eval_derivative(self, s):
# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
i = 0
l = []
for a in self.args:
i += 1
da = a.diff(s)
if da.is_zero:
continue
try:
df = self.fdiff(i)
except ArgumentIndexError:
df = Function.fdiff(self, i)
l.append(df * da)
return Add(*l)
def _eval_is_commutative(self):
return fuzzy_and(a.is_commutative for a in self.args)
def _eval_is_meromorphic(self, x, a):
if not self.args:
return True
if any(arg.has(x) for arg in self.args[1:]):
return False
arg = self.args[0]
if not arg._eval_is_meromorphic(x, a):
return None
return fuzzy_not(type(self).is_singular(arg.subs(x, a)))
_singularities: FuzzyBool | tuple[Expr, ...] = None
@classmethod
def is_singular(cls, a):
"""
Tests whether the argument is an essential singularity
or a branch point, or the functions is non-holomorphic.
"""
ss = cls._singularities
if ss in (True, None, False):
return ss
return fuzzy_or(a.is_infinite if s is S.ComplexInfinity
else (a - s).is_zero for s in ss)
def _eval_aseries(self, n, args0, x, logx):
"""
Compute an asymptotic expansion around args0, in terms of self.args.
This function is only used internally by _eval_nseries and should not
be called directly; derived classes can overwrite this to implement
asymptotic expansions.
"""
raise PoleError(filldedent('''
Asymptotic expansion of %s around %s is
not implemented.''' % (type(self), args0)))
def _eval_nseries(self, x, n, logx, cdir=0):
"""
This function does compute series for multivariate functions,
but the expansion is always in terms of *one* variable.
Examples
========
>>> from sympy import atan2
>>> from sympy.abc import x, y
>>> atan2(x, y).series(x, n=2)
atan2(0, y) + x/y + O(x**2)
>>> atan2(x, y).series(y, n=2)
-y/x + atan2(x, 0) + O(y**2)
This function also computes asymptotic expansions, if necessary
and possible:
>>> from sympy import loggamma
>>> loggamma(1/x)._eval_nseries(x,0,None)
-1/x - log(x)/x + log(x)/2 + O(1)
"""
from .symbol import uniquely_named_symbol
from sympy.series.order import Order
from sympy.sets.sets import FiniteSet
args = self.args
args0 = [t.limit(x, 0) for t in args]
if any(t.is_finite is False for t in args0):
from .numbers import oo, zoo, nan
a = [t.as_leading_term(x, logx=logx) for t in args]
a0 = [t.limit(x, 0) for t in a]
if any(t.has(oo, -oo, zoo, nan) for t in a0):
return self._eval_aseries(n, args0, x, logx)
# Careful: the argument goes to oo, but only logarithmically so. We
# are supposed to do a power series expansion "around the
# logarithmic term". e.g.
# f(1+x+log(x))
# -> f(1+logx) + x*f'(1+logx) + O(x**2)
# where 'logx' is given in the argument
a = [t._eval_nseries(x, n, logx) for t in args]
z = [r - r0 for (r, r0) in zip(a, a0)]
p = [Dummy() for _ in z]
q = []
v = None
for ai, zi, pi in zip(a0, z, p):
if zi.has(x):
if v is not None:
raise NotImplementedError
q.append(ai + pi)
v = pi
else:
q.append(ai)
e1 = self.func(*q)
if v is None:
return e1
s = e1._eval_nseries(v, n, logx)
o = s.getO()
s = s.removeO()
s = s.subs(v, zi).expand() + Order(o.expr.subs(v, zi), x)
return s
if (self.func.nargs is S.Naturals0
or (self.func.nargs == FiniteSet(1) and args0[0])
or any(c > 1 for c in self.func.nargs)):
e = self
e1 = e.expand()
if e == e1:
#for example when e = sin(x+1) or e = sin(cos(x))
#let's try the general algorithm
if len(e.args) == 1:
# issue 14411
e = e.func(e.args[0].cancel())
term = e.subs(x, S.Zero)
if term.is_finite is False or term is S.NaN:
raise PoleError("Cannot expand %s around 0" % (self))
series = term
fact = S.One
_x = uniquely_named_symbol('xi', self)
e = e.subs(x, _x)
for i in range(1, n):
fact *= Rational(i)
e = e.diff(_x)
subs = e.subs(_x, S.Zero)
if subs is S.NaN:
# try to evaluate a limit if we have to
subs = e.limit(_x, S.Zero)
if subs.is_finite is False:
raise PoleError("Cannot expand %s around 0" % (self))
term = subs*(x**i)/fact
term = term.expand()
series += term
return series + Order(x**n, x)
return e1.nseries(x, n=n, logx=logx)
arg = self.args[0]
l = []
g = None
# try to predict a number of terms needed
nterms = n + 2
cf = Order(arg.as_leading_term(x), x).getn()
if cf != 0:
nterms = (n/cf).ceiling()
for i in range(nterms):
g = self.taylor_term(i, arg, g)
g = g.nseries(x, n=n, logx=logx)
l.append(g)
return Add(*l) + Order(x**n, x)
def fdiff(self, argindex=1):
"""
Returns the first derivative of the function.
"""
if not (1 <= argindex <= len(self.args)):
raise ArgumentIndexError(self, argindex)
ix = argindex - 1
A = self.args[ix]
if A._diff_wrt:
if len(self.args) == 1 or not A.is_Symbol:
return _derivative_dispatch(self, A)
for i, v in enumerate(self.args):
if i != ix and A in v.free_symbols:
# it can't be in any other argument's free symbols
# issue 8510
break
else:
return _derivative_dispatch(self, A)
# See issue 4624 and issue 4719, 5600 and 8510
D = Dummy('xi_%i' % argindex, dummy_index=hash(A))
args = self.args[:ix] + (D,) + self.args[ix + 1:]
return Subs(Derivative(self.func(*args), D), D, A)
def _eval_as_leading_term(self, x, logx, cdir):
"""Stub that should be overridden by new Functions to return
the first non-zero term in a series if ever an x-dependent
argument whose leading term vanishes as x -> 0 might be encountered.
See, for example, cos._eval_as_leading_term.
"""
from sympy.series.order import Order
args = [a.as_leading_term(x, logx=logx) for a in self.args]
o = Order(1, x)
if any(x in a.free_symbols and o.contains(a) for a in args):
# Whereas x and any finite number are contained in O(1, x),
# expressions like 1/x are not. If any arg simplified to a
# vanishing expression as x -> 0 (like x or x**2, but not
# 3, 1/x, etc...) then the _eval_as_leading_term is needed
# to supply the first non-zero term of the series,
#
# e.g. expression leading term
# ---------- ------------
# cos(1/x) cos(1/x)
# cos(cos(x)) cos(1)
# cos(x) 1 <- _eval_as_leading_term needed
# sin(x) x <- _eval_as_leading_term needed
#
raise NotImplementedError(
'%s has no _eval_as_leading_term routine' % self.func)
else:
return self
| Function |
python | python-openxml__python-docx | src/docx/opc/package.py | {
"start": 6979,
"end": 8727
} | class ____:
"""Hosts static methods for unmarshalling a package from a |PackageReader|."""
@staticmethod
def unmarshal(pkg_reader, package, part_factory):
"""Construct graph of parts and realized relationships based on the contents of
`pkg_reader`, delegating construction of each part to `part_factory`.
Package relationships are added to `pkg`.
"""
parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory)
Unmarshaller._unmarshal_relationships(pkg_reader, package, parts)
for part in parts.values():
part.after_unmarshal()
package.after_unmarshal()
@staticmethod
def _unmarshal_parts(pkg_reader, package, part_factory):
"""Return a dictionary of |Part| instances unmarshalled from `pkg_reader`, keyed
by partname.
Side-effect is that each part in `pkg_reader` is constructed using
`part_factory`.
"""
parts = {}
for partname, content_type, reltype, blob in pkg_reader.iter_sparts():
parts[partname] = part_factory(partname, content_type, reltype, blob, package)
return parts
@staticmethod
def _unmarshal_relationships(pkg_reader, package, parts):
"""Add a relationship to the source object corresponding to each of the
relationships in `pkg_reader` with its target_part set to the actual target part
in `parts`."""
for source_uri, srel in pkg_reader.iter_srels():
source = package if source_uri == "/" else parts[source_uri]
target = srel.target_ref if srel.is_external else parts[srel.target_partname]
source.load_rel(srel.reltype, target, srel.rId, srel.is_external)
| Unmarshaller |
python | keon__algorithms | algorithms/linkedlist/intersection.py | {
"start": 1471,
"end": 2155
} | class ____(unittest.TestCase):
def test_intersection(self):
# create linked list as:
# 1 -> 3 -> 5
# \
# 7 -> 9 -> 11
# /
# 2 -> 4 -> 6
a1 = Node(1)
b1 = Node(3)
c1 = Node(5)
d = Node(7)
a2 = Node(2)
b2 = Node(4)
c2 = Node(6)
e = Node(9)
f = Node(11)
a1.next = b1
b1.next = c1
c1.next = d
a2.next = b2
b2.next = c2
c2.next = d
d.next = e
e.next = f
self.assertEqual(7, intersection(a1, a2).val)
if __name__ == '__main__':
unittest.main()
| TestSuite |
python | django__django | tests/db_functions/models.py | {
"start": 81,
"end": 345
} | class ____(models.Model):
name = models.CharField(max_length=50)
alias = models.CharField(max_length=50, null=True, blank=True)
goes_by = models.CharField(max_length=50, null=True, blank=True)
age = models.PositiveSmallIntegerField(default=30)
| Author |
python | huggingface__transformers | src/transformers/models/gpt_oss/modeling_gpt_oss.py | {
"start": 8833,
"end": 14371
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: GptOssConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[GptOssConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = freqs
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(x.dtype), sin.to(x.dtype)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def _apply_rotary_emb(
x: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
) -> torch.Tensor:
first_half, second_half = torch.chunk(x, 2, dim=-1)
first_ = first_half * cos - second_half * sin
second_ = second_half * cos + first_half * sin
return torch.cat((first_, second_), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = _apply_rotary_emb(q, cos, sin)
k_embed = _apply_rotary_emb(k, cos, sin)
return q_embed, k_embed
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs,
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
combined_logits = torch.cat([attn_weights, sinks], dim=-1)
# This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16
# when training with bsz>1 we clamp max values.
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
scores = probs[..., :-1] # we drop the sink here
attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| GptOssRotaryEmbedding |
python | pytorch__pytorch | test/inductor/extension_backends/cpp/extension_codegen_backend.py | {
"start": 163,
"end": 309
} | class ____(wrapper.PythonWrapperCodegen):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
| ExtensionWrapperCodegen |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 118575,
"end": 118639
} | class ____(UptimeTestCaseMixin, TestCase):
pass
| UptimeTestCase |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_mappedoperator.py | {
"start": 17081,
"end": 17254
} | class ____:
"""Nested fields for testing purposes."""
def __init__(self, field_1, field_2):
self.field_1 = field_1
self.field_2 = field_2
| NestedFields |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.