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 | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 68327,
"end": 68442
} | class ____:
name: str
status: ShardTypes
vector_queue_size: int
ShardStatus = _ShardStatus
| _ShardStatus |
python | lepture__authlib | authlib/integrations/base_client/framework_integration.py | {
"start": 26,
"end": 1871
} | class ____:
expires_in = 3600
def __init__(self, name, cache=None):
self.name = name
self.cache = cache
def _get_cache_data(self, key):
value = self.cache.get(key)
if not value:
return None
try:
return json.loads(value)
except (TypeError, ValueError):
return None
def _clear_session_state(self, session):
now = time.time()
for key in dict(session):
if "_authlib_" in key:
# TODO: remove in future
session.pop(key)
elif key.startswith("_state_"):
value = session[key]
exp = value.get("exp")
if not exp or exp < now:
session.pop(key)
def get_state_data(self, session, state):
key = f"_state_{self.name}_{state}"
if self.cache:
value = self._get_cache_data(key)
else:
value = session.get(key)
if value:
return value.get("data")
return None
def set_state_data(self, session, state, data):
key = f"_state_{self.name}_{state}"
if self.cache:
self.cache.set(key, json.dumps({"data": data}), self.expires_in)
else:
now = time.time()
session[key] = {"data": data, "exp": now + self.expires_in}
def clear_state_data(self, session, state):
key = f"_state_{self.name}_{state}"
if self.cache:
self.cache.delete(key)
else:
session.pop(key, None)
self._clear_session_state(session)
def update_token(self, token, refresh_token=None, access_token=None):
raise NotImplementedError()
@staticmethod
def load_config(oauth, name, params):
raise NotImplementedError()
| FrameworkIntegration |
python | django-debug-toolbar__django-debug-toolbar | tests/panels/test_sql.py | {
"start": 2265,
"end": 32305
} | class ____(BaseTestCase):
panel_id = SQLPanel.panel_id
def test_disabled(self):
config = {"DISABLE_PANELS": {"debug_toolbar.panels.sql.SQLPanel"}}
self.assertTrue(self.panel.enabled)
with self.settings(DEBUG_TOOLBAR_CONFIG=config):
self.assertFalse(self.panel.enabled)
def test_recording(self):
self.assertEqual(len(self.panel._queries), 0)
sql_call()
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
self.assertEqual(query["alias"], "default")
self.assertTrue("sql" in query)
self.assertTrue("duration" in query)
self.assertTrue("stacktrace" in query)
# ensure the stacktrace is populated
self.assertTrue(len(query["stacktrace"]) > 0)
def test_assert_num_queries_works(self):
"""
Confirm Django's assertNumQueries and CaptureQueriesContext works
See https://github.com/django-commons/django-debug-toolbar/issues/1791
"""
self.assertEqual(len(self.panel._queries), 0)
with self.assertNumQueries(1):
sql_call()
self.assertEqual(len(self.panel._queries), 1)
async def test_recording_async(self):
self.assertEqual(len(self.panel._queries), 0)
await async_sql_call()
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
self.assertEqual(query["alias"], "default")
self.assertTrue("sql" in query)
self.assertTrue("duration" in query)
self.assertTrue("stacktrace" in query)
# ensure the stacktrace is populated
self.assertTrue(len(query["stacktrace"]) > 0)
async def test_recording_concurrent_async(self):
self.assertEqual(len(self.panel._queries), 0)
await concurrent_async_sql_call()
# ensure query was logged
self.assertEqual(len(self.panel._queries), 2)
query = self.panel._queries[0]
self.assertEqual(query["alias"], "default")
self.assertTrue("sql" in query)
self.assertTrue("duration" in query)
self.assertTrue("stacktrace" in query)
# ensure the stacktrace is populated
self.assertTrue(len(query["stacktrace"]) > 0)
@override_settings(
DEBUG_TOOLBAR_CONFIG={
"SKIP_TOOLBAR_QUERIES": False,
"TOOLBAR_STORE_CLASS": "debug_toolbar.store.DatabaseStore",
}
)
def test_toolbar_model_query_is_tracked(self):
"""
Test is toolbar models are tracked when the `SKIP_TOOLBAR_QUERIES`
is set to False.
"""
self.assertEqual(len(self.panel._queries), 0)
patch_tracking_ddt_models()
sql_call_toolbar_model()
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
self.assertTrue(HistoryEntry._meta.db_table in query["sql"])
@override_settings(
DEBUG_TOOLBAR_CONFIG={
"SKIP_TOOLBAR_QUERIES": False,
"TOOLBAR_STORE_CLASS": "debug_toolbar.store.DatabaseStore",
}
)
async def test_toolbar_model_query_is_tracked_async(self):
"""
(async) Test is toolbar models are tracked when the `SKIP_TOOLBAR_QUERIES`
is set to False.
"""
self.assertEqual(len(self.panel._queries), 0)
patch_tracking_ddt_models()
await async_sql_call_toolbar_model()
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
self.assertTrue(HistoryEntry._meta.db_table in query["sql"])
@override_settings(
DEBUG_TOOLBAR_CONFIG={
"SKIP_TOOLBAR_QUERIES": True,
"TOOLBAR_STORE_CLASS": "debug_toolbar.store.DatabaseStore",
}
)
def test_toolbar_model_query_is_not_tracked(self):
"""
Test is toolbar models are not tracked when the `SKIP_TOOLBAR_QUERIES`
is set to True.
"""
self.assertEqual(len(self.panel._queries), 0)
patch_tracking_ddt_models()
sql_call_toolbar_model()
self.assertEqual(len(self.panel._queries), 0)
@override_settings(
DEBUG_TOOLBAR_CONFIG={
"SKIP_TOOLBAR_QUERIES": True,
"TOOLBAR_STORE_CLASS": "debug_toolbar.store.DatabaseStore",
}
)
async def test_toolbar_model_query_is_not_tracked_async(self):
"""
(async) Test is toolbar models are not tracked when the `SKIP_TOOLBAR_QUERIES`
is set to True.
"""
self.assertEqual(len(self.panel._queries), 0)
patch_tracking_ddt_models()
await async_sql_call_toolbar_model()
self.assertEqual(len(self.panel._queries), 0)
@unittest.skipUnless(
connection.vendor == "postgresql", "Test valid only on PostgreSQL"
)
def test_recording_chunked_cursor(self):
self.assertEqual(len(self.panel._queries), 0)
sql_call(use_iterator=True)
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
@patch(
"debug_toolbar.panels.sql.tracking.patch_cursor_wrapper_with_mixin",
wraps=sql_tracking.patch_cursor_wrapper_with_mixin,
)
def test_cursor_wrapper_singleton(self, mock_patch_cursor_wrapper):
sql_call()
# ensure that cursor wrapping is applied only once
self.assertIn(
mock_patch_cursor_wrapper.mock_calls,
[
[call(CursorWrapper, sql_tracking.NormalCursorMixin)],
# CursorDebugWrapper is used if the test is called with `--debug-sql`
[call(CursorDebugWrapper, sql_tracking.NormalCursorMixin)],
],
)
@patch(
"debug_toolbar.panels.sql.tracking.patch_cursor_wrapper_with_mixin",
wraps=sql_tracking.patch_cursor_wrapper_with_mixin,
)
def test_chunked_cursor_wrapper_singleton(self, mock_patch_cursor_wrapper):
sql_call(use_iterator=True)
# ensure that cursor wrapping is applied only once
self.assertIn(
mock_patch_cursor_wrapper.mock_calls,
[
[call(CursorWrapper, sql_tracking.NormalCursorMixin)],
# CursorDebugWrapper is used if the test is called with `--debug-sql`
[call(CursorDebugWrapper, sql_tracking.NormalCursorMixin)],
],
)
@patch(
"debug_toolbar.panels.sql.tracking.patch_cursor_wrapper_with_mixin",
wraps=sql_tracking.patch_cursor_wrapper_with_mixin,
)
async def test_cursor_wrapper_async(self, mock_patch_cursor_wrapper):
await sync_to_async(sql_call)()
self.assertIn(
mock_patch_cursor_wrapper.mock_calls,
[
[call(CursorWrapper, sql_tracking.NormalCursorMixin)],
# CursorDebugWrapper is used if the test is called with `--debug-sql`
[call(CursorDebugWrapper, sql_tracking.NormalCursorMixin)],
],
)
@patch(
"debug_toolbar.panels.sql.tracking.patch_cursor_wrapper_with_mixin",
wraps=sql_tracking.patch_cursor_wrapper_with_mixin,
)
async def test_cursor_wrapper_asyncio_ctx(self, mock_patch_cursor_wrapper):
self.assertTrue(sql_tracking.allow_sql.get())
await sync_to_async(sql_call)()
async def task():
sql_tracking.allow_sql.set(False)
# By disabling sql_tracking.allow_sql, we are indicating that any
# future SQL queries should be stopped. If SQL query occurs,
# it raises an exception.
with self.assertRaises(sql_tracking.SQLQueryTriggered):
await sync_to_async(sql_call)()
# Ensure this is called in another context
await asyncio.create_task(task())
# Because it was called in another context, it should not have affected ours
self.assertTrue(sql_tracking.allow_sql.get())
self.assertIn(
mock_patch_cursor_wrapper.mock_calls,
[
[
call(CursorWrapper, sql_tracking.NormalCursorMixin),
call(CursorWrapper, sql_tracking.ExceptionCursorMixin),
],
# CursorDebugWrapper is used if the test is called with `--debug-sql`
[
call(CursorDebugWrapper, sql_tracking.NormalCursorMixin),
call(CursorDebugWrapper, sql_tracking.ExceptionCursorMixin),
],
],
)
def test_generate_server_timing(self):
self.assertEqual(len(self.panel._queries), 0)
sql_call()
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
self.panel.generate_server_timing(self.request, response)
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
expected_data = {
"sql_time": {"title": "SQL 1 queries", "value": query["duration"]}
}
self.assertEqual(self.panel.get_server_timing_stats(), expected_data)
def test_non_ascii_query(self):
self.assertEqual(len(self.panel._queries), 0)
# non-ASCII text query
list(User.objects.extra(where=["username = 'apéro'"]))
self.assertEqual(len(self.panel._queries), 1)
# non-ASCII text parameters
list(User.objects.filter(username="thé"))
self.assertEqual(len(self.panel._queries), 2)
# non-ASCII bytes parameters
list(Binary.objects.filter(field__in=["café".encode()]))
self.assertEqual(len(self.panel._queries), 3)
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# ensure the panel renders correctly
self.assertIn("café", self.panel.content)
@unittest.skipUnless(
connection.vendor == "postgresql", "Test valid only on PostgreSQL"
)
def test_bytes_query(self):
self.assertEqual(len(self.panel._queries), 0)
with connection.cursor() as cursor:
cursor.execute(b"SELECT 1")
self.assertEqual(len(self.panel._queries), 1)
def test_param_conversion(self):
self.assertEqual(len(self.panel._queries), 0)
list(
User.objects.filter(first_name="Foo")
.filter(is_staff=True)
.filter(is_superuser=False)
)
list(
User.objects.annotate(group_count=Count("groups__id"))
.filter(group_count__lt=10)
.filter(group_count__gt=1)
)
list(
User.objects.filter(
date_joined=datetime.datetime(
2017, 12, 22, 16, 7, 1, tzinfo=datetime.timezone.utc
)
)
)
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# ensure query was logged
self.assertEqual(len(self.panel._queries), 3)
if connection.vendor == "mysql" and django.VERSION >= (4, 1):
# Django 4.1 started passing true/false back for boolean
# comparisons in MySQL.
expected_bools = '["Foo", true, false]'
else:
expected_bools = '["Foo"]'
if connection.vendor == "postgresql":
# PostgreSQL always includes timezone
expected_datetime = '["2017-12-22 16:07:01+00:00"]'
else:
expected_datetime = '["2017-12-22 16:07:01"]'
self.assertEqual(
tuple(query["params"] for query in self.panel._queries),
(
expected_bools,
"[10, 1]",
expected_datetime,
),
)
@unittest.skipUnless(
connection.vendor == "postgresql", "Test valid only on PostgreSQL"
)
def test_json_param_conversion(self):
self.assertEqual(len(self.panel._queries), 0)
list(PostgresJSON.objects.filter(field__contains={"foo": "bar"}))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
self.assertEqual(
self.panel._queries[0]["params"],
'["{\\"foo\\": \\"bar\\"}"]',
)
@unittest.skipUnless(
connection.vendor == "postgresql" and psycopg is None,
"Test valid only on PostgreSQL with psycopg2",
)
def test_tuple_param_conversion(self):
"""
Regression test for tuple parameter conversion.
"""
self.assertEqual(len(self.panel._queries), 0)
list(
PostgresJSON.objects.raw(
"SELECT * FROM tests_postgresjson WHERE field ->> 'key' IN %s",
[("a", "b'")],
)
)
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
self.assertEqual(self.panel._queries[0]["params"], '[["a", "b\'"]]')
def test_binary_param_force_text(self):
self.assertEqual(len(self.panel._queries), 0)
with connection.cursor() as cursor:
cursor.execute(
"SELECT * FROM tests_binary WHERE field = %s",
[connection.Database.Binary(b"\xff")],
)
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
self.assertEqual(len(self.panel._queries), 1)
self.assertIn(
"<strong>SELECT</strong> * <strong>FROM</strong>"
" tests_binary <strong>WHERE</strong> field =",
self.panel.content,
)
@unittest.skipUnless(connection.vendor != "sqlite", "Test invalid for SQLite")
def test_raw_query_param_conversion(self):
self.assertEqual(len(self.panel._queries), 0)
list(
User.objects.raw(
" ".join(
[
"SELECT *",
"FROM auth_user",
"WHERE first_name = %s",
"AND is_staff = %s",
"AND is_superuser = %s",
"AND date_joined = %s",
]
),
params=["Foo", True, False, datetime.datetime(2017, 12, 22, 16, 7, 1)],
)
)
list(
User.objects.raw(
" ".join(
[
"SELECT *",
"FROM auth_user",
"WHERE first_name = %(first_name)s",
"AND is_staff = %(is_staff)s",
"AND is_superuser = %(is_superuser)s",
"AND date_joined = %(date_joined)s",
]
),
params={
"first_name": "Foo",
"is_staff": True,
"is_superuser": False,
"date_joined": datetime.datetime(2017, 12, 22, 16, 7, 1),
},
)
)
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# ensure query was logged
self.assertEqual(len(self.panel._queries), 2)
self.assertEqual(
tuple(query["params"] for query in self.panel._queries),
(
'["Foo", true, false, "2017-12-22 16:07:01"]',
" ".join(
[
'{"first_name": "Foo",',
'"is_staff": true,',
'"is_superuser": false,',
'"date_joined": "2017-12-22 16:07:01"}',
]
),
),
)
def test_insert_content(self):
"""
Test that the panel only inserts content after generate_stats and
not the process_request.
"""
list(User.objects.filter(username="café"))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# ensure the panel renders correctly.
content = self.panel.content
self.assertIn("café", content)
self.assertValidHTML(content)
@override_settings(DEBUG_TOOLBAR_CONFIG={"ENABLE_STACKTRACES_LOCALS": True})
def test_insert_locals(self):
"""
Test that the panel inserts locals() content.
"""
local_var = "<script>alert('test');</script>" # noqa: F841
list(User.objects.filter(username="café"))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
self.assertIn("local_var", self.panel.content)
# Verify the escape logic works
content = self.panel.content
self.assertNotIn("<script>alert", content)
self.assertIn("<script>alert", content)
self.assertIn("djdt-locals", content)
def test_not_insert_locals(self):
"""
Test that the panel does not insert locals() content.
"""
list(User.objects.filter(username="café"))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
self.assertNotIn("djdt-locals", self.panel.content)
@unittest.skipUnless(
connection.vendor == "postgresql", "Test valid only on PostgreSQL"
)
def test_erroneous_query(self):
"""
Test that an error in the query isn't swallowed by the middleware.
"""
try:
connection.cursor().execute("erroneous query")
except DatabaseError as e:
self.assertTrue("erroneous query" in str(e))
@unittest.skipUnless(
connection.vendor == "postgresql", "Test valid only on PostgreSQL"
)
def test_execute_with_psycopg_composed_sql(self):
"""
Test command executed using a Composed psycopg object is logged.
Ref: https://www.psycopg.org/psycopg3/docs/api/sql.html
"""
try:
from psycopg import sql
except ImportError:
from psycopg2 import sql
self.assertEqual(len(self.panel._queries), 0)
with connection.cursor() as cursor:
command = sql.SQL("select {field} from {table}").format(
field=sql.Identifier("username"), table=sql.Identifier("auth_user")
)
cursor.execute(command)
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
self.assertEqual(query["alias"], "default")
self.assertTrue("sql" in query)
self.assertEqual(query["sql"], 'select "username" from "auth_user"')
def test_disable_stacktraces(self):
self.assertEqual(len(self.panel._queries), 0)
with self.settings(DEBUG_TOOLBAR_CONFIG={"ENABLE_STACKTRACES": False}):
sql_call()
# ensure query was logged
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
self.assertEqual(query["alias"], "default")
self.assertTrue("sql" in query)
self.assertTrue("duration" in query)
self.assertTrue("stacktrace" in query)
# ensure the stacktrace is empty
self.assertEqual([], query["stacktrace"])
@override_settings(
DEBUG=True,
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {"debug": True, "loaders": ["tests.loaders.LoaderWithSQL"]},
}
],
)
def test_regression_infinite_recursion(self):
"""
Test case for when the template loader runs a SQL query that causes
an infinite recursion in the SQL panel.
"""
self.assertEqual(len(self.panel._queries), 0)
render(self.request, "basic.html", {})
# Two queries are logged because the loader runs SQL every time a
# template is loaded and basic.html extends base.html.
self.assertEqual(len(self.panel._queries), 2)
query = self.panel._queries[0]
self.assertEqual(query["alias"], "default")
self.assertTrue("sql" in query)
self.assertTrue("duration" in query)
self.assertTrue("stacktrace" in query)
# ensure the stacktrace is populated
self.assertTrue(len(query["stacktrace"]) > 0)
def test_prettify_sql(self):
"""
Test case to validate that the PRETTIFY_SQL setting changes the output
of the sql when it's toggled. It does not validate what it does
though.
"""
with override_settings(DEBUG_TOOLBAR_CONFIG={"PRETTIFY_SQL": True}):
list(User.objects.filter(username__istartswith="spam"))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# The content formats the sql and prettifies it
self.assertTrue(self.panel.content)
pretty_sql = self.panel._queries[-1]["sql"]
self.assertEqual(len(self.panel._queries), 1)
# Recreate the panel to reset the queries. Content being a cached_property
# which doesn't have a way to reset it.
self.panel.disable_instrumentation()
self.panel = SQLPanel(self.panel.toolbar, self.panel.get_response)
self.panel.enable_instrumentation()
# Run it again, but with prettify off. Verify that it's different.
with override_settings(DEBUG_TOOLBAR_CONFIG={"PRETTIFY_SQL": False}):
list(User.objects.filter(username__istartswith="spam"))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# The content formats the sql and prettifies it
self.assertTrue(self.panel.content)
self.assertEqual(len(self.panel._queries), 1)
self.assertNotIn(pretty_sql, self.panel.content)
self.panel.disable_instrumentation()
self.panel = SQLPanel(self.panel.toolbar, self.panel.get_response)
self.panel.enable_instrumentation()
# Run it again, but with prettify back on.
# This is so we don't have to check what PRETTIFY_SQL does exactly,
# but we know it's doing something.
with override_settings(DEBUG_TOOLBAR_CONFIG={"PRETTIFY_SQL": True}):
list(User.objects.filter(username__istartswith="spam"))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# The content formats the sql and prettifies it
self.assertTrue(self.panel.content)
self.assertEqual(len(self.panel._queries), 1)
self.assertIn(pretty_sql, self.panel.content)
def test_simplification(self):
"""
Test case to validate that select lists for .count() and .exist() queries do not
get elided, but other select lists do.
"""
User.objects.count()
User.objects.exists()
list(User.objects.values_list("id"))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# The content formats the sql which injects the ellipsis character
self.assertTrue(self.panel.content)
self.assertEqual(len(self.panel._queries), 3)
self.assertNotIn("\u2022", self.panel._queries[0]["sql"])
self.assertNotIn("\u2022", self.panel._queries[1]["sql"])
self.assertIn("\u2022", self.panel._queries[2]["sql"])
def test_top_level_simplification(self):
"""
Test case to validate that top-level select lists get elided, but other select
lists for subselects do not.
"""
list(User.objects.filter(id__in=User.objects.filter(is_staff=True)))
list(User.objects.filter(id__lt=20).union(User.objects.filter(id__gt=10)))
if connection.vendor != "mysql":
list(
User.objects.filter(id__lt=20).intersection(
User.objects.filter(id__gt=10)
)
)
list(
User.objects.filter(id__lt=20).difference(
User.objects.filter(id__gt=10)
)
)
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
# The content formats the sql which injects the ellipsis character
self.assertTrue(self.panel.content)
if connection.vendor != "mysql":
self.assertEqual(len(self.panel._queries), 4)
else:
self.assertEqual(len(self.panel._queries), 2)
# WHERE ... IN SELECT ... queries should have only one elided select list
self.assertEqual(self.panel._queries[0]["sql"].count("SELECT"), 4)
self.assertEqual(self.panel._queries[0]["sql"].count("\u2022"), 3)
# UNION queries should have two elidid select lists
self.assertEqual(self.panel._queries[1]["sql"].count("SELECT"), 4)
self.assertEqual(self.panel._queries[1]["sql"].count("\u2022"), 6)
if connection.vendor != "mysql":
# INTERSECT queries should have two elidid select lists
self.assertEqual(self.panel._queries[2]["sql"].count("SELECT"), 4)
self.assertEqual(self.panel._queries[2]["sql"].count("\u2022"), 6)
# EXCEPT queries should have two elidid select lists
self.assertEqual(self.panel._queries[3]["sql"].count("SELECT"), 4)
self.assertEqual(self.panel._queries[3]["sql"].count("\u2022"), 6)
@override_settings(
DEBUG=True,
)
def test_flat_template_information(self):
"""
Test case for when the query is used in a flat template hierarchy
(without included templates).
"""
self.assertEqual(len(self.panel._queries), 0)
users = User.objects.all()
render(self.request, "sql/flat.html", {"users": users})
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
template_info = query["template_info"]
template_name = os.path.basename(template_info["name"])
self.assertEqual(template_name, "flat.html")
self.assertEqual(template_info["context"][3]["content"].strip(), "{{ users }}")
self.assertEqual(template_info["context"][3]["highlight"], True)
@override_settings(
DEBUG=True,
)
def test_nested_template_information(self):
"""
Test case for when the query is used in a nested template
hierarchy (with included templates).
"""
self.assertEqual(len(self.panel._queries), 0)
users = User.objects.all()
render(self.request, "sql/nested.html", {"users": users})
self.assertEqual(len(self.panel._queries), 1)
query = self.panel._queries[0]
template_info = query["template_info"]
template_name = os.path.basename(template_info["name"])
self.assertEqual(template_name, "included.html")
self.assertEqual(template_info["context"][0]["content"].strip(), "{{ users }}")
self.assertEqual(template_info["context"][0]["highlight"], True)
def test_similar_and_duplicate_grouping(self):
self.assertEqual(len(self.panel._queries), 0)
User.objects.filter(id=1).count()
User.objects.filter(id=1).count()
User.objects.filter(id=2).count()
User.objects.filter(id__lt=10).count()
User.objects.filter(id__lt=20).count()
User.objects.filter(id__gt=10, id__lt=20).count()
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
self.assertEqual(len(self.panel._queries), 6)
queries = self.panel._queries
query = queries[0]
self.assertEqual(query["similar_count"], 3)
self.assertEqual(query["duplicate_count"], 2)
query = queries[1]
self.assertEqual(query["similar_count"], 3)
self.assertEqual(query["duplicate_count"], 2)
query = queries[2]
self.assertEqual(query["similar_count"], 3)
self.assertTrue("duplicate_count" not in query)
query = queries[3]
self.assertEqual(query["similar_count"], 2)
self.assertTrue("duplicate_count" not in query)
query = queries[4]
self.assertEqual(query["similar_count"], 2)
self.assertTrue("duplicate_count" not in query)
query = queries[5]
self.assertTrue("similar_count" not in query)
self.assertTrue("duplicate_count" not in query)
self.assertEqual(queries[0]["similar_color"], queries[1]["similar_color"])
self.assertEqual(queries[0]["similar_color"], queries[2]["similar_color"])
self.assertEqual(queries[0]["duplicate_color"], queries[1]["duplicate_color"])
self.assertNotEqual(queries[0]["similar_color"], queries[0]["duplicate_color"])
self.assertEqual(queries[3]["similar_color"], queries[4]["similar_color"])
self.assertNotEqual(queries[0]["similar_color"], queries[3]["similar_color"])
self.assertNotEqual(queries[0]["duplicate_color"], queries[3]["similar_color"])
def test_explain_with_union(self):
list(User.objects.filter(id__lt=20).union(User.objects.filter(id__gt=10)))
response = self.panel.process_request(self.request)
self.panel.generate_stats(self.request, response)
query = self.panel._queries[0]
self.assertTrue(query["is_select"])
| SQLPanelTestCase |
python | h5py__h5py | h5py/tests/test_dataset_getitem.py | {
"start": 7245,
"end": 9362
} | class ____(TestCase):
def setUp(self):
TestCase.setUp(self)
self.dt = np.dtype('(3,2)f')
self.data = np.array([(3.2, -119), (42, 99.8), (3.14, 0)], dtype='f')
self.dset = self.f.create_dataset('x', (), dtype=self.dt)
self.dset[...] = self.data
def test_ndim(self):
""" Verify number of dimensions """
self.assertEqual(self.data.ndim, 2)
self.assertEqual(self.dset.ndim, 0)
def test_size(self):
""" Verify size """
self.assertEqual(self.dset.size, 1)
def test_nbytes(self):
""" Verify nbytes """
self.assertEqual(self.dset.nbytes, self.dset.dtype.itemsize) # not sure if 'f' is always alias for 'f4'
def test_shape(self):
""" Verify shape """
self.assertEqual(self.data.shape, (3, 2))
self.assertEqual(self.dset.shape, tuple())
def test_ellipsis(self):
""" Ellipsis -> ndarray promoted to underlying shape """
out = self.dset[...]
self.assertArrayEqual(out, self.data)
def test_tuple(self):
""" () -> same as ellipsis """
out = self.dset[...]
self.assertArrayEqual(out, self.data)
def test_slice(self):
""" slice -> ValueError """
with self.assertRaises(ValueError):
self.dset[0:4]
def test_multi_block_slice(self):
""" MultiBlockSlice -> ValueError """
with self.assertRaises(ValueError):
self.dset[h5py.MultiBlockSlice()]
def test_index(self):
""" index -> ValueError """
with self.assertRaises(ValueError):
self.dset[0]
def test_indexlist(self):
""" index list -> ValueError """
with self.assertRaises(ValueError):
self.dset[[]]
def test_mask(self):
""" mask -> ValueError """
mask = np.array(True, dtype='bool')
with self.assertRaises(ValueError):
self.dset[mask]
def test_fieldnames(self):
""" field name -> ValueError (no fields) """
with self.assertRaises(ValueError):
self.dset['field']
| TestScalarArray |
python | python-pillow__Pillow | src/PIL/DdsImagePlugin.py | {
"start": 4163,
"end": 7830
} | class ____(IntEnum):
UNKNOWN = 0
R8G8B8 = 20
A8R8G8B8 = 21
X8R8G8B8 = 22
R5G6B5 = 23
X1R5G5B5 = 24
A1R5G5B5 = 25
A4R4G4B4 = 26
R3G3B2 = 27
A8 = 28
A8R3G3B2 = 29
X4R4G4B4 = 30
A2B10G10R10 = 31
A8B8G8R8 = 32
X8B8G8R8 = 33
G16R16 = 34
A2R10G10B10 = 35
A16B16G16R16 = 36
A8P8 = 40
P8 = 41
L8 = 50
A8L8 = 51
A4L4 = 52
V8U8 = 60
L6V5U5 = 61
X8L8V8U8 = 62
Q8W8V8U8 = 63
V16U16 = 64
A2W10V10U10 = 67
D16_LOCKABLE = 70
D32 = 71
D15S1 = 73
D24S8 = 75
D24X8 = 77
D24X4S4 = 79
D16 = 80
D32F_LOCKABLE = 82
D24FS8 = 83
D32_LOCKABLE = 84
S8_LOCKABLE = 85
L16 = 81
VERTEXDATA = 100
INDEX16 = 101
INDEX32 = 102
Q16W16V16U16 = 110
R16F = 111
G16R16F = 112
A16B16G16R16F = 113
R32F = 114
G32R32F = 115
A32B32G32R32F = 116
CxV8U8 = 117
A1 = 118
A2B10G10R10_XR_BIAS = 119
BINARYBUFFER = 199
UYVY = i32(b"UYVY")
R8G8_B8G8 = i32(b"RGBG")
YUY2 = i32(b"YUY2")
G8R8_G8B8 = i32(b"GRGB")
DXT1 = i32(b"DXT1")
DXT2 = i32(b"DXT2")
DXT3 = i32(b"DXT3")
DXT4 = i32(b"DXT4")
DXT5 = i32(b"DXT5")
DX10 = i32(b"DX10")
BC4S = i32(b"BC4S")
BC4U = i32(b"BC4U")
BC5S = i32(b"BC5S")
BC5U = i32(b"BC5U")
ATI1 = i32(b"ATI1")
ATI2 = i32(b"ATI2")
MULTI2_ARGB8 = i32(b"MET1")
# Backward compatibility layer
module = sys.modules[__name__]
for item in DDSD:
assert item.name is not None
setattr(module, f"DDSD_{item.name}", item.value)
for item1 in DDSCAPS:
assert item1.name is not None
setattr(module, f"DDSCAPS_{item1.name}", item1.value)
for item2 in DDSCAPS2:
assert item2.name is not None
setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
for item3 in DDPF:
assert item3.name is not None
setattr(module, f"DDPF_{item3.name}", item3.value)
DDS_FOURCC = DDPF.FOURCC
DDS_RGB = DDPF.RGB
DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS
DDS_LUMINANCE = DDPF.LUMINANCE
DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS
DDS_ALPHA = DDPF.ALPHA
DDS_PAL8 = DDPF.PALETTEINDEXED8
DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT
DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH
DDS_HEADER_FLAGS_PITCH = DDSD.PITCH
DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE
DDS_HEIGHT = DDSD.HEIGHT
DDS_WIDTH = DDSD.WIDTH
DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE
DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP
DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX
DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX
DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX
DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY
DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY
DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ
DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ
DXT1_FOURCC = D3DFMT.DXT1
DXT3_FOURCC = D3DFMT.DXT3
DXT5_FOURCC = D3DFMT.DXT5
DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS
DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB
DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS
DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM
DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM
DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16
DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16
DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS
DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM
DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB
| D3DFMT |
python | donnemartin__interactive-coding-challenges | recursion_dynamic/max_profit_k/test_max_profit.py | {
"start": 18,
"end": 1564
} | class ____(unittest.TestCase):
def test_max_profit(self):
stock_trader = StockTrader()
self.assertRaises(TypeError, stock_trader.find_max_profit, None, None)
self.assertEqual(stock_trader.find_max_profit(prices=[], k=0), [])
prices = [5, 4, 3, 2, 1]
k = 3
self.assertEqual(stock_trader.find_max_profit(prices, k), (0, []))
prices = [2, 5, 7, 1, 4, 3, 1, 3]
profit, transactions = stock_trader.find_max_profit(prices, k)
self.assertEqual(profit, 10)
self.assertTrue(Transaction(Type.SELL,
day=7,
price=3) in transactions)
self.assertTrue(Transaction(Type.BUY,
day=6,
price=1) in transactions)
self.assertTrue(Transaction(Type.SELL,
day=4,
price=4) in transactions)
self.assertTrue(Transaction(Type.BUY,
day=3,
price=1) in transactions)
self.assertTrue(Transaction(Type.SELL,
day=2,
price=7) in transactions)
self.assertTrue(Transaction(Type.BUY,
day=0,
price=2) in transactions)
print('Success: test_max_profit')
def main():
test = TestMaxProfit()
test.test_max_profit()
if __name__ == '__main__':
main()
| TestMaxProfit |
python | doocs__leetcode | solution/1100-1199/1152.Analyze User Website Visit Pattern/Solution.py | {
"start": 0,
"end": 773
} | class ____:
def mostVisitedPattern(
self, username: List[str], timestamp: List[int], website: List[str]
) -> List[str]:
d = defaultdict(list)
for user, _, site in sorted(
zip(username, timestamp, website), key=lambda x: x[1]
):
d[user].append(site)
cnt = Counter()
for sites in d.values():
m = len(sites)
s = set()
if m > 2:
for i in range(m - 2):
for j in range(i + 1, m - 1):
for k in range(j + 1, m):
s.add((sites[i], sites[j], sites[k]))
for t in s:
cnt[t] += 1
return sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0]
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amplitude/components.py | {
"start": 640,
"end": 1542
} | class ____(RecordExtractor):
"""
Create records from complex response structure
Issue: https://github.com/airbytehq/airbyte/issues/23145
"""
def extract_records(self, response: requests.Response) -> List[Record]:
response_data = response.json().get("data", [])
if response_data:
# From the Amplitude documentation it follows that "series" is an array with one element which is itself
# an array that contains the average session length for each day.
# https://developers.amplitude.com/docs/dashboard-rest-api#returns-2
series = response_data.get("series", [])
if len(series) > 0:
series = series[0] # get the nested list
return [{"date": date, "length": length} for date, length in zip(response_data["xValues"], series)]
return []
| AverageSessionLengthRecordExtractor |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/directives.py | {
"start": 3114,
"end": 6741
} | class ____(converter.Base):
"""Parses compiler directives and converts them into AST annotations."""
def _process_symbol_directive(self, call_node, directive):
if len(call_node.args) < 1:
raise ValueError('"%s" requires a positional first argument'
' as the target' % directive.__name__)
target = call_node.args[0]
defs = anno.getanno(target, anno.Static.ORIG_DEFINITIONS)
for def_ in defs:
def_.directives[directive] = _map_args(call_node, directive)
return call_node
def _process_statement_directive(self, call_node, directive):
if self.state[_LoopScope].statements_visited > 1:
raise ValueError(
'"%s" must be the first statement in the loop block' % (
directive.__name__))
if self.state[_LoopScope].level < 2:
raise ValueError(
'"%s" must be used inside a statement' % directive.__name__)
target = self.state[_LoopScope].ast_node
node_anno = anno.getanno(target, anno.Basic.DIRECTIVES, {})
node_anno[directive] = _map_args(call_node, directive)
anno.setanno(target, anno.Basic.DIRECTIVES, node_anno)
return call_node
def visit_Name(self, node):
node = self.generic_visit(node)
if isinstance(node.ctx, gast.Load):
defs = anno.getanno(node, anno.Static.DEFINITIONS, ())
is_defined = bool(defs)
if not is_defined and node.id in self.ctx.info.namespace:
anno.setanno(node, STATIC_VALUE, self.ctx.info.namespace[node.id])
return node
def visit_Attribute(self, node):
node = self.generic_visit(node)
parent_val = anno.getanno(node.value, STATIC_VALUE, default=None)
if parent_val is not None and inspect.ismodule(parent_val):
if hasattr(parent_val, node.attr):
anno.setanno(node, STATIC_VALUE, getattr(parent_val, node.attr))
return node
def visit_Assign(self, node):
self.state[_LoopScope].statements_visited += 1
return self.generic_visit(node)
def visit_AugAssign(self, node):
self.state[_LoopScope].statements_visited += 1
return self.generic_visit(node)
def visit_Expr(self, node):
self.state[_LoopScope].statements_visited += 1
node = self.generic_visit(node)
if isinstance(node.value, gast.Call):
call_node = node.value
static_val = anno.getanno(call_node.func, STATIC_VALUE, default=None)
if static_val is not None:
# Note: directive calls are not output in the generated code, hence
# the removal from the code by returning None.
if static_val is directives.set_element_type:
self._process_symbol_directive(call_node, static_val)
return None
elif static_val is directives.set_loop_options:
self._process_statement_directive(call_node, static_val)
return None
return node
# TODO(mdan): This will be insufficient for other control flow.
# That means that if we ever have a directive that affects things other than
# loops, we'll need support for parallel scopes, or have multiple converters.
def _track_and_visit_loop(self, node):
self.state[_LoopScope].enter()
self.state[_LoopScope].ast_node = node
node = self.generic_visit(node)
# Edge case: a loop with just one directive statement would become empty.
if not node.body:
node.body = [gast.Pass()]
self.state[_LoopScope].exit()
return node
def visit_While(self, node):
return self._track_and_visit_loop(node)
def visit_For(self, node):
return self._track_and_visit_loop(node)
def transform(node, ctx):
return DirectivesTransformer(ctx).visit(node)
| DirectivesTransformer |
python | huggingface__transformers | tests/models/encoder_decoder/test_modeling_encoder_decoder.py | {
"start": 58893,
"end": 60398
} | class ____(unittest.TestCase):
def get_from_encoderdecoder_pretrained_model(self):
return EncoderDecoderModel.from_encoder_decoder_pretrained(
"google-bert/bert-base-uncased", "google-bert/bert-base-uncased"
)
def get_decoder_config(self):
config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
config.is_decoder = True
config.add_cross_attention = True
return config
def get_encoderdecoder_model(self):
return EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16")
def get_encoder_decoder_models(self):
encoder_model = BertModel.from_pretrained("google-bert/bert-base-uncased")
decoder_model = BertLMHeadModel.from_pretrained(
"google-bert/bert-base-uncased", config=self.get_decoder_config()
)
return {"encoder": encoder_model, "decoder": decoder_model}
def _check_configuration_tie(self, model):
assert id(model.decoder.config) == id(model.config.decoder)
assert id(model.encoder.config) == id(model.config.encoder)
@slow
def test_configuration_tie(self):
model = self.get_from_encoderdecoder_pretrained_model()
self._check_configuration_tie(model)
model = EncoderDecoderModel(**self.get_encoder_decoder_models())
self._check_configuration_tie(model)
model = self.get_encoderdecoder_model()
self._check_configuration_tie(model)
| EncoderDecoderModelTest |
python | numpy__numpy | numpy/polynomial/tests/test_symbol.py | {
"start": 2095,
"end": 3099
} | class ____:
"""
Ensure symbol is preserved for numeric operations on polynomials with
the same symbol
"""
p = poly.Polynomial([1, 2, 3], symbol='z')
def test_add(self, rhs):
out = self.p + rhs
assert_equal(out.symbol, 'z')
def test_sub(self, rhs):
out = self.p - rhs
assert_equal(out.symbol, 'z')
def test_polymul(self, rhs):
out = self.p * rhs
assert_equal(out.symbol, 'z')
def test_divmod(self, rhs):
for out in divmod(self.p, rhs):
assert_equal(out.symbol, 'z')
def test_radd(self, rhs):
out = rhs + self.p
assert_equal(out.symbol, 'z')
def test_rsub(self, rhs):
out = rhs - self.p
assert_equal(out.symbol, 'z')
def test_rmul(self, rhs):
out = rhs * self.p
assert_equal(out.symbol, 'z')
def test_rdivmod(self, rhs):
for out in divmod(rhs, self.p):
assert_equal(out.symbol, 'z')
| TestBinaryOperatorsSameSymbol |
python | conda__conda | conda/exceptions.py | {
"start": 2615,
"end": 3833
} | class ____(Help):
def __init__(self):
message = dals(
"""
usage: conda activate [-h] [--[no-]stack] [env_name_or_prefix]
Activate a conda environment.
Options:
positional arguments:
env_name_or_prefix The environment name or prefix to activate. If the
prefix is a relative path, it must start with './'
(or '.\\' on Windows).
optional arguments:
-h, --help Show this help message and exit.
--stack Stack the environment being activated on top of the
previous active environment, rather replacing the
current active environment with a new one. Currently,
only the PATH environment variable is stacked. This
may be enabled implicitly by the 'auto_stack'
configuration variable.
--no-stack Do not stack the environment. Overrides 'auto_stack'
setting.
"""
)
super().__init__(message)
| ActivateHelp |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 34192,
"end": 34975
} | class ____(TestCase):
def test_basic(self):
iterable = range(1, 5 + 1)
for n, expected in (
(1, [(1,), (2,), (3,), (4,), (5,)]),
(2, [(1, 2), (3, 4), (5,)]),
(3, [(1, 2, 3), (4, 5)]),
(4, [(1, 2, 3, 4), (5,)]),
(5, [(1, 2, 3, 4, 5)]),
(6, [(1, 2, 3, 4, 5)]),
):
with self.subTest(n=n):
actual = list(mi.batched(iterable, n))
self.assertEqual(actual, expected)
def test_strict(self):
with self.assertRaises(ValueError):
list(mi.batched('ABCDEFG', 3, strict=True))
self.assertEqual(
list(mi.batched('ABCDEF', 3, strict=True)),
[('A', 'B', 'C'), ('D', 'E', 'F')],
)
| BatchedTests |
python | neetcode-gh__leetcode | python/1239-maximum-length-of-a-concatenated-string-with-unique-characters.py | {
"start": 0,
"end": 837
} | class ____:
def maxLength(self, arr: List[str]) -> int:
charSet = set()
def overlap(charSet, s):
c = Counter(charSet) + Counter(s)
return max(c.values()) > 1
# prev = set()
# for c in s:
# if c in charSet or c in prev:
# return True
# prev.add(c)
# return False
def backtrack(i):
if i == len(arr):
return len(charSet)
res = 0
if not overlap(charSet, arr[i]):
for c in arr[i]:
charSet.add(c)
res = backtrack(i + 1)
for c in arr[i]:
charSet.remove(c)
return max(res, backtrack(i + 1)) # dont concatenate arr[i]
return backtrack(0)
| Solution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_s3.py | {
"start": 22478,
"end": 37746
} | class ____:
def test_s3_delete_single_object(self):
bucket = "testbucket"
key = "path/data.txt"
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
conn.upload_fileobj(Bucket=bucket, Key=key, Fileobj=BytesIO(b"input"))
# The object should be detected before the DELETE action is taken
objects_in_dest_bucket = conn.list_objects(Bucket=bucket, Prefix=key)
assert len(objects_in_dest_bucket["Contents"]) == 1
assert objects_in_dest_bucket["Contents"][0]["Key"] == key
op = S3DeleteObjectsOperator(task_id="test_task_s3_delete_single_object", bucket=bucket, keys=key)
op.execute(None)
# There should be no object found in the bucket created earlier
assert "Contents" not in conn.list_objects(Bucket=bucket, Prefix=key)
def test_s3_delete_multiple_objects(self):
bucket = "testbucket"
key_pattern = "path/data"
n_keys = 3
keys = [key_pattern + str(i) for i in range(n_keys)]
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
for k in keys:
conn.upload_fileobj(Bucket=bucket, Key=k, Fileobj=BytesIO(b"input"))
# The objects should be detected before the DELETE action is taken
objects_in_dest_bucket = conn.list_objects(Bucket=bucket, Prefix=key_pattern)
assert len(objects_in_dest_bucket["Contents"]) == n_keys
assert sorted(x["Key"] for x in objects_in_dest_bucket["Contents"]) == sorted(keys)
op = S3DeleteObjectsOperator(task_id="test_task_s3_delete_multiple_objects", bucket=bucket, keys=keys)
op.execute(None)
# There should be no object found in the bucket created earlier
assert "Contents" not in conn.list_objects(Bucket=bucket, Prefix=key_pattern)
@pytest.mark.db_test
def test_dates_from_template(self, session, testing_dag_bundle):
"""Specifically test for dates passed from templating that could be strings"""
bucket = "testbucket"
key_pattern = "path/data"
n_keys = 3
keys = [key_pattern + str(i) for i in range(n_keys)]
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
for k in keys:
conn.upload_fileobj(Bucket=bucket, Key=k, Fileobj=BytesIO(b"input"))
logical_date = utcnow()
dag = DAG("test_dag", start_date=datetime(2020, 1, 1), schedule=timedelta(days=1))
# use macros.ds_add since it returns a string, not a date
op = S3DeleteObjectsOperator(
task_id="XXXXXXXXXXXXXXXXXXXXXXX",
bucket=bucket,
from_datetime="{{ macros.ds_add(ds, -1) }}",
to_datetime="{{ macros.ds_add(ds, 1) }}",
dag=dag,
)
if hasattr(DagRun, "execution_date"): # Airflow 2.x.
dag_run = DagRun(
dag_id=dag.dag_id,
execution_date=logical_date,
run_id="test",
run_type=DagRunType.MANUAL,
state=DagRunState.RUNNING,
)
else:
dag_run = DagRun(
dag_id=dag.dag_id,
logical_date=logical_date,
run_id="test",
run_type=DagRunType.MANUAL,
state=DagRunState.RUNNING,
)
if AIRFLOW_V_3_0_PLUS:
from airflow.models.dag_version import DagVersion
sync_dag_to_db(dag)
dag_version = DagVersion.get_latest_version(dag.dag_id)
ti = TaskInstance(task=op, dag_version_id=dag_version.id)
else:
ti = TaskInstance(task=op)
ti.dag_run = dag_run
session.add(ti)
session.commit()
context = ti.get_template_context(session)
ti.render_templates(context)
op.execute(None)
assert "Contents" not in conn.list_objects(Bucket=bucket)
def test_s3_delete_from_to_datetime(self):
bucket = "testbucket"
key_pattern = "path/data"
n_keys = 3
keys = [key_pattern + str(i) for i in range(n_keys)]
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
for k in keys:
conn.upload_fileobj(Bucket=bucket, Key=k, Fileobj=BytesIO(b"input"))
# The objects should be detected before the DELETE action is taken
objects_in_dest_bucket = conn.list_objects(Bucket=bucket)
assert len(objects_in_dest_bucket["Contents"]) == n_keys
assert sorted(x["Key"] for x in objects_in_dest_bucket["Contents"]) == sorted(keys)
now = utcnow()
from_datetime = now.replace(year=now.year - 1)
to_datetime = now.replace(year=now.year + 1)
op = S3DeleteObjectsOperator(
task_id="test_task_s3_delete_prefix",
bucket=bucket,
from_datetime=from_datetime,
to_datetime=to_datetime,
)
op.execute(None)
# There should be no object found in the bucket created earlier
assert "Contents" not in conn.list_objects(Bucket=bucket)
def test_s3_delete_prefix(self):
bucket = "testbucket"
key_pattern = "path/data"
n_keys = 3
keys = [key_pattern + str(i) for i in range(n_keys)]
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
for k in keys:
conn.upload_fileobj(Bucket=bucket, Key=k, Fileobj=BytesIO(b"input"))
# The objects should be detected before the DELETE action is taken
objects_in_dest_bucket = conn.list_objects(Bucket=bucket, Prefix=key_pattern)
assert len(objects_in_dest_bucket["Contents"]) == n_keys
assert sorted(x["Key"] for x in objects_in_dest_bucket["Contents"]) == sorted(keys)
op = S3DeleteObjectsOperator(task_id="test_task_s3_delete_prefix", bucket=bucket, prefix=key_pattern)
op.execute(None)
# There should be no object found in the bucket created earlier
assert "Contents" not in conn.list_objects(Bucket=bucket, Prefix=key_pattern)
def test_s3_delete_empty_list(self):
bucket = "testbucket"
key_of_test = "path/data.txt"
keys = []
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
conn.upload_fileobj(Bucket=bucket, Key=key_of_test, Fileobj=BytesIO(b"input"))
# The object should be detected before the DELETE action is tested
objects_in_dest_bucket = conn.list_objects(Bucket=bucket, Prefix=key_of_test)
assert len(objects_in_dest_bucket["Contents"]) == 1
assert objects_in_dest_bucket["Contents"][0]["Key"] == key_of_test
op = S3DeleteObjectsOperator(task_id="test_s3_delete_empty_list", bucket=bucket, keys=keys)
op.execute(None)
# The object found in the bucket created earlier should still be there
assert len(objects_in_dest_bucket["Contents"]) == 1
# the object found should be consistent with dest_key specified earlier
assert objects_in_dest_bucket["Contents"][0]["Key"] == key_of_test
def test_s3_delete_empty_string(self):
bucket = "testbucket"
key_of_test = "path/data.txt"
keys = ""
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
conn.upload_fileobj(Bucket=bucket, Key=key_of_test, Fileobj=BytesIO(b"input"))
# The object should be detected before the DELETE action is tested
objects_in_dest_bucket = conn.list_objects(Bucket=bucket, Prefix=key_of_test)
assert len(objects_in_dest_bucket["Contents"]) == 1
assert objects_in_dest_bucket["Contents"][0]["Key"] == key_of_test
op = S3DeleteObjectsOperator(task_id="test_s3_delete_empty_string", bucket=bucket, keys=keys)
op.execute(None)
# The object found in the bucket created earlier should still be there
assert len(objects_in_dest_bucket["Contents"]) == 1
# the object found should be consistent with dest_key specified earlier
assert objects_in_dest_bucket["Contents"][0]["Key"] == key_of_test
@pytest.mark.parametrize(
("keys", "prefix", "from_datetime", "to_datetime"),
[
pytest.param("path/data.txt", "path/data", None, None, id="single-key-and-prefix"),
pytest.param(["path/data.txt"], "path/data", None, None, id="multiple-keys-and-prefix"),
pytest.param(
["path/data.txt"],
"path/data",
datetime(1992, 3, 8, 18, 52, 51),
None,
id="keys-prefix-and-from_datetime",
),
pytest.param(
["path/data.txt"],
"path/data",
datetime(1992, 3, 8, 18, 52, 51),
datetime(1993, 3, 8, 18, 52, 51),
id="keys-prefix-and-from-to_datetime",
),
pytest.param(None, None, None, None, id="all-none"),
],
)
def test_validate_keys_and_filters_in_constructor(self, keys, prefix, from_datetime, to_datetime):
with pytest.raises(
AirflowException,
match=r"Either keys or at least one of prefix, from_datetime, to_datetime should be set.",
):
S3DeleteObjectsOperator(
task_id="test_validate_keys_and_prefix_in_constructor",
bucket="foo-bar-bucket",
keys=keys,
prefix=prefix,
from_datetime=from_datetime,
to_datetime=to_datetime,
)
@pytest.mark.parametrize(
("keys", "prefix", "from_datetime", "to_datetime"),
[
pytest.param("path/data.txt", "path/data", None, None, id="single-key-and-prefix"),
pytest.param(["path/data.txt"], "path/data", None, None, id="multiple-keys-and-prefix"),
pytest.param(
["path/data.txt"],
"path/data",
datetime(1992, 3, 8, 18, 52, 51),
None,
id="keys-prefix-and-from_datetime",
),
pytest.param(
["path/data.txt"],
"path/data",
datetime(1992, 3, 8, 18, 52, 51),
datetime(1993, 3, 8, 18, 52, 51),
id="keys-prefix-and-from-to_datetime",
),
pytest.param(None, None, None, None, id="all-none"),
],
)
def test_validate_keys_and_prefix_in_execute(self, keys, prefix, from_datetime, to_datetime):
bucket = "testbucket"
key_of_test = "path/data.txt"
conn = boto3.client("s3")
conn.create_bucket(Bucket=bucket)
conn.upload_fileobj(Bucket=bucket, Key=key_of_test, Fileobj=BytesIO(b"input"))
# Set valid values for constructor, and change them later for emulate rendering template
op = S3DeleteObjectsOperator(
task_id="test_validate_keys_and_prefix_in_execute",
bucket=bucket,
keys="keys-exists",
prefix=None,
)
op.keys = keys
op.prefix = prefix
op.from_datetime = from_datetime
op.to_datetime = to_datetime
# The object should be detected before the DELETE action is tested
objects_in_dest_bucket = conn.list_objects(Bucket=bucket, Prefix=key_of_test)
assert len(objects_in_dest_bucket["Contents"]) == 1
assert objects_in_dest_bucket["Contents"][0]["Key"] == key_of_test
with pytest.raises(
AirflowException,
match=r"Either keys or at least one of prefix, from_datetime, to_datetime should be set.",
):
op.execute(None)
# The object found in the bucket created earlier should still be there
assert len(objects_in_dest_bucket["Contents"]) == 1
# the object found should be consistent with dest_key specified earlier
assert objects_in_dest_bucket["Contents"][0]["Key"] == key_of_test
@pytest.mark.parametrize("keys", ("path/data.txt", ["path/data.txt"]))
def test_get_openlineage_facets_on_complete_single_object(self, keys):
bucket = "testbucket"
expected_input = Dataset(
namespace=f"s3://{bucket}",
name="path/data.txt",
facets={
"lifecycleStateChange": LifecycleStateChangeDatasetFacet(
lifecycleStateChange=LifecycleStateChange.DROP.value,
previousIdentifier=PreviousIdentifier(
namespace=f"s3://{bucket}",
name="path/data.txt",
),
)
},
)
op = S3DeleteObjectsOperator(task_id="test_task_s3_delete_single_object", bucket=bucket, keys=keys)
op.hook = mock.MagicMock()
op.execute(None)
lineage = op.get_openlineage_facets_on_complete(None)
assert len(lineage.inputs) == 1
assert lineage.inputs[0] == expected_input
def test_get_openlineage_facets_on_complete_multiple_objects(self):
bucket = "testbucket"
keys = ["path/data1.txt", "path/data2.txt"]
expected_inputs = [
Dataset(
namespace=f"s3://{bucket}",
name="path/data1.txt",
facets={
"lifecycleStateChange": LifecycleStateChangeDatasetFacet(
lifecycleStateChange=LifecycleStateChange.DROP.value,
previousIdentifier=PreviousIdentifier(
namespace=f"s3://{bucket}",
name="path/data1.txt",
),
)
},
),
Dataset(
namespace=f"s3://{bucket}",
name="path/data2.txt",
facets={
"lifecycleStateChange": LifecycleStateChangeDatasetFacet(
lifecycleStateChange=LifecycleStateChange.DROP.value,
previousIdentifier=PreviousIdentifier(
namespace=f"s3://{bucket}",
name="path/data2.txt",
),
)
},
),
]
op = S3DeleteObjectsOperator(task_id="test_task_s3_delete_single_object", bucket=bucket, keys=keys)
op.hook = mock.MagicMock()
op.execute(None)
lineage = op.get_openlineage_facets_on_complete(None)
assert len(lineage.inputs) == 2
assert lineage.inputs == expected_inputs
@pytest.mark.parametrize("keys", ("", []))
@mock.patch("airflow.providers.amazon.aws.operators.s3.S3Hook")
def test_get_openlineage_facets_on_complete_no_objects(self, mock_hook, keys):
op = S3DeleteObjectsOperator(
task_id="test_task_s3_delete_single_object", bucket="testbucket", keys=keys
)
op.execute(None)
lineage = op.get_openlineage_facets_on_complete(None)
assert lineage == OperatorLineage()
def test_template_fields(self):
operator = S3DeleteObjectsOperator(
task_id="test_task_s3_delete_single_object", bucket="test-bucket", keys="test/file.csv"
)
validate_template_fields(operator)
| TestS3DeleteObjectsOperator |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tfr/python/tfr_gen.py | {
"start": 21722,
"end": 53978
} | class ____(transformer.CodeGenerator):
"""Visit the AST and generate MLIR TFR functions."""
def __init__(self, ctx, op_defs):
super(TFRGen, self).__init__(ctx)
self.ctx = ctx
self.symbol_table = SymbolTable()
self._op_defs = op_defs
def _create_mlir_loc(self, loc):
"""Creates mlir location from autograph ORIGIN value.
Args:
loc: OriginInfo
Returns:
A serialized mlir location string.
"""
if loc is not None and loc.loc.filename:
file_name = os.path.basename(loc.loc.filename)
return 'loc("{}":{}:{})'.format(file_name, loc.loc.lineno,
loc.loc.col_offset)
else:
return 'loc(unknown)'
def _emit_with_loc(self, op_str, node=None):
"""Emit the mlir operation with the location associated with the node.
Args:
op_str: The mlir operation string to be emitted.
node: The node of the AST tree, the mlir operation translated from.
"""
loc = ''
if node:
loc = self._create_mlir_loc(
anno.getanno(node, anno.Basic.ORIGIN, default=None))
self.emit(op_str + ' ' + loc)
def _get_inferred_type(self, node, default=None):
"""Return single type or a tuple of types if more than one type."""
types_ = anno.getanno(node, anno.Static.TYPES, None)
if not types_:
print('WARN: no Static.TYPES annotation. Fix the type inference pass: ')
self.debug_print(node)
return default
if len(types_) == 1:
type_, = types_
else:
type_ = types_
if default is not None and type_ != default:
print('WARN: type annotation {}({}) does not match {}({})'.format(
type_, type(type_), default, type(default)))
self.debug_print(node)
return type_
def _pack_tensor_list(self, value):
# This is packing a list of tensors, then the axis is 0.
axis = self._ssa_name('zero')
self._emit_with_loc('\n{} = arith.constant 0 : i64'.format(axis))
casted = self._ssa_name('pack')
self.emit('\n{} = tfr.call @tf__pack({}, {})'.format(casted, value, axis))
self._emit_with_loc(' : (!tfr.tensor_list, i64) -> !tfr.tensor')
# load the op def of tf.Pack
self._op_defs.lookup('Pack')
return casted, TFRTypes.TENSOR
def _index_to_I64(self, value, ty):
if ty == TFRTypes.INDEX:
casted = self._ssa_name('casted')
self._emit_with_loc('\n{} = arith.index_cast {} : index to i64'.format(
casted, value))
return casted, TFRTypes.I64
else:
return value, ty
def _i64_to_index(self, value, ty):
if ty == TFRTypes.I64:
casted = self._ssa_name('casted')
self._emit_with_loc('\n{} = arith.index_cast {} : i64 to index'.format(
casted, value))
return casted, TFRTypes.INDEX
else:
return value, ty
def _value_to_tensor(self, value, ty, node):
value, ty = self._index_to_I64(value, ty)
cst_tensor = self._ssa_name('cst')
self.emit('\n{} = "tfr.constant_tensor"({})'.format(cst_tensor, value))
self._emit_with_loc(' : ({}) -> !tfr.tensor'.format(ty), node)
return cst_tensor, TFRTypes.TENSOR
def _ssa_name(self, prefix):
if isinstance(prefix, qual_names.QN):
assert prefix.is_simple(), 'ANF transform should have cleaned this up'
prefix = prefix.ssf()
return '%' + self.ctx.namer.new_symbol(prefix, set())
def _op_def(self, op_name):
return op_def_registry.get(op_name)
def visit_block(self, block):
return [self.visit(item) for item in block]
def visit_Pass(self, node):
if self.symbol_table.in_scf_scope():
self._emit_with_loc('\nscf.yield', node)
else:
self._emit_with_loc('\ntfr.return', node)
def visit_Attribute(self, node):
node_type = self._get_inferred_type(node, None)
if isinstance(node.value, ast.Name):
if node.value.id == 'ag__':
# some variables are assigned with 'ag__.xxx' method, we should handle
# them following the autograph convensions.
return (node.attr, TFRTypes.AG_BUILTIN_FUNC)
if node_type == TFRTypes.TF_RAW_OP:
# This branch is used when it is inside tensorflow
return (node.attr, TFRTypes.TF_RAW_OP)
if node_type == TFRTypes.ATTR:
attr = self._ssa_name('attr')
tfr_type = _TF_DTYPE_TO_TFR.get(node.attr)
self._emit_with_loc(
'\n{} = tfr.constant {} -> !tfr.attr'.format(attr, tfr_type), node)
return (attr, TFRTypes.ATTR)
value, _ = self.visit(node.value)
tensor_type = self._get_inferred_type(node.value, None)
# TODO(fengliuai): use node_type once it
if node_type == TFRTypes.SHAPE:
print('TODO: use "node_type"')
if node.attr == 'shape' and tensor_type == TFRTypes.TENSOR:
ssa_value = self._ssa_name('shape')
self._emit_with_loc(
'\n{} = tfr.get_shape {} -> !shape.shape'.format(ssa_value, value),
node)
return (ssa_value, TFRTypes.SHAPE)
if isinstance(node.value, ast.Attribute):
if isinstance(node.value.value, ast.Name):
if node.value.value.id == 'tf' and node.value.attr == 'raw_ops':
return (node.attr, TFRTypes.TF_RAW_OP)
value, ty = self.visit(node.value)
# TODO(fengliuai): use node_type once it
if node_type == TFRTypes.TF_TENSOR_SHAPE_FUNC:
print('TODO: use "node_type"')
if ty == TFRTypes.SHAPE and node.attr == 'as_list':
return (value, TFRTypes.TF_TENSOR_SHAPE_FUNC)
raise NotImplementedError('Attribute kind not recognized.')
def visit_Assign(self, node):
values = self.visit(node.value)
if isinstance(node.targets[0], ast.Tuple):
targets = [elt.id for elt in node.targets[0].elts]
elif isinstance(node.targets[0], ast.Name):
targets = [node.targets[0].id]
else:
raise NotImplementedError('Assignment target type not recognized.')
if isinstance(values, list):
if isinstance(node.value, ast.Call):
expected = tuple(t for n, t in values)
if len(values) == 1:
expected = expected[0]
elif isinstance(node.value, ast.Tuple):
expected = tuple(t for n, t in values)
else:
raise ValueError('unknown assignment target node', node.value)
ty = self._get_inferred_type(node.value, expected)
if len(targets) == len(values):
# TODO(mdan): This should already be a tuple.
ty_ = (ty,) if len(values) == 1 else ty
for key, value, t in zip(targets, values, ty_):
ssa_value, _ = value
self.symbol_table.insert_symbol(key, ssa_value, t)
elif len(values) == 1:
name, tys = values[0]
if ty == TFRTypes.TENSOR_LIST:
# assign single tensor_list to multiple variables
for idx, key in enumerate(targets):
idx_name = self._ssa_name('idx')
self._emit_with_loc(
'\n{} = arith.constant {} : index'.format(idx_name, idx), node)
elt_name = self._ssa_name('elt')
self.emit('\n{} = tfr.get_element {}[{}]'.format(
elt_name, name, idx_name))
self._emit_with_loc(' : (!tfr.tensor_list, index) -> !tfr.tensor',
node)
self.symbol_table.insert_symbol(key, elt_name, TFRTypes.TENSOR)
else:
# assign single value to multiple targets. This single value is
# usually a function return. The return type should be in the tuple of
# the value.
for idx, key in enumerate(targets):
ssa_name = '{}#{}'.format(name, idx)
ssa_type = tys[idx]
self.symbol_table.insert_symbol(key, ssa_name, ssa_type)
elif len(targets) == 1:
ssa_names = [n for n, _ in values]
self.symbol_table.insert_symbol(targets[0], ssa_names, ty)
return
ty = self._get_inferred_type(node.value, values[1])
self.symbol_table.insert_symbol(targets[0], values[0], ty)
def _emit_binary_op(self, op, lhs, lhs_ty, rhs, rhs_ty):
assert lhs_ty, rhs_ty
if isinstance(op, ast.Sub):
code = 'arith.sub'
elif isinstance(op, ast.Add):
code = 'arith.add'
elif isinstance(op, ast.Mult):
code = 'arith.mul'
elif isinstance(op, ast.Div):
code = 'arith.div'
else:
raise NotImplementedError('BinOp operator not recognized' + op)
if lhs_ty == TFRTypes.I64 or lhs_ty == TFRTypes.I32:
suffix = 'i'
elif lhs_ty == TFRTypes.F32:
suffix = 'f'
else:
raise NotImplementedError('BinOp operand type not recognized' + op)
ret = self._ssa_name(code)
self._emit_with_loc(
'\n{} = {}{} {}, {} : {}'.format(ret, code, suffix, lhs, rhs, lhs_ty),
op)
return ret, lhs_ty
def visit_AugAssign(self, node):
lhs, lhs_ty = self.visit(node.target)
rhs, rhs_ty = self.visit(node.value)
ret, ret_ty = self._emit_binary_op(node.op, lhs, lhs_ty, rhs, rhs_ty)
self.symbol_table.insert_symbol(node.target.id, ret, ret_ty)
def visit_BinOp(self, node):
lhs, lhs_ty = self.visit(node.left)
rhs, rhs_ty = self.visit(node.right)
return self._emit_binary_op(node.op, lhs, lhs_ty, rhs, rhs_ty)
def visit_BoolOp(self, node):
values = [self.visit(value) for value in node.values]
# TODO(fengliuai): Handle more ast node types.
if isinstance(node.op, ast.Or):
raise NotImplementedError('Or operator not recognized')
elif isinstance(node.op, ast.And):
raise NotImplementedError('And operator not recognized')
def visit_Call(self, node):
func_name, func_type = self.visit(node.func)
func_type = self._get_inferred_type(node.func, func_type)
if func_type == TFRTypes.AG_BUILTIN_FUNC:
if func_name == 'if_stmt':
cond, _ = self.visit(node.args[0])
body, _ = self.visit(node.args[1])
orelse, _ = self.visit(node.args[2])
get_state, _ = self.visit(node.args[3])
nouts = int(node.args[6].value)
out_symbols = []
# The out symbols are just a Tuple of names
for out in node.args[5].elts[:nouts]:
val, ty = self.symbol_table.lookup(out.value)
out_symbols.append(out.value)
return self._visit_if_stmt(cond, body, orelse, get_state, out_symbols,
node)
elif func_name == 'for_stmt':
range_ = self._visit_iter(node.args[0])
body, _ = self.visit(node.args[2])
get_state, _ = self.visit(node.args[3])
loop_carried = [out.value for out in node.args[5].elts]
# TODO(fengliuai): opt is not used here.
return self._visit_for_stmt(range_, body, get_state, loop_carried, node)
elif func_name == 'Undefined':
val = self._ssa_name(node.args[0].value)
return (val, TFRTypes.AG_UNDEFINED_VAL)
elif func_name == 'UndefinedReturnValue':
val = self._ssa_name('return_val')
return (val, TFRTypes.AG_UNDEFINED_VAL)
if func_type == TFRTypes.TF_RAW_OP:
return self._visit_tf_op(func_name, node.args, node.keywords, node)
if func_type == TFRTypes.TFR_BUILTIN_FUNC:
return self._visit_tfr_builtins(func_name, node.args, node)
if func_type == types.FunctionType:
return self._visit_tf_op(func_name, node.args, node.keywords, node)
if func_type == TFRTypes.TF_TENSOR_SHAPE_FUNC:
return (func_name, TFRTypes.TF_TENSOR_SHAPE_LIST)
if func_type == TFRTypes.PY_BUILTIN_FUNC:
if func_name == 'len':
arg, ty = self.visit(node.args[0])
ty = self._get_inferred_type(node.args[0], ty)
if ty == TFRTypes.TF_TENSOR_SHAPE_LIST:
len_value = self._ssa_name('len')
self._emit_with_loc(
'\n{} = shape.rank {} : !shape.shape -> !shape.size'.format(
len_value, arg), node)
size_value = self._ssa_name('len_size')
self._emit_with_loc(
'\n{} = shape.size_to_index {} : !shape.size'.format(
size_value, len_value), node)
elif ty == TFRTypes.TENSOR_LIST:
size_value = self._ssa_name('len')
self._emit_with_loc(
'\n{} = tfr.get_length {} -> index'.format(size_value, arg), node)
return (size_value, TFRTypes.INDEX)
raise NotImplementedError('call operator not recognized: {} {}'.format(
func_name, func_type))
def visit_Compare(self, node):
lhs, lhs_ty = self.visit(node.left)
for op, right in zip(node.ops, node.comparators):
rhs, rhs_ty = self.visit(right)
if isinstance(op, ast.Eq):
pred = 'eq'
elif isinstance(op, ast.Lt):
pred = 'ult'
elif isinstance(op, ast.LtE):
pred = 'ule'
elif isinstance(op, ast.Gt):
pred = 'ugt'
elif isinstance(op, ast.GtE):
pred = 'uge'
elif isinstance(op, ast.NotEq):
pred = 'ne'
else:
raise NotImplementedError('Compare operator not recognized')
ret = self._ssa_name(pred)
if lhs_ty == TFRTypes.ATTR:
self._emit_with_loc(
'\n{} = tfr.equal {}, {} -> i1'.format(ret, lhs, rhs), node)
else:
if lhs_ty == TFRTypes.I64:
code = 'arith.cmpi'
elif lhs_ty == TFRTypes.F32:
code = 'arith.cmpf'
elif lhs_ty == TFRTypes.INDEX:
code = 'arith.cmpi'
# TODO(fengliuai): the reverse type inference should solve the issue.
rhs, _ = self._i64_to_index(rhs, rhs_ty)
else:
raise NotImplementedError('Compare operand type not recognized')
self._emit_with_loc(
'\n{} = {} "{}", {}, {} : {}'.format(ret, code, pred, lhs, rhs,
lhs_ty), node)
return ret, TFRTypes.I1
def visit_Constant(self, node):
cst_name = self._ssa_name('cst')
if node.value is None:
cst_ty = TFRTypes.NONE
elif isinstance(node.value, bool):
cst_ty = self._get_inferred_type(node)
cst_val = str(node.value).lower()
self._emit_with_loc('\n{} = arith.constant {}'.format(cst_name, cst_val),
node)
else:
cst_ty = self._get_inferred_type(node)
cst_val = node.value
if cst_ty == TFRTypes.ATTR:
self._emit_with_loc(
'\n{} = tfr.constant "{}" -> {}'.format(cst_name, cst_val, cst_ty),
node)
else:
self._emit_with_loc(
'\n{} = arith.constant {} : {}'.format(cst_name, cst_val, cst_ty),
node)
return cst_name, cst_ty
def visit_FunctionDef(self, node):
op_def, derived_attrs = self._op_defs.lookup(node.name, node, True)
if op_def is None:
# Nested function. Insert it to symbol table for looking up later.
self.symbol_table.insert_symbol(node.name, node, None)
return
op_name = op_def.name
if self.symbol_table.lookup(op_name):
raise LookupError('Composition has not been registered for op: ' +
op_name)
else:
self.symbol_table.insert_symbol(node.name, None, None)
self.symbol_table.enter_scope()
self.emit('\ntfr.func @tf__{0}('.format(_camel_to_snake(op_name)))
arg_list = []
idx = 0
max_idx = len(op_def.input_arg) + len(op_def.attr)
for arg in node.args.args:
arg_name = self._ssa_name(anno.getanno(arg, anno.Basic.QN))
arg_type = anno.getanno(arg, anno.Static.TYPES)[0]
arg_attr = ''
if idx >= len(op_def.input_arg):
attr_def = op_def.attr[idx - len(op_def.input_arg)]
# skip the derived attributes
while attr_def.name in derived_attrs and (idx + 1) < max_idx:
idx += 1
attr_def = op_def.attr[idx - len(op_def.input_arg)]
if idx >= max_idx:
raise ValueError('Argument is not defined in OpDef: ' + arg_name)
arg_attr += '{{tfr.name="{}"'.format(attr_def.name)
if attr_def.HasField('default_value'):
default_val = _get_val_from_proto(arg_type, attr_def.default_value)
arg_attr += ',tfr.default={}'.format(default_val)
arg_attr += '}'
idx += 1
arg_str = '{}: {}{}'.format(arg_name, arg_type, arg_attr)
arg_list.append(arg_str)
self.symbol_table.insert_symbol(arg.id, arg_name, arg_type)
ret_type_list = []
for ret_def in op_def.output_arg:
if ret_def.number_attr or ret_def.type_list_attr:
ret_type_list.append(str(TFRTypes.TENSOR_LIST))
else:
ret_type_list.append(str(TFRTypes.TENSOR))
self.emit('{}) -> ({}) {{'.format(', '.join(arg_list),
', '.join(ret_type_list)))
self.visit_block(node.body)
self._emit_with_loc('\n}', node)
self.symbol_table.exit_scope()
def visit_arguments(self, node):
# TODO(fengliuai): return ordered the types and names.
# We need to order the arguments to match the assumption in the TFR dialect.
raise NotImplementedError('arguments not supported.')
def visit_Lambda(self, node):
raise NotImplementedError('Lambda not supported.')
def _get_mlir_ssa_values(self, name_prefix, out_types):
"""Create MLIR convention SSA values."""
out_ssa_values = []
if not out_types:
return '', out_ssa_values
out_name = self._ssa_name(name_prefix)
if len(out_types) == 1:
out_name_suffix = ''
out_ssa_values.append(out_name)
else:
# For multiple returns, MLIR uses '%s:i' when they are defined and
# '%s#i' when they are used.
out_name_suffix = ':{}'.format(len(out_types))
for idx, _ in enumerate(out_types):
out_ssa_values.append('{}#{}'.format(out_name, idx))
return '{}{}'.format(out_name, out_name_suffix), out_ssa_values
def _visit_if_stmt(self, cond, body_def, orelse_def, get_state, out_symbols,
node):
self.emit('\n')
ret_str, ret_ssa_values = self._get_mlir_ssa_values(
'if_stmt', [TFRTypes.TENSOR] * len(out_symbols))
if ret_ssa_values:
self.emit(ret_str + ' = ')
out_types = []
for symbol, ssa_value in zip(out_symbols, ret_ssa_values):
out_types.append(str(TFRTypes.TENSOR))
self.emit('scf.if {} -> ({}) {{'.format(cond, ', '.join(out_types)))
# Create a new scope in case the local variables are leaked.
self.symbol_table.enter_scope(scf_scope=True)
self.visit_block(body_def.body)
self.visit_block(get_state.body)
self.symbol_table.exit_scope()
self.emit('\n} else {')
# Create a new scope in case the local variables are leaked.
self.symbol_table.enter_scope(scf_scope=True)
self.visit_block(orelse_def.body)
self.visit_block(get_state.body)
self.symbol_table.exit_scope()
# add ssa values to the symbol table
for symbol, ssa_value in zip(out_symbols, ret_ssa_values):
self.symbol_table.insert_symbol(symbol, ssa_value, TFRTypes.TENSOR)
self._emit_with_loc('\n}', node)
return list(zip(ret_ssa_values, out_types))
def _visit_iter(self, node):
if isinstance(node, ast.Call):
f_name = anno.getanno(node.func, anno.Basic.QN)
if f_name == QN('range'):
args = [self.visit(arg) for arg in node.args]
begin = None
step = None
end = None
if len(args) == 1:
end, end_ty = args[0]
elif len(args) == 2:
begin, begin_ty = args[0]
end, end_ty = args[1]
elif len(args) == 3:
begin, begin_ty = args[0]
end, end_ty = args[1]
step, step_ty = args[2]
if begin is None:
begin = self._ssa_name('begin')
self._emit_with_loc('\n{} = arith.constant 0 : index'.format(begin),
node)
elif begin_ty != TFRTypes.INDEX:
begin_ = self._ssa_name('begin')
self._emit_with_loc(
'\n{} = arith.index_cast {} : {} to index'.format(
begin_, begin, begin_ty), node)
begin = begin_
if end_ty != TFRTypes.INDEX:
end_ = self._ssa_name('end')
self._emit_with_loc(
'\n{} = arith.index_cast {} : {} to index'.format(
end_, end, end_ty), node)
end = end_
if step is None:
step = self._ssa_name('step')
self._emit_with_loc('\n{} = arith.constant 1 : index'.format(step),
node)
elif step_ty != TFRTypes.INDEX:
step_ = self._ssa_name('step')
self._emit_with_loc(
'\n{} = arith.index_cast {} : {} to index'.format(
step_, step, step_ty), node)
step = step_
return begin, end, step
raise NotImplementedError('Iterator entity not supported.' + node)
def _visit_for_stmt(self, range_, body_def, get_state, loop_carried, node):
self.emit('\n')
ret_str, ret_ssa_values = self._get_mlir_ssa_values(
'for_stmt', [TFRTypes.TENSOR] * len(loop_carried))
if ret_ssa_values:
self.emit(ret_str + ' = ')
# Before enter the loop, we use the original ssa values as the initial
# values to the loop iteration arguments. We also create new ssa values as
# the returns of the scf for statements. The symbol table needs to be
# updated to these new ssa values before it enters the scope of the loop.
out_types = []
init_values = []
for symbol, ssa_value in zip(loop_carried, ret_ssa_values):
init, ty = self.symbol_table.lookup(symbol)
self.symbol_table.insert_symbol(symbol, ssa_value, ty)
out_types.append(str(ty))
init_values.append((init, ty))
# Create a new scope in case the local variables are leaked.
self.symbol_table.enter_scope(scf_scope=True)
# Create the iteration variable with index type
assert len(body_def.args.args) == 1
it_name = body_def.args.args[0].id
it = self._ssa_name(it_name)
self.symbol_table.insert_symbol(it_name, it, TFRTypes.INDEX)
self.emit('scf.for {} = {} to {} step {} '.format(it, range_[0], range_[1],
range_[2]))
if loop_carried:
iter_args = []
for symbol, init in zip(loop_carried, init_values):
# create new ssa values for the loop carried variables
it_arg = self._ssa_name('it_arg')
self.symbol_table.insert_symbol(symbol, it_arg, init[1])
iter_args.append('{} = {}'.format(it_arg, init[0]))
self.emit('iter_args({}) '.format(', '.join(iter_args)))
self.emit('-> ({}) {{'.format(', '.join(out_types)))
else:
self.emit(' {')
self.visit_block(body_def.body)
self.visit_block(get_state.body)
self.symbol_table.exit_scope()
self._emit_with_loc('\n}', node)
return list(zip(ret_ssa_values, out_types))
def _emit_default_constant_from_proto(self, attr_def):
"""emit mlir constant statement from default value of the ArgDef proto."""
name = self._ssa_name('cst')
cst_ty = _get_type_from_proto(None, attr_def)
try:
cst_val = _get_val_from_proto(cst_ty, attr_def.default_value)
except AttributeError:
raise AttributeError(
f'attribute "{attr_def.name}" does not have default_value. If the '
"attribute names from the API and OpDef don't match, please add it "
'to _ATTRIBUTE_RENAMES.')
if cst_ty == TFRTypes.ATTR:
self._emit_with_loc('\n{} = tfr.constant {} -> {}'.format(
name, cst_val, cst_ty))
elif cst_ty == TFRTypes.I1:
self._emit_with_loc('\n{} = arith.constant {}'.format(name, cst_val))
else:
self._emit_with_loc('\n{} = arith.constant {} : {}'.format(
name, cst_val, cst_ty))
return name, cst_ty
def visit_keyword(self, node):
return node.arg, self.visit(node.value)
def _visit_tfr_builtins(self, op_name, args, node):
arg_strs = []
arg_tys = []
for arg in args:
value, ty = self.visit(arg)
arg_strs.append(value)
arg_tys.append(ty)
tfr_op_name = 'tfr.' + op_name[5:]
ret_tys = (
TFR_BUILTINS[op_name](*arg_tys)
if callable(TFR_BUILTINS[op_name]) else TFR_BUILTINS[op_name])
# Convert the tfr builtin returns to a list.
if isinstance(ret_tys, tuple):
ret_tys = list(ret_tys)
else:
ret_tys = [ret_tys]
ret_str, ret_ssa_values = self._get_mlir_ssa_values(op_name, ret_tys)
arg_str = ', '.join(arg_strs)
arg_ty_str = ', '.join(str(ty) for ty in arg_tys)
ret_ty_str = ', '.join(str(ty) for ty in ret_tys)
self._emit_with_loc('\n{} = {}({}) : ({}) -> ({})'.format(
ret_str, tfr_op_name, arg_str, arg_ty_str, ret_ty_str), node)
return list(zip(ret_ssa_values, ret_tys))
def _visit_tf_op(self, op_name, args, keywords, node):
op_def, derived_attrs = self._op_defs.lookup(op_name)
ret_tys = [_get_type_from_proto(arg) for arg in op_def.output_arg]
ret_str, ret_ssa_values = self._get_mlir_ssa_values(op_name, ret_tys)
arg_strs = []
ty_strs = []
for arg in args:
value, ty = self.visit(arg)
arg_strs.append(value)
ty_strs.append(str(ty))
input_args = [arg for arg in op_def.input_arg]
attrs_no_default = [
attr for attr in op_def.attr
if not attr.HasField('default_value') and attr.name not in derived_attrs
]
attrs_with_default = [
attr for attr in op_def.attr
if attr.HasField('default_value') and attr.name not in derived_attrs
]
kw_args = {}
for arg in keywords:
value, (ssa_name, ty) = self.visit(arg)
ty = self._get_inferred_type(arg.value, ty)
# TODO(b/203493652): see comment on _ATTRIBUTE_RENAMES
if op_name in _ATTRIBUTE_RENAMES and value in _ATTRIBUTE_RENAMES[op_name]:
value = _ATTRIBUTE_RENAMES[op_name][value]
kw_args[value] = (ssa_name, ty)
# tensor arguments and attribute arguments
ordered_args = input_args + attrs_no_default + attrs_with_default
for attr_def in ordered_args[len(args):]:
if attr_def.name in kw_args:
value, ty = kw_args[attr_def.name]
if attr_def in input_args:
if ty in _ATTRIBUTE_TYPES:
# the argument shouldn't be used as tf op calls directly.
value, ty = self._value_to_tensor(value, ty, node)
if ty is TFRTypes.TENSOR_LIST and not _require_tensor_list(attr_def):
value, ty = self._pack_tensor_list(value)
else:
value, ty = self._emit_default_constant_from_proto(attr_def)
arg_strs.append(value)
ty_strs.append(str(ty))
if ret_ssa_values:
self.emit('\n{} = '.format(ret_str))
self.emit('tfr.call @tf__{}('.format(_camel_to_snake(op_name)))
arg_str = ', '.join(arg_strs)
arg_ty_str = ', '.join(ty_strs)
ret_ty_str = ', '.join([str(ty) for ty in ret_tys])
self._emit_with_loc(
'{}) : ({}) -> ({})'.format(arg_str, arg_ty_str, ret_ty_str), node)
return list(zip(ret_ssa_values, ret_tys))
def visit_If(self, node):
raise NotImplementedError('If not supported.')
def visit_Name(self, node):
val_and_lookup_type = self.symbol_table.lookup(node.id)
if val_and_lookup_type:
(val, lookup_type) = val_and_lookup_type
elif node.id in TFR_BUILTINS:
val = node.id
lookup_type = anno.getanno(node, anno.Static.TYPES, types.FunctionType)
else:
op_def, _ = self._op_defs.lookup(node.id)
val = op_def.name
lookup_type = anno.getanno(node, anno.Static.TYPES, types.FunctionType)
type_ = self._get_inferred_type(node, lookup_type)
return val, type_
def visit_Return(self, node):
values = self.visit(node.value)
if self.symbol_table.in_scf_scope():
self.emit('\nscf.yield ')
else:
self.emit('\ntfr.return ')
if not values:
return
if isinstance(values, list):
vals, tys = zip(*values)
else:
vals = values[0]
tys = values[1]
if isinstance(tys, list) or isinstance(tys, tuple):
tys = [str(t) for t in tys]
self._emit_with_loc('{} : {}'.format(', '.join(vals), ', '.join(tys)),
node)
elif tys != TFRTypes.NONE:
# TODO(fengliuai): scf region yield uses this branch. Fix it.
self._emit_with_loc('{} : {}'.format(vals, tys), node)
def visit_Subscript(self, node):
val, ty = self.visit(node.value)
type_ = self._get_inferred_type(node.value, ty)
# TODO(fengliuai): Here we hardcode the node.slice here to get the index
# type. Use the visit method once the type inference is done.
# slice_val, slice_ty = self.visit(node.slice)
s = node.slice
if not isinstance(s, (ast.Tuple, ast.Slice)):
if isinstance(s, ast.Constant):
# TODO(fengliuai): promote to an assignment
idx_val = self._ssa_name('cst')
self._emit_with_loc(
'\n{} = arith.constant {} : index'.format(idx_val, s.value), node)
else:
idx_val, _ = self.visit(s)
else:
raise NotImplementedError('non-index slice not supported.')
elt = self._ssa_name('elt')
if type_ == TFRTypes.TENSOR_LIST:
self.emit('\n{} = tfr.get_element {}[{}] '.format(elt, val, idx_val))
self._emit_with_loc(': (!tfr.tensor_list, index) -> !tfr.tensor', node)
return (elt, TFRTypes.TENSOR)
elif type_ == TFRTypes.TF_TENSOR_SHAPE_LIST:
size_ = self._ssa_name('size')
self.emit('\n{} = shape.get_extent {}, {}'.format(size_, val, idx_val))
self._emit_with_loc(': !shape.shape, index -> !shape.size', node)
self._emit_with_loc(
'\n{} = shape.size_to_index {} : !shape.size'.format(elt, size_),
node)
return (elt, TFRTypes.INDEX)
def visit_List(self, node):
out_type = self._get_inferred_type(node)
vals = []
tys = []
for elt in node.elts:
val, ty = self.visit(elt)
ty = self._get_inferred_type(elt, ty)
if ty in _ATTRIBUTE_TYPES and out_type == TFRTypes.TENSOR_LIST:
# This list is a tensor list, then cast all the input values to tensors.
val, ty = self._value_to_tensor(val, ty, node)
else:
# We shouldn't use index type to build the list because list will be use
# as attribute.
val, ty = self._index_to_I64(val, ty)
vals.append(val)
tys.append(str(ty))
list_val = self._ssa_name('list')
self.emit('\n{} = "tfr.build_list"({})'.format(list_val, ', '.join(vals)))
self._emit_with_loc(' : ({}) -> {}'.format(', '.join(tys), out_type), node)
return (list_val, out_type)
def visit_Tuple(self, node):
return [self.visit(elt) for elt in node.elts]
def visit_UnaryOp(self, node):
value, ty = self.visit(node.operand)
if isinstance(node.op, ast.USub):
zero_value = self._ssa_name('zero')
ssa_value = self._ssa_name('cst')
if ty == TFRTypes.I32 or ty == TFRTypes.I64:
self._emit_with_loc(
'\n{} = arith.constant 0 : {}'.format(zero_value, ty), node)
self._emit_with_loc(
'\n{} = arith.subi {}, {} : {}'.format(ssa_value, zero_value, value,
ty), node)
elif ty == TFRTypes.F32:
self._emit_with_loc(
'\n{} = arith.constant 0.0 : {}'.format(zero_value, ty), node)
self._emit_with_loc(
'\n{} = arith.subf {}, {} : {}'.format(ssa_value, zero_value, value,
ty), node)
else:
raise NotImplementedError('USub type not recognized: ' + str(ty))
return ssa_value, ty
raise NotImplementedError('USub operator not recognized')
def visit_For(self, node):
raise NotImplementedError('For operator not recognized')
def visit_While(self, node):
raise NotImplementedError('While operator not recognized')
def visit_Try(self, node):
# Only handles the body of the try statement.
self.visit_block(node.body)
def _apply_py_to_tf_passes(node, ctx):
"""Apply transformations from PyToTF to match tf.function tracing."""
# TODO(fengliuai): we don't know which passes are required, thus we evaluate
# each one when the corresponding node is handled.
# copied from PyToTF.transform_ast
node = return_statements.transform(node, ctx, False)
node = control_flow.transform(node, ctx)
return node
| TFRGen |
python | realpython__materials | python-wav-files/waveio/reader.py | {
"start": 1495,
"end": 3338
} | class ____:
DEFAULT_MAX_FRAMES = 1024
def __init__(self, path):
self._wav_file = wave.open(str(path))
self.metadata = WAVMetadata(
PCMEncoding(self._wav_file.getsampwidth()),
self._wav_file.getframerate(),
self._wav_file.getnchannels(),
self._wav_file.getnframes(),
)
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
self._wav_file.close()
@cached_property
def stereo(self):
return 2 == self.metadata.num_channels
@cached_property
@reshape("rows")
def frames(self):
return self._read(self.metadata.num_frames, start_frame=0)
@cached_property
@reshape("columns")
def channels(self):
return self.frames
@reshape("columns")
def channels_sliced(self, start_seconds=0.0, end_seconds=None):
if end_seconds is None:
end_seconds = self.metadata.num_seconds
frames_slice = slice(
round(self.metadata.frames_per_second * start_seconds),
round(self.metadata.frames_per_second * end_seconds),
)
frames_range = range(*frames_slice.indices(self.metadata.num_frames))
values = self._read(len(frames_range), frames_range.start)
return ArraySlice(values, frames_range)
@reshape("columns")
def channels_lazy(self, max_frames=DEFAULT_MAX_FRAMES):
self._wav_file.rewind()
while True:
chunk = self._read(max_frames)
if chunk.size == 0:
break
yield chunk
def _read(self, max_frames=None, start_frame=None):
if start_frame is not None:
self._wav_file.setpos(start_frame)
frames = self._wav_file.readframes(max_frames)
return self.metadata.encoding.decode(frames)
| WAVReader |
python | apache__avro | lang/py/avro/schema.py | {
"start": 18379,
"end": 20022
} | class ____(EqualByPropsMixin, NamedSchema):
def __init__(self, name, namespace, size, names=None, other_props=None, validate_names: bool = True):
# Ensure valid ctor args
if not isinstance(size, int) or size < 0:
fail_msg = "Fixed Schema requires a valid positive integer for size property."
raise avro.errors.AvroException(fail_msg)
# Call parent ctor
NamedSchema.__init__(self, "fixed", name, namespace, names, other_props, validate_names=validate_names)
# Add class members
self.set_prop("size", size)
# read-only properties
@property
def size(self):
return self.get_prop("size")
def match(self, writer):
"""Return True if the current schema (as reader) matches the writer schema.
@arg writer: the schema to match against
@return bool
"""
return self.type == writer.type and self.check_props(writer, ["fullname", "size"])
def to_json(self, names=None):
names = names or Names(validate_names=self.validate_names)
if self.fullname in names.names:
return self.name_ref(names)
names.names[self.fullname] = self
return names.prune_namespace(self.props)
def to_canonical_json(self, names=None):
to_dump = self.canonical_properties
to_dump["name"] = self.fullname
return to_dump
def validate(self, datum):
"""Return self if datum is a valid representation of this schema, else None."""
return self if isinstance(datum, bytes) and len(datum) == self.size else None
#
# Decimal Fixed Type
#
| FixedSchema |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI045.py | {
"start": 994,
"end": 1079
} | class ____:
def __iter__(self) -> typing.Iterator:
...
| TypingIteratorReturn |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed3.py | {
"start": 1502,
"end": 1562
} | class ____(ParentClosed4):
b: Required[int]
| ChildClosed4_3 |
python | spyder-ide__spyder | spyder/widgets/simplecodeeditor.py | {
"start": 2049,
"end": 18129
} | class ____(QPlainTextEdit, BaseEditMixin):
"""Simple editor with highlight features."""
LANGUAGE_HIGHLIGHTERS = {
'Python': (sh.PythonSH, '#'),
'Cython': (sh.CythonSH, '#'),
'Fortran77': (sh.Fortran77SH, 'c'),
'Fortran': (sh.FortranSH, '!'),
'Idl': (sh.IdlSH, ';'),
'Diff': (sh.DiffSH, ''),
'GetText': (sh.GetTextSH, '#'),
'Nsis': (sh.NsisSH, '#'),
'Html': (sh.HtmlSH, ''),
'Yaml': (sh.YamlSH, '#'),
'Cpp': (sh.CppSH, '//'),
'OpenCL': (sh.OpenCLSH, '//'),
'Enaml': (sh.EnamlSH, '#'),
'Markdown': (sh.MarkdownSH, '#'),
# Every other language
'None': (sh.TextSH, ''),
}
# --- Signals
# ------------------------------------------------------------------------
sig_focus_changed = Signal()
"""
This signal when the focus of the editor changes, either by a
`focusInEvent` or `focusOutEvent` event.
"""
def __init__(self, parent=None):
super().__init__(parent)
# Variables
self._linenumber_enabled = None
self._color_scheme = "spyder/dark"
self._language = None
self._blanks_enabled = None
self._scrollpastend_enabled = None
self._wrap_mode = None
self._highlight_current_line = None
self.supported_language = False
# Widgets
self._highlighter = None
self.linenumberarea = LineNumberArea(self)
# Widget setup
self.update_linenumberarea_width(0)
self._apply_current_line_highlight()
# Style
self.css = qstylizer.style.StyleSheet()
# Signals
self.blockCountChanged.connect(self.update_linenumberarea_width)
self.updateRequest.connect(self.update_linenumberarea)
self.cursorPositionChanged.connect(self._apply_current_line_highlight)
# --- Private API
# ------------------------------------------------------------------------
def _apply_color_scheme(self):
hl = self._highlighter
if hl is not None:
hl.setup_formats(self.font())
if self._color_scheme is not None:
hl.set_color_scheme(self._color_scheme)
self._set_palette(background=hl.get_background_color(),
foreground=hl.get_foreground_color())
def _set_palette(self, background, foreground):
self.css.QPlainTextEdit.setValues(
background=background.name(),
color=foreground.name(),
)
self.setStyleSheet(self.css.toString())
self.rehighlight()
def _apply_current_line_highlight(self):
if self._highlighter and self._highlight_current_line:
extra_selections = []
selection = QTextEdit.ExtraSelection()
line_color = self._highlighter.get_currentline_color()
selection.format.setBackground(line_color)
selection.format.setProperty(QTextFormat.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
extra_selections.append(selection)
self.setExtraSelections(extra_selections)
else:
self.setExtraSelections([])
# --- Qt Overrides
# ------------------------------------------------------------------------
def focusInEvent(self, event):
self.sig_focus_changed.emit()
super().focusInEvent(event)
def focusOutEvent(self, event):
self.sig_focus_changed.emit()
super().focusInEvent(event)
def resizeEvent(self, event):
super().resizeEvent(event)
if self._linenumber_enabled:
cr = self.contentsRect()
self.linenumberarea.setGeometry(
QRect(
cr.left(),
cr.top(),
self.linenumberarea_width(),
cr.height(),
)
)
# --- Public API
# ------------------------------------------------------------------------
def setup_editor(
self,
linenumbers=True,
color_scheme="spyder/dark",
language="py",
font=None,
show_blanks=False,
wrap=False,
highlight_current_line=True,
scroll_past_end=False,
):
"""
Setup editor options.
Parameters
----------
color_scheme: str, optional
Default is "spyder/dark".
language: str, optional
Default is "py".
font: QFont or None
Default is None.
show_blanks: bool, optional
Default is False/
wrap: bool, optional
Default is False.
highlight_current_line: bool, optional
Default is True.
scroll_past_end: bool, optional
Default is False
"""
if font:
self.set_font(font)
self.set_highlight_current_line(highlight_current_line)
self.set_blanks_enabled(show_blanks)
self.toggle_line_numbers(linenumbers)
self.set_scrollpastend_enabled(scroll_past_end)
self.set_language(language)
self.set_color_scheme(color_scheme)
self.toggle_wrap_mode(wrap)
def set_font(self, font):
"""
Set the editor font.
Parameters
----------
font: QFont
Font to use.
"""
if font:
self.setFont(font)
self._apply_color_scheme()
def set_color_scheme(self, color_scheme):
"""
Set the editor color scheme.
Parameters
----------
color_scheme: str
Color scheme to use.
"""
self._color_scheme = color_scheme
self._apply_color_scheme()
def set_language(self, language):
"""
Set current syntax highlighting to use `language`.
Parameters
----------
language: str or None
Language name or known extensions.
"""
sh_class = sh.TextSH
language = str(language).lower()
self.supported_language = False
for (key, value) in LANGUAGE_EXTENSIONS.items():
if language in (key.lower(), ) + value:
sh_class, __ = self.LANGUAGE_HIGHLIGHTERS[key]
self._language = key
self.supported_language = True
self._highlighter = sh_class(
self.document(), self.font(), self._color_scheme)
self._apply_color_scheme()
def toggle_line_numbers(self, state):
"""
Set visibility of line number area
Parameters
----------
state: bool
Visible state of the line number area.
"""
self._linenumber_enabled = state
self.linenumberarea.setVisible(state)
self.update_linenumberarea_width(())
def set_scrollpastend_enabled(self, state):
"""
Set scroll past end state.
Parameters
----------
state: bool
Scroll past end state.
"""
self._scrollpastend_enabled = state
self.setCenterOnScroll(state)
self.setDocument(self.document())
def toggle_wrap_mode(self, state):
"""
Set line wrap..
Parameters
----------
state: bool
Wrap state.
"""
self.set_wrap_mode('word' if state else None)
def set_wrap_mode(self, mode=None):
"""
Set line wrap mode.
Parameters
----------
mode: str or None, optional
"word", or "character". Default is None.
"""
if mode == 'word':
wrap_mode = QTextOption.WrapAtWordBoundaryOrAnywhere
elif mode == 'character':
wrap_mode = QTextOption.WrapAnywhere
else:
wrap_mode = QTextOption.NoWrap
self.setWordWrapMode(wrap_mode)
def set_highlight_current_line(self, value):
"""
Set if the current line is highlighted.
Parameters
----------
value: bool
The value of the current line highlight option.
"""
self._highlight_current_line = value
self._apply_current_line_highlight()
def set_blanks_enabled(self, state):
"""
Show blank spaces.
Parameters
----------
state: bool
Blank spaces visibility.
"""
self._blanks_enabled = state
option = self.document().defaultTextOption()
option.setFlags(option.flags()
| QTextOption.AddSpaceForLineAndParagraphSeparators)
if self._blanks_enabled:
option.setFlags(option.flags() | QTextOption.ShowTabsAndSpaces)
else:
option.setFlags(option.flags() & ~QTextOption.ShowTabsAndSpaces)
self.document().setDefaultTextOption(option)
# Rehighlight to make the spaces less apparent.
self.rehighlight()
# --- Line number area
# ------------------------------------------------------------------------
def linenumberarea_paint_event(self, event):
"""
Paint the line number area.
"""
if self._linenumber_enabled:
painter = QPainter(self.linenumberarea)
painter.fillRect(
event.rect(),
self._highlighter.get_sideareas_color(),
)
block = self.firstVisibleBlock()
block_number = block.blockNumber()
top = round(self.blockBoundingGeometry(block).translated(
self.contentOffset()).top())
bottom = top + round(self.blockBoundingRect(block).height())
font = self.font()
active_block = self.textCursor().block()
active_line_number = active_block.blockNumber() + 1
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and bottom >= event.rect().top():
number = block_number + 1
if number == active_line_number:
font.setWeight(QFont.Weight.Bold)
painter.setFont(font)
painter.setPen(
self._highlighter.get_foreground_color())
else:
font.setWeight(QFont.Weight.Normal)
painter.setFont(font)
painter.setPen(QColor(Qt.darkGray))
right_padding = self.linenumberarea._right_padding
painter.drawText(
0,
top,
self.linenumberarea.width() - right_padding,
self.fontMetrics().height(),
Qt.AlignRight, str(number),
)
block = block.next()
top = bottom
bottom = top + round(self.blockBoundingRect(block).height())
block_number += 1
def linenumberarea_width(self):
"""
Return the line number area width.
Returns
-------
int
Line number are width in pixels.
Notes
-----
If the line number area is disabled this will return zero.
"""
width = 0
if self._linenumber_enabled:
digits = 1
count = max(1, self.blockCount())
while count >= 10:
count /= 10
digits += 1
fm = self.fontMetrics()
width = (self.linenumberarea._left_padding
+ self.linenumberarea._right_padding
+ fm.width('9') * digits)
return width
def update_linenumberarea_width(self, new_block_count=None):
"""
Update the line number area width based on the number of blocks in
the document.
Parameters
----------
new_block_count: int
The current number of blocks in the document.
"""
self.setViewportMargins(self.linenumberarea_width(), 0, 0, 0)
def update_linenumberarea(self, rect, dy):
"""
Update scroll position of line number area.
"""
if self._linenumber_enabled:
if dy:
self.linenumberarea.scroll(0, dy)
else:
self.linenumberarea.update(
0, rect.y(), self.linenumberarea.width(), rect.height())
if rect.contains(self.viewport().rect()):
self.update_linenumberarea_width(0)
# --- Text and cursor handling
# ------------------------------------------------------------------------
def set_selection(self, start, end):
"""
Set current text selection.
Parameters
----------
start: int
Selection start position.
end: int
Selection end position.
"""
cursor = self.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
def stdkey_backspace(self):
if not self.has_selected_text():
self.moveCursor(QTextCursor.PreviousCharacter,
QTextCursor.KeepAnchor)
self.remove_selected_text()
def restrict_cursor_position(self, position_from, position_to):
"""
Restrict the cursor from being inside from and to positions.
Parameters
----------
position_from: int
Selection start position.
position_to: int
Selection end position.
"""
position_from = self.get_position(position_from)
position_to = self.get_position(position_to)
cursor = self.textCursor()
cursor_position = cursor.position()
if cursor_position < position_from or cursor_position > position_to:
self.set_cursor_position(position_to)
def truncate_selection(self, position_from):
"""
Restrict the cursor selection to start from the given position.
Parameters
----------
position_from: int
Selection start position.
"""
position_from = self.get_position(position_from)
cursor = self.textCursor()
start, end = cursor.selectionStart(), cursor.selectionEnd()
if start < end:
start = max([position_from, start])
else:
end = max([position_from, end])
self.set_selection(start, end)
def set_text(self, text):
"""
Set `text` of the document.
Parameters
----------
text: str
Text to set.
"""
self.setPlainText(text)
def append(self, text):
"""
Add `text` to the end of the document.
Parameters
----------
text: str
Text to append.
"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.End)
cursor.insertText(text)
def get_visible_block_numbers(self):
"""Get the first and last visible block numbers."""
first = self.firstVisibleBlock().blockNumber()
bottom_right = QPoint(self.viewport().width() - 1,
self.viewport().height() - 1)
last = self.cursorForPosition(bottom_right).blockNumber()
return (first, last)
# --- Syntax highlighter
# ------------------------------------------------------------------------
def rehighlight(self):
"""
Reapply syntax highligthing to the document.
"""
if self._highlighter:
self._highlighter.rehighlight()
self._apply_current_line_highlight()
if __name__ == "__main__":
from spyder.utils.qthelpers import qapplication
app = qapplication()
editor = SimpleCodeEditor()
editor.setup_editor(language="markdown")
editor.set_text("# Hello!")
editor.show()
app.exec_()
| SimpleCodeEditor |
python | geekcomputers__Python | Delete_Linked_List.py | {
"start": 94,
"end": 1411
} | class ____:
def __init__(self):
self.head = None
def Insert_At_End(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def Delete(self, key):
temp = self.head
if temp is None:
return "Can't Delete!"
else:
if temp.data == key:
self.head = temp.next
temp = None
while temp is not None:
prev = temp
temp = temp.next
curr = temp.next
if temp.data == key:
prev.next = curr
return
def Display(self):
temp = self.head
while temp:
print(temp.data, "->", end=" ")
temp = temp.next
print("None")
if __name__ == "__main__":
L_list = Linked_List()
L_list.Insert_At_End(1)
L_list.Insert_At_End(2)
L_list.Insert_At_End(3)
L_list.Insert_At_End(4)
L_list.Insert_At_End(5)
L_list.Insert_At_End(6)
L_list.Insert_At_End(7)
print("Linked List: ")
L_list.Display()
print("Deleted Linked List: ")
L_list.Delete(3)
L_list.Display()
| Linked_List |
python | pallets__werkzeug | src/werkzeug/formparser.py | {
"start": 10705,
"end": 15847
} | class ____:
def __init__(
self,
stream_factory: TStreamFactory | None = None,
max_form_memory_size: int | None = None,
cls: type[MultiDict[str, t.Any]] | None = None,
buffer_size: int = 64 * 1024,
max_form_parts: int | None = None,
) -> None:
self.max_form_memory_size = max_form_memory_size
self.max_form_parts = max_form_parts
if stream_factory is None:
stream_factory = default_stream_factory
self.stream_factory = stream_factory
if cls is None:
cls = t.cast("type[MultiDict[str, t.Any]]", MultiDict)
self.cls = cls
self.buffer_size = buffer_size
def fail(self, message: str) -> te.NoReturn:
raise ValueError(message)
def get_part_charset(self, headers: Headers) -> str:
# Figure out input charset for current part
content_type = headers.get("content-type")
if content_type:
parameters = parse_options_header(content_type)[1]
ct_charset = parameters.get("charset", "").lower()
# A safe list of encodings. Modern clients should only send ASCII or UTF-8.
# This list will not be extended further.
if ct_charset in {"ascii", "us-ascii", "utf-8", "iso-8859-1"}:
return ct_charset
return "utf-8"
def start_file_streaming(
self, event: File, total_content_length: int | None
) -> t.IO[bytes]:
content_type = event.headers.get("content-type")
try:
content_length = _plain_int(event.headers["content-length"])
except (KeyError, ValueError):
content_length = 0
container = self.stream_factory(
total_content_length=total_content_length,
filename=event.filename,
content_type=content_type,
content_length=content_length,
)
return container
def parse(
self, stream: t.IO[bytes], boundary: bytes, content_length: int | None
) -> tuple[MultiDict[str, str], MultiDict[str, FileStorage]]:
current_part: Field | File
field_size: int | None = None
container: t.IO[bytes] | list[bytes]
_write: t.Callable[[bytes], t.Any]
parser = MultipartDecoder(
boundary,
max_form_memory_size=self.max_form_memory_size,
max_parts=self.max_form_parts,
)
fields = []
files = []
for data in _chunk_iter(stream.read, self.buffer_size):
parser.receive_data(data)
event = parser.next_event()
while not isinstance(event, (Epilogue, NeedData)):
if isinstance(event, Field):
current_part = event
field_size = 0
container = []
_write = container.append
elif isinstance(event, File):
current_part = event
field_size = None
container = self.start_file_streaming(event, content_length)
_write = container.write
elif isinstance(event, Data):
if self.max_form_memory_size is not None and field_size is not None:
# Ensure that accumulated data events do not exceed limit.
# Also checked within single event in MultipartDecoder.
field_size += len(event.data)
if field_size > self.max_form_memory_size:
raise RequestEntityTooLarge()
_write(event.data)
if not event.more_data:
if isinstance(current_part, Field):
value = b"".join(container).decode(
self.get_part_charset(current_part.headers), "replace"
)
fields.append((current_part.name, value))
else:
container = t.cast(t.IO[bytes], container)
container.seek(0)
files.append(
(
current_part.name,
FileStorage(
container,
current_part.filename,
current_part.name,
headers=current_part.headers,
),
)
)
event = parser.next_event()
return self.cls(fields), self.cls(files)
def _chunk_iter(read: t.Callable[[int], bytes], size: int) -> t.Iterator[bytes | None]:
"""Read data in chunks for multipart/form-data parsing. Stop if no data is read.
Yield ``None`` at the end to signal end of parsing.
"""
while True:
data = read(size)
if not data:
break
yield data
yield None
| MultiPartParser |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/containers.py | {
"start": 45065,
"end": 46025
} | class ____:
"""
Scroll offsets for the :class:`.Window` class.
Note that left/right offsets only make sense if line wrapping is disabled.
"""
def __init__(
self,
top: int | Callable[[], int] = 0,
bottom: int | Callable[[], int] = 0,
left: int | Callable[[], int] = 0,
right: int | Callable[[], int] = 0,
) -> None:
self._top = top
self._bottom = bottom
self._left = left
self._right = right
@property
def top(self) -> int:
return to_int(self._top)
@property
def bottom(self) -> int:
return to_int(self._bottom)
@property
def left(self) -> int:
return to_int(self._left)
@property
def right(self) -> int:
return to_int(self._right)
def __repr__(self) -> str:
return f"ScrollOffsets(top={self._top!r}, bottom={self._bottom!r}, left={self._left!r}, right={self._right!r})"
| ScrollOffsets |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/hooks/search_ads.py | {
"start": 1285,
"end": 7905
} | class ____(GoogleBaseHook):
"""Hook for the Google Search Ads 360 Reporting API."""
_conn: build | None = None
default_api_version: str = "v0"
def __init__(
self,
api_version: str | None = None,
gcp_conn_id: str = "google_search_ads_default",
**kwargs,
) -> None:
super().__init__(gcp_conn_id=gcp_conn_id, **kwargs)
self.api_version = api_version or self.default_api_version
def _get_config(self) -> None:
"""
Set up Google Search Ads config from Connection.
This pulls the connections from db, and uses it to set up
``google_search_ads_client``.
"""
conn = self.get_connection(self.gcp_conn_id)
if "google_search_ads_client" not in conn.extra_dejson:
raise AirflowException("google_search_ads_client not found in extra field")
self.google_search_ads_config = conn.extra_dejson["google_search_ads_client"]
def get_credentials(self) -> Credentials:
"""Return the credential instance for search ads."""
self._get_config()
self.logger().info(f"Credential configuration: {self.google_search_ads_config}")
return Credentials(**self.google_search_ads_config)
def get_conn(self) -> Resource:
if not self._conn:
creds = self.get_credentials()
self._conn = build(
"searchads360",
self.api_version,
credentials=creds,
cache_discovery=False,
)
return self._conn
@cached_property
def customer_service(self):
return self.get_conn().customers()
@cached_property
def fields_service(self):
return self.get_conn().searchAds360Fields()
def search(
self,
customer_id: str,
query: str,
page_token: str | None = None,
page_size: int = 10000,
return_total_results_count: bool = False,
summary_row_setting: str | None = None,
validate_only: bool = False,
):
"""
Search and download the report. Use pagination to download entire report.
:param customer_id: The ID of the customer being queried.
:param query: The query to execute.
:param page_token: Token of the page to retrieve. If not specified, the first page of results will be
returned. Use the value obtained from `next_page_token` in the previous response
in order to request the next page of results.
:param page_size: Number of elements to retrieve in a single page. When too large a page is requested,
the server may decide to further limit the number of returned resources.
Default is 10000.
:param return_total_results_count: If true, the total number of results that match the query ignoring
the LIMIT clause will be included in the response. Default is false.
:param summary_row_setting: Determines whether a summary row will be returned. By default,
summary row is not returned. If requested, the summary row will be sent
in a response by itself after all others query results are returned.
:param validate_only: If true, the request is validated but not executed. Default is false.
"""
params: dict[str, Any] = {
"query": query,
"pageSize": page_size,
"returnTotalResultsCount": return_total_results_count,
"validateOnly": validate_only,
}
if page_token is not None:
params.update({"pageToken": page_token})
if summary_row_setting is not None:
params.update({"summaryRowSetting": summary_row_setting})
response = (
self.customer_service.searchAds360()
.search(customerId=customer_id, body=params)
.execute(num_retries=self.num_retries)
)
self.log.info("Search response: %s", response)
return response
def get_custom_column(self, customer_id: str, custom_column_id: str):
"""
Retrieve the requested custom column in full detail.
:param customer_id: The customer id
:param custom_column_id: The custom column id
"""
resource_name = f"customers/{customer_id}/customColumns/{custom_column_id}"
response = (
self.customer_service.customColumns()
.get(resourceName=resource_name)
.execute(num_retries=self.num_retries)
)
self.log.info("Retrieved custom column: %s", response)
return response
def list_custom_columns(self, customer_id: str):
"""
Retrieve all the custom columns associated with the customer in full detail.
:param customer_id: The customer id
"""
response = (
self.customer_service.customColumns()
.list(customerId=customer_id)
.execute(num_retries=self.num_retries)
)
self.log.info("Listing the custom columns: %s", response)
return response
def get_field(self, field_name: str):
"""
Retrieve the requested field details.
:param field_name: The name of the field.
"""
resource_name = f"searchAds360Fields/{field_name}"
response = self.fields_service.get(resourceName=resource_name).execute(num_retries=self.num_retries)
self.log.info("Retrieved field: %s", response)
return response
def search_fields(self, query: str, page_token: str | None = None, page_size: int | None = 10000):
"""
Retrieve all the fields that match with the given search.
:param query: The query string to execute.
:param page_token: Token of the page to retrieve. If not specified, the first page of results will be
returned. Use the value obtained from `next_page_token` in the previous response
in order to request the next page of results.
:param page_size: Number of elements to retrieve in a single page. When too large a page is requested,
the server may decide to further limit the number of returned resources.
Default 10000.
"""
params: dict[str, Any] = {
"query": query,
"pageSize": page_size,
}
if page_token is not None:
params.update({"pageToken": page_token})
response = self.fields_service.search(body=params).execute(num_retries=self.num_retries)
self.log.info("Retrieved fields: %s", response)
return response
| GoogleSearchAdsReportingHook |
python | prabhupant__python-ds | data_structures/graphs/count_paths_between_nodes.py | {
"start": 37,
"end": 946
} | class ____:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def count_paths_util(self, u, d, visited, path_count):
visited[u] = True
if u == d:
path_count[0] += 1
else:
i = 0
for i in range(len(self.graph[u])):
if not visited[self.graph[u][i]]:
self.count_paths_util(self.graph[u][i], d, visited, path_count)
visited[u] = False
def count_paths(self, s, d):
visited = [False] * self.V
path_count = [0]
self.count_paths_util(s, d, visited, path_count)
return path_count[0]
g = Graph(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(0, 3)
g.add_edge(2, 0)
g.add_edge(2, 1)
g.add_edge(1, 3)
s = 2
d = 3
print(g.count_paths(s, d))
| Graph |
python | agronholm__apscheduler | tests/test_schedulers.py | {
"start": 47388,
"end": 58957
} | class ____:
def test_interface_parity(self) -> None:
"""
Ensure that the sync scheduler has the same properties and methods as the async
schedulers, and the method parameters match too.
"""
actual_attributes = set(dir(Scheduler))
expected_attributes = sorted(
attrname for attrname in dir(AsyncScheduler) if not attrname.startswith("_")
)
for attrname in expected_attributes:
if attrname not in actual_attributes:
pytest.fail(f"SyncScheduler is missing the {attrname} attribute")
async_attrval = getattr(AsyncScheduler, attrname)
sync_attrval = getattr(Scheduler, attrname)
if callable(async_attrval):
async_sig = signature(async_attrval)
async_args: dict[int, list] = defaultdict(list)
for param in async_sig.parameters.values():
if param.name not in ("task_status", "is_async"):
async_args[param.kind].append(param)
sync_sig = signature(sync_attrval)
sync_args: dict[int, list] = defaultdict(list)
for param in sync_sig.parameters.values():
sync_args[param.kind].append(param)
for kind, args in async_args.items():
assert args == sync_args[kind], (
f"Parameter mismatch for {attrname}(): {args} != {sync_args[kind]}"
)
def test_repr(self) -> None:
scheduler = Scheduler(identity="my identity")
assert repr(scheduler) == (
"Scheduler(identity='my identity', role=<SchedulerRole.both: 3>, "
"data_store=MemoryDataStore(), event_broker=LocalEventBroker())"
)
def test_configure(self) -> None:
executor = ThreadPoolJobExecutor()
task_defaults = TaskDefaults(job_executor="executor1")
scheduler = Scheduler(
identity="identity",
role=SchedulerRole.scheduler,
max_concurrent_jobs=150,
cleanup_interval=5,
job_executors={"executor1": executor},
task_defaults=task_defaults,
)
assert scheduler.identity == "identity"
assert scheduler.role is SchedulerRole.scheduler
assert scheduler.max_concurrent_jobs == 150
assert scheduler.cleanup_interval == timedelta(seconds=5)
assert scheduler.job_executors == {"executor1": executor}
assert scheduler.task_defaults == task_defaults
@pytest.mark.parametrize("as_default", [False, True])
def test_threadpool_executor(self, as_default: bool) -> None:
with Scheduler() as scheduler:
scheduler.start_in_background()
if as_default:
thread_id = scheduler.run_job(threading.get_ident)
else:
thread_id = scheduler.run_job(
threading.get_ident, job_executor="threadpool"
)
assert thread_id != threading.get_ident()
def test_processpool_executor(self) -> None:
with Scheduler() as scheduler:
scheduler.start_in_background()
pid = scheduler.run_job(os.getpid, job_executor="processpool")
assert pid != os.getpid()
def test_properties(self) -> None:
with Scheduler() as scheduler:
assert isinstance(scheduler.data_store, MemoryDataStore)
assert isinstance(scheduler.event_broker, LocalEventBroker)
assert scheduler.role is SchedulerRole.both
assert isinstance(scheduler.identity, str)
assert len(scheduler.job_executors) == 3
assert isinstance(scheduler.job_executors["async"], AsyncJobExecutor)
assert isinstance(
scheduler.job_executors["threadpool"], ThreadPoolJobExecutor
)
assert isinstance(
scheduler.job_executors["processpool"], ProcessPoolJobExecutor
)
assert isinstance(scheduler.task_defaults, TaskDefaults)
assert scheduler.state is RunState.stopped
def test_use_without_contextmanager(self, mocker: MockFixture) -> None:
fake_atexit_register = mocker.patch("atexit.register")
scheduler = Scheduler()
scheduler.subscribe(lambda event: None)
fake_atexit_register.assert_called_once_with(scheduler._exit_stack.close)
scheduler._exit_stack.close()
def test_configure_task(self) -> None:
queue: Queue[Event] = Queue()
with Scheduler() as scheduler:
scheduler.subscribe(queue.put_nowait)
scheduler.configure_task("mytask", func=dummy_sync_job)
scheduler.configure_task("mytask", misfire_grace_time=2)
tasks = scheduler.get_tasks()
assert len(tasks) == 1
assert tasks[0].id == "mytask"
assert tasks[0].func == f"{__name__}:dummy_sync_job"
assert tasks[0].misfire_grace_time == timedelta(seconds=2)
event = queue.get(timeout=1)
assert isinstance(event, TaskAdded)
assert event.task_id == "mytask"
event = queue.get(timeout=1)
assert isinstance(event, TaskUpdated)
assert event.task_id == "mytask"
def test_add_remove_schedule(self, timezone: ZoneInfo) -> None:
queue: Queue[Event] = Queue()
with Scheduler() as scheduler:
scheduler.subscribe(queue.put_nowait)
now = datetime.now(timezone)
trigger = DateTrigger(now)
schedule_id = scheduler.add_schedule(dummy_async_job, trigger, id="foo")
assert schedule_id == "foo"
schedules = scheduler.get_schedules()
assert len(schedules) == 1
assert schedules[0].id == "foo"
assert schedules[0].task_id == f"{__name__}:dummy_async_job"
schedule = scheduler.get_schedule(schedule_id)
assert schedules[0] == schedule
scheduler.remove_schedule(schedule_id)
assert not scheduler.get_schedules()
event = queue.get(timeout=1)
assert isinstance(event, TaskAdded)
assert event.task_id == f"{__name__}:dummy_async_job"
event = queue.get(timeout=1)
assert isinstance(event, ScheduleAdded)
assert event.schedule_id == "foo"
assert event.next_fire_time == now
event = queue.get(timeout=1)
assert isinstance(event, ScheduleRemoved)
assert event.schedule_id == "foo"
assert not event.finished
def test_add_job_wait_result(self) -> None:
queue: Queue[Event] = Queue()
with Scheduler() as scheduler:
assert scheduler.get_jobs() == []
scheduler.subscribe(queue.put_nowait)
job_id = scheduler.add_job(dummy_sync_job, result_expiration_time=10)
event = queue.get(timeout=1)
assert isinstance(event, TaskAdded)
assert event.task_id == f"{__name__}:dummy_sync_job"
event = queue.get(timeout=1)
assert isinstance(event, JobAdded)
assert event.job_id == job_id
jobs = scheduler.get_jobs()
assert len(jobs) == 1
assert jobs[0].id == job_id
assert jobs[0].task_id == f"{__name__}:dummy_sync_job"
with pytest.raises(JobLookupError):
scheduler.get_job_result(job_id, wait=False)
scheduler.start_in_background()
event = queue.get(timeout=1)
assert isinstance(event, SchedulerStarted)
event = queue.get(timeout=1)
assert isinstance(event, JobAcquired)
assert event.job_id == job_id
assert event.task_id == f"{__name__}:dummy_sync_job"
assert event.schedule_id is None
event = queue.get(timeout=1)
assert isinstance(event, JobReleased)
assert event.job_id == job_id
assert event.task_id == f"{__name__}:dummy_sync_job"
assert event.schedule_id is None
assert event.outcome is JobOutcome.success
result = scheduler.get_job_result(job_id)
assert result
assert result.outcome is JobOutcome.success
assert result.return_value == "returnvalue"
def test_wait_until_stopped(self) -> None:
queue: Queue[Event] = Queue()
with Scheduler() as scheduler:
scheduler.configure_task("stop", func=scheduler.stop)
scheduler.add_job("stop")
scheduler.subscribe(queue.put_nowait)
scheduler.start_in_background()
scheduler.wait_until_stopped()
event = queue.get(timeout=1)
assert isinstance(event, SchedulerStarted)
event = queue.get(timeout=1)
assert isinstance(event, JobAcquired)
event = queue.get(timeout=1)
assert isinstance(event, JobReleased)
event = queue.get(timeout=1)
assert isinstance(event, SchedulerStopped)
def test_explicit_cleanup(self) -> None:
with Scheduler(cleanup_interval=None) as scheduler:
event = threading.Event()
scheduler.add_schedule(
event.set, DateTrigger(datetime.now(timezone.utc)), id="event_set"
)
scheduler.start_in_background()
assert event.wait(3)
# The schedule should still be around, but with a null next_fire_time
schedule = scheduler.get_schedule("event_set")
assert schedule.next_fire_time is None
# After the cleanup, the schedule should be gone
scheduler.cleanup()
with pytest.raises(ScheduleLookupError):
scheduler.get_schedule("event_set")
def test_run_until_stopped(self) -> None:
queue: Queue[Event] = Queue()
with Scheduler() as scheduler:
scheduler.configure_task("stop", func=scheduler.stop)
scheduler.add_job("stop")
scheduler.subscribe(queue.put_nowait)
scheduler.run_until_stopped()
event = queue.get(timeout=1)
assert isinstance(event, SchedulerStarted)
event = queue.get(timeout=1)
assert isinstance(event, JobAcquired)
event = queue.get(timeout=1)
assert isinstance(event, JobReleased)
event = queue.get(timeout=1)
assert isinstance(event, SchedulerStopped)
def test_uwsgi_threads_error(self, monkeypatch: MonkeyPatch) -> None:
mod = ModuleType("uwsgi")
monkeypatch.setitem(sys.modules, "uwsgi", mod)
mod.has_threads = False
with pytest.raises(
RuntimeError, match="The scheduler seems to be running under uWSGI"
):
Scheduler().start_in_background()
def test_uwsgi_threads_error_subprocess(self) -> None:
uwsgi_path = Path(sysconfig.get_path("scripts")) / "uwsgi"
if not uwsgi_path.is_file():
pytest.skip("uwsgi is not installed")
# This tests the error with a real uWSGI subprocess
script_path = (
Path(__file__).parent.parent / "examples" / "web" / "wsgi_noframework.py"
)
assert script_path.is_file()
proc = subprocess.run(
["uwsgi", "--http", ":8000", "--need-app", "--wsgi-file", str(script_path)],
capture_output=True,
)
assert proc.returncode == 22
assert b"The scheduler seems to be running under uWSGI" in proc.stderr
| TestSyncScheduler |
python | mlflow__mlflow | mlflow/models/model_config.py | {
"start": 192,
"end": 5072
} | class ____:
"""
ModelConfig used in code to read a YAML configuration file or a dictionary.
Args:
development_config: Path to the YAML configuration file or a dictionary containing the
configuration. If the configuration is not provided, an error is raised
.. code-block:: python
:caption: Example usage in model code
from mlflow.models import ModelConfig
# Load the configuration from a dictionary
config = ModelConfig(development_config={"key1": "value1"})
print(config.get("key1"))
.. code-block:: yaml
:caption: yaml file for model configuration
key1: value1
another_key:
- value2
- value3
.. code-block:: python
:caption: Example yaml usage in model code
from mlflow.models import ModelConfig
# Load the configuration from a file
config = ModelConfig(development_config="config.yaml")
print(config.get("key1"))
When invoking the ModelConfig locally in a model file, development_config can be passed in
which would be used as configuration for the model.
.. code-block:: python
:caption: Example to use ModelConfig when logging model as code: agent.py
import mlflow
from mlflow.models import ModelConfig
config = ModelConfig(development_config={"key1": "value1"})
class TestModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
return config.get("key1")
mlflow.models.set_model(TestModel())
But this development_config configuration file will be overridden when logging a model.
When no model_config is passed in while logging the model, an error will be raised when
trying to load the model using ModelConfig.
Note: development_config is not used when logging the model.
.. code-block:: python
:caption: Example to use agent.py to log the model: deploy.py
model_config = {"key1": "value2"}
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model", python_model="agent.py", model_config=model_config
)
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)
# This will print "value2" as the model_config passed in while logging the model
print(loaded_model.predict(None))
"""
def __init__(self, *, development_config: str | dict[str, Any] | None = None):
config = globals().get("__mlflow_model_config__", None)
# Here mlflow_model_config have 3 states:
# 1. None, this means if the mlflow_model_config is None, use development_config if
# available
# 2. "", Empty string, this means the users explicitly didn't set the model config
# while logging the model so if ModelConfig is used, it should throw an error
# 3. A valid path, this means the users have set the model config while logging the
# model so use that path
if config is not None:
self.config = config
else:
self.config = development_config
if not self.config:
raise FileNotFoundError(
"Config file is not provided which is needed to load the model. "
"Please provide a valid path."
)
if not isinstance(self.config, dict) and not os.path.isfile(self.config):
raise FileNotFoundError(f"Config file '{self.config}' not found.")
def _read_config(self):
"""Reads the YAML configuration file and returns its contents.
Raises:
FileNotFoundError: If the configuration file does not exist.
yaml.YAMLError: If there is an error parsing the YAML content.
Returns:
dict or None: The content of the YAML file as a dictionary, or None if the
config path is not set.
"""
if isinstance(self.config, dict):
return self.config
with open(self.config) as file:
try:
return yaml.safe_load(file)
except yaml.YAMLError as e:
raise MlflowException(
f"Error parsing YAML file: {e}", error_code=INVALID_PARAMETER_VALUE
)
def to_dict(self):
"""Returns the configuration as a dictionary."""
return self._read_config()
def get(self, key):
"""Gets the value of a top-level parameter in the configuration."""
config_data = self._read_config()
if config_data and key in config_data:
return config_data[key]
else:
raise KeyError(f"Key '{key}' not found in configuration: {config_data}.")
def _set_model_config(model_config):
globals()["__mlflow_model_config__"] = model_config
| ModelConfig |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 4399,
"end": 4570
} | class ____(BaseStringType):
"""Xsd:string with whitespace collapsing, e.g. multiple spaces reduced to one,
leading and trailing space stripped."""
pass
| XsdToken |
python | pytorch__pytorch | torch/ao/quantization/backend_config/backend_config.py | {
"start": 11140,
"end": 17346
} | class ____:
# TODO: refer to NativeBackendConfig once that is implemented
"""Config that defines the set of patterns that can be quantized on a given backend, and how reference
quantized models can be produced from these patterns.
A pattern in this context refers to a module, a functional, an operator, or a directed acyclic graph
of the above. Each pattern supported on the target backend can be individually configured through
:class:`~torch.ao.quantization.backend_config.BackendPatternConfig` in terms of:
(1) The supported input/output activation, weight, and bias data types
(2) How observers and quant/dequant ops are inserted in order to construct the reference pattern, and
(3) (Optionally) Fusion, QAT, and reference module mappings.
The format of the patterns is described in:
https://github.com/pytorch/pytorch/blob/master/torch/ao/quantization/backend_config/README.md
Example usage::
import torch
from torch.ao.quantization.backend_config import (
BackendConfig,
BackendPatternConfig,
DTypeConfig,
ObservationType,
)
weighted_int8_dtype_config = DTypeConfig(
input_dtype=torch.quint8,
output_dtype=torch.quint8,
weight_dtype=torch.qint8,
bias_dtype=torch.float)
def fuse_conv2d_relu(is_qat, conv, relu):
return torch.ao.nn.intrinsic.ConvReLU2d(conv, relu)
# For quantizing Linear
linear_config = BackendPatternConfig(torch.nn.Linear) \
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
.add_dtype_config(weighted_int8_dtype_config) \
.set_root_module(torch.nn.Linear) \
.set_qat_module(torch.ao.nn.qat.Linear) \
.set_reference_quantized_module(torch.ao.nn.quantized.reference.Linear)
# For fusing Conv2d + ReLU into ConvReLU2d
conv_relu_config = BackendPatternConfig((torch.nn.Conv2d, torch.nn.ReLU)) \
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
.add_dtype_config(weighted_int8_dtype_config) \
.set_fused_module(torch.ao.nn.intrinsic.ConvReLU2d) \
.set_fuser_method(fuse_conv2d_relu)
# For quantizing ConvReLU2d
fused_conv_relu_config = BackendPatternConfig(torch.ao.nn.intrinsic.ConvReLU2d) \
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
.add_dtype_config(weighted_int8_dtype_config) \
.set_root_module(torch.nn.Conv2d) \
.set_qat_module(torch.ao.nn.intrinsic.qat.ConvReLU2d) \
.set_reference_quantized_module(torch.ao.nn.quantized.reference.Conv2d)
backend_config = BackendConfig("my_backend") \
.set_backend_pattern_config(linear_config) \
.set_backend_pattern_config(conv_relu_config) \
.set_backend_pattern_config(fused_conv_relu_config)
"""
def __init__(self, name: str = ""):
self.name = name
# Store all BackendPatternConfigs in a map to handle duplicates
# Note: the key in this map uses the complex reversed tuple format.
# This is intended only for internal use; users who wish to access
# the original patterns should go through `self.configs` instead.
self._pattern_complex_format_to_config: dict[Pattern, BackendPatternConfig] = {}
def __repr__(self):
return f"BackendConfig({self.__dict__})"
def set_name(self, name: str) -> BackendConfig:
"""
Set the name of the target backend.
"""
self.name = name
return self
def set_backend_pattern_config(self, config: BackendPatternConfig) -> BackendConfig:
"""
Set the config for an pattern that can be run on the target backend.
This overrides any existing config for the given pattern.
"""
# Avoid circular dependencies
pattern_complex_format = torch.ao.quantization.backend_config.utils._get_pattern_in_reversed_nested_tuple_format(
config
) # type: ignore[attr-defined]
self._pattern_complex_format_to_config[pattern_complex_format] = config
return self
def set_backend_pattern_configs(
self, configs: list[BackendPatternConfig]
) -> BackendConfig:
"""
Set the configs for patterns that can be run on the target backend.
This overrides any existing config for a given pattern if it was previously registered already.
"""
for conf in configs:
self.set_backend_pattern_config(conf)
return self
@property
def configs(self) -> list[BackendPatternConfig]:
"""
Return a copy of the list of configs set in this `BackendConfig`.
"""
return list(self._pattern_complex_format_to_config.values())
@classmethod
def from_dict(cls, backend_config_dict: dict[str, Any]) -> BackendConfig:
"""
Create a ``BackendConfig`` from a dictionary with the following items:
"name": the name of the target backend
"configs": a list of dictionaries that each represents a `BackendPatternConfig`
"""
conf = cls(backend_config_dict.get(NAME_DICT_KEY, ""))
for d in backend_config_dict.get(CONFIGS_DICT_KEY, []):
if isinstance(d, BackendPatternConfig):
conf.set_backend_pattern_config(d)
elif isinstance(d, dict):
conf.set_backend_pattern_config(BackendPatternConfig.from_dict(d))
else:
raise ValueError(
f"Expected backend_config_dict['{CONFIGS_DICT_KEY}'] to be a dictionary"
)
return conf
def to_dict(self) -> dict[str, Any]:
"""
Convert this ``BackendConfig`` to a dictionary with the items described in
:func:`~torch.ao.quantization.backend_config.BackendConfig.from_dict`.
"""
return {
NAME_DICT_KEY: self.name,
CONFIGS_DICT_KEY: [c.to_dict() for c in self.configs],
}
| BackendConfig |
python | coleifer__peewee | tests/regressions.py | {
"start": 20845,
"end": 20932
} | class ____(TestModel):
game = ForeignKeyField(Game)
points = IntegerField()
| Score |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v2.py | {
"start": 2757,
"end": 3186
} | class ____(sharded_variable.ShardedVariableMixin):
"""A ShardedVariable class for TPU."""
@property
def _in_graph_mode(self):
return self.variables[0]._in_graph_mode # pylint: disable=protected-access
def _add_key_attr(op, name):
op._set_attr(_NAME_KEY, attr_value_pb2.AttrValue(s=compat.as_bytes(name))) # pylint: disable=protected-access
@tf_export("tpu.experimental.embedding.TPUEmbedding")
| TPUEmbeddingVariable |
python | pytorch__pytorch | torch/distributed/elastic/agent/server/api.py | {
"start": 10665,
"end": 12540
} | class ____:
"""The class is used by the agent to exchange the information with other agents.
The information is used to determine the rank of the workers that agent
manages in heterogeneous environments, where different agents can have
different number of workers.
"""
__slots__ = ["role", "rank", "local_world_size"]
def __init__(self, role: str, rank: int, local_world_size: int):
r"""Initialize the agent class instance.
Args:
role (str): user-defined role for the workers with this spec
rank (int): the rank of the agent
local_world_size (int): number of local workers to run
"""
self.role = role
self.rank = rank
self.local_world_size = local_world_size
def serialize(self) -> bytes:
dict_data = {
"role": self.role,
"rank": self.rank,
"local_world_size": self.local_world_size,
}
return json.dumps(dict_data).encode(encoding="UTF-8")
@staticmethod
def deserialize(data: bytes):
dict_data = json.loads(data.decode(encoding="UTF-8"))
return _RoleInstanceInfo(
dict_data["role"], dict_data["rank"], dict_data["local_world_size"]
)
@staticmethod
def compare(obj1, obj2) -> int:
if obj1.role == obj2.role:
return obj1.rank - obj2.rank
elif obj1.role > obj2.role:
return 1
else:
return -1
@staticmethod
def find_role_boundaries(roles_infos: list, role: str) -> tuple[int, int]:
start_idx, end_idx = -1, -1
for idx, role_info in enumerate(roles_infos):
if role_info.role == role:
if start_idx == -1:
start_idx = idx
end_idx = idx
return (start_idx, end_idx)
@dataclass
| _RoleInstanceInfo |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/agent.py | {
"start": 348,
"end": 462
} | class ____(BaseModel):
"""Agent metadata key-value pair."""
key: str
value: str
| DgApiAgentMetadataEntry |
python | tensorflow__tensorflow | tensorflow/lite/python/lite_v2_test.py | {
"start": 148193,
"end": 159725
} | class ____(lite_v2_test_util.ModelTest):
@test_util.run_v2_only
def testCond(self):
input_data = {
'x': tf.constant([1.0, 2.0], shape=[1, 2]),
'b': tf.constant(True),
}
weights = tf.Variable([[0.1, 0.2], [0.3, 0.4]], dtype=tf.float32)
def true_fn(x):
return tf.matmul(x, weights)
def false_fn(x):
return tf.add(x, weights)
@tf.function(
input_signature=[
tf.TensorSpec(shape=[1, 2], dtype=tf.float32),
tf.TensorSpec(shape=(), dtype=tf.bool),
]
)
def model(x, b):
return tf.cond(
b, true_fn=lambda: true_fn(x), false_fn=lambda: false_fn(x)
)
concrete_func = model.get_concrete_function()
# Convert model.
converter = lite.TFLiteConverterV2.from_concrete_functions(
[concrete_func], model
)
tflite_model = converter.convert()
# Check values from converted model.
expected_value = concrete_func(**input_data)
actual_value = self._evaluateTFLiteModel(
tflite_model, [input_data['x'], input_data['b']]
)[0]
self.assertAllClose(expected_value, actual_value)
@test_util.run_v2_only
def testCondWithFullIntegerQuantization(self):
weights = tf.Variable([[0.1, 0.2], [0.3, 0.4]], dtype=tf.float32)
def true_fn(x):
return tf.matmul(x, weights)
def false_fn(x):
return tf.add(x, weights)
@tf.function(
input_signature=[
tf.TensorSpec(shape=[1, 2], dtype=tf.float32),
tf.TensorSpec(shape=(), dtype=tf.bool),
]
)
def model(x, b):
return tf.cond(
b, true_fn=lambda: true_fn(x), false_fn=lambda: false_fn(x)
)
def calibration_gen():
for _ in range(5):
yield [
np.random.uniform(-1, 1, size=(1, 2)).astype(np.float32),
tf.constant(True),
]
for _ in range(5):
yield [
np.random.uniform(-1, 1, size=(1, 2)).astype(np.float32),
tf.constant(False),
]
concrete_func = model.get_concrete_function()
# Convert model.
converter = lite.TFLiteConverterV2.from_concrete_functions(
[concrete_func], model
)
converter.optimizations = [lite.Optimize.DEFAULT]
converter.representative_dataset = calibration_gen
tflite_model = converter.convert()
self.assertIsNotNone(tflite_model)
@test_util.run_v2_only
def testConverterErrorOnControlFlowV1Ops(self):
filename = resource_loader.get_path_to_datafile(
'testdata/control_flow_v1_saved_model'
)
converter = lite.TFLiteConverterV2.from_saved_model(filename)
with self.assertRaises(convert.ConverterError) as error:
converter.convert()
self.assertIn(
'Failed to functionalize Control Flow V1 ops. Consider using Control '
'Flow V2 ops instead. See https://www.tensorflow.org/api_docs/python/'
'tf/compat/v1/enable_control_flow_v2.',
str(error.exception),
)
@test_util.run_v2_only
def testStaticRnn(self):
input_data = tf.constant(
np.array(np.random.random_sample((3, 10)), dtype=np.float32)
)
cell = tf.keras.layers.LSTMCell(10)
@tf.function(
input_signature=[tf.TensorSpec(shape=[3, 10], dtype=tf.float32)]
)
def model(x):
seq = tf.split(x, 3, 0)
return rnn.static_rnn(cell, seq, dtype=tf.float32, sequence_length=[1])
concrete_func = model.get_concrete_function()
# Convert model.
converter = lite.TFLiteConverterV2.from_concrete_functions(
[concrete_func], model
)
tflite_model = converter.convert()
# Check values from converted model.
expected_value = concrete_func(input_data)[0]
actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])
for expected, actual in zip(expected_value, actual_value):
self.assertAllClose(expected, actual)
@test_util.run_v2_only
def testWhileLoop(self):
input_data = tf.constant([1.0, 2.0, 3.0, 4.0], shape=[2, 2])
weights = tf.Variable([[0.1, 0.2], [0.3, 0.4]], dtype=tf.float32)
def condition(x):
return tf.reduce_sum(x) < 100
def body(x):
return tf.add(x, weights)
@tf.function(
input_signature=[tf.TensorSpec(shape=[2, 2], dtype=tf.float32)]
)
def model(x):
return tf.while_loop(condition, body, [x])
concrete_func = model.get_concrete_function()
# Convert model.
converter = lite.TFLiteConverterV2.from_concrete_functions(
[concrete_func], model
)
tflite_model = converter.convert()
# Check values from converted model.
expected_value = concrete_func(input_data)[0]
actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
self.assertAllClose(expected_value, actual_value)
@test_util.run_v2_only
def testDynamicRnn(self):
input_data = tf.constant(
np.array(np.random.random_sample((3, 10, 10)), dtype=np.float32)
)
cell = tf.keras.layers.LSTMCell(10)
@tf.function(
input_signature=[tf.TensorSpec(shape=[3, 10, 10], dtype=tf.float32)]
)
def model(x):
rnn_layer = tf.keras.layers.RNN([cell], return_sequences=True)
return rnn_layer(x)
concrete_func = model.get_concrete_function()
# Convert model.
converter = lite.TFLiteConverterV2.from_concrete_functions(
[concrete_func], model
)
tflite_model = converter.convert()
# Check values from converted model.
expected_value = concrete_func(input_data)
lite_outputs = self._evaluateTFLiteModel(tflite_model, [input_data])
self.assertLen(lite_outputs, 1)
actual_value = lite_outputs[0]
for expected, actual in zip(expected_value, actual_value):
self.assertAllClose(expected, actual)
@parameterized.named_parameters(
('LSTMBatchSizeOne', tf.keras.layers.LSTM, True),
('LSTM', tf.keras.layers.LSTM, False),
('SimpleRNNBatchSizeOne', tf.keras.layers.SimpleRNN, True),
('SimpleRNN', tf.keras.layers.SimpleRNN, False),
('GRUBatchSizeOne', tf.keras.layers.GRU, True),
('GRU', tf.keras.layers.GRU, False),
)
@test_util.run_v2_only
def testKerasRNN(self, rnn_layer, default_to_single_batch):
input_data = tf.constant(
np.array(np.random.random_sample((1, 10, 10)), dtype=np.float32)
)
rnn_obj = rnn_layer(units=10, input_shape=(10, 10))
model = tf.keras.models.Sequential([
tf.keras.layers.Input(shape=(10, 10), name='input'),
rnn_obj,
])
# Convert model.
converter = lite.TFLiteConverterV2.from_keras_model(model)
converter._experimental_default_to_single_batch_in_tensor_list_ops = (
default_to_single_batch
)
if not default_to_single_batch:
converter.target_spec.supported_ops = [
lite.OpsSet.TFLITE_BUILTINS,
lite.OpsSet.SELECT_TF_OPS,
]
tflite_model = converter.convert()
actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
# Check values from converted model.
expected_value = model.predict(input_data)
self.assertAllClose(expected_value, actual_value, atol=1e-05)
@parameterized.named_parameters(
('LSTM', tf.keras.layers.LSTM),
('SimpleRNN', tf.keras.layers.SimpleRNN),
('GRU', tf.keras.layers.GRU),
)
@test_util.run_v2_only
def testKerasRNNMultiBatches(self, rnn_layer):
input_data = tf.constant(
np.array(np.random.random_sample((4, 10, 10)), dtype=np.float32)
)
# Specify a fixed batch size(4) for the test model.
x = tf.keras.layers.Input(batch_shape=(4, 10, 10))
y = rnn_layer(units=10, input_shape=(10, 10))(x)
model = tf.keras.Model(inputs=[x], outputs=[y])
# Convert model.
converter = lite.TFLiteConverterV2.from_keras_model(model)
tflite_model = converter.convert()
actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
# Check values from converted model.
expected_value = model.predict(input_data)
self.assertAllClose(expected_value, actual_value, atol=1e-05)
@test_util.run_v2_only
def testKerasRNNLSTMFloat16Quant(self):
input_data = tf.constant(
np.array(np.random.random_sample((4, 10, 10)), dtype=np.float32)
)
# Specify a fixed batch size(4) for the test model.
x = tf.keras.layers.Input(batch_shape=(4, 10, 10))
y = tf.keras.layers.LSTM(units=10, input_shape=(10, 10))(x)
model = tf.keras.Model(inputs=[x], outputs=[y])
# Convert model.
converter = lite.TFLiteConverterV2.from_keras_model(model)
converter.optimizations = [lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
tflite_model = converter.convert()
actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
# Check values from converted model.
expected_value = model.predict(input_data)
self.assertAllClose(expected_value, actual_value, atol=1e-03)
@parameterized.named_parameters(
('ForceToUseBatchSizeOne', True), ('DontForceToUseBatchSizeOne', False)
)
@test_util.run_v2_only
def testKerasBidirectionalRNNReturnSequence(self, default_to_single_batch):
input_data = tf.constant(
np.array(np.random.random_sample((1, 10, 10)), dtype=np.float32)
)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Input(shape=(10, 10), name='input'))
model.add(
tf.keras.layers.Bidirectional(
tf.keras.layers.LSTM(units=10, return_sequences=True),
input_shape=(10, 10),
)
)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(5))
model.add(tf.keras.layers.Activation('softmax'))
# Convert model.
converter = lite.TFLiteConverterV2.from_keras_model(model)
converter._experimental_default_to_single_batch_in_tensor_list_ops = (
default_to_single_batch
)
if not default_to_single_batch:
converter.target_spec.supported_ops = [
lite.OpsSet.TFLITE_BUILTINS,
lite.OpsSet.SELECT_TF_OPS,
]
tflite_model = converter.convert()
actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
# Check values from converted model.
expected_value = model.predict(input_data)
self.assertAllClose(expected_value, actual_value, atol=1e-05)
@parameterized.named_parameters(
('ForceToUseBatchSizeOne', True), ('DontForceToUseBatchSizeOne', False)
)
@test_util.run_v2_only
def testKerasBidirectionalRNN(self, default_to_single_batch):
input_data = tf.constant(
np.array(np.random.random_sample((1, 10, 10)), dtype=np.float32)
)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Input(shape=(10, 10), name='input'))
model.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(units=10)))
model.add(tf.keras.layers.Dense(5))
model.add(tf.keras.layers.Activation('softmax'))
# Convert model.
converter = lite.TFLiteConverterV2.from_keras_model(model)
converter._experimental_default_to_single_batch_in_tensor_list_ops = (
default_to_single_batch
)
if not default_to_single_batch:
converter.target_spec.supported_ops = [
lite.OpsSet.TFLITE_BUILTINS,
lite.OpsSet.SELECT_TF_OPS,
]
tflite_model = converter.convert()
actual_value = self._evaluateTFLiteModel(tflite_model, [input_data])[0]
# Check values from converted model.
expected_value = model.predict(input_data)
self.assertAllClose(expected_value, actual_value, atol=1e-05)
| ControlFlowTest |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 31235,
"end": 31585
} | class ____(PrefectBaseModel):
ip_network: IPvAnyNetwork
enabled: bool
description: Optional[str] = Field(
default=None, description="A description of the IP entry."
)
last_seen: Optional[str] = Field(
default=None,
description="The last time this IP was seen accessing Prefect Cloud.",
)
| IPAllowlistEntry |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format16.py | {
"start": 315,
"end": 1711
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format16.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line"})
chart.axis_ids = [43943040, 44287488]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
"data_labels": {
"value": 1,
"category": 1,
"series_name": 1,
"position": "center",
},
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/blenderbot/modeling_blenderbot.py | {
"start": 4990,
"end": 10711
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Optional[BlenderbotConfig] = None,
layer_idx: Optional[int] = None,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
self.config = config
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
self.is_causal = is_causal
self.layer_idx = layer_idx
if layer_idx is None and self.is_decoder:
logger.warning_once(
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
"will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
"when creating this class."
)
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
cache_position: Optional[torch.Tensor] = None,
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
# determine input shapes
bsz, tgt_len = hidden_states.shape[:-1]
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
kv_input_shape = (bsz, src_len, -1, self.head_dim)
# get query proj
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
is_updated = False
if past_key_values is not None:
if isinstance(past_key_values, EncoderDecoderCache):
is_updated = past_key_values.is_updated.get(self.layer_idx)
if is_cross_attention:
# after the first generated id, we can subsequently re-use all key/value_states from cache
curr_past_key_values = past_key_values.cross_attention_cache
else:
curr_past_key_values = past_key_values.self_attention_cache
else:
curr_past_key_values = past_key_values
current_states = key_value_states if is_cross_attention else hidden_states
if is_cross_attention and past_key_values is not None and is_updated:
# reuse k,v, cross_attentions
key_states = curr_past_key_values.layers[self.layer_idx].keys
value_states = curr_past_key_values.layers[self.layer_idx].values
else:
key_states = self.k_proj(current_states)
value_states = self.v_proj(current_states)
key_states = key_states.view(*kv_input_shape).transpose(1, 2)
value_states = value_states.view(*kv_input_shape).transpose(1, 2)
if past_key_values is not None:
# save all key/value_states to cache to be re-used for fast auto-regressive generation
cache_position = cache_position if not is_cross_attention else None
key_states, value_states = curr_past_key_values.update(
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
)
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
past_key_values.is_updated[self.layer_idx] = True
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.dropout,
scaling=self.scaling,
output_attentions=output_attentions,
**kwargs,
)
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
# Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Blenderbot, MBART->BLENDERBOT
| BlenderbotAttention |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 243403,
"end": 245009
} | class ____:
@pytest.mark.parametrize('byteorder', ['<', '>'])
@pytest.mark.parametrize('dtype', [float, int, complex])
def test_basic(self, byteorder, dtype):
dt = np.dtype(dtype).newbyteorder(byteorder)
x = (np.random.random((4, 7)) * 5).astype(dt)
buf = x.tobytes()
assert_array_equal(np.frombuffer(buf, dtype=dt), x.flat)
@pytest.mark.parametrize("obj", [np.arange(10), b"12345678"])
def test_array_base(self, obj):
# Objects (including NumPy arrays), which do not use the
# `release_buffer` slot should be directly used as a base object.
# See also gh-21612
new = np.frombuffer(obj)
assert new.base is obj
def test_empty(self):
assert_array_equal(np.frombuffer(b''), np.array([]))
@pytest.mark.skipif(IS_PYPY,
reason="PyPy's memoryview currently does not track exports. See: "
"https://foss.heptapod.net/pypy/pypy/-/issues/3724")
def test_mmap_close(self):
# The old buffer protocol was not safe for some things that the new
# one is. But `frombuffer` always used the old one for a long time.
# Checks that it is safe with the new one (using memoryviews)
with tempfile.TemporaryFile(mode='wb') as tmp:
tmp.write(b"asdf")
tmp.flush()
mm = mmap.mmap(tmp.fileno(), 0)
arr = np.frombuffer(mm, dtype=np.uint8)
with pytest.raises(BufferError):
mm.close() # cannot close while array uses the buffer
del arr
mm.close()
| TestFromBuffer |
python | pypa__setuptools | setuptools/_vendor/backports/tarfile/__init__.py | {
"start": 10389,
"end": 10589
} | class ____(HeaderError):
"""Exception for missing and invalid extended headers."""
pass
#---------------------------
# internal stream interface
#---------------------------
| SubsequentHeaderError |
python | protocolbuffers__protobuf | python/google/protobuf/internal/text_format_test.py | {
"start": 2901,
"end": 25373
} | class ____(TextFormatBase):
def testPrintExotic(self, message_module):
message = message_module.TestAllTypes()
message.repeated_int64.append(-9223372036854775808)
message.repeated_uint64.append(18446744073709551615)
message.repeated_double.append(123.456)
message.repeated_double.append(1.23e22)
message.repeated_double.append(1.23e-18)
message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
message.repeated_string.append(u'\u00fc\ua71f')
self.CompareToGoldenText(
self.RemoveRedundantZeros(
text_format.MessageToString(message, as_utf8=True)
),
'repeated_int64: -9223372036854775808\n'
'repeated_uint64: 18446744073709551615\n'
'repeated_double: 123.456\n'
'repeated_double: 1.23e+22\n'
'repeated_double: 1.23e-18\n'
'repeated_string:'
' "\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""\n'
'repeated_string: "üꜟ"\n',
)
def testPrintFloatPrecision(self, message_module):
message = message_module.TestAllTypes()
message.repeated_float.append(0.0)
message.repeated_float.append(0.8)
message.repeated_float.append(1.0)
message.repeated_float.append(1.2)
message.repeated_float.append(1.23)
message.repeated_float.append(1.234)
message.repeated_float.append(1.2345)
message.repeated_float.append(1.23456)
message.repeated_float.append(1.2e10)
message.repeated_float.append(1.23e10)
message.repeated_float.append(1.234e10)
message.repeated_float.append(1.2345e10)
message.repeated_float.append(1.23456e10)
message.repeated_float.append(float('NaN'))
message.repeated_float.append(float('inf'))
message.repeated_double.append(0.0)
message.repeated_double.append(0.8)
message.repeated_double.append(1.0)
message.repeated_double.append(1.2)
message.repeated_double.append(1.23)
message.repeated_double.append(1.234)
message.repeated_double.append(1.2345)
message.repeated_double.append(1.23456)
message.repeated_double.append(1.234567)
message.repeated_double.append(1.2345678)
message.repeated_double.append(1.23456789)
message.repeated_double.append(1.234567898)
message.repeated_double.append(1.2345678987)
message.repeated_double.append(1.23456789876)
message.repeated_double.append(1.234567898765)
message.repeated_double.append(1.2345678987654)
message.repeated_double.append(1.23456789876543)
message.repeated_double.append(1.2e100)
message.repeated_double.append(1.23e100)
message.repeated_double.append(1.234e100)
message.repeated_double.append(1.2345e100)
message.repeated_double.append(1.23456e100)
message.repeated_double.append(1.234567e100)
message.repeated_double.append(1.2345678e100)
message.repeated_double.append(1.23456789e100)
message.repeated_double.append(1.234567898e100)
message.repeated_double.append(1.2345678987e100)
message.repeated_double.append(1.23456789876e100)
message.repeated_double.append(1.234567898765e100)
message.repeated_double.append(1.2345678987654e100)
message.repeated_double.append(1.23456789876543e100)
# pylint: disable=g-long-ternary
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_format.MessageToString(message)),
'repeated_float: 0\n'
'repeated_float: 0.8\n'
'repeated_float: 1\n'
'repeated_float: 1.2\n'
'repeated_float: 1.23\n'
'repeated_float: 1.234\n'
'repeated_float: 1.2345\n'
'repeated_float: 1.23456\n'
# Note that these don't use scientific notation.
'repeated_float: 12000000000\n'
'repeated_float: 12300000000\n'
'repeated_float: 12340000000\n'
'repeated_float: 12345000000\n'
'repeated_float: 12345600000\n'
'repeated_float: nan\n'
'repeated_float: inf\n'
'repeated_double: 0\n'
'repeated_double: 0.8\n'
'repeated_double: 1\n'
'repeated_double: 1.2\n'
'repeated_double: 1.23\n'
'repeated_double: 1.234\n'
'repeated_double: 1.2345\n'
'repeated_double: 1.23456\n'
'repeated_double: 1.234567\n'
'repeated_double: 1.2345678\n'
'repeated_double: 1.23456789\n'
'repeated_double: 1.234567898\n'
'repeated_double: 1.2345678987\n'
'repeated_double: 1.23456789876\n'
'repeated_double: 1.234567898765\n'
'repeated_double: 1.2345678987654\n'
'repeated_double: 1.23456789876543\n'
'repeated_double: 1.2e+100\n'
'repeated_double: 1.23e+100\n'
'repeated_double: 1.234e+100\n'
'repeated_double: 1.2345e+100\n'
'repeated_double: 1.23456e+100\n'
'repeated_double: 1.234567e+100\n'
'repeated_double: 1.2345678e+100\n'
'repeated_double: 1.23456789e+100\n'
'repeated_double: 1.234567898e+100\n'
'repeated_double: 1.2345678987e+100\n'
'repeated_double: 1.23456789876e+100\n'
'repeated_double: 1.234567898765e+100\n'
'repeated_double: 1.2345678987654e+100\n'
'repeated_double: 1.23456789876543e+100\n')
def testPrintExoticUnicodeSubclass(self, message_module):
class UnicodeSub(str):
pass
message = message_module.TestAllTypes()
message.repeated_string.append(UnicodeSub(u'\u00fc\ua71f'))
self.CompareToGoldenText(
text_format.MessageToString(message, as_utf8=True),
'repeated_string: "üꜟ"\n')
def testPrintNestedMessageAsOneLine(self, message_module):
message = message_module.TestAllTypes()
msg = message.repeated_nested_message.add()
msg.bb = 42
self.CompareToGoldenText(
text_format.MessageToString(message, as_one_line=True),
'repeated_nested_message { bb: 42 }')
def testPrintRepeatedFieldsAsOneLine(self, message_module):
message = message_module.TestAllTypes()
message.repeated_int32.append(1)
message.repeated_int32.append(1)
message.repeated_int32.append(3)
message.repeated_string.append('Google')
message.repeated_string.append('Zurich')
self.CompareToGoldenText(
text_format.MessageToString(message, as_one_line=True),
'repeated_int32: 1 repeated_int32: 1 repeated_int32: 3 '
'repeated_string: "Google" repeated_string: "Zurich"')
def VerifyPrintShortFormatRepeatedFields(self, message_module, as_one_line):
message = message_module.TestAllTypes()
message.repeated_int32.append(1)
message.repeated_string.append('Google')
message.repeated_string.append('Hello,World')
message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_FOO)
message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAR)
message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAZ)
message.optional_nested_message.bb = 3
for i in (21, 32):
msg = message.repeated_nested_message.add()
msg.bb = i
expected_ascii = (
'optional_nested_message {\n bb: 3\n}\n'
'repeated_int32: [1]\n'
'repeated_string: "Google"\n'
'repeated_string: "Hello,World"\n'
'repeated_nested_message {\n bb: 21\n}\n'
'repeated_nested_message {\n bb: 32\n}\n'
'repeated_foreign_enum: [FOREIGN_FOO, FOREIGN_BAR, FOREIGN_BAZ]\n')
if as_one_line:
expected_ascii = expected_ascii.replace('\n', ' ')
expected_ascii = re.sub(r'\s+', ' ', expected_ascii)
expected_ascii = re.sub(r'\s$', '', expected_ascii)
actual_ascii = text_format.MessageToString(
message, use_short_repeated_primitives=True,
as_one_line=as_one_line)
self.CompareToGoldenText(actual_ascii, expected_ascii)
parsed_message = message_module.TestAllTypes()
text_format.Parse(actual_ascii, parsed_message)
self.assertEqual(parsed_message, message)
def testPrintShortFormatRepeatedFields(self, message_module):
self.VerifyPrintShortFormatRepeatedFields(message_module, False)
self.VerifyPrintShortFormatRepeatedFields(message_module, True)
def testPrintNestedNewLineInStringAsOneLine(self, message_module):
message = message_module.TestAllTypes()
message.optional_string = 'a\nnew\nline'
self.CompareToGoldenText(
text_format.MessageToString(message, as_one_line=True),
'optional_string: "a\\nnew\\nline"')
def testPrintExoticAsOneLine(self, message_module):
message = message_module.TestAllTypes()
message.repeated_int64.append(-9223372036854775808)
message.repeated_uint64.append(18446744073709551615)
message.repeated_double.append(123.456)
message.repeated_double.append(1.23e22)
message.repeated_double.append(1.23e-18)
message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
message.repeated_string.append(u'\u00fc\ua71f')
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_format.MessageToString(
message, as_one_line=True, as_utf8=True)),
'repeated_int64: -9223372036854775808'
' repeated_uint64: 18446744073709551615'
' repeated_double: 123.456'
' repeated_double: 1.23e+22'
' repeated_double: 1.23e-18'
' repeated_string: '
'"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""'
' repeated_string: "üꜟ"')
def testRoundTripExoticAsOneLine(self, message_module):
message = message_module.TestAllTypes()
message.repeated_int64.append(-9223372036854775808)
message.repeated_uint64.append(18446744073709551615)
message.repeated_double.append(123.456)
message.repeated_double.append(1.23e22)
message.repeated_double.append(1.23e-18)
message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
message.repeated_string.append(u'\u00fc\ua71f')
# Test as_utf8 = False.
wire_text = text_format.MessageToString(message,
as_one_line=True,
as_utf8=False)
parsed_message = message_module.TestAllTypes()
r = text_format.Parse(wire_text, parsed_message)
self.assertIs(r, parsed_message)
self.assertEqual(message, parsed_message)
# Test as_utf8 = True.
wire_text = text_format.MessageToString(message,
as_one_line=True,
as_utf8=True)
parsed_message = message_module.TestAllTypes()
r = text_format.Parse(wire_text, parsed_message)
self.assertIs(r, parsed_message)
self.assertEqual(message, parsed_message,
'\n%s != %s' % (message, parsed_message))
def testPrintRawUtf8String(self, message_module):
message = message_module.TestAllTypes()
message.repeated_string.append(u'\u00fc\t\ua71f')
text = text_format.MessageToString(message, as_utf8=True)
golden_unicode = u'repeated_string: "\u00fc\\t\ua71f"\n'
golden_text = golden_unicode
# MessageToString always returns a native str.
self.CompareToGoldenText(text, golden_text)
parsed_message = message_module.TestAllTypes()
text_format.Parse(text, parsed_message)
self.assertEqual(
message, parsed_message, '\n%s != %s (%s != %s)' %
(message, parsed_message, message.repeated_string[0],
parsed_message.repeated_string[0]))
def testPrintFloatFormat(self, message_module):
# Check that float_format argument is passed to sub-message formatting.
message = message_module.NestedTestAllTypes()
message.payload.optional_float = 1.25
# Check rounding at 15 significant digits
message.payload.optional_double = -.000003456789012345678
# Check no decimal point.
message.payload.repeated_float.append(-5642)
# Check no trailing zeros.
message.payload.repeated_double.append(.000078900)
formatted_fields = ['optional_float: 1.25',
'optional_double: -3.45678901234568e-6',
'repeated_float: -5642', 'repeated_double: 7.89e-5']
text_message = text_format.MessageToString(message, float_format='.15g')
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_message),
'payload {{\n {0}\n {1}\n {2}\n {3}\n}}\n'.format(
*formatted_fields))
# as_one_line=True is a separate code branch where float_format is passed.
text_message = text_format.MessageToString(message,
as_one_line=True,
float_format='.15g')
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_message),
'payload {{ {0} {1} {2} {3} }}'.format(*formatted_fields))
# 32-bit 1.2 is noisy when extended to 64-bit:
# >>> struct.unpack('f', struct.pack('f', 1.2))[0]
# 1.2000000476837158
message.payload.optional_float = 1.2
formatted_fields = ['optional_float: 1.2',
'optional_double: -3.45678901234568e-6',
'repeated_float: -5642', 'repeated_double: 7.89e-5']
text_message = text_format.MessageToString(message, float_format='.7g',
double_format='.15g')
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_message),
'payload {{\n {0}\n {1}\n {2}\n {3}\n}}\n'.format(
*formatted_fields))
# Test only set float_format affect both float and double fields.
formatted_fields = ['optional_float: 1.2',
'optional_double: -3.456789e-6',
'repeated_float: -5642', 'repeated_double: 7.89e-5']
text_message = text_format.MessageToString(message, float_format='.7g')
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_message),
'payload {{\n {0}\n {1}\n {2}\n {3}\n}}\n'.format(
*formatted_fields))
# Test default float_format will automatic print shortest float.
message.payload.optional_float = 1.2345678912
message.payload.optional_double = 1.2345678912
formatted_fields = ['optional_float: 1.2345679',
'optional_double: 1.2345678912',
'repeated_float: -5642', 'repeated_double: 7.89e-5']
text_message = text_format.MessageToString(message)
self.CompareToGoldenText(
self.RemoveRedundantZeros(text_message),
'payload {{\n {0}\n {1}\n {2}\n {3}\n}}\n'.format(
*formatted_fields))
message.Clear()
message.payload.optional_float = 1.1000000000011
self.assertEqual(text_format.MessageToString(message),
'payload {\n optional_float: 1.1\n}\n')
message.payload.optional_float = 1.00000075e-36
self.assertEqual(text_format.MessageToString(message),
'payload {\n optional_float: 1.00000075e-36\n}\n')
message.payload.optional_float = 12345678912345e+11
self.assertEqual(text_format.MessageToString(message),
'payload {\n optional_float: 1.234568e+24\n}\n')
def testMessageToString(self, message_module):
message = message_module.ForeignMessage()
message.c = 123
self.assertEqual('c: 123\n', str(message))
def testMessageToStringUnicode(self, message_module):
golden_unicode = u'Á short desçription and a 🍌.'
golden_bytes = golden_unicode.encode('utf-8')
message = message_module.TestAllTypes()
message.optional_string = golden_unicode
message.optional_bytes = golden_bytes
text = text_format.MessageToString(message, as_utf8=True)
golden_message = textwrap.dedent(
'optional_string: "Á short desçription and a 🍌."\n'
'optional_bytes: '
r'"\303\201 short des\303\247ription and a \360\237\215\214."'
'\n')
self.CompareToGoldenText(text, golden_message)
def testMessageToStringASCII(self, message_module):
golden_unicode = u'Á short desçription and a 🍌.'
golden_bytes = golden_unicode.encode('utf-8')
message = message_module.TestAllTypes()
message.optional_string = golden_unicode
message.optional_bytes = golden_bytes
text = text_format.MessageToString(message, as_utf8=False) # ASCII
golden_message = (
'optional_string: '
r'"\303\201 short des\303\247ription and a \360\237\215\214."'
'\n'
'optional_bytes: '
r'"\303\201 short des\303\247ription and a \360\237\215\214."'
'\n')
self.CompareToGoldenText(text, golden_message)
def testPrintField(self, message_module):
message = message_module.TestAllTypes()
field = message.DESCRIPTOR.fields_by_name['optional_float']
value = message.optional_float
out = text_format.TextWriter(False)
text_format.PrintField(field, value, out)
self.assertEqual('optional_float: 0.0\n', out.getvalue())
out.close()
# Test Printer
out = text_format.TextWriter(False)
printer = text_format._Printer(out)
printer.PrintField(field, value)
self.assertEqual('optional_float: 0.0\n', out.getvalue())
out.close()
def testPrintFieldValue(self, message_module):
message = message_module.TestAllTypes()
field = message.DESCRIPTOR.fields_by_name['optional_float']
value = message.optional_float
out = text_format.TextWriter(False)
text_format.PrintFieldValue(field, value, out)
self.assertEqual('0.0', out.getvalue())
out.close()
# Test Printer
out = text_format.TextWriter(False)
printer = text_format._Printer(out)
printer.PrintFieldValue(field, value)
self.assertEqual('0.0', out.getvalue())
out.close()
def testCustomOptions(self, message_module):
message_descriptor = (unittest_custom_options_pb2.
TestMessageWithCustomOptions.DESCRIPTOR)
message_proto = descriptor_pb2.DescriptorProto()
message_descriptor.CopyToProto(message_proto)
expected_text = (
'name: "TestMessageWithCustomOptions"\n'
'field {\n'
' name: "field1"\n'
' number: 1\n'
' label: LABEL_OPTIONAL\n'
' type: TYPE_STRING\n'
' options {\n'
' ctype: CORD\n'
' [proto2_unittest.field_opt1]: 8765432109\n'
' }\n'
'}\n'
'field {\n'
' name: "oneof_field"\n'
' number: 2\n'
' label: LABEL_OPTIONAL\n'
' type: TYPE_INT32\n'
' oneof_index: 0\n'
'}\n'
'field {\n'
' name: "map_field"\n'
' number: 3\n'
' label: LABEL_REPEATED\n'
' type: TYPE_MESSAGE\n'
' type_name: ".proto2_unittest.TestMessageWithCustomOptions.'
'MapFieldEntry"\n'
' options {\n'
' [proto2_unittest.field_opt1]: 12345\n'
' }\n'
'}\n'
'nested_type {\n'
' name: "MapFieldEntry"\n'
' field {\n'
' name: "key"\n'
' number: 1\n'
' label: LABEL_OPTIONAL\n'
' type: TYPE_STRING\n'
' }\n'
' field {\n'
' name: "value"\n'
' number: 2\n'
' label: LABEL_OPTIONAL\n'
' type: TYPE_STRING\n'
' }\n'
' options {\n'
' map_entry: true\n'
' }\n'
'}\n'
'enum_type {\n'
' name: "AnEnum"\n'
' value {\n'
' name: "ANENUM_VAL1"\n'
' number: 1\n'
' }\n'
' value {\n'
' name: "ANENUM_VAL2"\n'
' number: 2\n'
' options {\n'
' [proto2_unittest.enum_value_opt1]: 123\n'
' }\n'
' }\n'
' options {\n'
' [proto2_unittest.enum_opt1]: -789\n'
' }\n'
'}\n'
'options {\n'
' message_set_wire_format: false\n'
' [proto2_unittest.message_opt1]: -56\n'
'}\n'
'oneof_decl {\n'
' name: "AnOneof"\n'
' options {\n'
' [proto2_unittest.oneof_opt1]: -99\n'
' }\n'
'}\n')
self.assertEqual(expected_text,
text_format.MessageToString(message_proto))
parsed_proto = descriptor_pb2.DescriptorProto()
text_format.Parse(expected_text, parsed_proto)
self.assertEqual(message_proto, parsed_proto)
@unittest.skipIf(
api_implementation.Type() == 'upb',
"upb API doesn't support old UnknownField API. The TextFormat library "
"needs to convert to the new API.")
def testPrintUnknownFieldsEmbeddedMessageInBytes(self, message_module):
inner_msg = message_module.TestAllTypes()
inner_msg.optional_int32 = 101
inner_msg.optional_double = 102.0
inner_msg.optional_string = u'hello'
inner_msg.optional_bytes = b'103'
inner_msg.optional_nested_message.bb = 105
inner_data = inner_msg.SerializeToString()
outer_message = message_module.TestAllTypes()
outer_message.optional_int32 = 101
outer_message.optional_bytes = inner_data
all_data = outer_message.SerializeToString()
empty_message = message_module.TestEmptyMessage()
empty_message.ParseFromString(all_data)
self.assertEqual(' 1: 101\n'
' 15 {\n'
' 1: 101\n'
' 12: 4636878028842991616\n'
' 14: "hello"\n'
' 15: "103"\n'
' 18 {\n'
' 1: 105\n'
' }\n'
' }\n',
text_format.MessageToString(empty_message,
indent=2,
print_unknown_fields=True))
self.assertEqual('1: 101 '
'15 { '
'1: 101 '
'12: 4636878028842991616 '
'14: "hello" '
'15: "103" '
'18 { 1: 105 } '
'}',
text_format.MessageToString(empty_message,
print_unknown_fields=True,
as_one_line=True))
def testBytestDoubleQuotes(self, message_module):
msg = message_module.TestAllTypes(optional_bytes=b'"')
self.assertEqual(str(msg), 'optional_bytes: "\\""\n')
def testBytesSingleQuote(self, message_module):
msg = message_module.TestAllTypes(optional_bytes=b"'")
self.assertEqual(str(msg), 'optional_bytes: "\\\'"\n')
@parameterized.parameters(unittest_pb2, unittest_proto3_arena_pb2)
| TextFormatMessageToStringTests |
python | Lightning-AI__lightning | tests/tests_pytorch/core/test_datamodules.py | {
"start": 4306,
"end": 8452
} | class ____(BoringDataModule):
def __init__(self, data_dir: str):
super().__init__()
self.data_dir = data_dir
def test_dm_pickle_after_init():
dm = BoringDataModule()
pickle.dumps(dm)
@RunIf(sklearn=True)
def test_train_loop_only(tmp_path):
seed_everything(7)
dm = ClassifDataModule()
model = ClassificationModel()
model.validation_step = None
model.test_step = None
trainer = Trainer(default_root_dir=tmp_path, max_epochs=1, enable_model_summary=False)
# fit model
trainer.fit(model, datamodule=dm)
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert trainer.callback_metrics["train_loss"] < 1.1
@RunIf(sklearn=True)
def test_train_val_loop_only(tmp_path):
seed_everything(7)
dm = ClassifDataModule()
model = ClassificationModel()
model.validation_step = None
trainer = Trainer(default_root_dir=tmp_path, max_epochs=1, enable_model_summary=False)
# fit model
trainer.fit(model, datamodule=dm)
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert trainer.callback_metrics["train_loss"] < 1.1
def test_dm_checkpoint_save_and_load(tmp_path):
class CustomBoringModel(BoringModel):
def validation_step(self, batch, batch_idx):
out = super().validation_step(batch, batch_idx)
self.log("early_stop_on", out["x"])
return out
class CustomBoringDataModule(BoringDataModule):
def state_dict(self) -> dict[str, Any]:
return {"my": "state_dict"}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
self.my_state_dict = state_dict
dm = CustomBoringDataModule()
model = CustomBoringModel()
trainer = Trainer(
default_root_dir=tmp_path,
max_epochs=1,
limit_train_batches=2,
limit_val_batches=1,
enable_model_summary=False,
callbacks=[ModelCheckpoint(dirpath=tmp_path, monitor="early_stop_on")],
)
# fit model
trainer.fit(model, datamodule=dm)
checkpoint_path = list(trainer.checkpoint_callback.best_k_models.keys())[0]
checkpoint = torch.load(checkpoint_path, weights_only=True)
assert dm.__class__.__qualname__ in checkpoint
assert checkpoint[dm.__class__.__qualname__] == {"my": "state_dict"}
for trainer_fn in TrainerFn:
trainer.state.fn = trainer_fn
trainer._checkpoint_connector._restore_modules_and_callbacks(checkpoint_path)
assert dm.my_state_dict == {"my": "state_dict"}
@RunIf(sklearn=True, skip_windows=True) # Flaky test on Windows for unknown reasons
def test_full_loop(tmp_path):
seed_everything(7)
dm = ClassifDataModule()
model = ClassificationModel()
trainer = Trainer(default_root_dir=tmp_path, max_epochs=1, enable_model_summary=False, deterministic="warn")
# fit model
trainer.fit(model, dm)
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert dm.trainer is not None
# validate
result = trainer.validate(model, dm)
assert dm.trainer is not None
assert result[0]["val_acc"] > 0.6
# test
result = trainer.test(model, dm)
assert dm.trainer is not None
assert result[0]["test_acc"] > 0.57
def test_dm_reload_dataloaders_every_n_epochs(tmp_path):
"""Test datamodule, where trainer argument reload_dataloaders_every_n_epochs is set to a non negative integer."""
class CustomBoringDataModule(BoringDataModule):
def __init__(self):
super().__init__()
self._epochs_called_for = []
def train_dataloader(self):
assert self.trainer.current_epoch not in self._epochs_called_for
self._epochs_called_for.append(self.trainer.current_epoch)
return super().train_dataloader()
dm = CustomBoringDataModule()
model = BoringModel()
model.validation_step = None
model.test_step = None
trainer = Trainer(
default_root_dir=tmp_path, max_epochs=3, limit_train_batches=2, reload_dataloaders_every_n_epochs=2
)
trainer.fit(model, dm)
| DataDirDataModule |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 222858,
"end": 223669
} | class ____(MemoryCopyNode):
"""
Copy the contents of slice src to slice dst. Does not support indirect
slices.
memslice1[...] = memslice2
memslice1[:] = memslice2
"""
is_memview_copy_assignment = True
copy_slice_cname = "__pyx_memoryview_copy_contents"
def _generate_assignment_code(self, src, code):
dst = self.dst
src.type.assert_direct_dims(src.pos)
dst.type.assert_direct_dims(dst.pos)
code.putln(code.error_goto_if_neg(
"%s(%s, %s, %d, %d, %d)" % (self.copy_slice_cname,
src.result(), dst.result(),
src.type.ndim, dst.type.ndim,
dst.type.dtype.is_pyobject),
dst.pos))
| MemoryCopySlice |
python | great-expectations__great_expectations | tests/metrics/test_metric.py | {
"start": 1114,
"end": 1635
} | class ____:
@pytest.mark.unit
def test_success(self):
class MyColumnValuesAbove(ColumnMetric[ColumnValuesAboveResult]):
name = FULLY_QUALIFIED_METRIC_NAME
min_value: Comparable
strict_min: bool = False
@pytest.mark.unit
def test_success_without_generic_return_types(self):
class MyColumnValuesAbove(ColumnMetric):
name = FULLY_QUALIFIED_METRIC_NAME
min_value: Comparable
strict_min: bool = False
| TestMetricDefinition |
python | encode__django-rest-framework | tests/test_filters.py | {
"start": 2682,
"end": 11738
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
# Sequence of title/text is:
#
# z abc
# zz bcd
# zzz cde
# ...
for idx in range(10):
title = 'z' * (idx + 1)
text = (
chr(idx + ord('a')) +
chr(idx + ord('b')) +
chr(idx + ord('c'))
)
SearchFilterModel(title=title, text=text).save()
SearchFilterModel(title='A title', text='The long text').save()
SearchFilterModel(title='The title', text='The "text').save()
def test_search(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('title', 'text')
view = SearchListView.as_view()
request = factory.get('/', {'search': 'b'})
response = view(request)
assert response.data == [
{'id': 1, 'title': 'z', 'text': 'abc'},
{'id': 2, 'title': 'zz', 'text': 'bcd'}
]
def test_search_returns_same_queryset_if_no_search_fields_or_terms_provided(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
view = SearchListView.as_view()
request = factory.get('/')
response = view(request)
expected = SearchFilterSerializer(SearchFilterModel.objects.all(),
many=True).data
assert response.data == expected
def test_exact_search(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('=title', 'text')
view = SearchListView.as_view()
request = factory.get('/', {'search': 'zzz'})
response = view(request)
assert response.data == [
{'id': 3, 'title': 'zzz', 'text': 'cde'}
]
def test_startswith_search(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('title', '^text')
view = SearchListView.as_view()
request = factory.get('/', {'search': 'b'})
response = view(request)
assert response.data == [
{'id': 2, 'title': 'zz', 'text': 'bcd'}
]
def test_regexp_search(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('$title', '$text')
view = SearchListView.as_view()
request = factory.get('/', {'search': 'z{2} ^b'})
response = view(request)
assert response.data == [
{'id': 2, 'title': 'zz', 'text': 'bcd'}
]
def test_search_with_nonstandard_search_param(self):
with override_settings(REST_FRAMEWORK={'SEARCH_PARAM': 'query'}):
reload_module(filters)
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('title', 'text')
view = SearchListView.as_view()
request = factory.get('/', {'query': 'b'})
response = view(request)
assert response.data == [
{'id': 1, 'title': 'z', 'text': 'abc'},
{'id': 2, 'title': 'zz', 'text': 'bcd'}
]
reload_module(filters)
def test_search_with_filter_subclass(self):
class CustomSearchFilter(filters.SearchFilter):
# Filter that dynamically changes search fields
def get_search_fields(self, view, request):
if request.query_params.get('title_only'):
return ('$title',)
return super().get_search_fields(view, request)
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (CustomSearchFilter,)
search_fields = ('$title', '$text')
view = SearchListView.as_view()
request = factory.get('/', {'search': r'^\w{3}$'})
response = view(request)
assert len(response.data) == 10
request = factory.get('/', {'search': r'^\w{3}$', 'title_only': 'true'})
response = view(request)
assert response.data == [
{'id': 3, 'title': 'zzz', 'text': 'cde'}
]
def test_search_field_with_null_characters(self):
view = generics.GenericAPIView()
request = factory.get('/?search=\0as%00d\x00f')
request = view.initialize_request(request)
with self.assertRaises(ValidationError):
filters.SearchFilter().get_search_terms(request)
def test_search_field_with_custom_lookup(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('text__iendswith',)
view = SearchListView.as_view()
request = factory.get('/', {'search': 'c'})
response = view(request)
assert response.data == [
{'id': 1, 'title': 'z', 'text': 'abc'},
]
def test_search_field_with_additional_transforms(self):
from django.test.utils import register_lookup
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('text__trim', )
view = SearchListView.as_view()
# an example custom transform, that trims `a` from the string.
class TrimA(Transform):
function = 'TRIM'
lookup_name = 'trim'
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
return "trim(%s, 'a')" % sql, params
with register_lookup(CharField, TrimA):
# Search including `a`
request = factory.get('/', {'search': 'abc'})
response = view(request)
assert response.data == []
# Search excluding `a`
request = factory.get('/', {'search': 'bc'})
response = view(request)
assert response.data == [
{'id': 1, 'title': 'z', 'text': 'abc'},
{'id': 2, 'title': 'zz', 'text': 'bcd'},
]
def test_search_field_with_multiple_words(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('title', 'text')
search_query = 'foo bar,baz'
view = SearchListView()
request = factory.get('/', {'search': search_query})
request = view.initialize_request(request)
rendered_search_field = filters.SearchFilter().to_html(
request=request, queryset=view.queryset, view=view
)
assert search_query in rendered_search_field
def test_search_field_with_escapes(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('title', 'text',)
view = SearchListView.as_view()
request = factory.get('/', {'search': '"\\\"text"'})
response = view(request)
assert response.data == [
{'id': 12, 'title': 'The title', 'text': 'The "text'},
]
def test_search_field_with_quotes(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('title', 'text',)
view = SearchListView.as_view()
request = factory.get('/', {'search': '"long text"'})
response = view(request)
assert response.data == [
{'id': 11, 'title': 'A title', 'text': 'The long text'},
]
| SearchFilterTests |
python | dagster-io__dagster | python_modules/libraries/dagster-sigma/dagster_sigma/resource.py | {
"start": 1757,
"end": 2729
} | class ____(str, enum.Enum):
PENDING = "pending"
BUILDING = "building"
READY = "ready"
def build_folder_path_err(folder: Any, idx: int, param_name: str):
return (
f"{param_name} at index {idx} is not a sequence: `{folder!r}`.\n"
"Paths should be specified as a list of folder names, starting from the root folder."
)
def validate_folder_path_input(folder_input: Optional[Sequence[Sequence[str]]], param_name: str):
check.opt_sequence_param(folder_input, param_name, of_type=Sequence)
if folder_input:
for idx, folder in enumerate(folder_input):
check.invariant(
not isinstance(folder, str),
build_folder_path_err(folder, idx, param_name),
)
check.is_iterable(
folder,
of_type=str,
additional_message=build_folder_path_err(folder, idx, param_name),
)
@record_custom
| SigmaMaterializationStatus |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_subgraph.py | {
"start": 86730,
"end": 96968
} | class ____(torch.nn.Module):
def forward(self, primals_1: "Sym(s77)", getitem_17: "Sym(s77)", getitem_19: "Sym(s77)", getitem_21: "Sym(s77)", getitem_23: "Sym(s77)", getitem_16: "f32[s77, 16]", getitem_18: "f32[s77, 16]", getitem_20: "f32[s77, 16]", getitem_22: "f32[s77, 16]", cos: "f32[s77, 16]", tangents_1: "f32[]"):
expand: "f32[s77, 16]" = torch.ops.aten.expand.default(tangents_1, [primals_1, 16]); tangents_1 = primals_1 = None
partitioned_bw_subgraph_0_0 = self.partitioned_bw_subgraph_0_0
invoke_subgraph_15 = torch.ops.higher_order.invoke_subgraph(partitioned_bw_subgraph_0_0, 'partitioned_bw_subgraph_0_0', getitem_23, getitem_22, expand); partitioned_bw_subgraph_0_0 = getitem_23 = getitem_22 = None
getitem_5: "f32[s77, 16]" = invoke_subgraph_15[1]; invoke_subgraph_15 = None
add_16: "f32[s77, 16]" = torch.ops.aten.add.Tensor(expand, getitem_5); expand = getitem_5 = None
partitioned_bw_subgraph_0_3 = self.partitioned_bw_subgraph_0_1
invoke_subgraph_13 = torch.ops.higher_order.invoke_subgraph(partitioned_bw_subgraph_0_3, 'partitioned_bw_subgraph_0_1', getitem_21, getitem_20, add_16); partitioned_bw_subgraph_0_3 = getitem_21 = getitem_20 = add_16 = None
getitem_8: "f32[s77, 16]" = invoke_subgraph_13[1]; invoke_subgraph_13 = None
mul_10: "f32[s77, 16]" = torch.ops.aten.mul.Tensor(getitem_8, cos); getitem_8 = cos = None
partitioned_bw_subgraph_0_2 = self.partitioned_bw_subgraph_0_1
invoke_subgraph_11 = torch.ops.higher_order.invoke_subgraph(partitioned_bw_subgraph_0_2, 'partitioned_bw_subgraph_0_1', getitem_19, getitem_18, mul_10); partitioned_bw_subgraph_0_2 = getitem_19 = getitem_18 = mul_10 = None
getitem_11: "f32[s77, 16]" = invoke_subgraph_11[1]; invoke_subgraph_11 = None
partitioned_bw_subgraph_0_1 = self.partitioned_bw_subgraph_0_1
invoke_subgraph_9 = torch.ops.higher_order.invoke_subgraph(partitioned_bw_subgraph_0_1, 'partitioned_bw_subgraph_0_1', getitem_17, getitem_16, getitem_11); partitioned_bw_subgraph_0_1 = getitem_17 = getitem_16 = getitem_11 = None
getitem_14: "f32[s77, 16]" = invoke_subgraph_9[1]; invoke_subgraph_9 = None
return (None, getitem_14)
class partitioned_bw_subgraph_0_0(torch.nn.Module):
def forward(self, primals_0: "Sym(s77)", primals_1: "f32[s77, 16]", tangents_0: "f32[s77, 16]"):
sin: "f32[s77, 16]" = torch.ops.aten.sin.default(primals_1); primals_1 = None
neg: "f32[s77, 16]" = torch.ops.aten.neg.default(sin); sin = None
mul_9: "f32[s77, 16]" = torch.ops.aten.mul.Tensor(tangents_0, neg); tangents_0 = neg = None
return (None, mul_9)
class partitioned_bw_subgraph_0_1(torch.nn.Module):
def forward(self, primals_0: "Sym(s77)", primals_1: "f32[s77, 16]", tangents_0: "f32[s77, 16]"):
sin: "f32[s77, 16]" = torch.ops.aten.sin.default(primals_1); primals_1 = None
neg: "f32[s77, 16]" = torch.ops.aten.neg.default(sin); sin = None
mul_10: "f32[s77, 16]" = torch.ops.aten.mul.Tensor(tangents_0, neg); tangents_0 = neg = None
return (None, mul_10)
""",
ignore_empty_lines=True,
)
def test_div(self):
@nested_compile_region
def gn(x):
div = torch.div(1024, 256, rounding_mode="trunc")
return div * torch.ones(64, div) * x
def fn(x):
return gn(x)
x = torch.randn(64, 1, requires_grad=True)
opt_fn = torch.compile(fn, fullgraph=True)
ref = fn(x)
res = opt_fn(x)
self.assertEqual(ref, res)
@requires_gpu
def test_preserves_strides(self):
class _CustomPass(PatternMatcherPass):
def __init__(self) -> None:
super().__init__()
def __call__(self, g: torch.fx.Graph):
self.apply(g)
g = _CustomPass()
called = False
x = torch.randn(4, 4, 2, 2, device=GPU_TYPE)
other = torch.randn(4, 4, 2, 2, device=GPU_TYPE)
@register_graph_pattern(
CallFunctionVarArgs(torch.ops.aten.permute),
pass_dict=g,
)
def _(match, *args, **kwargs):
flat_args, spec = pytree.tree_flatten((args, kwargs))
def decomp(*flat_args):
args, kwargs = pytree.tree_unflatten(flat_args, spec)
return torch.ops.mylib.force_channels_last(
torch.ops.aten.permute(*args, **kwargs)
)
nonlocal called
called = True
match.replace_by_example(decomp, flat_args)
from torch._inductor import config
with torch.library._scoped_library("mylib", "FRAGMENT") as lib:
lib.define(
"force_channels_last(Tensor x) -> Tensor",
tags=[torch._C.Tag.flexible_layout],
)
def impl2(x):
return x.clone(memory_format=torch.channels_last)
lib.impl("force_channels_last", impl2, "CompositeExplicitAutograd")
lib.define(
"add_op(Tensor x, Tensor y) -> Tensor",
)
def impl(x, y):
out = y.clone() # contiguous with strides (16, 4, 2, 1)
out.add_(x.transpose(-1, -2))
return out
def meta(x, y):
return torch.empty_like(y, memory_format=torch.contiguous_format)
lib.impl("add_op", impl, "CompositeExplicitAutograd")
lib.impl("add_op", meta, "Meta")
@nested_compile_region
def gn(y, z):
return torch.ops.mylib.add_op.default(y, z)
def f(x, other):
y = x.transpose(2, 3).contiguous().transpose(2, 3)
z = y.sin().transpose(2, 3)
return gn(y, z)
with config.patch(
post_grad_custom_post_pass=g,
):
f_compile = torch.compile(f, fullgraph=True)
self.assertEqual(f(x, other), f_compile(x, other))
self.assertTrue(called)
@requires_gpu
def test_preserves_output_strides(self):
# Have a graph pass that changes strides for the output op of the
# invoke_subgraph, and check if the output strides are preserved
x = torch.randn(4, 4, 2, 2, device=GPU_TYPE)
other = torch.randn(4, 4, 2, 2, device=GPU_TYPE)
class _CustomPass(PatternMatcherPass):
def __init__(self) -> None:
super().__init__()
def __call__(self, g: torch.fx.Graph):
self.apply(g)
g = _CustomPass()
called = False
@register_graph_pattern(
CallFunctionVarArgs(torch.ops.aten.permute),
pass_dict=g,
)
def _(match, *args, **kwargs):
flat_args, spec = pytree.tree_flatten((args, kwargs))
def decomp(*flat_args):
args, kwargs = pytree.tree_unflatten(flat_args, spec)
return torch.ops.mylib.force_channels_last(
torch.ops.aten.permute(*args, **kwargs)
)
nonlocal called
called = True
match.replace_by_example(decomp, flat_args)
from torch._inductor import config
with torch.library._scoped_library("mylib", "FRAGMENT") as lib:
lib.define(
"force_channels_last(Tensor x) -> Tensor",
tags=[torch._C.Tag.flexible_layout],
)
def impl2(x):
return x.clone(memory_format=torch.channels_last)
lib.impl("force_channels_last", impl2, "CompositeExplicitAutograd")
lib.define(
"add_op(Tensor x, Tensor y) -> Tensor",
)
def impl(x, y):
# Check that the input strides are preserved. This helps in
# testing that the HOP preserves the output strides.
assert x.stride() == (16, 4, 1, 2)
assert y.stride() == (16, 4, 2, 1)
out = y.clone() # contiguous with strides (16, 4, 2, 1)
out.add_(x.transpose(-1, -2))
return out
def meta(x, y):
return torch.empty_like(y, memory_format=torch.contiguous_format)
lib.impl("add_op", impl, "CompositeExplicitAutograd")
lib.impl("add_op", meta, "Meta")
@nested_compile_region
def gn(x, other):
y = x.transpose(2, 3).contiguous().transpose(2, 3)
z = y.sin().transpose(2, 3)
return y, z
def f(x, other):
y, z = gn(x, other)
return torch.ops.mylib.add_op.default(y, z)
with config.patch(
post_grad_custom_post_pass=g,
):
f_compile = torch.compile(f, fullgraph=True)
self.assertEqual(f(x, other), f_compile(x, other))
self.assertTrue(called)
def test_udf_output(self):
class Foo:
def __init__(self, a, b):
self.a = a
self.b = b
@nested_compile_region
def gn(x, y):
a = torch.sin(x)
b = torch.cos(y)
return Foo(a, b)
def fn(x, y):
foo1 = gn(x, y)
foo2 = gn(foo1.a, y)
return foo1.b + foo2.a # + foo2.b
backend = AotEagerAndRecordGraphs()
opt_fn = torch.compile(fn, backend=backend, fullgraph=True)
x = torch.randn(8, 8, requires_grad=True)
y = torch.randn(8, 8, requires_grad=True)
x_clone = x.detach().clone().requires_grad_(True)
y_clone = y.detach().clone().requires_grad_(True)
ref = fn(x, y)
res = opt_fn(x_clone, y_clone)
ref.sum().backward()
res.sum().backward()
self.assertEqual(ref, res)
self.assertEqual(x.grad, x_clone.grad)
if not TEST_WITH_CROSSREF:
self.assertExpectedInline(
normalize_gm(backend.graphs[0].print_readable(print_output=False)),
"""\
| GraphModule |
python | Textualize__textual | src/textual/renderables/sparkline.py | {
"start": 485,
"end": 4243
} | class ____(Generic[T]):
"""A sparkline representing a series of data.
Args:
data: The sequence of data to render.
width: The width of the sparkline/the number of buckets to partition the data into.
min_color: The color of values equal to the min value in data.
max_color: The color of values equal to the max value in data.
summary_function: Function that will be applied to each bucket.
"""
BARS = "▁▂▃▄▅▆▇█"
def __init__(
self,
data: Sequence[T],
*,
width: int | None,
min_color: Color = Color.from_rgb(0, 255, 0),
max_color: Color = Color.from_rgb(255, 0, 0),
summary_function: SummaryFunction[T] = max,
) -> None:
self.data: Sequence[T] = data
self.width = width
self.min_color = Style.from_color(min_color)
self.max_color = Style.from_color(max_color)
self.summary_function: SummaryFunction[T] = summary_function
@classmethod
def _buckets(cls, data: list[T], num_buckets: int) -> Iterable[Sequence[T]]:
"""Partition ``data`` into ``num_buckets`` buckets. For example, the data
[1, 2, 3, 4] partitioned into 2 buckets is [[1, 2], [3, 4]].
Args:
data: The data to partition.
num_buckets: The number of buckets to partition the data into.
"""
bucket_step = Fraction(len(data), num_buckets)
for bucket_no in range(num_buckets):
start = int(bucket_step * bucket_no)
end = int(bucket_step * (bucket_no + 1))
partition = data[start:end]
if partition:
yield partition
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
width = self.width or options.max_width
len_data = len(self.data)
if len_data == 0:
yield Segment("▁" * width, self.min_color)
return
if len_data == 1:
yield Segment("█" * width, self.max_color)
return
minimum, maximum = min(self.data), max(self.data)
extent = maximum - minimum or 1
buckets = tuple(self._buckets(list(self.data), num_buckets=width))
bucket_index = 0.0
bars_rendered = 0
step = len(buckets) / width
summary_function = self.summary_function
min_color, max_color = self.min_color.color, self.max_color.color
assert min_color is not None
assert max_color is not None
while bars_rendered < width:
partition = buckets[int(bucket_index)]
partition_summary = summary_function(partition)
height_ratio = (partition_summary - minimum) / extent
bar_index = int(height_ratio * (len(self.BARS) - 1))
bar_color = blend_colors(min_color, max_color, height_ratio)
bars_rendered += 1
bucket_index += step
yield Segment(self.BARS[bar_index], Style.from_color(bar_color))
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
return Measurement(self.width or options.max_width, 1)
if __name__ == "__main__":
console = Console()
def last(l: Sequence[T]) -> T:
return l[-1]
funcs: Sequence[SummaryFunction[int]] = (
min,
max,
last,
statistics.median,
statistics.mean,
)
nums = [10, 2, 30, 60, 45, 20, 7, 8, 9, 10, 50, 13, 10, 6, 5, 4, 3, 7, 20]
console.print(f"data = {nums}\n")
for f in funcs:
console.print(
f"{f.__name__}:\t",
Sparkline(nums, width=12, summary_function=f),
end="",
)
console.print("\n")
| Sparkline |
python | django__django | django/views/generic/edit.py | {
"start": 386,
"end": 2457
} | class ____(ContextMixin):
"""Provide a way to show and handle a form in a request."""
initial = {}
form_class = None
success_url = None
prefix = None
def get_initial(self):
"""Return the initial data to use for forms on this view."""
return self.initial.copy()
def get_prefix(self):
"""Return the prefix to use for forms."""
return self.prefix
def get_form_class(self):
"""Return the form class to use."""
return self.form_class
def get_form(self, form_class=None):
"""Return an instance of the form to be used in this view."""
if form_class is None:
form_class = self.get_form_class()
return form_class(**self.get_form_kwargs())
def get_form_kwargs(self):
"""Return the keyword arguments for instantiating the form."""
kwargs = {
"initial": self.get_initial(),
"prefix": self.get_prefix(),
}
if self.request.method in ("POST", "PUT"):
kwargs.update(
{
"data": self.request.POST,
"files": self.request.FILES,
}
)
return kwargs
def get_success_url(self):
"""Return the URL to redirect to after processing a valid form."""
if not self.success_url:
raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.")
return str(self.success_url) # success_url may be lazy
def form_valid(self, form):
"""If the form is valid, redirect to the supplied URL."""
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form):
"""If the form is invalid, render the invalid form."""
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
"""Insert the form into the context dict."""
if "form" not in kwargs:
kwargs["form"] = self.get_form()
return super().get_context_data(**kwargs)
| FormMixin |
python | getsentry__sentry-python | sentry_sdk/integrations/__init__.py | {
"start": 11672,
"end": 12735
} | class ____(ABC):
"""Baseclass for all integrations.
To accept options for an integration, implement your own constructor that
saves those options on `self`.
"""
install = None
"""Legacy method, do not implement."""
identifier = None # type: str
"""String unique ID of integration type"""
@staticmethod
@abstractmethod
def setup_once():
# type: () -> None
"""
Initialize the integration.
This function is only called once, ever. Configuration is not available
at this point, so the only thing to do here is to hook into exception
handlers, and perhaps do monkeypatches.
Inside those hooks `Integration.current` can be used to access the
instance again.
"""
pass
def setup_once_with_options(self, options=None):
# type: (Optional[Dict[str, Any]]) -> None
"""
Called after setup_once in rare cases on the instance and with options since we don't have those available above.
"""
pass
| Integration |
python | sympy__sympy | sympy/physics/optics/gaussopt.py | {
"start": 7488,
"end": 8054
} | class ____(RayTransferMatrix):
"""
Ray Transfer Matrix for a thin lens.
Parameters
==========
f :
The focal distance.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import ThinLens
>>> from sympy import symbols
>>> f = symbols('f')
>>> ThinLens(f)
Matrix([
[ 1, 0],
[-1/f, 1]])
"""
def __new__(cls, f):
f = sympify(f)
return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
###
# Representation for geometric ray
###
| ThinLens |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_origin.py | {
"start": 11197,
"end": 14745
} | class ____(IHaveNew, LegacyNamedTupleMixin, CodeLocationOrigin):
"""Identifies a repository location hosted in a gRPC server managed by the user. Dagster
is not responsible for managing the lifecycle of the server.
"""
host: str
port: Optional[int]
socket: Optional[str]
location_name: str # pyright: ignore[reportIncompatibleMethodOverride]
use_ssl: Optional[bool]
additional_metadata: Optional[Mapping[str, Any]]
def __new__(
cls,
host: str,
port: Optional[int] = None,
socket: Optional[str] = None,
location_name: Optional[str] = None,
use_ssl: Optional[bool] = None,
additional_metadata: Optional[Mapping[str, Any]] = None,
):
return super().__new__(
cls,
host=host,
port=port,
socket=socket,
location_name=location_name
if location_name
else _assign_grpc_location_name(port, socket, host),
use_ssl=use_ssl,
additional_metadata=additional_metadata,
)
def get_display_metadata(self) -> Mapping[str, str]:
metadata = {
"host": self.host,
"port": str(self.port) if self.port else None,
"socket": self.socket,
**(self.additional_metadata if self.additional_metadata else {}),
}
return {key: value for key, value in metadata.items() if value is not None}
def reload_location(self, instance: "DagsterInstance") -> "GrpcServerCodeLocation":
# deferred for import perf
import grpc
from dagster._core.remote_representation.code_location import GrpcServerCodeLocation
try:
self.create_client().reload_code(timeout=instance.code_server_reload_timeout)
except Exception as e:
# Handle case when this is called against `dagster api grpc` servers that don't have this API method implemented
if (
isinstance(e.__cause__, grpc.RpcError)
and cast("grpc.RpcError", e.__cause__).code() == grpc.StatusCode.UNIMPLEMENTED
):
pass
else:
raise
return GrpcServerCodeLocation(self, instance=instance)
def create_location(self, instance: "DagsterInstance") -> "GrpcServerCodeLocation":
from dagster._core.remote_representation.code_location import GrpcServerCodeLocation
return GrpcServerCodeLocation(self, instance=instance)
def create_client(self) -> "DagsterGrpcClient":
from dagster._grpc.client import DagsterGrpcClient
return DagsterGrpcClient(
port=self.port,
socket=self.socket,
host=self.host,
use_ssl=bool(self.use_ssl),
)
@property
def is_shutdown_supported(self) -> bool:
return True
def shutdown_server(self) -> None:
try:
self.create_client().shutdown_server()
except DagsterUserCodeUnreachableError:
# Server already shutdown
pass
@property
def loadable_target_origin(self) -> LoadableTargetOrigin:
raise DagsterInvariantViolationError(
"A GrpcServerCodeLocationOrigin does not directly know its loadable target."
)
# Different storage field name for backcompat
@whitelist_for_serdes(
storage_name="ExternalRepositoryOrigin",
storage_field_names={"code_location_origin": "repository_location_origin"},
)
@record(kw_only=False)
| GrpcServerCodeLocationOrigin |
python | PyCQA__pylint | doc/data/messages/t/too-few-public-methods/good/dataclass_and_function.py | {
"start": 44,
"end": 191
} | class ____:
name: str
fruit_of_residence: Fruit
def bore(worm: Worm):
print(f"{worm.name} is boring into {worm.fruit_of_residence}")
| Worm |
python | kamyu104__LeetCode-Solutions | Python/special-array-with-x-elements-greater-than-or-equal-x.py | {
"start": 1769,
"end": 3033
} | class ____(object):
def specialArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MAX_NUM = 1000
def counting_sort(nums, reverse=False): # Time: O(n), Space: O(n)
count = [0]*(MAX_NUM+1)
for num in nums:
count[num] += 1
for i in xrange(1, len(count)):
count[i] += count[i-1]
result = [0]*len(nums)
if not reverse:
for num in reversed(nums): # stable sort
count[num] -= 1
result[count[num]] = num
else:
for num in nums: # stable sort
count[num] -= 1
result[count[num]] = num
result.reverse()
return result
nums = counting_sort(nums, reverse=True) # extra O(n) space for stable sort
left, right = 0, len(nums)-1
while left <= right: # Time: O(logn)
mid = left + (right-left)//2
if nums[mid] <= mid:
right = mid-1
else:
left = mid+1
return -1 if left < len(nums) and nums[left] == left else left
# Time: O(nlogn)
# Space: O(1)
# sort solution
| Solution3 |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 16345,
"end": 47673
} | class ____:
"""
Tracks and applies a sequence of environment variable modifications.
This class provides a high-level interface for building up a list of environment changes,
such as setting, unsetting, appending, prepending, or removing values from environment
variables. Modifications are stored and can be applied to a given environment dictionary, or
rendered as shell code.
Package authors typically receive an instance of this class and call :meth:`set`,
:meth:`unset`, :meth:`prepend_path`, :meth:`remove_path`, etc., to queue up modifications.
Spack runs :meth:`apply_modifications` to apply these modifications to the environment when
needed.
Modifications can be grouped by variable name, reversed (where possible), validated for
suspicious patterns, and extended from other instances. The class also supports tracing the
origin of modifications for debugging.
Example:
.. code-block:: python
env = EnvironmentModifications()
env.set("FOO", "bar")
env.prepend_path("PATH", "/custom/bin")
env.apply_modifications() # applies changes to os.environ
"""
def __init__(
self, other: Optional["EnvironmentModifications"] = None, traced: Union[None, bool] = None
):
"""Initializes a new instance, copying commands from 'other' if it is not None.
Args:
other: list of environment modifications to be extended (optional)
traced: enable or disable stack trace inspection to log the origin
of the environment modifications
"""
self.traced = TRACING_ENABLED if traced is None else bool(traced)
self.env_modifications: List[Union[NameModifier, NameValueModifier]] = []
if other is not None:
self.extend(other)
def __iter__(self):
return iter(self.env_modifications)
def __len__(self):
return len(self.env_modifications)
def extend(self, other: "EnvironmentModifications"):
"""Extends the current instance with modifications from another instance."""
self._check_other(other)
self.env_modifications.extend(other.env_modifications)
@staticmethod
def _check_other(other: "EnvironmentModifications"):
if not isinstance(other, EnvironmentModifications):
raise TypeError("other must be an instance of EnvironmentModifications")
def _trace(self) -> Optional[Trace]:
"""Returns a trace object if tracing is enabled, else None."""
if not self.traced:
return None
stack = inspect.stack()
try:
_, filename, lineno, _, context, index = stack[2]
assert index is not None, "index must be an integer"
current_context = context[index].strip() if context is not None else "unknown context"
except Exception:
filename = "unknown file"
lineno = -1
current_context = "unknown context"
return Trace(filename=filename, lineno=lineno, context=current_context)
def set(self, name: str, value: str, *, force: bool = False, raw: bool = False) -> None:
"""Stores a request to set an environment variable.
Args:
name: name of the environment variable
value: value of the environment variable
force: if True, audit will not consider this modification a warning
raw: if True, format of value string is skipped
"""
value = _validate_value(name, value)
item = SetEnv(name, value, trace=self._trace(), force=force, raw=raw)
self.env_modifications.append(item)
def append_flags(self, name: str, value: str, sep: str = " ") -> None:
"""Stores a request to append flags to an environment variable.
Args:
name: name of the environment variable
value: flags to be appended
sep: separator for the flags (default: ``" "``)
"""
value = _validate_value(name, value)
item = AppendFlagsEnv(name, value, separator=sep, trace=self._trace())
self.env_modifications.append(item)
def unset(self, name: str) -> None:
"""Stores a request to unset an environment variable.
Args:
name: name of the environment variable
"""
item = UnsetEnv(name, trace=self._trace())
self.env_modifications.append(item)
def remove_flags(self, name: str, value: str, sep: str = " ") -> None:
"""Stores a request to remove flags from an environment variable
Args:
name: name of the environment variable
value: flags to be removed
sep: separator for the flags (default: ``" "``)
"""
value = _validate_value(name, value)
item = RemoveFlagsEnv(name, value, separator=sep, trace=self._trace())
self.env_modifications.append(item)
def set_path(self, name: str, elements: ListOfPaths, separator: str = os.pathsep) -> None:
"""Stores a request to set an environment variable to a list of paths,
separated by a character defined in input.
Args:
name: name of the environment variable
elements: ordered list paths
separator: separator for the paths (default: :data:`os.pathsep`)
"""
elements = [_validate_path_value(name, x) for x in elements]
item = SetPath(name, elements, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def append_path(
self, name: str, path: Union[str, pathlib.PurePath], separator: str = os.pathsep
) -> None:
"""Stores a request to append a path to list of paths.
Args:
name: name of the environment variable
path: path to be appended
separator: separator for the paths (default: :data:`os.pathsep`)
"""
path = _validate_path_value(name, path)
item = AppendPath(name, path, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def prepend_path(
self, name: str, path: Union[str, pathlib.PurePath], separator: str = os.pathsep
) -> None:
"""Stores a request to prepend a path to list of paths.
Args:
name: name of the environment variable
path: path to be prepended
separator: separator for the paths (default: :data:`os.pathsep`)
"""
path = _validate_path_value(name, path)
item = PrependPath(name, path, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def remove_first_path(
self, name: str, path: Union[str, pathlib.PurePath], separator: str = os.pathsep
) -> None:
"""Stores a request to remove first instance of path from a list of paths.
Args:
name: name of the environment variable
path: path to be removed
separator: separator for the paths (default: :data:`os.pathsep`)
"""
path = _validate_path_value(name, path)
item = RemoveFirstPath(name, path, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def remove_last_path(
self, name: str, path: Union[str, pathlib.PurePath], separator: str = os.pathsep
) -> None:
"""Stores a request to remove last instance of path from a list of paths.
Args:
name: name of the environment variable
path: path to be removed
separator: separator for the paths (default: :data:`os.pathsep`)
"""
path = _validate_path_value(name, path)
item = RemoveLastPath(name, path, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def remove_path(
self, name: str, path: Union[str, pathlib.PurePath], separator: str = os.pathsep
) -> None:
"""Stores a request to remove a path from a list of paths.
Args:
name: name of the environment variable
path: path to be removed
separator: separator for the paths (default: :data:`os.pathsep`)
"""
path = _validate_path_value(name, path)
item = RemovePath(name, path, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def deprioritize_system_paths(self, name: str, separator: str = os.pathsep) -> None:
"""Stores a request to deprioritize system paths in a path list,
otherwise preserving the order.
Args:
name: name of the environment variable
separator: separator for the paths (default: :data:`os.pathsep`)
"""
item = DeprioritizeSystemPaths(name, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def prune_duplicate_paths(self, name: str, separator: str = os.pathsep) -> None:
"""Stores a request to remove duplicates from a path list, otherwise
preserving the order.
Args:
name: name of the environment variable
separator: separator for the paths (default: :data:`os.pathsep`)
"""
item = PruneDuplicatePaths(name, separator=separator, trace=self._trace())
self.env_modifications.append(item)
def group_by_name(self) -> Dict[str, ModificationList]:
"""Returns a dict of the current modifications keyed by variable name."""
modifications = collections.defaultdict(list)
for item in self:
modifications[item.name].append(item)
return modifications
def drop(self, *name) -> bool:
"""Drop all modifications to the variable with the given name."""
old_mods = self.env_modifications
new_mods = [x for x in self.env_modifications if x.name not in name]
self.env_modifications = new_mods
return len(old_mods) != len(new_mods)
def is_unset(self, variable_name: str) -> bool:
"""Returns :data:`True` if the last modification to a variable is to unset it,
:data:`False` otherwise."""
modifications = self.group_by_name()
if variable_name not in modifications:
return False
# The last modification must unset the variable for it to be considered unset
return isinstance(modifications[variable_name][-1], UnsetEnv)
def clear(self):
"""Clears the current list of modifications."""
self.env_modifications = []
def reversed(self) -> "EnvironmentModifications":
"""Returns the EnvironmentModifications object that will reverse self
Only creates reversals for additions to the environment, as reversing
:meth:`unset` and :meth:`remove_path` modifications is impossible.
Reversible operations are :meth:`set`, :meth:`prepend_path`, :meth:`append_path`,
:meth:`set_path`, and :meth:`append_flags`.
"""
rev = EnvironmentModifications()
for envmod in reversed(self.env_modifications):
if isinstance(envmod, SetEnv):
tty.debug("Reversing `Set` environment operation may lose the original value")
rev.unset(envmod.name)
elif isinstance(envmod, AppendPath):
rev.remove_last_path(envmod.name, envmod.value)
elif isinstance(envmod, PrependPath):
rev.remove_first_path(envmod.name, envmod.value)
elif isinstance(envmod, SetPath):
tty.debug("Reversing `SetPath` environment operation may lose the original value")
rev.unset(envmod.name)
elif isinstance(envmod, AppendFlagsEnv):
rev.remove_flags(envmod.name, envmod.value)
else:
tty.debug(
f"Skipping reversal of irreversible operation {type(envmod)} {envmod.name}"
)
return rev
def apply_modifications(self, env: Optional[MutableMapping[str, str]] = None):
"""Applies the modifications to the environment.
Args:
env: environment to be modified. If None, :obj:`os.environ` will be used.
"""
env = os.environ if env is None else env
modifications = self.group_by_name()
for _, actions in sorted(modifications.items()):
for modifier in actions:
modifier.execute(env)
def shell_modifications(
self,
shell: str = "sh" if sys.platform != "win32" else os.environ.get("SPACK_SHELL", "bat"),
explicit: bool = False,
env: Optional[MutableMapping[str, str]] = None,
) -> str:
"""Return shell code to apply the modifications."""
modifications = self.group_by_name()
env = os.environ if env is None else env
new_env = dict(env.items())
for _, actions in sorted(modifications.items()):
for modifier in actions:
modifier.execute(new_env)
if "MANPATH" in new_env and not new_env["MANPATH"].endswith(os.pathsep):
new_env["MANPATH"] += os.pathsep
cmds = ""
for name in sorted(set(modifications)):
new = new_env.get(name, None)
old = env.get(name, None)
if explicit or new != old:
if new is None:
cmds += _SHELL_UNSET_STRINGS[shell].format(name)
else:
value = new_env[name]
if shell not in ("bat", "pwsh"):
value = shlex.quote(value)
cmd = _SHELL_SET_STRINGS[shell].format(name, value)
cmds += cmd
return cmds
@staticmethod
def from_sourcing_file(
filename: Path, *arguments: str, **kwargs: Any
) -> "EnvironmentModifications":
"""Returns the environment modifications that have the same effect as
sourcing the input file in a shell.
Args:
filename: the file to be sourced
*arguments: arguments to pass on the command line
Keyword Args:
shell (str): the shell to use (default: ``bash``)
shell_options (str): options passed to the shell (default: ``-c``)
source_command (str): the command to run (default: ``source``)
suppress_output (str): redirect used to suppress output of command
(default: ``&> /dev/null``)
concatenate_on_success (str): operator used to execute a command
only when the previous command succeeds (default: ``&&``)
exclude ([str or re.Pattern[str]]): ignore any modifications of these
variables (default: [])
include ([str or re.Pattern[str]]): always respect modifications of these
variables (default: []). Supersedes any excluded variables.
clean (bool): in addition to removing empty entries,
also remove duplicate entries (default: False).
"""
tty.debug(f"EnvironmentModifications.from_sourcing_file: {filename}")
# Check if the file actually exists
if not os.path.isfile(filename):
msg = f"Trying to source non-existing file: {filename}"
raise RuntimeError(msg)
# Prepare include and exclude lists of environment variable names
exclude = kwargs.get("exclude", [])
include = kwargs.get("include", [])
clean = kwargs.get("clean", False)
# Other variables unrelated to sourcing a file
exclude.extend(
[
# Bash internals
"SHLVL",
"_",
"PWD",
"OLDPWD",
"PS1",
"PS2",
"ENV",
# Environment Modules or Lmod
"LOADEDMODULES",
"_LMFILES_",
"MODULEPATH",
"MODULERCFILE",
"BASH_FUNC_ml()",
"BASH_FUNC_module()",
# Environment Modules-specific configuration
"MODULESHOME",
"BASH_FUNC__module_raw()",
r"MODULES_(.*)",
r"__MODULES_(.*)",
r"(\w*)_mod(quar|share)",
# Lmod-specific configuration
r"LMOD_(.*)",
]
)
before_kwargs = {**kwargs}
if sys.platform == "win32":
# Windows cannot source os.devnull, but it can echo from it
# so we override the "source" action in the method that
# extracts the env (environment_after_sourcing_files)
if "source_command" not in kwargs:
before_kwargs["source_command"] = "echo"
# Compute the environments before and after sourcing
# First look at the environment after doing nothing to
# establish baseline
before = sanitize(
environment_after_sourcing_files(os.devnull, **before_kwargs),
exclude=exclude,
include=include,
)
file_and_args = (filename,) + arguments
after = sanitize(
environment_after_sourcing_files(file_and_args, **kwargs),
exclude=exclude,
include=include,
)
# Delegate to the other factory
return EnvironmentModifications.from_environment_diff(before, after, clean)
@staticmethod
def from_environment_diff(
before: MutableMapping[str, str], after: MutableMapping[str, str], clean: bool = False
) -> "EnvironmentModifications":
"""Constructs the environment modifications from the diff of two environments.
Args:
before: environment before the modifications are applied
after: environment after the modifications are applied
clean: in addition to removing empty entries, also remove duplicate entries
"""
# Fill the EnvironmentModifications instance
env = EnvironmentModifications()
# New variables
new_variables = list(set(after) - set(before))
# Variables that have been unset
unset_variables = list(set(before) - set(after))
# Variables that have been modified
common_variables = set(before).intersection(set(after))
modified_variables = [x for x in common_variables if before[x] != after[x]]
# Consistent output order - looks nicer, easier comparison...
new_variables.sort()
unset_variables.sort()
modified_variables.sort()
def return_separator_if_any(*args):
separators = [os.pathsep] if sys.platform == "win32" else [":", ";"]
for separator in separators:
for arg in args:
if separator in arg:
return separator
return None
# Add variables to env.
# Assume that variables with 'PATH' in the name or that contain
# separators like ':' or ';' are more likely to be paths
for variable_name in new_variables:
sep = return_separator_if_any(after[variable_name])
if sep:
env.prepend_path(variable_name, after[variable_name], separator=sep)
elif "PATH" in variable_name:
env.prepend_path(variable_name, after[variable_name])
else:
# We just need to set the variable to the new value
env.set(variable_name, after[variable_name])
for variable_name in unset_variables:
env.unset(variable_name)
for variable_name in modified_variables:
value_before = before[variable_name]
value_after = after[variable_name]
sep = return_separator_if_any(value_before, value_after)
if sep:
before_list = value_before.split(sep)
after_list = value_after.split(sep)
# Filter out empty strings
before_list = list(filter(None, before_list))
after_list = list(filter(None, after_list))
# Remove duplicate entries (worse matching, bloats env)
if clean:
before_list = list(dedupe(before_list))
after_list = list(dedupe(after_list))
# The reassembled cleaned entries
value_before = sep.join(before_list)
value_after = sep.join(after_list)
# Paths that have been removed
remove_list = [ii for ii in before_list if ii not in after_list]
# Check that nothing has been added in the middle of
# before_list
remaining_list = [ii for ii in before_list if ii in after_list]
try:
start = after_list.index(remaining_list[0])
end = after_list.index(remaining_list[-1])
search = sep.join(after_list[start : end + 1])
except IndexError:
env.prepend_path(variable_name, value_after)
continue
if search not in value_before:
# We just need to set the variable to the new value
env.prepend_path(variable_name, value_after)
else:
try:
prepend_list = after_list[:start]
prepend_list.reverse() # Preserve order after prepend
except KeyError:
prepend_list = []
try:
append_list = after_list[end + 1 :]
except KeyError:
append_list = []
for item in remove_list:
env.remove_path(variable_name, item)
for item in append_list:
env.append_path(variable_name, item)
for item in prepend_list:
env.prepend_path(variable_name, item)
else:
# We just need to set the variable to the new value
env.set(variable_name, value_after)
return env
def _set_or_unset_not_first(
variable: str, changes: ModificationList, errstream: Callable[[str], None]
):
"""Check if we are going to set or unset something after other
modifications have already been requested.
"""
indexes = [
ii
for ii, item in enumerate(changes)
if ii != 0 and isinstance(item, (SetEnv, UnsetEnv)) and not getattr(item, "force", False)
]
if indexes:
good = "\t \t{}"
nogood = "\t--->\t{}"
errstream(f"Different requests to set/unset '{variable}' have been found")
for idx, item in enumerate(changes):
print_format = nogood if idx in indexes else good
errstream(print_format.format(item.trace))
def validate(env: EnvironmentModifications, errstream: Callable[[str], None]):
"""Validates the environment modifications to check for the presence of
suspicious patterns. Prompts a warning for everything that was found.
Current checks:
- set or unset variables after other changes on the same variable
Args:
env: list of environment modifications
errstream: callable to log error messages
"""
if not env.traced:
return
modifications = env.group_by_name()
for variable, list_of_changes in sorted(modifications.items()):
_set_or_unset_not_first(variable, list_of_changes, errstream)
def inspect_path(
root: Path,
inspections: MutableMapping[str, List[str]],
exclude: Optional[Callable[[Path], bool]] = None,
) -> EnvironmentModifications:
"""Inspects ``root`` to search for the subdirectories in ``inspections``.
Adds every path found to a list of prepend-path commands and returns it.
Args:
root: absolute path where to search for subdirectories
inspections: maps relative paths to a list of environment
variables that will be modified if the path exists. The
modifications are not performed immediately, but stored in a
command object that is returned to client
exclude: optional callable. If present it must accept an
absolute path and return True if it should be excluded from the
inspection
Examples:
The following lines execute an inspection in ``/usr`` to search for
``/usr/include`` and ``/usr/lib64``. If found we want to prepend
``/usr/include`` to ``CPATH`` and ``/usr/lib64`` to ``MY_LIB64_PATH``.
.. code-block:: python
# Set up the dictionary containing the inspection
inspections = {
"include": ["CPATH"],
"lib64": ["MY_LIB64_PATH"]
}
# Get back the list of command needed to modify the environment
env = inspect_path("/usr", inspections)
# Eventually execute the commands
env.apply_modifications()
"""
if exclude is None:
exclude = lambda x: False
env = EnvironmentModifications()
# Inspect the prefix to check for the existence of common directories
for relative_path, variables in inspections.items():
expected = os.path.join(root, os.path.normpath(relative_path))
if os.path.isdir(expected) and not exclude(expected):
for variable in variables:
env.prepend_path(variable, expected)
return env
@contextlib.contextmanager
def preserve_environment(*variables: str):
"""Ensures that the value of the environment variables passed as
arguments is the same before entering to the context manager and after
exiting it.
Variables that are unset before entering the context manager will be
explicitly unset on exit.
Args:
variables: list of environment variables to be preserved
"""
cache = {}
for var in variables:
# The environment variable to be preserved might not be there.
# In that case store None as a placeholder.
cache[var] = os.environ.get(var, None)
yield
for var in variables:
value = cache[var]
msg = "[PRESERVE_ENVIRONMENT]"
if value is not None:
# Print a debug statement if the value changed
if var not in os.environ:
msg += ' {0} was unset, will be reset to "{1}"'
tty.debug(msg.format(var, value))
elif os.environ[var] != value:
msg += ' {0} was set to "{1}", will be reset to "{2}"'
tty.debug(msg.format(var, os.environ[var], value))
os.environ[var] = value
elif var in os.environ:
msg += ' {0} was set to "{1}", will be unset'
tty.debug(msg.format(var, os.environ[var]))
del os.environ[var]
def environment_after_sourcing_files(
*files: Union[Path, Tuple[str, ...]], **kwargs
) -> Dict[str, str]:
"""Returns a dictionary with the environment that one would have
after sourcing the files passed as argument.
Args:
*files: each item can either be a string containing the path
of the file to be sourced or a sequence, where the first element
is the file to be sourced and the remaining are arguments to be
passed to the command line
Keyword Args:
env (dict): the initial environment (default: current environment)
shell (str): the shell to use (default: ``/bin/bash`` or ``cmd.exe`` (Windows))
shell_options (str): options passed to the shell (default: ``-c`` or ``/C`` (Windows))
source_command (str): the command to run (default: ``source``)
suppress_output (str): redirect used to suppress output of command
(default: ``&> /dev/null``)
concatenate_on_success (str): operator used to execute a command
only when the previous command succeeds (default: ``&&``)
"""
# Set the shell executable that will be used to source files
if sys.platform == "win32":
shell_cmd = kwargs.get("shell", "cmd.exe")
shell_options = kwargs.get("shell_options", "/C")
suppress_output = kwargs.get("suppress_output", "> nul")
source_command = kwargs.get("source_command", "")
else:
shell_cmd = kwargs.get("shell", "/bin/bash")
shell_options = kwargs.get("shell_options", "-c")
suppress_output = kwargs.get("suppress_output", "&> /dev/null")
source_command = kwargs.get("source_command", "source")
concatenate_on_success = kwargs.get("concatenate_on_success", "&&")
def _source_single_file(file_and_args, environment):
shell_options_list = shell_options.split()
source_file = [source_command]
source_file.extend(x for x in file_and_args)
source_file = " ".join(source_file)
dump_cmd = "import os, json; print(json.dumps(dict(os.environ)))"
dump_environment_cmd = sys.executable + f' -E -c "{dump_cmd}"'
# Try to source the file
source_file_arguments = " ".join(
[source_file, suppress_output, concatenate_on_success, dump_environment_cmd]
)
# Popens argument processing can break command invocations
# on Windows, compose to a string to avoid said processing
cmd = [shell_cmd, *shell_options_list, source_file_arguments]
cmd = " ".join(cmd) if sys.platform == "win32" else cmd
with subprocess.Popen(
cmd, env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE
) as shell:
output, _ = shell.communicate()
return json.loads(output)
current_environment = kwargs.get("env", dict(os.environ))
for file in files:
# Normalize the input to the helper function
if isinstance(file, str):
file = (file,)
current_environment = _source_single_file(file, environment=current_environment)
return current_environment
def sanitize(
environment: MutableMapping[str, str], exclude: List[str], include: List[str]
) -> Dict[str, str]:
"""Returns a copy of the input dictionary where all the keys that
match an excluded pattern and don't match an included pattern are
removed.
Args:
environment (dict): input dictionary
exclude (list): literals or regex patterns to be excluded
include (list): literals or regex patterns to be included
"""
def set_intersection(fullset, *args):
# A set intersection using string literals and regexs
meta = "[" + re.escape("[$()*?[]^{|}") + "]"
subset = fullset & set(args) # As literal
for name in args:
if re.search(meta, name):
pattern = re.compile(name)
for k in fullset:
if re.match(pattern, k):
subset.add(k)
return subset
# Don't modify input, make a copy instead
environment = dict(environment)
# include supersedes any excluded items
prune = set_intersection(set(environment), *exclude)
prune -= set_intersection(prune, *include)
for k in prune:
environment.pop(k, None)
return environment
| EnvironmentModifications |
python | mlflow__mlflow | tests/pyfunc/test_model_export_with_class_and_artifacts.py | {
"start": 10804,
"end": 42180
} | class ____(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
return model_input
def test_log_model_calls_register_model(sklearn_knn_model, main_scoped_model_class):
with mlflow.start_run():
with mock.patch(
"mlflow.tracking._model_registry.fluent._register_model"
) as register_model_mock:
registered_model_name = "AdsModel1"
pyfunc_model_info = mlflow.pyfunc.log_model(
name="pyfunc_model",
python_model=DummyModel(),
registered_model_name=registered_model_name,
)
assert_register_model_called_with_local_model_path(
register_model_mock, pyfunc_model_info.model_uri, registered_model_name
)
def test_log_model_no_registered_model_name(sklearn_knn_model, main_scoped_model_class):
with mlflow.start_run():
with mock.patch(
"mlflow.tracking._model_registry.fluent._register_model"
) as register_model_mock:
mlflow.pyfunc.log_model(
name="pyfunc_model",
python_model=DummyModel(),
)
register_model_mock.assert_not_called()
def test_model_load_from_remote_uri_succeeds(
sklearn_knn_model, main_scoped_model_class, tmp_path, mock_s3_bucket, iris_data
):
artifact_root = f"s3://{mock_s3_bucket}"
artifact_repo = S3ArtifactRepository(artifact_root)
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
sklearn_artifact_path = "sk_model"
artifact_repo.log_artifacts(sklearn_model_path, artifact_path=sklearn_artifact_path)
def test_predict(sk_model, model_input):
return sk_model.predict(model_input) * 2
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(test_predict),
conda_env=_conda_env(),
)
pyfunc_artifact_path = "pyfunc_model"
artifact_repo.log_artifacts(pyfunc_model_path, artifact_path=pyfunc_artifact_path)
model_uri = artifact_root + "/" + pyfunc_artifact_path
loaded_pyfunc_model = mlflow.pyfunc.load_model(model_uri=model_uri)
np.testing.assert_array_equal(
loaded_pyfunc_model.predict(iris_data[0]),
test_predict(sk_model=sklearn_knn_model, model_input=iris_data[0]),
)
def test_add_to_model_adds_specified_kwargs_to_mlmodel_configuration():
custom_kwargs = {
"key1": "value1",
"key2": 20,
"key3": range(10),
}
model_config = Model()
mlflow.pyfunc.add_to_model(
model=model_config,
loader_module=os.path.basename(__file__)[:-3],
data="data",
code="code",
env=None,
**custom_kwargs,
)
assert mlflow.pyfunc.FLAVOR_NAME in model_config.flavors
assert all(item in model_config.flavors[mlflow.pyfunc.FLAVOR_NAME] for item in custom_kwargs)
def test_pyfunc_model_serving_without_conda_env_activation_succeeds_with_main_scoped_class(
sklearn_knn_model, main_scoped_model_class, iris_data, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
def test_predict(sk_model, model_input):
return sk_model.predict(model_input) * 2
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(test_predict),
conda_env=_conda_env(),
)
loaded_pyfunc_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_path)
sample_input = pd.DataFrame(iris_data[0])
scoring_response = pyfunc_serve_and_score_model(
model_uri=pyfunc_model_path,
data=sample_input,
content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON,
extra_args=["--env-manager", "local"],
)
assert scoring_response.status_code == 200
np.testing.assert_array_equal(
np.array(json.loads(scoring_response.text)["predictions"]),
loaded_pyfunc_model.predict(sample_input),
)
def test_pyfunc_model_serving_with_conda_env_activation_succeeds_with_main_scoped_class(
sklearn_knn_model, main_scoped_model_class, iris_data, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
def test_predict(sk_model, model_input):
return sk_model.predict(model_input) * 2
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(test_predict),
conda_env=_conda_env(),
)
loaded_pyfunc_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_path)
sample_input = pd.DataFrame(iris_data[0])
scoring_response = pyfunc_serve_and_score_model(
model_uri=pyfunc_model_path,
data=sample_input,
content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON,
)
assert scoring_response.status_code == 200
np.testing.assert_array_equal(
np.array(json.loads(scoring_response.text)["predictions"]),
loaded_pyfunc_model.predict(sample_input),
)
def test_pyfunc_model_serving_without_conda_env_activation_succeeds_with_module_scoped_class(
sklearn_knn_model, iris_data, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
def test_predict(sk_model, model_input):
return sk_model.predict(model_input) * 2
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=ModuleScopedSklearnModel(test_predict),
code_paths=[os.path.dirname(tests.__file__)],
conda_env=_conda_env(),
)
loaded_pyfunc_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_path)
sample_input = pd.DataFrame(iris_data[0])
scoring_response = pyfunc_serve_and_score_model(
model_uri=pyfunc_model_path,
data=sample_input,
content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON,
extra_args=["--env-manager", "local"],
)
assert scoring_response.status_code == 200
np.testing.assert_array_equal(
np.array(json.loads(scoring_response.text)["predictions"]),
loaded_pyfunc_model.predict(sample_input),
)
def test_pyfunc_cli_predict_command_without_conda_env_activation_succeeds(
sklearn_knn_model, main_scoped_model_class, iris_data, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
def test_predict(sk_model, model_input):
return sk_model.predict(model_input) * 2
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(test_predict),
conda_env=_conda_env(),
)
loaded_pyfunc_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_path)
sample_input = pd.DataFrame(iris_data[0])
input_csv_path = os.path.join(tmp_path, "input with spaces.csv")
sample_input.to_csv(input_csv_path, header=True, index=False)
output_json_path = os.path.join(tmp_path, "output.json")
process = Popen(
[
sys.executable,
"-m",
"mlflow",
"models",
"predict",
"--model-uri",
pyfunc_model_path,
"-i",
input_csv_path,
"--content-type",
"csv",
"-o",
output_json_path,
"--env-manager",
"local",
],
stdout=PIPE,
stderr=PIPE,
preexec_fn=os.setsid,
)
_, stderr = process.communicate()
assert process.wait() == 0, f"stderr = \n\n{stderr}\n\n"
with open(output_json_path) as f:
result_df = pd.DataFrame(data=json.load(f)["predictions"])
np.testing.assert_array_equal(
result_df.values.transpose()[0], loaded_pyfunc_model.predict(sample_input)
)
def test_pyfunc_cli_predict_command_with_conda_env_activation_succeeds(
sklearn_knn_model, main_scoped_model_class, iris_data, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
def test_predict(sk_model, model_input):
return sk_model.predict(model_input) * 2
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(test_predict),
conda_env=_conda_env(),
)
loaded_pyfunc_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_path)
sample_input = pd.DataFrame(iris_data[0])
input_csv_path = os.path.join(tmp_path, "input with spaces.csv")
sample_input.to_csv(input_csv_path, header=True, index=False)
output_json_path = os.path.join(tmp_path, "output.json")
process = Popen(
[
sys.executable,
"-m",
"mlflow",
"models",
"predict",
"--model-uri",
pyfunc_model_path,
"-i",
input_csv_path,
"--content-type",
"csv",
"-o",
output_json_path,
],
stderr=PIPE,
stdout=PIPE,
preexec_fn=os.setsid,
)
stdout, stderr = process.communicate()
assert process.wait() == 0, f"stdout = \n\n{stdout}\n\n stderr = \n\n{stderr}\n\n"
with open(output_json_path) as f:
result_df = pandas.DataFrame(json.load(f)["predictions"])
np.testing.assert_array_equal(
result_df.values.transpose()[0], loaded_pyfunc_model.predict(sample_input)
)
def test_save_model_persists_specified_conda_env_in_mlflow_model_directory(
sklearn_knn_model, main_scoped_model_class, pyfunc_custom_env, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(
sk_model=sklearn_knn_model,
path=sklearn_model_path,
serialization_format=mlflow.sklearn.SERIALIZATION_FORMAT_CLOUDPICKLE,
)
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(predict_fn=None),
conda_env=pyfunc_custom_env,
)
pyfunc_conf = _get_flavor_configuration(
model_path=pyfunc_model_path, flavor_name=mlflow.pyfunc.FLAVOR_NAME
)
saved_conda_env_path = os.path.join(pyfunc_model_path, pyfunc_conf[mlflow.pyfunc.ENV]["conda"])
assert os.path.exists(saved_conda_env_path)
assert saved_conda_env_path != pyfunc_custom_env
with open(pyfunc_custom_env) as f:
pyfunc_custom_env_parsed = yaml.safe_load(f)
with open(saved_conda_env_path) as f:
saved_conda_env_parsed = yaml.safe_load(f)
assert saved_conda_env_parsed == pyfunc_custom_env_parsed
def test_save_model_persists_requirements_in_mlflow_model_directory(
sklearn_knn_model, main_scoped_model_class, pyfunc_custom_env, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(
sk_model=sklearn_knn_model,
path=sklearn_model_path,
serialization_format=mlflow.sklearn.SERIALIZATION_FORMAT_CLOUDPICKLE,
)
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(predict_fn=None),
conda_env=pyfunc_custom_env,
)
saved_pip_req_path = os.path.join(pyfunc_model_path, "requirements.txt")
_compare_conda_env_requirements(pyfunc_custom_env, saved_pip_req_path)
def test_log_model_with_pip_requirements(sklearn_knn_model, main_scoped_model_class, tmp_path):
expected_mlflow_version = _mlflow_major_version_string()
python_model = main_scoped_model_class(predict_fn=None)
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
# Path to a requirements file
req_file = tmp_path.joinpath("requirements.txt")
req_file.write_text("a")
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
python_model=python_model,
pip_requirements=str(req_file),
artifacts={"sk_model": sklearn_model_path},
)
_assert_pip_requirements(
model_info.model_uri,
[expected_mlflow_version, "a"],
strict=True,
)
# List of requirements
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
python_model=python_model,
pip_requirements=[f"-r {req_file}", "b"],
artifacts={"sk_model": sklearn_model_path},
)
_assert_pip_requirements(
model_info.model_uri,
[expected_mlflow_version, "a", "b"],
strict=True,
)
# Constraints file
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
python_model=python_model,
pip_requirements=[f"-c {req_file}", "b"],
artifacts={"sk_model": sklearn_model_path},
)
_assert_pip_requirements(
model_info.model_uri,
[expected_mlflow_version, "b", "-c constraints.txt"],
["a"],
strict=True,
)
def test_log_model_with_extra_pip_requirements(
sklearn_knn_model, main_scoped_model_class, tmp_path
):
expected_mlflow_version = _mlflow_major_version_string()
sklearn_model_path = str(tmp_path.joinpath("sklearn_model"))
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
python_model = main_scoped_model_class(predict_fn=None)
default_reqs = mlflow.pyfunc.get_default_pip_requirements()
# Path to a requirements file
req_file = tmp_path.joinpath("requirements.txt")
req_file.write_text("a")
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
python_model=python_model,
artifacts={"sk_model": sklearn_model_path},
extra_pip_requirements=str(req_file),
)
_assert_pip_requirements(
model_info.model_uri,
[expected_mlflow_version, *default_reqs, "a"],
)
# List of requirements
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
artifacts={"sk_model": sklearn_model_path},
python_model=python_model,
extra_pip_requirements=[f"-r {req_file}", "b"],
)
_assert_pip_requirements(
model_info.model_uri,
[expected_mlflow_version, *default_reqs, "a", "b"],
)
# Constraints file
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
artifacts={"sk_model": sklearn_model_path},
python_model=python_model,
extra_pip_requirements=[f"-c {req_file}", "b"],
)
_assert_pip_requirements(
model_info.model_uri,
[expected_mlflow_version, *default_reqs, "b", "-c constraints.txt"],
["a"],
)
def test_log_model_persists_specified_conda_env_in_mlflow_model_directory(
sklearn_knn_model, main_scoped_model_class, pyfunc_custom_env
):
sklearn_artifact_path = "sk_model"
with mlflow.start_run():
sklearn_model_info = mlflow.sklearn.log_model(sklearn_knn_model, name=sklearn_artifact_path)
pyfunc_artifact_path = "pyfunc_model"
with mlflow.start_run():
pyfunc_model_info = mlflow.pyfunc.log_model(
name=pyfunc_artifact_path,
artifacts={"sk_model": sklearn_model_info.model_uri},
python_model=main_scoped_model_class(predict_fn=None),
conda_env=pyfunc_custom_env,
)
pyfunc_model_path = _download_artifact_from_uri(pyfunc_model_info.model_uri)
pyfunc_conf = _get_flavor_configuration(
model_path=pyfunc_model_path, flavor_name=mlflow.pyfunc.FLAVOR_NAME
)
saved_conda_env_path = os.path.join(pyfunc_model_path, pyfunc_conf[mlflow.pyfunc.ENV]["conda"])
assert os.path.exists(saved_conda_env_path)
assert saved_conda_env_path != pyfunc_custom_env
with open(pyfunc_custom_env) as f:
pyfunc_custom_env_parsed = yaml.safe_load(f)
with open(saved_conda_env_path) as f:
saved_conda_env_parsed = yaml.safe_load(f)
assert saved_conda_env_parsed == pyfunc_custom_env_parsed
def test_model_log_persists_requirements_in_mlflow_model_directory(
sklearn_knn_model, main_scoped_model_class, pyfunc_custom_env
):
sklearn_artifact_path = "sk_model"
with mlflow.start_run():
sklearn_model_info = mlflow.sklearn.log_model(sklearn_knn_model, name=sklearn_artifact_path)
pyfunc_artifact_path = "pyfunc_model"
with mlflow.start_run():
pyfunc_model_info = mlflow.pyfunc.log_model(
name=pyfunc_artifact_path,
artifacts={"sk_model": sklearn_model_info.model_uri},
python_model=main_scoped_model_class(predict_fn=None),
conda_env=pyfunc_custom_env,
)
pyfunc_model_path = _download_artifact_from_uri(pyfunc_model_info.model_uri)
saved_pip_req_path = os.path.join(pyfunc_model_path, "requirements.txt")
_compare_conda_env_requirements(pyfunc_custom_env, saved_pip_req_path)
def test_save_model_without_specified_conda_env_uses_default_env_with_expected_dependencies(
sklearn_logreg_model, main_scoped_model_class, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_model")
mlflow.sklearn.save_model(sk_model=sklearn_logreg_model, path=sklearn_model_path)
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
python_model=main_scoped_model_class(predict_fn=None),
conda_env=_conda_env(),
)
_assert_pip_requirements(pyfunc_model_path, mlflow.pyfunc.get_default_pip_requirements())
def test_log_model_without_specified_conda_env_uses_default_env_with_expected_dependencies(
sklearn_knn_model, main_scoped_model_class
):
sklearn_artifact_path = "sk_model"
with mlflow.start_run():
sklearn_model_info = mlflow.sklearn.log_model(sklearn_knn_model, name=sklearn_artifact_path)
pyfunc_artifact_path = "pyfunc_model"
with mlflow.start_run():
pyfunc_model_info = mlflow.pyfunc.log_model(
name=pyfunc_artifact_path,
artifacts={
"sk_model": sklearn_model_info.model_uri,
},
python_model=main_scoped_model_class(predict_fn=None),
)
_assert_pip_requirements(
pyfunc_model_info.model_uri, mlflow.pyfunc.get_default_pip_requirements()
)
def test_save_model_correctly_resolves_directory_artifact_with_nested_contents(
tmp_path, model_path, iris_data
):
directory_artifact_path = os.path.join(tmp_path, "directory_artifact")
nested_file_relative_path = os.path.join(
"my", "somewhat", "heavily", "nested", "directory", "myfile.txt"
)
nested_file_path = os.path.join(directory_artifact_path, nested_file_relative_path)
os.makedirs(os.path.dirname(nested_file_path))
nested_file_text = "some sample file text"
with open(nested_file_path, "w") as f:
f.write(nested_file_text)
class ArtifactValidationModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
expected_file_path = os.path.join(
context.artifacts["testdir"], nested_file_relative_path
)
if not os.path.exists(expected_file_path):
return False
else:
with open(expected_file_path) as f:
return f.read() == nested_file_text
mlflow.pyfunc.save_model(
path=model_path,
artifacts={"testdir": directory_artifact_path},
python_model=ArtifactValidationModel(),
conda_env=_conda_env(),
)
loaded_model = mlflow.pyfunc.load_model(model_uri=model_path)
assert loaded_model.predict(iris_data[0])
def test_save_model_with_no_artifacts_does_not_produce_artifacts_dir(model_path):
mlflow.pyfunc.save_model(
path=model_path,
python_model=ModuleScopedSklearnModel(predict_fn=None),
artifacts=None,
conda_env=_conda_env(),
)
assert os.path.exists(model_path)
assert "artifacts" not in os.listdir(model_path)
pyfunc_conf = _get_flavor_configuration(
model_path=model_path, flavor_name=mlflow.pyfunc.FLAVOR_NAME
)
assert mlflow.pyfunc.model.CONFIG_KEY_ARTIFACTS not in pyfunc_conf
def test_save_model_with_python_model_argument_of_invalid_type_raises_exception(
tmp_path,
):
with pytest.raises(
MlflowException,
match="must be a PythonModel instance, callable object, or path to a",
):
mlflow.pyfunc.save_model(path=os.path.join(tmp_path, "model1"), python_model=5)
with pytest.raises(
MlflowException,
match="must be a PythonModel instance, callable object, or path to a",
):
mlflow.pyfunc.save_model(
path=os.path.join(tmp_path, "model2"), python_model=["not a python model"]
)
with pytest.raises(MlflowException, match="The provided model path"):
mlflow.pyfunc.save_model(
path=os.path.join(tmp_path, "model3"), python_model="not a valid filepath"
)
def test_save_model_with_unsupported_argument_combinations_throws_exception(model_path):
with pytest.raises(
MlflowException,
match="Either `loader_module` or `python_model` must be specified",
) as exc_info:
mlflow.pyfunc.save_model(
path=model_path,
artifacts={"artifact": "/path/to/artifact"},
python_model=None,
)
python_model = ModuleScopedSklearnModel(predict_fn=None)
loader_module = __name__
with pytest.raises(
MlflowException,
match="The following sets of parameters cannot be specified together",
) as exc_info:
mlflow.pyfunc.save_model(
path=model_path, python_model=python_model, loader_module=loader_module
)
assert str(python_model) in str(exc_info)
assert str(loader_module) in str(exc_info)
with pytest.raises(
MlflowException,
match="The following sets of parameters cannot be specified together",
) as exc_info:
mlflow.pyfunc.save_model(
path=model_path,
python_model=python_model,
data_path="/path/to/data",
artifacts={"artifact": "/path/to/artifact"},
)
with pytest.raises(
MlflowException,
match="Either `loader_module` or `python_model` must be specified",
):
mlflow.pyfunc.save_model(path=model_path, python_model=None, loader_module=None)
def test_log_model_with_unsupported_argument_combinations_throws_exception():
match = (
"Either `loader_module` or `python_model` must be specified. A `loader_module` "
"should be a python module. A `python_model` should be a subclass of "
"PythonModel"
)
with mlflow.start_run(), pytest.raises(MlflowException, match=match):
mlflow.pyfunc.log_model(
name="pyfunc_model",
artifacts={"artifact": "/path/to/artifact"},
python_model=None,
)
python_model = ModuleScopedSklearnModel(predict_fn=None)
loader_module = __name__
with (
mlflow.start_run(),
pytest.raises(
MlflowException,
match="The following sets of parameters cannot be specified together",
) as exc_info,
):
mlflow.pyfunc.log_model(
name="pyfunc_model",
python_model=python_model,
loader_module=loader_module,
)
assert str(python_model) in str(exc_info)
assert str(loader_module) in str(exc_info)
with (
mlflow.start_run(),
pytest.raises(
MlflowException,
match="The following sets of parameters cannot be specified together",
) as exc_info,
):
mlflow.pyfunc.log_model(
name="pyfunc_model",
python_model=python_model,
data_path="/path/to/data",
artifacts={"artifact1": "/path/to/artifact"},
)
with (
mlflow.start_run(),
pytest.raises(
MlflowException,
match="Either `loader_module` or `python_model` must be specified",
),
):
mlflow.pyfunc.log_model(name="pyfunc_model", python_model=None, loader_module=None)
def test_repr_can_be_called_without_run_id_or_artifact_path():
model_meta = Model(
artifact_path=None,
run_id=None,
flavors={"python_function": {"loader_module": "someFlavour"}},
)
class TestModel:
def predict(self, model_input, params=None):
return model_input
model_impl = TestModel()
assert "flavor: someFlavour" in mlflow.pyfunc.PyFuncModel(model_meta, model_impl).__repr__()
def test_load_model_with_differing_cloudpickle_version_at_micro_granularity_logs_warning(
model_path,
):
class TestModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
return model_input
mlflow.pyfunc.save_model(path=model_path, python_model=TestModel())
saver_cloudpickle_version = "0.5.8"
model_config_path = os.path.join(model_path, "MLmodel")
model_config = Model.load(model_config_path)
model_config.flavors[mlflow.pyfunc.FLAVOR_NAME][
mlflow.pyfunc.model.CONFIG_KEY_CLOUDPICKLE_VERSION
] = saver_cloudpickle_version
model_config.save(model_config_path)
log_messages = []
def custom_warn(message_text, *args, **kwargs):
log_messages.append(message_text % args % kwargs)
loader_cloudpickle_version = "0.5.7"
with (
mock.patch("mlflow.pyfunc._logger.warning") as warn_mock,
mock.patch("cloudpickle.__version__") as cloudpickle_version_mock,
):
cloudpickle_version_mock.__str__ = lambda *args, **kwargs: loader_cloudpickle_version
warn_mock.side_effect = custom_warn
mlflow.pyfunc.load_model(model_uri=model_path)
assert any(
"differs from the version of CloudPickle that is currently running" in log_message
and saver_cloudpickle_version in log_message
and loader_cloudpickle_version in log_message
for log_message in log_messages
)
def test_load_model_with_missing_cloudpickle_version_logs_warning(model_path):
class TestModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
return model_input
mlflow.pyfunc.save_model(path=model_path, python_model=TestModel())
model_config_path = os.path.join(model_path, "MLmodel")
model_config = Model.load(model_config_path)
del model_config.flavors[mlflow.pyfunc.FLAVOR_NAME][
mlflow.pyfunc.model.CONFIG_KEY_CLOUDPICKLE_VERSION
]
model_config.save(model_config_path)
log_messages = []
def custom_warn(message_text, *args, **kwargs):
log_messages.append(message_text % args % kwargs)
with mock.patch("mlflow.pyfunc._logger.warning") as warn_mock:
warn_mock.side_effect = custom_warn
mlflow.pyfunc.load_model(model_uri=model_path)
assert any(
(
"The version of CloudPickle used to save the model could not be found"
" in the MLmodel configuration"
)
in log_message
for log_message in log_messages
)
def test_save_and_load_model_with_special_chars(
sklearn_knn_model, main_scoped_model_class, iris_data, tmp_path
):
sklearn_model_path = os.path.join(tmp_path, "sklearn_ model")
mlflow.sklearn.save_model(sk_model=sklearn_knn_model, path=sklearn_model_path)
def test_predict(sk_model, model_input):
return sk_model.predict(model_input) * 2
# Intentionally create a path that has non-url-compatible characters
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_ :% model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
artifacts={"sk_model": sklearn_model_path},
conda_env=_conda_env(),
python_model=main_scoped_model_class(test_predict),
)
loaded_pyfunc_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_path)
np.testing.assert_array_equal(
loaded_pyfunc_model.predict(iris_data[0]),
test_predict(sk_model=sklearn_knn_model, model_input=iris_data[0]),
)
def test_model_with_code_path_containing_main(tmp_path):
"""Test that the __main__ module is unaffected by model loading"""
directory = tmp_path.joinpath("model_with_main")
directory.mkdir()
main = directory.joinpath("__main__.py")
main.write_text("# empty main")
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
python_model=mlflow.pyfunc.model.PythonModel(),
code_paths=[str(directory)],
)
assert "__main__" in sys.modules
mlflow.pyfunc.load_model(model_info.model_uri)
assert "__main__" in sys.modules
def test_model_save_load_with_metadata(tmp_path):
pyfunc_model_path = os.path.join(tmp_path, "pyfunc_model")
mlflow.pyfunc.save_model(
path=pyfunc_model_path,
conda_env=_conda_env(),
python_model=mlflow.pyfunc.model.PythonModel(),
metadata={"metadata_key": "metadata_value"},
)
reloaded_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_path)
assert reloaded_model.metadata.metadata["metadata_key"] == "metadata_value"
def test_model_log_with_metadata():
pyfunc_artifact_path = "pyfunc_model"
with mlflow.start_run():
mlflow.pyfunc.log_model(
name=pyfunc_artifact_path,
python_model=mlflow.pyfunc.model.PythonModel(),
metadata={"metadata_key": "metadata_value"},
)
pyfunc_model_uri = f"runs:/{mlflow.active_run().info.run_id}/{pyfunc_artifact_path}"
reloaded_model = mlflow.pyfunc.load_model(model_uri=pyfunc_model_uri)
assert reloaded_model.metadata.metadata["metadata_key"] == "metadata_value"
| DummyModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-klaviyo/components.py | {
"start": 5762,
"end": 9016
} | class ____(RecordTransformation):
"""
Campaigns detailed stream fetches detailed campaigns info:
estimated_recipient_count: integer
campaign_messages: list of objects.
To get this data CampaignsDetailedTransformation makes extra API requests:
https://a.klaviyo.com/api/campaign-recipient-estimations/{campaign_id}
https://developers.klaviyo.com/en/v2024-10-15/reference/get_messages_for_campaign
"""
config: Config
api_revision = "2024-10-15"
url_base = "https://a.klaviyo.com/api/"
name = "campaigns_detailed"
max_retries = 5
max_time = 60 * 10
def __init__(self, config: Config, **kwargs):
self.logger = logging.getLogger("airbyte")
self.config = config
self._api_key = self.config["api_key"]
self._http_client = HttpClient(
name=self.name,
logger=self.logger,
error_handler=self.get_error_handler(),
api_budget=APIBudget(policies=[]),
backoff_strategy=self.get_backoff_strategy(),
message_repository=InMemoryMessageRepository(),
)
def transform(
self,
record: Dict[str, Any],
config: Optional[Config] = None,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
) -> None:
self._set_recipient_count(record)
self._set_campaign_message(record)
def _set_recipient_count(self, record: Mapping[str, Any]) -> None:
campaign_id = record["id"]
_, recipient_count_response = self._http_client.send_request(
url=f"{self.url_base}campaign-recipient-estimations/{campaign_id}",
request_kwargs={},
headers=self.request_headers(),
http_method="GET",
)
record["estimated_recipient_count"] = (
recipient_count_response.json().get("data", {}).get("attributes", {}).get("estimated_recipient_count", 0)
)
def _set_campaign_message(self, record: Mapping[str, Any]) -> None:
messages_link = record.get("relationships", {}).get("campaign-messages", {}).get("links", {}).get("related")
if messages_link:
_, campaign_message_response = self._http_client.send_request(
url=messages_link, request_kwargs={}, headers=self.request_headers(), http_method="GET"
)
record["campaign_messages"] = campaign_message_response.json().get("data")
def get_backoff_strategy(self) -> BackoffStrategy:
return WaitTimeFromHeaderBackoffStrategy(header="Retry-After", max_waiting_time_in_seconds=self.max_time, parameters={}, config={})
def request_headers(self):
return {
"Accept": "application/json",
"Revision": self.api_revision,
"Authorization": f"Klaviyo-API-Key {self._api_key}",
}
def get_error_handler(self) -> ErrorHandler:
error_mapping = DEFAULT_ERROR_MAPPING | {
404: ErrorResolution(ResponseAction.IGNORE, FailureType.config_error, "Resource not found. Ignoring.")
}
return HttpStatusErrorHandler(logger=self.logger, error_mapping=error_mapping, max_retries=self.max_retries)
@dataclass
| CampaignsDetailedTransformation |
python | scipy__scipy | scipy/fft/_backend.py | {
"start": 130,
"end": 6544
} | class ____:
"""The default backend for fft calculations
Notes
-----
We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
treats the domain as a hierarchy. This means the user can install a single
backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
"""
__ua_domain__ = "numpy.scipy.fft"
@staticmethod
def __ua_function__(method, args, kwargs):
fn = getattr(_basic_backend, method.__name__, None)
if fn is None:
fn = getattr(_realtransforms_backend, method.__name__, None)
if fn is None:
fn = getattr(_fftlog_backend, method.__name__, None)
if fn is None:
return NotImplemented
return fn(*args, **kwargs)
_named_backends = {
'scipy': _ScipyBackend,
}
def _backend_from_arg(backend):
"""Maps strings to known backends and validates the backend"""
if isinstance(backend, str):
try:
backend = _named_backends[backend]
except KeyError as e:
raise ValueError(f'Unknown backend {backend}') from e
if backend.__ua_domain__ != 'numpy.scipy.fft':
raise ValueError('Backend does not implement "numpy.scipy.fft"')
return backend
def set_global_backend(backend, coerce=False, only=False, try_last=False):
"""Sets the global fft backend
This utility method replaces the default backend for permanent use. It
will be tried in the list of backends automatically, unless the
``only`` flag is set on a backend. This will be the first tried
backend outside the :obj:`set_backend` context manager.
Parameters
----------
backend : {object, 'scipy'}
The backend to use.
Can either be a ``str`` containing the name of a known backend
{'scipy'} or an object that implements the uarray protocol.
coerce : bool
Whether to coerce input types when trying this backend.
only : bool
If ``True``, no more backends will be tried if this fails.
Implied by ``coerce=True``.
try_last : bool
If ``True``, the global backend is tried after registered backends.
Raises
------
ValueError: If the backend does not implement ``numpy.scipy.fft``.
Notes
-----
This will overwrite the previously set global backend, which, by default, is
the SciPy implementation.
Examples
--------
We can set the global fft backend:
>>> from scipy.fft import fft, set_global_backend
>>> set_global_backend("scipy") # Sets global backend (default is "scipy").
>>> fft([1]) # Calls the global backend
array([1.+0.j])
"""
backend = _backend_from_arg(backend)
ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
def register_backend(backend):
"""
Register a backend for permanent use.
Registered backends have the lowest priority and will be tried after the
global backend.
Parameters
----------
backend : {object, 'scipy'}
The backend to use.
Can either be a ``str`` containing the name of a known backend
{'scipy'} or an object that implements the uarray protocol.
Raises
------
ValueError: If the backend does not implement ``numpy.scipy.fft``.
Examples
--------
We can register a new fft backend:
>>> from scipy.fft import fft, register_backend, set_global_backend
>>> class NoopBackend: # Define an invalid Backend
... __ua_domain__ = "numpy.scipy.fft"
... def __ua_function__(self, func, args, kwargs):
... return NotImplemented
>>> set_global_backend(NoopBackend()) # Set the invalid backend as global
>>> register_backend("scipy") # Register a new backend
# The registered backend is called because
# the global backend returns `NotImplemented`
>>> fft([1])
array([1.+0.j])
>>> set_global_backend("scipy") # Restore global backend to default
"""
backend = _backend_from_arg(backend)
ua.register_backend(backend)
def set_backend(backend, coerce=False, only=False):
"""Context manager to set the backend within a fixed scope.
Upon entering the ``with`` statement, the given backend will be added to
the list of available backends with the highest priority. Upon exit, the
backend is reset to the state before entering the scope.
Parameters
----------
backend : {object, 'scipy'}
The backend to use.
Can either be a ``str`` containing the name of a known backend
{'scipy'} or an object that implements the uarray protocol.
coerce : bool, optional
Whether to allow expensive conversions for the ``x`` parameter. e.g.,
copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
only : bool, optional
If only is ``True`` and this backend returns ``NotImplemented``, then a
BackendNotImplemented error will be raised immediately. Ignoring any
lower priority backends.
Examples
--------
>>> import scipy.fft as fft
>>> with fft.set_backend('scipy', only=True):
... fft.fft([1]) # Always calls the scipy implementation
array([1.+0.j])
"""
backend = _backend_from_arg(backend)
return ua.set_backend(backend, coerce=coerce, only=only)
def skip_backend(backend):
"""Context manager to skip a backend within a fixed scope.
Within the context of a ``with`` statement, the given backend will not be
called. This covers backends registered both locally and globally. Upon
exit, the backend will again be considered.
Parameters
----------
backend : {object, 'scipy'}
The backend to skip.
Can either be a ``str`` containing the name of a known backend
{'scipy'} or an object that implements the uarray protocol.
Examples
--------
>>> import scipy.fft as fft
>>> fft.fft([1]) # Calls default SciPy backend
array([1.+0.j])
>>> with fft.skip_backend('scipy'): # We explicitly skip the SciPy backend
... fft.fft([1]) # leaving no implementation available
Traceback (most recent call last):
...
BackendNotImplementedError: No selected backends had an implementation ...
"""
backend = _backend_from_arg(backend)
return ua.skip_backend(backend)
set_global_backend('scipy', try_last=True)
| _ScipyBackend |
python | keon__algorithms | tests/test_array.py | {
"start": 9495,
"end": 10379
} | class ____(unittest.TestCase):
def test_remove_duplicates(self):
self.assertListEqual(
remove_duplicates(
[1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6, 7, 7, 7, 8, 8, 9, 10, 10]
),
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
)
self.assertListEqual(
remove_duplicates(["hey", "hello", "hello", "car", "house", "house"]),
["hey", "hello", "car", "house"],
)
self.assertListEqual(
remove_duplicates([True, True, False, True, False, None, None]),
[True, False, None],
)
self.assertListEqual(
remove_duplicates([1, 1, "hello", "hello", True, False, False]),
[1, "hello", False],
)
self.assertListEqual(
remove_duplicates([1, "hello", True, False]), [1, "hello", False]
)
| TestRemoveDuplicate |
python | openai__openai-python | src/openai/types/evals/runs/output_item_list_response.py | {
"start": 1842,
"end": 2165
} | class ____(BaseModel):
cached_tokens: int
"""The number of tokens retrieved from cache."""
completion_tokens: int
"""The number of completion tokens generated."""
prompt_tokens: int
"""The number of prompt tokens used."""
total_tokens: int
"""The total number of tokens used."""
| SampleUsage |
python | doocs__leetcode | solution/3100-3199/3151.Special Array I/Solution.py | {
"start": 0,
"end": 133
} | class ____:
def isArraySpecial(self, nums: List[int]) -> bool:
return all(a % 2 != b % 2 for a, b in pairwise(nums))
| Solution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/transfers/test_gcs_to_s3.py | {
"start": 1724,
"end": 20840
} | class ____:
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute__match_glob(self, mock_hook):
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
match_glob=f"**/*{DELIMITER}",
)
hook, bucket = _create_test_bucket()
bucket.put_object(Key=MOCK_FILES[0], Body=b"testing")
operator.execute(None)
mock_hook.return_value.list.assert_called_once_with(
bucket_name=GCS_BUCKET,
match_glob=f"**/*{DELIMITER}",
prefix=PREFIX,
user_project=None,
)
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_incremental(self, mock_hook):
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
)
hook, bucket = _create_test_bucket()
bucket.put_object(Key=MOCK_FILES[0], Body=b"testing")
# we expect all except first file in MOCK_FILES to be uploaded
# and all the MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
assert sorted(MOCK_FILES[1:]) == sorted(uploaded_files)
assert sorted(MOCK_FILES) == sorted(hook.list_keys("bucket", delimiter="/"))
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_without_replace(self, mock_hook):
"""
Tests scenario where all the files are already in origin and destination without replace
"""
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
)
hook, bucket = _create_test_bucket()
for mock_file in MOCK_FILES:
bucket.put_object(Key=mock_file, Body=b"testing")
# we expect nothing to be uploaded
# and all the MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
assert uploaded_files == []
assert sorted(MOCK_FILES) == sorted(hook.list_keys("bucket", delimiter="/"))
@pytest.mark.parametrize(
argnames="dest_s3_url",
argvalues=[f"{S3_BUCKET}/test/", f"{S3_BUCKET}/test"],
)
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_without_replace_with_folder_structure(self, mock_hook, dest_s3_url):
mock_files_gcs = [f"test{idx}/{mock_file}" for idx, mock_file in enumerate(MOCK_FILES)]
mock_files_s3 = [f"test/test{idx}/{mock_file}" for idx, mock_file in enumerate(MOCK_FILES)]
mock_hook.return_value.list.return_value = mock_files_gcs
hook, bucket = _create_test_bucket()
for mock_file_s3 in mock_files_s3:
bucket.put_object(Key=mock_file_s3, Body=b"testing")
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=dest_s3_url,
replace=False,
)
# we expect nothing to be uploaded
# and all the MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
assert uploaded_files == []
assert sorted(mock_files_s3) == sorted(hook.list_keys("bucket", prefix="test/"))
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute(self, mock_hook):
"""
Tests the scenario where there are no files in destination bucket
"""
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
)
hook, _ = _create_test_bucket()
# we expect all MOCK_FILES to be uploaded
# and all MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
assert sorted(MOCK_FILES) == sorted(uploaded_files)
assert sorted(MOCK_FILES) == sorted(hook.list_keys("bucket", delimiter="/"))
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_with_replace(self, mock_hook):
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=True,
)
hook, bucket = _create_test_bucket()
for mock_file in MOCK_FILES:
bucket.put_object(Key=mock_file, Body=b"testing")
# we expect all MOCK_FILES to be uploaded and replace the existing ones
# and all MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
assert sorted(MOCK_FILES) == sorted(uploaded_files)
assert sorted(MOCK_FILES) == sorted(hook.list_keys("bucket", delimiter="/"))
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_incremental_with_replace(self, mock_hook):
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=True,
)
hook, bucket = _create_test_bucket()
for mock_file in MOCK_FILES[:2]:
bucket.put_object(Key=mock_file, Body=b"testing")
# we expect all the MOCK_FILES to be uploaded and replace the existing ones
# and all MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
assert sorted(MOCK_FILES) == sorted(uploaded_files)
assert sorted(MOCK_FILES) == sorted(hook.list_keys("bucket", delimiter="/"))
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.S3Hook")
def test_execute_should_handle_with_default_dest_s3_extra_args(self, s3_mock_hook, mock_hook):
mock_hook.return_value.list.return_value = MOCK_FILES
mock_hook.return_value.download.return_value = b"testing"
s3_mock_hook.return_value = mock.Mock()
s3_mock_hook.parse_s3_url.return_value = mock.Mock()
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=True,
)
operator.execute(None)
s3_mock_hook.assert_called_once_with(aws_conn_id="aws_default", extra_args={}, verify=None)
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.S3Hook")
def test_execute_should_pass_dest_s3_extra_args_to_s3_hook(self, s3_mock_hook, mock_hook):
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
s3_mock_hook.return_value = mock.Mock()
s3_mock_hook.parse_s3_url.return_value = mock.Mock()
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=True,
dest_s3_extra_args={
"ContentLanguage": "value",
},
)
operator.execute(None)
s3_mock_hook.assert_called_once_with(
aws_conn_id="aws_default", extra_args={"ContentLanguage": "value"}, verify=None
)
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
@mock.patch("airflow.providers.amazon.aws.hooks.s3.S3Hook.load_file")
def test_execute_with_s3_acl_policy(self, mock_load_file, mock_gcs_hook):
mock_gcs_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_gcs_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
s3_acl_policy=S3_ACL_POLICY,
)
_create_test_bucket()
operator.execute(None)
# Make sure the acl_policy parameter is passed to the upload method
_, kwargs = mock_load_file.call_args
assert kwargs["acl_policy"] == S3_ACL_POLICY
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_without_keep_director_structure(self, mock_hook):
mock_hook.return_value.list.return_value = MOCK_FILES
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
keep_directory_structure=False,
)
hook, _ = _create_test_bucket()
# we expect all except first file in MOCK_FILES to be uploaded
# and all the MOCK_FILES to be present at the S3 bucket
uploaded_files = operator.execute(None)
assert sorted(MOCK_FILES) == sorted(uploaded_files)
assert hook.check_for_prefix(bucket_name="bucket", prefix=PREFIX + "/", delimiter="/") is True
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_with_flatten_structure(self, mock_hook):
"""Test that flatten_structure parameter flattens directory structure."""
mock_files_with_paths = ["dir1/subdir1/file1.csv", "dir2/subdir2/file2.csv", "dir3/file3.csv"]
mock_hook.return_value.list.return_value = mock_files_with_paths
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
flatten_structure=True,
)
hook, _ = _create_test_bucket()
uploaded_files = operator.execute(None)
# Verify all files were uploaded
assert sorted(mock_files_with_paths) == sorted(uploaded_files)
# Verify files are stored with flattened structure (only filenames)
expected_s3_keys = ["file1.csv", "file2.csv", "file3.csv"]
actual_keys = hook.list_keys("bucket", delimiter="/")
assert sorted(expected_s3_keys) == sorted(actual_keys)
@mock.patch("airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSHook")
def test_execute_with_flatten_structure_duplicate_filenames(self, mock_hook):
"""Test that flatten_structure handles duplicate filenames correctly."""
mock_files_with_duplicates = [
"dir1/file.csv",
"dir2/file.csv", # Same filename as above
"dir3/other.csv",
]
mock_hook.return_value.list.return_value = mock_files_with_duplicates
with NamedTemporaryFile() as f:
gcs_provide_file = mock_hook.return_value.provide_file
gcs_provide_file.return_value.__enter__.return_value.name = f.name
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
replace=False,
flatten_structure=True,
)
_, _ = _create_test_bucket()
# Mock the logging to verify warning is logged
mock_path = "airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSToS3Operator.log"
with mock.patch(mock_path) as mock_log:
uploaded_files = operator.execute(None)
# Only one of the duplicate files should be uploaded
assert len(uploaded_files) == 2
assert "dir3/other.csv" in uploaded_files
first_or_second = "dir1/file.csv" in uploaded_files or "dir2/file.csv" in uploaded_files
assert first_or_second
# Verify warning was logged for duplicate
mock_log.warning.assert_called()
def test_execute_with_flatten_structure_and_keep_directory_structure_warning(self):
"""Test warning when both flatten_structure and keep_directory_structure are True."""
mock_path = "airflow.providers.amazon.aws.transfers.gcs_to_s3.GCSToS3Operator.log"
with mock.patch(mock_path) as mock_log:
GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=PREFIX,
dest_aws_conn_id="aws_default",
dest_s3_key=S3_BUCKET,
flatten_structure=True,
keep_directory_structure=True, # This should trigger warning
)
# Verify warning was logged during initialization
expected_warning = "flatten_structure=True takes precedence over keep_directory_structure=True"
mock_log.warning.assert_called_once_with(expected_warning)
@pytest.mark.parametrize(
("flatten_structure", "input_path", "expected_output"),
[
# Tests with flatten_structure=True
(True, "dir1/subdir1/file.csv", "file.csv"),
(True, "path/to/deep/nested/file.txt", "file.txt"),
(True, "simple.txt", "simple.txt"),
(True, "", ""),
# Tests with flatten_structure=False (preserves original paths)
(False, "dir1/subdir1/file.csv", "dir1/subdir1/file.csv"),
(False, "path/to/deep/nested/file.txt", "path/to/deep/nested/file.txt"),
(False, "simple.txt", "simple.txt"),
(False, "", ""),
],
)
def test_transform_file_path(self, flatten_structure, input_path, expected_output):
"""Test _transform_file_path method with various flatten_structure settings."""
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
dest_s3_key=S3_BUCKET,
flatten_structure=flatten_structure,
)
result = operator._transform_file_path(input_path)
assert result == expected_output
@pytest.mark.parametrize(
("gcs_prefix", "dest_s3_key", "expected_input", "expected_output"),
[
("dir/pre", "s3://bucket/dest_dir/", "dir/pre", "dest_dir/"),
("dir/pre", "s3://bucket/dest_dir", "dir/pre", "dest_dir"),
("dir/pre/", "s3://bucket/dest_dir/", "dir/pre/", "dest_dir/"),
("dir/pre", "s3://bucket/", "dir/pre", "/"),
("dir/pre", "s3://bucket", "dir/pre", "/"),
("", "s3://bucket/", "/", "/"),
("", "s3://bucket", "/", "/"),
],
)
def test_get_openlineage_facets_on_start(self, gcs_prefix, dest_s3_key, expected_input, expected_output):
operator = GCSToS3Operator(
task_id=TASK_ID,
gcs_bucket=GCS_BUCKET,
prefix=gcs_prefix,
dest_s3_key=dest_s3_key,
)
result = operator.get_openlineage_facets_on_start()
assert not result.job_facets
assert not result.run_facets
assert len(result.outputs) == 1
assert len(result.inputs) == 1
assert result.outputs[0].namespace == S3_BUCKET.rstrip("/")
assert result.outputs[0].name == expected_output
assert result.inputs[0].namespace == f"gs://{GCS_BUCKET}"
assert result.inputs[0].name == expected_input
| TestGCSToS3Operator |
python | joke2k__faker | faker/providers/address/en_IN/__init__.py | {
"start": 139,
"end": 13657
} | class ____(AddressProvider):
# City and States names taken from wikipedia
# Street format taken from some common famous places in India
# Link for cities: https://en.wikipedia.org/wiki/List_of_cities_in_India_by_population
# Link for States: https://en.wikipedia.org/wiki/States_and_union_territories_of_India
# Links for street name formats: https://www.mumbai77.com/city/3313/travel/old-new-street-names/
city_formats = ("{{city_name}}",)
street_name_formats = (
"{{last_name}} Nagar",
"{{last_name}} Zila",
"{{last_name}} Street",
"{{last_name}} Ganj",
"{{last_name}} Road",
"{{last_name}} Path",
"{{last_name}} Marg",
"{{last_name}} Chowk",
"{{last_name}} Circle",
"{{last_name}}",
)
street_address_formats = (
"{{building_number}}, {{street_name}}",
"{{building_number}}\n{{street_name}}",
)
address_formats = (
"{{street_address}}\n{{city}} {{postcode}}",
"{{street_address}}\n{{city}}-{{postcode}}",
"{{street_address}}, {{city}} {{postcode}}",
"{{street_address}}, {{city}}-{{postcode}}",
)
building_number_formats = ("H.No. ###", "###", "H.No. ##", "##", "##/##", "##/###")
postcode_formats = ("######",)
cities = (
"Mumbai",
"Delhi",
"Kolkata",
"Chennai",
"Bangalore",
"Hyderabad",
"Ahmedabad",
"Kanpur",
"Pune",
"Surat",
"Jaipur",
"Lucknow",
"Nagpur",
"Indore",
"Bhopal",
"Ludhiana",
"Patna",
"Visakhapatnam",
"Vadodara",
"Agra",
"Thane",
"Kalyan-Dombivli",
"Varanasi",
"Ranchi",
"Nashik",
"Dhanbad",
"Faridabad",
"Meerut",
"Pimpri-Chinchwad",
"Howrah",
"Allahabad",
"Ghaziabad",
"Rajkot",
"Amritsar",
"Jabalpur",
"Coimbatore",
"Madurai",
"Srinagar",
"Aurangabad",
"Solapur",
"Vijayawada",
"Jodhpur",
"Gwalior",
"Guwahati",
"Chandigarh",
"Hubli–Dharwad",
"Mysore",
"Tiruchirappalli",
"Bareilly",
"Jalandhar",
"Navi Mumbai",
"Salem",
"Kota",
"Vasai-Virar",
"Aligarh",
"Moradabad",
"Bhubaneswar",
"Gorakhpur",
"Raipur",
"Bhiwandi",
"Kochi",
"Jamshedpur",
"Bhilai",
"Amravati",
"Cuttack",
"Warangal",
"Bikaner",
"Mira-Bhayandar",
"Guntur",
"Bhavnagar",
"Durgapur",
"Kolhapur",
"Ajmer",
"Asansol",
"Ulhasnagar",
"Siliguri",
"Jalgaon",
"Saharanpur",
"Jamnagar",
"Bhatpara",
"Sangli-Miraj & Kupwad",
"Kozhikode",
"Nanded",
"Ujjain",
"Dehradun",
"Rourkela",
"Gulbarga",
"Tirunelveli",
"Malegaon",
"Akola",
"Belgaum",
"Mangalore",
"Bokaro",
"South Dumdum",
"Udaipur",
"Gaya",
"Maheshtala",
"Jhansi",
"Nellore",
"Jammu",
"Thiruvananthapuram",
"Davanagere",
"Kollam",
"Panihati",
"Kurnool",
"Tiruppur",
"Dhule",
"Bhagalpur",
"Rajpur Sonarpur",
"Kakinada",
"Thrissur",
"Bellary",
"Muzaffarnagar",
"Korba",
"Rajahmundry",
"Kamarhati",
"Ambattur",
"Berhampur",
"Ahmednagar",
"Muzaffarpur",
"Noida",
"Patiala",
"Mathura",
"New Delhi",
"Latur",
"Sambalpur",
"Shahjahanpur",
"Kulti",
"Chandrapur",
"Nizamabad",
"Rohtak",
"Bardhaman",
"Rampur",
"Bhilwara",
"Firozabad",
"Bilaspur",
"Shimoga",
"Agartala",
"Gopalpur",
"Darbhanga",
"Panipat",
"Bally",
"Alwar",
"Parbhani",
"Ichalkaranji",
"Anantapuram",
"Baranagar",
"Tumkur",
"Ramagundam",
"Jalna",
"Durg",
"Sagar",
"Bihar Sharif",
"Dewas",
"Barasat",
"Avadi",
"Farrukhabad",
"Aizawl",
"Tirupati",
"Bijapur",
"Satara",
"Satna",
"Ratlam",
"Imphal",
"Pondicherry",
"North Dumdum",
"Anantapur",
"Khammam",
"Ozhukarai",
"Bathinda",
"Thoothukudi",
"Thanjavur",
"Naihati",
"Sonipat",
"Mau",
"Tiruvottiyur",
"Hapur",
"Sri Ganganagar",
"Karnal",
"Etawah",
"Nagercoil",
"Raichur",
"Raurkela Industrial Township",
"Secunderabad",
"Karimnagar",
"Mirzapur",
"Bharatpur",
"Ambarnath",
"Arrah",
"Uluberia",
"Serampore",
"Dindigul",
"Gandhinagar",
"Burhanpur",
"Nadiad",
"Eluru",
"Yamunanagar",
"Kharagpur",
"Munger",
"Pali",
"Katni",
"Singrauli",
"Tenali",
"Sikar",
"Silchar",
"Rewa",
"Sambhal",
"Machilipatnam",
"Vellore",
"Alappuzha",
"Bulandshahr",
"Haridwar",
"Vijayanagaram",
"Erode",
"Gurgaon",
"Bidar",
"Bhusawal",
"Khandwa",
"Purnia",
"Haldia",
"Chinsurah",
"Bhiwani",
"Raebareli",
"Junagadh",
"Bahraich",
"Gandhidham",
"Mango",
"Raiganj",
"Amroha",
"Sultan Pur Majra",
"Hospet",
"Bidhannagar",
"Malda",
"Sirsa",
"Berhampore",
"Jaunpur",
"Surendranagar Dudhrej",
"Madhyamgram",
"Kirari Suleman Nagar",
"Bhind",
"Nandyal",
"Chittoor",
"Bhalswa Jahangir Pur",
"Fatehpur",
"Morena",
"Nangloi Jat",
"Ongole",
"Karawal Nagar",
"Shivpuri",
"Morbi",
"Unnao",
"Pallavaram",
"Kumbakonam",
"Shimla",
"Mehsana",
"Panchkula",
"Orai",
"Ambala",
"Dibrugarh",
"Guna",
"Danapur",
"Sasaram",
"Anand",
"Kottayam",
"Hazaribagh",
"Kadapa",
"Saharsa",
"Nagaon",
"Loni",
"Hajipur",
"Dehri",
"Bettiah",
"Katihar",
"Deoghar",
"Jorhat",
"Siwan",
"Panvel",
"Hosur",
"Tinsukia",
"Bongaigaon",
"Motihari",
"Jamalpur",
"Suryapet",
"Begusarai",
"Miryalaguda",
"Proddatur",
"Karaikudi",
"Kishanganj",
"Phusro",
"Buxar",
"Tezpur",
"Jehanabad",
"Aurangabad",
"Chapra",
"Ramgarh",
"Gangtok",
"Adoni",
"Amaravati",
"Ballia",
"Bhimavaram",
"Dharmavaram",
"Giridih",
"Gudivada",
"Guntakal",
"Hindupur",
"Kavali",
"Khora ",
"Ghaziabad",
"Madanapalle",
"Mahbubnagar",
"Medininagar",
"Narasaraopet",
"Phagwara",
"Pudukkottai",
"Srikakulam",
"Tadepalligudem",
"Tadipatri",
"Udupi",
)
states = (
"Andhra Pradesh",
"Arunachal Pradesh",
"Assam",
"Bihar",
"Chhattisgarh",
"Goa",
"Gujarat",
"Haryana",
"Himachal Pradesh",
"Jharkhand",
"Karnataka",
"Kerala",
"Madhya Pradesh",
"Maharashtra",
"Manipur",
"Meghalaya",
"Mizoram",
"Nagaland",
"Odisha",
"Punjab",
"Rajasthan",
"Sikkim",
"Tamil Nadu",
"Telangana",
"Tripura",
"Uttar Pradesh",
"Uttarakhand",
"West Bengal",
)
states_abbr: Tuple[str, ...] = (
"AP",
"AR",
"AS",
"BR",
"CG",
"GA",
"GJ",
"HR",
"HP",
"JH",
"KA",
"KL",
"MP",
"MH",
"MN",
"ML",
"MZ",
"NL",
"OD",
"PB",
"RJ",
"SK",
"TN",
"TG",
"TR",
"UK",
"UP",
"WB",
)
union_territories = (
("Andaman and Nicobar Islands",),
("Chandigarh",),
("Dadra and Nagar Haveli, Dadra & Nagar Haveli",),
("Daman and Diu",),
("Delhi, National Capital Territory of Delhi",),
("Jammu and Kashmir",),
("Ladakh",),
("Lakshadweep",),
("Pondicherry",),
("Puducherry",),
)
union_territories_abbr = (
"AN",
"CH",
"DN",
"DD",
"DL",
"JK",
"LA",
"LD",
"PY",
)
# https://en.wikipedia.org/wiki/Postal_Index_Number
# FIXME: Some states such as `BR/JH` / `UK/UP` have similar PIN code ranges
# FIXME: as mentioned in above link.
state_pincode: Dict[str, List[Range]] = {
"AP": [(510_000, 539_999)],
"AR": [(790_000, 792_999)],
"AS": [(780_000, 789_999)],
"BR": [(800_000, 859_999)],
"CG": [(490_000, 499_999)],
"GA": [(403_000, 403_999)],
"GJ": [(360_000, 399_999)],
"HR": [(120_000, 139_999)],
"HP": [(170_000, 179_999)],
"JH": [(800_000, 859_999)],
"KA": [(560_000, 599_999)],
"KL": [(670_000, 681_999), (683_000, 699_999)],
"MP": [(450_000, 489_999)],
"MH": [(400_000, 402_999), (404_000, 449_999)],
"MN": [(795_000, 795_999)],
"ML": [(793_000, 794_999)],
"MZ": [(796_000, 796_999)],
"NL": [(797_000, 798_999)],
"OD": [(750_000, 779_999)],
"PB": [(140_000, 159_999)],
"RJ": [(300_000, 349_999)],
"SK": [(737_000, 737_999)],
"TN": [(600_000, 669_999)],
"TG": [(500_000, 509_999)],
"TR": [(799_000, 799_999)],
"UK": [(200_000, 289_999)],
"UP": [(200_000, 289_999)],
"WB": [(700_000, 736_999), (738_000, 743_999), (745_000, 749_999)],
}
union_territories_pincode: Dict[str, List[Range]] = {
"AN": [(744_000, 744_999)],
"CH": [(160_000, 169_999)],
"DN": [(396_000, 396_999)],
"DD": [(396_000, 396_999)],
"DL": [(110_000, 119_999)],
"JK": [(180_000, 199_999)],
"LA": [(180_000, 199_999)],
"LD": [(682_000, 682_999)],
"PY": [(605_000, 605_999)],
}
army_pincode: Dict[str, Range] = {"APS": (900_000, 999_999)}
def city_name(self) -> str:
return self.random_element(self.cities)
def administrative_unit(self) -> str:
return self.random_element(self.states)
state = administrative_unit
def union_territory(self) -> str:
"""Returns random union territory name"""
return self.random_element(self.union_territories)[0]
def pincode_in_state(self, state_abbr: Optional[str] = None, include_union_territories: bool = False) -> int:
"""Random PIN Code within provided state abbreviation
:param state_abbr: State Abbr, defaults to None
:param include_union_territories: Include Union Territories ?, defaults to False
:raises ValueError: If incorrect state abbr
:return: PIN Code
"""
known_abbrs = self.states_abbr
if include_union_territories:
known_abbrs += self.union_territories_abbr
if state_abbr is None:
state_abbr = self.random_element(known_abbrs)
if state_abbr in known_abbrs:
codes = self.state_pincode
if include_union_territories:
codes.update(self.union_territories_pincode)
pincode_range = self.random_element(codes[state_abbr])
return self.generator.random.randint(*pincode_range)
raise ValueError("State Abbreviation not found in list")
def pincode_in_military(self) -> int:
"""Random PIN Code within Army Postal Service range"""
key: str = self.random_element(self.army_pincode.keys())
return self.generator.random.randint(*self.army_pincode[key])
# Aliases
def zipcode_in_state(self, state_abbr: Optional[str] = None, include_union_territories: bool = False) -> int:
return self.pincode_in_state(state_abbr, include_union_territories)
def postcode_in_state(self, state_abbr: Optional[str] = None, include_union_territories: bool = False) -> int:
return self.pincode_in_state(state_abbr, include_union_territories)
def pincode_in_army(self) -> int:
return self.pincode_in_military()
def zipcode_in_military(self) -> int:
return self.pincode_in_military()
def zipcode_in_army(self) -> int:
return self.pincode_in_military()
def postcode_in_military(self) -> int:
return self.pincode_in_military()
def postcode_in_army(self) -> int:
return self.pincode_in_military()
| Provider |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py | {
"start": 1760,
"end": 2079
} | class ____(BaseModel):
class Config(BaseConfig):
mutable_default: list[int] = []
immutable_annotation: Sequence[int] = []
without_annotation = []
class_variable: ClassVar[list[int]] = []
final_variable: Final[list[int]] = []
from pydantic.v1 import BaseModel as V1BaseModel
| H |
python | ray-project__ray | rllib/examples/envs/classes/multi_agent/bandit_envs_discrete.py | {
"start": 3555,
"end": 6413
} | class ____(gym.Env):
"""Wheel bandit environment for 2D contexts
(see https://arxiv.org/abs/1802.09127).
"""
DEFAULT_CONFIG_WHEEL = {
"delta": 0.5,
"mu_1": 1.2,
"mu_2": 1,
"mu_3": 50,
"std": 0.01,
}
feature_dim = 2
num_actions = 5
def __init__(self, config=None):
self.config = copy.copy(self.DEFAULT_CONFIG_WHEEL)
if config is not None and type(config) is dict:
self.config.update(config)
self.delta = self.config["delta"]
self.mu_1 = self.config["mu_1"]
self.mu_2 = self.config["mu_2"]
self.mu_3 = self.config["mu_3"]
self.std = self.config["std"]
self.action_space = Discrete(self.num_actions)
self.observation_space = Box(low=-1, high=1, shape=(self.feature_dim,))
self.means = [self.mu_1] + 4 * [self.mu_2]
self._elapsed_steps = 0
self._current_context = None
def _sample_context(self):
while True:
state = np.random.uniform(-1, 1, self.feature_dim)
if np.linalg.norm(state) <= 1:
return state
def reset(self, *, seed=None, options=None):
self._current_context = self._sample_context()
return self._current_context, {}
def step(self, action):
assert (
self._elapsed_steps is not None
), "Cannot call env.step() before calling reset()"
action = int(action)
self._elapsed_steps += 1
rewards = [
np.random.normal(self.means[j], self.std) for j in range(self.num_actions)
]
context = self._current_context
r_big = np.random.normal(self.mu_3, self.std)
if np.linalg.norm(context) >= self.delta:
if context[0] > 0:
if context[1] > 0:
# First quadrant
rewards[1] = r_big
opt_action = 1
else:
# Fourth quadrant
rewards[4] = r_big
opt_action = 4
else:
if context[1] > 0:
# Second quadrant
rewards[2] = r_big
opt_action = 2
else:
# Third quadrant
rewards[3] = r_big
opt_action = 3
else:
# Smaller region where action 0 is optimal
opt_action = 0
reward = rewards[action]
regret = rewards[opt_action] - reward
self._current_context = self._sample_context()
return (
self._current_context,
reward,
True,
False,
{"regret": regret, "opt_action": opt_action},
)
def render(self, mode="human"):
raise NotImplementedError
| WheelBanditEnv |
python | pytorch__pytorch | torch/distributed/pipelining/schedules.py | {
"start": 24623,
"end": 26484
} | class ____(PipelineScheduleSingle):
"""
The forward-only schedule.
Will go through all the microbatches and perform only the forward pass
"""
def _step_microbatches(
self,
arg_mbs: list | None = None,
kwarg_mbs: list | None = None,
target_mbs: list | None = None,
losses: list | None = None,
return_outputs: bool = True,
):
"""
Run one iteration of the pipeline schedule
"""
if target_mbs is not None or losses is not None:
raise RuntimeError(
"Forward-only schedule does not support loss computation"
)
arg_mbs, kwarg_mbs = self._check_inputs(arg_mbs, kwarg_mbs, target_mbs, losses)
self._initialize_stage(arg_mbs[0], kwarg_mbs[0])
# Delay send waits
fwd_sends_to_wait: list[list[dist.Work]] = []
# Run microbatches
for i in range(self._n_microbatches):
with record_function(f"Forward {i}"):
ops = self._stage.get_fwd_recv_ops(i)
works = _sorted_batch_p2p(ops, desc="fwd_recv")
for work in works.values():
_wait_batch_p2p(work)
self._stage.forward_one_chunk(i, arg_mbs[i], kwarg_mbs[i]) # type: ignore[index]
ops = self._stage.get_fwd_send_ops(i)
works = _sorted_batch_p2p(ops, desc="fwd_send")
fwd_sends_to_wait.extend(works.values())
logger.debug("[%s] Forwarded microbatch %s", self._stage.stage_index, i)
# Wait for all forward sends to finish
# This should not have performance impact because by the time the first
# backward arrives all the forward sends should have been finished.
for work in fwd_sends_to_wait:
_wait_batch_p2p(work)
| _ScheduleForwardOnly |
python | huggingface__transformers | examples/modular-transformers/modeling_test_detr.py | {
"start": 14348,
"end": 16105
} | class ____(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
need paper, generalized to work on images.
"""
def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None):
super().__init__()
self.embedding_dim = embedding_dim
self.temperature = temperature
self.normalize = normalize
if scale is not None and normalize is False:
raise ValueError("normalize should be True if scale is passed")
if scale is None:
scale = 2 * math.pi
self.scale = scale
def forward(self, pixel_values, pixel_mask):
if pixel_mask is None:
raise ValueError("No pixel mask provided")
y_embed = pixel_mask.cumsum(1, dtype=pixel_values.dtype)
x_embed = pixel_mask.cumsum(2, dtype=pixel_values.dtype)
if self.normalize:
eps = 1e-6
y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale
x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale
dim_t = torch.arange(self.embedding_dim, dtype=pixel_values.dtype, device=pixel_values.device)
dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.embedding_dim)
pos_x = x_embed[:, :, :, None] / dim_t
pos_y = y_embed[:, :, :, None] / dim_t
pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
return pos
| TestDetrSinePositionEmbedding |
python | PrefectHQ__prefect | src/prefect/docker/docker_image.py | {
"start": 402,
"end": 3138
} | class ____:
"""
Configuration used to build and push a Docker image for a deployment.
Attributes:
name: The name of the Docker image to build, including the registry and
repository.
tag: The tag to apply to the built image.
dockerfile: The path to the Dockerfile to use for building the image. If
not provided, a default Dockerfile will be generated.
**build_kwargs: Additional keyword arguments to pass to the Docker build request.
See the [`docker-py` documentation](https://docker-py.readthedocs.io/en/stable/images.html#docker.models.images.ImageCollection.build)
for more information.
"""
def __init__(
self,
name: str,
tag: Optional[str] = None,
dockerfile: str = "auto",
**build_kwargs: Any,
):
image_name, image_tag = parse_image_tag(name)
if tag and image_tag:
raise ValueError(
f"Only one tag can be provided - both {image_tag!r} and {tag!r} were"
" provided as tags."
)
namespace, repository = split_repository_path(image_name)
# if the provided image name does not include a namespace (registry URL or user/org name),
# use the default namespace
if not namespace:
namespace = PREFECT_DEFAULT_DOCKER_BUILD_NAMESPACE.value()
# join the namespace and repository to create the full image name
# ignore namespace if it is None
self.name: str = "/".join(filter(None, [namespace, repository]))
self.tag: str = tag or image_tag or slugify(now("UTC").isoformat())
self.dockerfile: str = dockerfile
self.build_kwargs: dict[str, Any] = build_kwargs
@property
def reference(self) -> str:
return f"{self.name}:{self.tag}"
def build(self) -> None:
full_image_name = self.reference
build_kwargs = self.build_kwargs.copy()
if "context" not in build_kwargs:
build_kwargs["context"] = Path.cwd()
build_kwargs["tag"] = full_image_name
build_kwargs["pull"] = build_kwargs.get("pull", True)
if self.dockerfile == "auto":
with generate_default_dockerfile():
build_image(**build_kwargs)
else:
build_kwargs["dockerfile"] = self.dockerfile
build_image(**build_kwargs)
def push(self) -> None:
with docker_client() as client:
events = client.api.push(
repository=self.name, tag=self.tag, stream=True, decode=True
)
for event in events:
if "error" in event:
raise PushError(event["error"])
| DockerImage |
python | spack__spack | lib/spack/spack/detection/test.py | {
"start": 1406,
"end": 7283
} | class ____:
"""Runs an external detection test"""
def __init__(self, *, test: DetectionTest, repository: spack.repo.RepoPath) -> None:
self.test = test
self.repository = repository
self.tmpdir = tempfile.TemporaryDirectory()
def execute(self) -> List[spack.spec.Spec]:
"""Executes a test and returns the specs that have been detected.
This function sets-up a test in a temporary directory, according to the prescriptions
in the test layout, then performs a detection by executables and returns the specs that
have been detected.
"""
with self._mock_layout() as path_hints:
entries = by_path([self.test.pkg_name], path_hints=path_hints)
_, unqualified_name = spack.repo.partition_package_name(self.test.pkg_name)
specs = set(entries[unqualified_name])
return list(specs)
@contextlib.contextmanager
def _mock_layout(self) -> Generator[List[str], None, None]:
hints = set()
try:
for entry in self.test.layout:
exes = self._create_executable_scripts(entry)
for mock_executable in exes:
hints.add(str(mock_executable.parent))
yield list(hints)
finally:
self.tmpdir.cleanup()
def _create_executable_scripts(self, mock_executables: MockExecutables) -> List[pathlib.Path]:
import spack.vendor.jinja2
relative_paths = mock_executables.executables
script = mock_executables.script
script_template = spack.vendor.jinja2.Template("#!/bin/bash\n{{ script }}\n")
result = []
for mock_exe_path in relative_paths:
rel_path = pathlib.Path(mock_exe_path)
abs_path = pathlib.Path(self.tmpdir.name) / rel_path
abs_path.parent.mkdir(parents=True, exist_ok=True)
abs_path.write_text(script_template.render(script=script))
filesystem.set_executable(abs_path)
result.append(abs_path)
return result
@property
def expected_specs(self) -> List[spack.spec.Spec]:
return [
spack.spec.Spec.from_detection(
item.spec, external_path=self.tmpdir.name, extra_attributes=item.extra_attributes
)
for item in self.test.results
]
def detection_tests(pkg_name: str, repository: spack.repo.RepoPath) -> List[Runner]:
"""Returns a list of test runners for a given package.
Currently, detection tests are specified in a YAML file, called ``detection_test.yaml``,
alongside the ``package.py`` file.
This function reads that file to create a bunch of ``Runner`` objects.
Args:
pkg_name: name of the package to test
repository: repository where the package lives
"""
result = []
detection_tests_content = read_detection_tests(pkg_name, repository)
current_platform = str(spack.platforms.host())
tests_by_path = detection_tests_content.get("paths", [])
for single_test_data in tests_by_path:
if current_platform not in single_test_data.get("platforms", [current_platform]):
continue
mock_executables = []
for layout in single_test_data["layout"]:
mock_executables.append(
MockExecutables(executables=layout["executables"], script=layout["script"])
)
expected_results = []
for assertion in single_test_data["results"]:
expected_results.append(
ExpectedTestResult(
spec=assertion["spec"], extra_attributes=assertion.get("extra_attributes", {})
)
)
current_test = DetectionTest(
pkg_name=pkg_name, layout=mock_executables, results=expected_results
)
result.append(Runner(test=current_test, repository=repository))
return result
def read_detection_tests(pkg_name: str, repository: spack.repo.RepoPath) -> Dict[str, Any]:
"""Returns the normalized content of the detection_tests.yaml associated with the package
passed in input.
The content is merged with that of any package that is transitively included using the
"includes" attribute.
Args:
pkg_name: name of the package to test
repository: repository in which to search for packages
"""
content_stack, seen = [], set()
included_packages: Deque[str] = collections.deque()
root_detection_yaml, result = _detection_tests_yaml(pkg_name, repository)
included_packages.extend(result.get("includes", []))
seen |= set(result.get("includes", []))
while included_packages:
current_package = included_packages.popleft()
try:
current_detection_yaml, content = _detection_tests_yaml(current_package, repository)
except FileNotFoundError as e:
msg = (
f"cannot read the detection tests from the '{current_package}' package, "
f"included by {root_detection_yaml}"
)
raise FileNotFoundError(msg + f"\n\n\t{e}\n")
content_stack.append((current_package, content))
included_packages.extend(x for x in content.get("includes", []) if x not in seen)
seen |= set(content.get("includes", []))
result.setdefault("paths", [])
for pkg_name, content in content_stack:
result["paths"].extend(content.get("paths", []))
return result
def _detection_tests_yaml(
pkg_name: str, repository: spack.repo.RepoPath
) -> Tuple[pathlib.Path, Dict[str, Any]]:
pkg_dir = pathlib.Path(repository.filename_for_package_name(pkg_name)).parent
detection_tests_yaml = pkg_dir / "detection_test.yaml"
with open(str(detection_tests_yaml), encoding="utf-8") as f:
content = spack_yaml.load(f)
return detection_tests_yaml, content
| Runner |
python | google__pytype | pytype/pytd/parse/node_test.py | {
"start": 256,
"end": 351
} | class ____(Node):
"""For equality testing. Same attributes as Node3."""
x: Any
y: Any
| Node2 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 284231,
"end": 284560
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("DiscussionComment", graphql_name="node")
| DiscussionCommentEdge |
python | pytorch__pytorch | test/onnx/ops/test_ops.py | {
"start": 346,
"end": 2672
} | class ____(common_utils.TestCase):
def test_symbolic_has_correct_schema(self):
torch.library.opcheck(
_symbolic_impl._symbolic,
([torch.tensor(1)], "CustomOp", 1),
dict(
shape=[
1,
],
attr_keys=["key"],
attr_types=["i"],
attr_pos=[(0, 1)],
attr_ints=[1],
attr_floats=[1.0],
attr_strs=["attr"],
metadata_props_keys=["meta_key"],
metadata_props_values=["meta_value"],
domain="custom_domain",
version=42,
),
)
# Empty inputs
torch.library.opcheck(
_symbolic_impl._symbolic,
([], "CustomOp", 1),
dict(
shape=[
1,
],
attr_keys=[],
attr_types=[],
attr_pos=[],
attr_ints=[],
attr_floats=[],
attr_strs=[],
metadata_props_keys=[],
metadata_props_values=[],
),
)
def test_symbolic_multi_out_has_correct_schema(self):
torch.library.opcheck(
_symbolic_impl._symbolic_multi_out,
([torch.tensor(1)], "CustomMultiOutOp", [1, 2, 10]),
dict(
shapes=[[1, 2], [42], []],
attr_keys=["key"],
attr_types=["i"],
attr_pos=[(0, 1)],
attr_ints=[1],
attr_floats=[1.0],
attr_strs=["attr"],
metadata_props_keys=["meta_key"],
metadata_props_values=["meta_value"],
domain="",
version=1,
),
)
# Empty inputs
torch.library.opcheck(
_symbolic_impl._symbolic_multi_out,
([], "CustomMultiOutOp", []),
dict(
shapes=[],
attr_keys=[],
attr_types=[],
attr_pos=[],
attr_ints=[],
attr_floats=[],
attr_strs=[],
metadata_props_keys=[],
metadata_props_values=[],
),
)
| SchemaTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 18905,
"end": 19063
} | class ____:
error: Optional[SerializableErrorInfo]
@whitelist_for_serdes(storage_name="ExternalExecutionParamsData")
@record_custom
| SensorExecutionErrorSnap |
python | coleifer__peewee | playhouse/sqlite_ext.py | {
"start": 30619,
"end": 34204
} | class ____(VirtualModel):
class Meta:
extension_module = 'lsm1'
filename = None
@classmethod
def clean_options(cls, options):
filename = cls._meta.filename
if not filename:
raise ValueError('LSM1 extension requires that you specify a '
'filename for the LSM database.')
else:
if len(filename) >= 2 and filename[0] != '"':
filename = '"%s"' % filename
if not cls._meta.primary_key:
raise ValueError('LSM1 models must specify a primary-key field.')
key = cls._meta.primary_key
if isinstance(key, AutoField):
raise ValueError('LSM1 models must explicitly declare a primary '
'key field.')
if not isinstance(key, (TextField, BlobField, IntegerField)):
raise ValueError('LSM1 key must be a TextField, BlobField, or '
'IntegerField.')
key._hidden = True
if isinstance(key, IntegerField):
data_type = 'UINT'
elif isinstance(key, BlobField):
data_type = 'BLOB'
else:
data_type = 'TEXT'
cls._meta.prefix_arguments = [filename, '"%s"' % key.name, data_type]
# Does the key map to a scalar value, or a tuple of values?
if len(cls._meta.sorted_fields) == 2:
cls._meta._value_field = cls._meta.sorted_fields[1]
else:
cls._meta._value_field = None
return options
@classmethod
def load_extension(cls, path='lsm.so'):
cls._meta.database.load_extension(path)
@staticmethod
def slice_to_expr(key, idx):
if idx.start is not None and idx.stop is not None:
return key.between(idx.start, idx.stop)
elif idx.start is not None:
return key >= idx.start
elif idx.stop is not None:
return key <= idx.stop
@staticmethod
def _apply_lookup_to_query(query, key, lookup):
if isinstance(lookup, slice):
expr = LSMTable.slice_to_expr(key, lookup)
if expr is not None:
query = query.where(expr)
return query, False
elif isinstance(lookup, Expression):
return query.where(lookup), False
else:
return query.where(key == lookup), True
@classmethod
def get_by_id(cls, pk):
query, is_single = cls._apply_lookup_to_query(
cls.select().namedtuples(),
cls._meta.primary_key,
pk)
if is_single:
row = query.get()
return row[1] if cls._meta._value_field is not None else row
else:
return query
@classmethod
def set_by_id(cls, key, value):
if cls._meta._value_field is not None:
data = {cls._meta._value_field: value}
elif isinstance(value, tuple):
data = {}
for field, fval in zip(cls._meta.sorted_fields[1:], value):
data[field] = fval
elif isinstance(value, dict):
data = value
elif isinstance(value, cls):
data = value.__dict__
data[cls._meta.primary_key] = key
cls.replace(data).execute()
@classmethod
def delete_by_id(cls, pk):
query, is_single = cls._apply_lookup_to_query(
cls.delete(),
cls._meta.primary_key,
pk)
return query.execute()
OP.MATCH = 'MATCH'
def _sqlite_regexp(regex, value):
return re.search(regex, value) is not None
| LSMTable |
python | Delgan__loguru | loguru/_recattrs.py | {
"start": 3542,
"end": 4612
} | class ____:
"""A class representing a process record with ID and name.
Attributes
----------
id : int
The process ID
name : str
The process name
"""
__slots__ = ("id", "name")
def __init__(self, id_, name):
"""Initialize a RecordProcess instance.
Parameters
----------
id_ : int
The process ID
name : str
The process name
"""
self.id = id_
self.name = name
def __repr__(self):
"""Return string representation of RecordProcess.
Returns
-------
str
Formatted string with id and name
"""
return "(id=%r, name=%r)" % (self.id, self.name)
def __format__(self, spec):
"""Format the RecordProcess instance.
Parameters
----------
spec : str
Format specification
Returns
-------
str
Formatted ID according to specification
"""
return self.id.__format__(spec)
| RecordProcess |
python | doocs__leetcode | solution/0300-0399/0327.Count of Range Sum/Solution.py | {
"start": 339,
"end": 852
} | class ____:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
s = list(accumulate(nums, initial=0))
arr = sorted(set(v for x in s for v in (x, x - lower, x - upper)))
tree = BinaryIndexedTree(len(arr))
ans = 0
for x in s:
l = bisect_left(arr, x - upper) + 1
r = bisect_left(arr, x - lower) + 1
ans += tree.query(r) - tree.query(l - 1)
tree.update(bisect_left(arr, x) + 1, 1)
return ans
| Solution |
python | ray-project__ray | rllib/execution/segment_tree.py | {
"start": 51,
"end": 6381
} | class ____:
"""A Segment Tree data structure.
https://en.wikipedia.org/wiki/Segment_tree
Can be used as regular array, but with two important differences:
a) Setting an item's value is slightly slower. It is O(lg capacity),
instead of O(1).
b) Offers efficient `reduce` operation which reduces the tree's values
over some specified contiguous subsequence of items in the array.
Operation could be e.g. min/max/sum.
The data is stored in a list, where the length is 2 * capacity.
The second half of the list stores the actual values for each index, so if
capacity=8, values are stored at indices 8 to 15. The first half of the
array contains the reduced-values of the different (binary divided)
segments, e.g. (capacity=4):
0=not used
1=reduced-value over all elements (array indices 4 to 7).
2=reduced-value over array indices (4 and 5).
3=reduced-value over array indices (6 and 7).
4-7: values of the tree.
NOTE that the values of the tree are accessed by indices starting at 0, so
`tree[0]` accesses `internal_array[4]` in the above example.
"""
def __init__(
self, capacity: int, operation: Any, neutral_element: Optional[Any] = None
):
"""Initializes a Segment Tree object.
Args:
capacity: Total size of the array - must be a power of two.
operation: Lambda obj, obj -> obj
The operation for combining elements (eg. sum, max).
Must be a mathematical group together with the set of
possible values for array elements.
neutral_element (Optional[obj]): The neutral element for
`operation`. Use None for automatically finding a value:
max: float("-inf"), min: float("inf"), sum: 0.0.
"""
assert (
capacity > 0 and capacity & (capacity - 1) == 0
), "Capacity must be positive and a power of 2!"
self.capacity = capacity
if neutral_element is None:
neutral_element = (
0.0
if operation is operator.add
else float("-inf")
if operation is max
else float("inf")
)
self.neutral_element = neutral_element
self.value = [self.neutral_element for _ in range(2 * capacity)]
self.operation = operation
def reduce(self, start: int = 0, end: Optional[int] = None) -> Any:
"""Applies `self.operation` to subsequence of our values.
Subsequence is contiguous, includes `start` and excludes `end`.
self.operation(
arr[start], operation(arr[start+1], operation(... arr[end])))
Args:
start: Start index to apply reduction to.
end (Optional[int]): End index to apply reduction to (excluded).
Returns:
any: The result of reducing self.operation over the specified
range of `self._value` elements.
"""
if end is None:
end = self.capacity
elif end < 0:
end += self.capacity
# Init result with neutral element.
result = self.neutral_element
# Map start/end to our actual index space (second half of array).
start += self.capacity
end += self.capacity
# Example:
# internal-array (first half=sums, second half=actual values):
# 0 1 2 3 | 4 5 6 7
# - 6 1 5 | 1 0 2 3
# tree.sum(0, 3) = 3
# internally: start=4, end=7 -> sum values 1 0 2 = 3.
# Iterate over tree starting in the actual-values (second half)
# section.
# 1) start=4 is even -> do nothing.
# 2) end=7 is odd -> end-- -> end=6 -> add value to result: result=2
# 3) int-divide start and end by 2: start=2, end=3
# 4) start still smaller end -> iterate once more.
# 5) start=2 is even -> do nothing.
# 6) end=3 is odd -> end-- -> end=2 -> add value to result: result=1
# NOTE: This adds the sum of indices 4 and 5 to the result.
# Iterate as long as start != end.
while start < end:
# If start is odd: Add its value to result and move start to
# next even value.
if start & 1:
result = self.operation(result, self.value[start])
start += 1
# If end is odd: Move end to previous even value, then add its
# value to result. NOTE: This takes care of excluding `end` in any
# situation.
if end & 1:
end -= 1
result = self.operation(result, self.value[end])
# Divide both start and end by 2 to make them "jump" into the
# next upper level reduce-index space.
start //= 2
end //= 2
# Then repeat till start == end.
return result
def __setitem__(self, idx: int, val: float) -> None:
"""
Inserts/overwrites a value in/into the tree.
Args:
idx: The index to insert to. Must be in [0, `self.capacity`)
val: The value to insert.
"""
assert 0 <= idx < self.capacity, f"idx={idx} capacity={self.capacity}"
# Index of the leaf to insert into (always insert in "second half"
# of the tree, the first half is reserved for already calculated
# reduction-values).
idx += self.capacity
self.value[idx] = val
# Recalculate all affected reduction values (in "first half" of tree).
idx = idx >> 1 # Divide by 2 (faster than division).
while idx >= 1:
update_idx = 2 * idx # calculate only once
# Update the reduction value at the correct "first half" idx.
self.value[idx] = self.operation(
self.value[update_idx], self.value[update_idx + 1]
)
idx = idx >> 1 # Divide by 2 (faster than division).
def __getitem__(self, idx: int) -> Any:
assert 0 <= idx < self.capacity
return self.value[idx + self.capacity]
def get_state(self):
return self.value
def set_state(self, state):
assert len(state) == self.capacity * 2
self.value = state
| SegmentTree |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 131821,
"end": 132529
} | class ____(TorchHigherOrderOperatorVariable):
def _call_function(
self,
tx: "InstructionTranslator",
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
from .builder import wrap_fx_proxy
p_args = tuple(arg.as_proxy() for arg in args)
p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()}
return wrap_fx_proxy(
tx=tx,
proxy=tx.output.create_proxy(
"call_function",
self.value,
args=p_args,
kwargs=p_kwargs,
),
example_value=None,
)
| RunWithRNGStateHigherOrderVariable |
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/hpux.py | {
"start": 793,
"end": 8345
} | class ____(Hardware):
"""
HP-UX-specific subclass of Hardware. Defines memory and CPU facts:
- memfree_mb
- memtotal_mb
- swapfree_mb
- swaptotal_mb
- processor
- processor_cores
- processor_count
- model
- firmware
"""
platform = 'HP-UX'
def populate(self, collected_facts=None):
hardware_facts = {}
# TODO: very inefficient calls to machinfo,
# should just make one and then deal with finding the data (see facts/sysctl)
# but not going to change unless there is hp/ux for testing
cpu_facts = self.get_cpu_facts(collected_facts=collected_facts)
memory_facts = self.get_memory_facts()
hw_facts = self.get_hw_facts()
hardware_facts.update(cpu_facts)
hardware_facts.update(memory_facts)
hardware_facts.update(hw_facts)
return hardware_facts
def get_cpu_facts(self, collected_facts=None):
cpu_facts = {}
collected_facts = collected_facts or {}
if collected_facts.get('ansible_architecture') in ['9000/800', '9000/785']:
rc, out, err = self.module.run_command("ioscan -FkCprocessor | wc -l", use_unsafe_shell=True)
cpu_facts['processor_count'] = int(out.strip())
# Working with machinfo mess
elif collected_facts.get('ansible_architecture') == 'ia64':
if collected_facts.get('ansible_distribution_version') == "B.11.23":
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep 'Number of CPUs'", use_unsafe_shell=True)
if out:
cpu_facts['processor_count'] = int(out.strip().split('=')[1])
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep 'processor family'", use_unsafe_shell=True)
if out:
cpu_facts['processor'] = re.search('.*(Intel.*)', out).groups()[0].strip()
rc, out, err = self.module.run_command("ioscan -FkCprocessor | wc -l", use_unsafe_shell=True)
cpu_facts['processor_cores'] = int(out.strip())
if collected_facts.get('ansible_distribution_version') == "B.11.31":
# if machinfo return cores strings release B.11.31 > 1204
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep core | wc -l", use_unsafe_shell=True)
if out.strip() == '0':
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Intel", use_unsafe_shell=True)
cpu_facts['processor_count'] = int(out.strip().split(" ")[0])
# If hyperthreading is active divide cores by 2
rc, out, err = self.module.run_command("/usr/sbin/psrset | grep LCPU", use_unsafe_shell=True)
data = re.sub(' +', ' ', out).strip().split(' ')
if len(data) == 1:
hyperthreading = 'OFF'
else:
hyperthreading = data[1]
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep logical", use_unsafe_shell=True)
data = out.strip().split(" ")
if hyperthreading == 'ON':
cpu_facts['processor_cores'] = int(data[0]) / 2
else:
if len(data) == 1:
cpu_facts['processor_cores'] = cpu_facts['processor_count']
else:
cpu_facts['processor_cores'] = int(data[0])
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Intel |cut -d' ' -f4-", use_unsafe_shell=True)
cpu_facts['processor'] = out.strip()
else:
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | egrep 'socket[s]?$' | tail -1", use_unsafe_shell=True)
cpu_facts['processor_count'] = int(out.strip().split(" ")[0])
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep -e '[0-9] core' | tail -1", use_unsafe_shell=True)
cpu_facts['processor_cores'] = int(out.strip().split(" ")[0])
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Intel", use_unsafe_shell=True)
cpu_facts['processor'] = out.strip()
return cpu_facts
def get_memory_facts(self, collected_facts=None):
memory_facts = {}
collected_facts = collected_facts or {}
pagesize = 4096
rc, out, err = self.module.run_command("/usr/bin/vmstat | tail -1", use_unsafe_shell=True)
data = int(re.sub(' +', ' ', out).split(' ')[5].strip())
memory_facts['memfree_mb'] = pagesize * data // 1024 // 1024
if collected_facts.get('ansible_architecture') in ['9000/800', '9000/785']:
try:
rc, out, err = self.module.run_command("grep Physical /var/adm/syslog/syslog.log")
data = re.search('.*Physical: ([0-9]*) Kbytes.*', out).groups()[0].strip()
memory_facts['memtotal_mb'] = int(data) // 1024
except AttributeError:
# For systems where memory details aren't sent to syslog or the log has rotated, use parsed
# adb output. Unfortunately /dev/kmem doesn't have world-read, so this only works as root.
if os.access("/dev/kmem", os.R_OK):
rc, out, err = self.module.run_command("echo 'phys_mem_pages/D' | adb -k /stand/vmunix /dev/kmem | tail -1 | awk '{print $2}'",
use_unsafe_shell=True)
if not err:
data = out
memory_facts['memtotal_mb'] = int(data) / 256
else:
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo | grep Memory", use_unsafe_shell=True)
data = re.search(r'Memory[\ :=]*([0-9]*).*MB.*', out).groups()[0].strip()
memory_facts['memtotal_mb'] = int(data)
rc, out, err = self.module.run_command("/usr/sbin/swapinfo -m -d -f -q")
memory_facts['swaptotal_mb'] = int(out.strip())
rc, out, err = self.module.run_command("/usr/sbin/swapinfo -m -d -f | egrep '^dev|^fs'", use_unsafe_shell=True)
swap = 0
for line in out.strip().splitlines():
swap += int(re.sub(' +', ' ', line).split(' ')[3].strip())
memory_facts['swapfree_mb'] = swap
return memory_facts
def get_hw_facts(self, collected_facts=None):
hw_facts = {}
collected_facts = collected_facts or {}
rc, out, err = self.module.run_command("model")
hw_facts['model'] = out.strip()
if collected_facts.get('ansible_architecture') == 'ia64':
separator = ':'
if collected_facts.get('ansible_distribution_version') == "B.11.23":
separator = '='
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo |grep -i 'Firmware revision' | grep -v BMC", use_unsafe_shell=True)
hw_facts['firmware_version'] = out.split(separator)[1].strip()
rc, out, err = self.module.run_command("/usr/contrib/bin/machinfo |grep -i 'Machine serial number' ", use_unsafe_shell=True)
if rc == 0 and out:
hw_facts['product_serial'] = out.split(separator)[1].strip()
return hw_facts
| HPUXHardware |
python | PrefectHQ__prefect | tests/server/models/test_saved_searches.py | {
"start": 2918,
"end": 4622
} | class ____:
@pytest.fixture
async def saved_searches(self, session):
saved_search_1 = await models.saved_searches.create_saved_search(
session=session,
saved_search=schemas.core.SavedSearch(
name="My SavedSearch 1",
),
)
saved_search_2 = await models.saved_searches.create_saved_search(
session=session,
saved_search=schemas.core.SavedSearch(
name="My SavedSearch 2",
),
)
await session.commit()
return [saved_search_1, saved_search_2]
async def test_read_saved_searches(self, saved_searches, session):
read_saved_searches = await models.saved_searches.read_saved_searches(
session=session
)
assert len(read_saved_searches) == len(saved_searches)
async def test_read_saved_searches_applies_limit(self, saved_searches, session):
read_saved_searches = await models.saved_searches.read_saved_searches(
session=session, limit=1
)
assert {search.id for search in read_saved_searches} == {saved_searches[0].id}
async def test_read_saved_searches_applies_offset(self, saved_searches, session):
read_saved_searches = await models.saved_searches.read_saved_searches(
session=session, offset=1
)
assert {search.id for search in read_saved_searches} == {saved_searches[1].id}
async def test_read_saved_searches_returns_empty_list(self, session):
read_saved_searches = await models.saved_searches.read_saved_searches(
session=session
)
assert len(read_saved_searches) == 0
| TestReadSavedSearches |
python | pandas-dev__pandas | pandas/plotting/_matplotlib/core.py | {
"start": 42599,
"end": 44697
} | class ____(MPLPlot, ABC):
"""
Abstract class for plotting on plane, currently scatter and hexbin.
"""
_layout_type = "single"
def __init__(self, data, x, y, **kwargs) -> None:
MPLPlot.__init__(self, data, **kwargs)
if x is None or y is None:
raise ValueError(self._kind + " requires an x and y column")
if is_integer(x) and not holds_integer(self.data.columns):
x = self.data.columns[x]
if is_integer(y) and not holds_integer(self.data.columns):
y = self.data.columns[y]
self.x = x
self.y = y
@final
def _get_nseries(self, data: Series | DataFrame) -> int:
return 1
@final
def _post_plot_logic(self, ax: Axes, data) -> None:
x, y = self.x, self.y
xlabel = self.xlabel if self.xlabel is not None else pprint_thing(x)
ylabel = self.ylabel if self.ylabel is not None else pprint_thing(y)
# error: Argument 1 to "set_xlabel" of "_AxesBase" has incompatible
# type "Hashable"; expected "str"
ax.set_xlabel(xlabel) # type: ignore[arg-type]
ax.set_ylabel(ylabel) # type: ignore[arg-type]
@final
def _plot_colorbar(self, ax: Axes, *, fig: Figure, **kwds):
# Addresses issues #10611 and #10678:
# When plotting scatterplots and hexbinplots in IPython
# inline backend the colorbar axis height tends not to
# exactly match the parent axis height.
# The difference is due to small fractional differences
# in floating points with similar representation.
# To deal with this, this method forces the colorbar
# height to take the height of the parent axes.
# For a more detailed description of the issue
# see the following link:
# https://github.com/ipython/ipython/issues/11215
# GH33389, if ax is used multiple times, we should always
# use the last one which contains the latest information
# about the ax
img = ax.collections[-1]
return fig.colorbar(img, ax=ax, **kwds)
| PlanePlot |
python | pytorch__pytorch | torch/profiler/_memory_profiler.py | {
"start": 1578,
"end": 2248
} | class ____:
"""Bundle storage pointer and id.
All profiling logic should use `allocation_id`, however it is useful to
print storage pointers for debugging and unit tests sometimes look up
values using the storage data pointer of a live Tensor."""
ptr: int
allocation_id: int
def __repr__(self) -> str:
return f"{hex(self.ptr):>18} ({self.allocation_id})"
def __eq__(self, other: object) -> bool:
return isinstance(other, _Storage) and self.allocation_id == other.allocation_id
def __hash__(self) -> int:
return hash(self.allocation_id)
@dataclasses.dataclass(eq=True, unsafe_hash=True, frozen=True)
| _Storage |
python | wepe__MachineLearning | KMeans/kmeans.py | {
"start": 181,
"end": 3515
} | class ____(object):
"""
- 参数
n_clusters:
聚类个数,即k
initCent:
质心初始化方式,可选"random"或指定一个具体的array,默认random,即随机初始化
max_iter:
最大迭代次数
"""
def __init__(self,n_clusters=5,initCent='random',max_iter=300):
if hasattr(initCent, '__array__'):
n_clusters = initCent.shape[0]
self.centroids = np.asarray(initCent, dtype=np.float)
else:
self.centroids = None
self.n_clusters = n_clusters
self.max_iter = max_iter
self.initCent = initCent
self.clusterAssment = None
self.labels = None
self.sse = None
#计算两点的欧式距离
def _distEclud(self, vecA, vecB):
return np.linalg.norm(vecA - vecB)
#随机选取k个质心,必须在数据集的边界内
def _randCent(self, X, k):
n = X.shape[1] #特征维数
centroids = np.empty((k,n)) #k*n的矩阵,用于存储质心
for j in range(n): #产生k个质心,一维一维地随机初始化
minJ = min(X[:,j])
rangeJ = float(max(X[:,j]) - minJ)
centroids[:,j] = (minJ + rangeJ * np.random.rand(k,1)).flatten()
return centroids
def fit(self, X):
#类型检查
if not isinstance(X,np.ndarray):
try:
X = np.asarray(X)
except:
raise TypeError("numpy.ndarray required for X")
m = X.shape[0]#m代表样本数量
self.clusterAssment = np.empty((m,2))#m*2的矩阵,第一列存储样本点所属的族的索引值,
#第二列存储该点与所属族的质心的平方误差
if self.initCent == 'random':
self.centroids = self._randCent(X, self.n_clusters)
clusterChanged = True
for _ in range(self.max_iter):
clusterChanged = False
for i in range(m):#将每个样本点分配到离它最近的质心所属的族
minDist = np.inf; minIndex = -1
for j in range(self.n_clusters):
distJI = self._distEclud(self.centroids[j,:],X[i,:])
if distJI < minDist:
minDist = distJI; minIndex = j
if self.clusterAssment[i,0] != minIndex:
clusterChanged = True
self.clusterAssment[i,:] = minIndex,minDist**2
if not clusterChanged:#若所有样本点所属的族都不改变,则已收敛,结束迭代
break
for i in range(self.n_clusters):#更新质心,即将每个族中的点的均值作为质心
ptsInClust = X[np.nonzero(self.clusterAssment[:,0]==i)[0]]#取出属于第i个族的所有点
self.centroids[i,:] = np.mean(ptsInClust, axis=0)
self.labels = self.clusterAssment[:,0]
self.sse = sum(self.clusterAssment[:,1])
def predict(self,X):#根据聚类结果,预测新输入数据所属的族
#类型检查
if not isinstance(X,np.ndarray):
try:
X = np.asarray(X)
except:
raise TypeError("numpy.ndarray required for X")
m = X.shape[0]#m代表样本数量
preds = np.empty((m,))
for i in range(m):#将每个样本点分配到离它最近的质心所属的族
minDist = np.inf
for j in range(self.n_clusters):
distJI = self._distEclud(self.centroids[j,:],X[i,:])
if distJI < minDist:
minDist = distJI
preds[i] = j
return preds
| KMeans |
python | huggingface__transformers | src/transformers/models/kosmos2_5/processing_kosmos2_5.py | {
"start": 1022,
"end": 1399
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"padding": True,
"return_token_type_ids": False,
"stride": 0,
"truncation": True,
},
"images_kwargs": {
"max_patches": 4096,
},
"common_kwargs": {"return_tensors": "pt"},
}
| Kosmos2_5ProcessorKwargs |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_float.py | {
"start": 2113,
"end": 3383
} | class ____(_BaseTestFloat):
test_cls = Float32
scalar_type = np.float32
valid_dtype = (np.dtype(">f4"), np.dtype("<f4"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.uint16),
np.dtype(np.float64),
)
valid_json_v2 = (
{"name": ">f4", "object_codec_id": None},
{"name": "<f4", "object_codec_id": None},
)
valid_json_v3 = ("float32",)
invalid_json_v2 = (
"|f4",
"float32",
"|i1",
)
invalid_json_v3 = (
"|f4",
"|i1",
{"name": "float32", "configuration": {"endianness": "little"}},
)
scalar_v2_params = (
(Float32(), 1.0),
(Float32(), -1.0),
(Float32(), "NaN"),
(Float32(), "Infinity"),
)
scalar_v3_params = (
(Float32(), 1.0),
(Float32(), -1.0),
(Float32(), "NaN"),
(Float32(), "Infinity"),
)
cast_value_params = (
(Float32(), 1.0, np.float32(1.0)),
(Float32(), -1.0, np.float32(-1.0)),
(Float32(), "NaN", np.float32("NaN")),
)
invalid_scalar_params = ((Float32(), {"set!"}),)
hex_string_params = (("0x7fc00000", np.nan), ("0x7fc00001", np.nan), ("0x3f800000", 1.0))
item_size_params = (Float32(),)
| TestFloat32 |
python | GoogleCloudPlatform__python-docs-samples | endpoints/getting-started-grpc/helloworld_pb2_grpc.py | {
"start": 702,
"end": 1398
} | class ____:
"""The greeting service definition."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SayHello = channel.unary_unary(
"/helloworld.Greeter/SayHello",
request_serializer=helloworld__pb2.HelloRequest.SerializeToString,
response_deserializer=helloworld__pb2.HelloReply.FromString,
)
self.SayHelloAgain = channel.unary_unary(
"/helloworld.Greeter/SayHelloAgain",
request_serializer=helloworld__pb2.HelloRequest.SerializeToString,
response_deserializer=helloworld__pb2.HelloReply.FromString,
)
| GreeterStub |
python | plotly__plotly.py | plotly/graph_objs/scatterternary/marker/colorbar/_title.py | {
"start": 233,
"end": 4070
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterternary.marker.colorbar"
_path_str = "scatterternary.marker.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterternary.marker.colorbar.title.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.scatterternary.marker.colorbar.title.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def side(self):
"""
Determines the location of color bar's title with respect to
the color bar. Defaults to "top" when `orientation` if "v" and
defaults to "right" when `orientation` if "h".
The 'side' property is an enumeration that may be specified as:
- One of the following enumeration values:
['right', 'top', 'bottom']
Returns
-------
Any
"""
return self["side"]
@side.setter
def side(self, val):
self["side"] = val
@property
def text(self):
"""
Sets the title of the color bar.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def _prop_descriptions(self):
return """\
font
Sets this color bar's title font.
side
Determines the location of color bar's title with
respect to the color bar. Defaults to "top" when
`orientation` if "v" and defaults to "right" when
`orientation` if "h".
text
Sets the title of the color bar.
"""
def __init__(self, arg=None, font=None, side=None, text=None, **kwargs):
"""
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scatterternary
.marker.colorbar.Title`
font
Sets this color bar's title font.
side
Determines the location of color bar's title with
respect to the color bar. Defaults to "top" when
`orientation` if "v" and defaults to "right" when
`orientation` if "h".
text
Sets the title of the color bar.
Returns
-------
Title
"""
super().__init__("title")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scatterternary.marker.colorbar.Title
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterternary.marker.colorbar.Title`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("font", arg, font)
self._set_property("side", arg, side)
self._set_property("text", arg, text)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Title |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-pgvector/integration_tests/integration_test.py | {
"start": 375,
"end": 13135
} | class ____(BaseIntegrationTest):
def setUp(self):
with open("secrets/config.json", "r") as f:
self.config = json.loads(f.read())
def tearDown(self):
pass
def test_check_valid_config(self):
outcome = DestinationPGVector().check(logging.getLogger("airbyte"), self.config)
assert outcome.status == Status.SUCCEEDED
def test_check_invalid_config(self):
outcome = DestinationPGVector().check(
logging.getLogger("airbyte"),
{
"processing": {
"text_fields": ["str_col"],
"chunk_size": 1000,
"metadata_fields": ["int_col"],
},
"embedding": {"mode": "openai", "openai_key": "mykey"},
"indexing": {
"host": "MYACCOUNT",
"role": "MYUSERNAME",
"warehouse": "MYWAREHOUSE",
"database": "MYDATABASE",
"default_schema": "MYSCHEMA",
"username": "MYUSERNAME",
"credentials": {"password": "xxxxxxx"},
},
},
)
assert outcome.status == Status.FAILED
def _get_db_connection(self):
return psycopg2.connect(
dbname=self.config["indexing"]["database"],
user=self.config["indexing"]["username"],
password=self.config["indexing"]["credentials"]["password"],
host=self.config["indexing"]["host"],
port=self.config["indexing"]["port"],
)
def _get_record_count(self, table_name):
"""Return the number of records in the table."""
conn = self._get_db_connection()
cursor = conn.cursor()
cursor.execute(f"SELECT COUNT(*) FROM {table_name};")
result = cursor.fetchone()
cursor.close()
conn.close()
return result[0]
def _get_all_records(self, table_name) -> list[dict[str, Any]]:
"""Return all records from the table as a list of dictionaries."""
conn = self._get_db_connection()
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM {table_name};")
column_names = [desc[0] for desc in cursor.description]
result: list[dict[str, Any]] = []
for row in cursor.fetchall():
result.append(dict(zip(column_names, row)))
cursor.close()
conn.close()
return result
def _delete_table(self, table_name):
conn = self._get_db_connection()
cursor = conn.cursor()
cursor.execute(f"DROP TABLE IF EXISTS {table_name};")
conn.commit()
conn.close()
def _run_cosine_similarity(self, query_vector, table_name):
conn = self._get_db_connection()
cursor = conn.cursor()
query = f"""
SELECT DOCUMENT_CONTENT
FROM {table_name}
ORDER BY VECTOR_L2_DISTANCE(
CAST({query_vector} AS VECTOR(FLOAT, 1536)),
embedding
)
LIMIT 1
"""
cursor.execute(query)
result = cursor.fetchone()
cursor.close()
conn.close()
return result
def test_write(self):
self._delete_table("mystream")
catalog = self._get_configured_catalog(DestinationSyncMode.overwrite)
first_state_message = self._state({"state": "1"})
first_record = [
self._record(
stream="mystream",
str_value=f"Dogs are number {i}",
int_value=i,
)
for i in range(5)
]
# initial sync with replace
destination = DestinationPGVector()
_ = list(
destination.write(
config=self.config,
configured_catalog=catalog,
input_messages=[*first_record, first_state_message],
)
)
assert self._get_record_count("mystream") == 5
# subsequent sync with append
append_catalog = self._get_configured_catalog(DestinationSyncMode.append)
list(
destination.write(
config=self.config,
configured_catalog=append_catalog,
input_messages=[self._record("mystream", "Cats are nice", 6), first_state_message],
)
)
assert self._get_record_count("mystream") == 6
def test_write_and_replace(self):
self._delete_table("mystream")
catalog = self._get_configured_catalog(DestinationSyncMode.overwrite)
first_state_message = self._state({"state": "1"})
first_five_records = [
self._record(
stream="mystream",
str_value=f"Dogs are number {i}",
int_value=i,
)
for i in range(5)
]
# initial sync with replace
destination = DestinationPGVector()
list(
destination.write(
config=self.config,
configured_catalog=catalog,
input_messages=[*first_five_records, first_state_message],
)
)
assert self._get_record_count("mystream") == 5
# subsequent sync with append
append_catalog = self._get_configured_catalog(DestinationSyncMode.append)
list(
destination.write(
config=self.config,
configured_catalog=append_catalog,
input_messages=[self._record("mystream", "Cats are nice", 6), first_state_message],
)
)
assert self._get_record_count("mystream") == 6
# subsequent sync with append_dedup
append_dedup_catalog = self._get_configured_catalog(DestinationSyncMode.append_dedup)
list(
destination.write(
config=self.config,
configured_catalog=append_dedup_catalog,
input_messages=[
self._record("mystream", "Cats are nice too", 4),
first_state_message,
],
)
)
# TODO: FIXME: This should be 6, but it's 7 because the deduplication is not working
assert self._get_record_count("mystream") == 6
# comment the following so we can use fake for testing
# embeddings = OpenAIEmbeddings(openai_api_key=self.config["embedding"]["openai_key"])
# result = self._run_cosine_similarity(embeddings.embed_query("feline animals"), "mystream")
# assert(len(result) == 1)
# result[0] == "str_col: Cats are nice"
def test_overwrite_mode_deletes_records(self):
self._delete_table("mystream")
catalog = self._get_configured_catalog(DestinationSyncMode.overwrite)
first_state_message = self._state({"state": "1"})
first_four_records = [
self._record(
stream="mystream",
str_value=f"Dogs are number {i}",
int_value=i,
)
for i in range(4)
]
# initial sync with replace
destination = DestinationPGVector()
list(destination.write(self.config, catalog, [*first_four_records, first_state_message]))
assert self._get_record_count("mystream") == 4
# following should replace existing records
append_catalog = self._get_configured_catalog(DestinationSyncMode.overwrite)
list(
destination.write(
config=self.config,
configured_catalog=append_catalog,
input_messages=[self._record("mystream", "Cats are nice", 6), first_state_message],
)
)
assert self._get_record_count("mystream") == 1
def test_record_write_fidelity(self):
self._delete_table("mystream")
catalog = self._get_configured_catalog(DestinationSyncMode.overwrite)
first_state_message = self._state({"state": "1"})
records = [
self._record(
stream="mystream",
str_value=f"Dogs are number {i}",
int_value=i,
)
for i in range(1)
]
# initial sync with replace
destination = DestinationPGVector()
list(destination.write(self.config, catalog, [*records, first_state_message]))
assert self._get_record_count("mystream") == 1
first_written_record = self._get_all_records("mystream")[0]
assert list(first_written_record.keys()) == [
"document_id",
"chunk_id",
"metadata",
"document_content",
"embedding",
]
assert first_written_record.pop("embedding")
assert first_written_record.pop("chunk_id")
metadata = first_written_record.pop("metadata")
_ = metadata
# TODO: Fix the data type issue here (currently stringified):
# assert isinstance(metadata, dict), f"METADATA should be a dict: {metadata}"
# assert metadata["int_col"] == 0
assert first_written_record == {
"document_id": "Stream_mystream_Key_0",
"document_content": "str_col: Dogs are number 0",
}
def test_write_with_chunk_size_5(self):
self._delete_table("mystream")
self.config["processing"]["chunk_size"] = 5
catalog = self._get_configured_catalog(DestinationSyncMode.overwrite)
first_state_message = self._state({"state": "1"})
first_record = [
self._record(
stream="mystream",
str_value=f"Dogs are number {i}",
int_value=i,
)
for i in range(5)
]
# initial sync with replace
destination = DestinationPGVector()
_ = list(
destination.write(
config=self.config,
configured_catalog=catalog,
input_messages=[*first_record, first_state_message],
)
)
assert self._get_record_count("mystream") == 15
# subsequent sync with append
append_catalog = self._get_configured_catalog(DestinationSyncMode.append)
list(
destination.write(
config=self.config,
configured_catalog=append_catalog,
input_messages=[self._record("mystream", "Cats are nice", 6), first_state_message],
)
)
assert self._get_record_count("mystream") == 18
# subsequent sync with append_dedup
append_dedup_catalog = self._get_configured_catalog(DestinationSyncMode.append_dedup)
list(
destination.write(
config=self.config,
configured_catalog=append_dedup_catalog,
input_messages=[
self._record("mystream", "Cats are nice too", 4),
first_state_message,
],
)
)
assert self._get_record_count("mystream") == 18
def test_write_fidelity_with_chunk_size_5(self):
self._delete_table("mystream")
self.config["processing"]["chunk_size"] = 5
catalog = self._get_configured_catalog(DestinationSyncMode.overwrite)
first_state_message = self._state({"state": "1"})
records = [
self._record(
stream="mystream",
str_value=f"Dogs are number {i}",
int_value=i,
)
for i in range(1)
]
# initial sync with replace
destination = DestinationPGVector()
list(destination.write(self.config, catalog, [*records, first_state_message]))
assert self._get_record_count("mystream") == 3
first_written_record = self._get_all_records("mystream")[0]
second_written_record = self._get_all_records("mystream")[1]
third_written_record = self._get_all_records("mystream")[2]
assert list(first_written_record.keys()) == [
"document_id",
"chunk_id",
"metadata",
"document_content",
"embedding",
]
assert first_written_record.pop("embedding")
assert first_written_record.pop("chunk_id")
metadata = first_written_record.pop("metadata")
_ = metadata
assert first_written_record == {
"document_id": "Stream_mystream_Key_0",
"document_content": "str_col:",
}
assert second_written_record["document_id"] == "Stream_mystream_Key_0"
assert second_written_record["document_content"] == "Dogs are"
assert third_written_record["document_id"] == "Stream_mystream_Key_0"
assert third_written_record["document_content"] == "number 0"
| PGVectorIntegrationTest |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 40359,
"end": 40966
} | class ____(PrefectFilterBaseModel):
"""Filter by `Deployment.work_queue_name`."""
any_: Optional[list[str]] = Field(
default=None,
description="A list of work queue names to include",
examples=[["work_queue_1", "work_queue_2"]],
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
filters: list[sa.ColumnExpressionArgument[bool]] = []
if self.any_ is not None:
filters.append(db.Deployment.work_queue_name.in_(self.any_))
return filters
| DeploymentFilterWorkQueueName |
python | huggingface__transformers | tests/models/siglip/test_modeling_siglip.py | {
"start": 20307,
"end": 21163
} | class ____(SiglipModelTester):
def __init__(self, parent):
super().__init__(parent)
self.batch_size = self.vision_model_tester.batch_size
self.num_hidden_layers = self.vision_model_tester.num_hidden_layers
self.hidden_size = self.vision_model_tester.hidden_size
self.seq_length = self.vision_model_tester.seq_length
def prepare_config_and_inputs(self):
_, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
config = self.get_config()
return config, pixel_values
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, pixel_values = config_and_inputs
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
| SiglipForImageClassificationModelTester |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/context.py | {
"start": 5230,
"end": 5846
} | class ____(Protocol):
_partition_loading_context: PartitionLoadingContext
Self = TypeVar("Self", bound=_HasPartitionLoadingContext)
def use_partition_loading_context(
func: Callable[Concatenate[Self, P], T_Return],
) -> Callable[Concatenate[Self, P], T_Return]:
"""Decorator for methods that will use the partition loading context."""
@wraps(func)
def wrapper(self: Self, *args: P.args, **kwargs: P.kwargs) -> T_Return:
with partition_loading_context(new_ctx=self._partition_loading_context):
return func(self, *args, **kwargs)
return wrapper
| _HasPartitionLoadingContext |
python | pypa__setuptools | setuptools/_distutils/version.py | {
"start": 1471,
"end": 3669
} | class ____:
"""Abstract base class for version numbering classes. Just provides
constructor (__init__) and reproducer (__repr__), because those
seem to be the same for all version numbering classes; and route
rich comparisons to _cmp.
"""
def __init__(self, vstring=None):
if vstring:
self.parse(vstring)
warnings.warn(
"distutils Version classes are deprecated. Use packaging.version instead.",
DeprecationWarning,
stacklevel=2,
)
def __repr__(self):
return f"{self.__class__.__name__} ('{self}')"
def __eq__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c == 0
def __lt__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c < 0
def __le__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c <= 0
def __gt__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c > 0
def __ge__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c >= 0
# Interface for version-number classes -- must be implemented
# by the following classes (the concrete ones -- Version should
# be treated as an abstract class).
# __init__ (string) - create and take same action as 'parse'
# (string parameter is optional)
# parse (string) - convert a string representation to whatever
# internal representation is appropriate for
# this style of version numbering
# __str__ (self) - convert back to a string; should be very similar
# (if not identical to) the string supplied to parse
# __repr__ (self) - generate Python code to recreate
# the instance
# _cmp (self, other) - compare two version numbers ('other' may
# be an unparsed version string, or another
# instance of your version class)
| Version |
python | networkx__networkx | networkx/algorithms/tests/test_cuts.py | {
"start": 3035,
"end": 3676
} | class ____:
"""Unit tests for the :func:`~networkx.conductance` function."""
def test_graph(self):
G = nx.barbell_graph(5, 0)
# Consider the singleton sets containing the "bridge" nodes.
# There is only one cut edge, and each set has volume five.
S = {4}
T = {5}
conductance = nx.conductance(G, S, T)
expected = 1 / 5
assert expected == conductance
# Test with no input T
G2 = nx.barbell_graph(3, 0)
# There is only one cut edge, and each set has volume seven.
S2 = {0, 1, 2}
assert nx.conductance(G2, S2) == 1 / 7
| TestConductance |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 21714,
"end": 24292
} | class ____(BuiltinFunctionT):
_id = "sha256"
_inputs = [("value", (BYTES32_T, BytesT.any(), StringT.any()))]
_return_type = BYTES32_T
def _try_fold(self, node):
validate_call_args(node, 1)
value = node.args[0].get_folded_value()
if isinstance(value, (vy_ast.Bytes, vy_ast.HexBytes)):
value = value.value
elif isinstance(value, vy_ast.Str):
value = value.value.encode()
elif isinstance(value, vy_ast.Hex):
value = value.bytes_value
else:
raise UnfoldableNode
hash_ = f"0x{hashlib.sha256(value).hexdigest()}"
return vy_ast.Hex.from_node(node, value=hash_)
def infer_arg_types(self, node, expected_return_typ=None):
self._validate_arg_types(node)
# return a concrete type for `value`
value_type = get_possible_types_from_node(node.args[0]).pop()
return [value_type]
@process_inputs
def build_IR(self, expr, args, kwargs, context):
sub = args[0]
# bytes32 input
if sub.typ == BYTES32_T:
return IRnode.from_list(
[
"seq",
["mstore", MemoryPositions.FREE_VAR_SPACE, sub],
_make_sha256_call(
inp_start=MemoryPositions.FREE_VAR_SPACE,
inp_len=32,
out_start=MemoryPositions.FREE_VAR_SPACE,
out_len=32,
),
["mload", MemoryPositions.FREE_VAR_SPACE], # push value onto stack
],
typ=BYTES32_T,
add_gas_estimate=SHA256_BASE_GAS + 1 * SHA256_PER_WORD_GAS,
)
# bytearay-like input
# special case if it's already in memory
sub = ensure_in_memory(sub, context)
return IRnode.from_list(
[
"with",
"_sub",
sub,
[
"seq",
_make_sha256_call(
# TODO use add_ofst if sub is statically known
inp_start=["add", "_sub", 32],
inp_len=["mload", "_sub"],
out_start=MemoryPositions.FREE_VAR_SPACE,
out_len=32,
),
["mload", MemoryPositions.FREE_VAR_SPACE],
],
],
typ=BYTES32_T,
add_gas_estimate=SHA256_BASE_GAS + sub.typ.maxlen * SHA256_PER_WORD_GAS,
)
| Sha256 |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_reflection.py | {
"start": 4443,
"end": 10226
} | class ____:
@classmethod
def bar(cls):
pass
def baz(cls):
pass
def __repr__(self):
return "SoNotFoo()"
def test_class_names_are_not_included_in_class_method_prettiness():
assert get_pretty_function_description(Foo.bar) == "bar"
def test_repr_is_included_in_bound_method_prettiness():
assert get_pretty_function_description(Foo().baz) == "SoNotFoo().baz"
def test_class_is_not_included_in_unbound_method():
assert get_pretty_function_description(Foo.baz) == "baz"
def test_does_not_error_on_confused_sources():
def ed(f, *args):
return f
x = ed(
lambda x, y: (x * y).conjugate() == x.conjugate() * y.conjugate(),
complex,
complex,
)
get_pretty_function_description(x)
def test_digests_are_reasonably_unique():
assert function_digest(test_simple_conversion) != function_digest(
test_does_not_error_on_confused_sources
)
def test_digest_returns_the_same_value_for_two_calls():
assert function_digest(test_simple_conversion) == function_digest(
test_simple_conversion
)
def test_can_digest_a_built_in_function():
import math
assert function_digest(math.isnan) != function_digest(range)
def test_can_digest_a_unicode_lambda():
function_digest(lambda x: "☃" in str(x))
def test_can_digest_a_function_with_no_name():
def foo(x, y):
pass
function_digest(partial(foo, 1))
def test_arg_string_is_in_order():
def foo(c, a, b, f, a1):
pass
assert repr_call(foo, (1, 2, 3, 4, 5), {}) == "foo(c=1, a=2, b=3, f=4, a1=5)"
assert (
repr_call(foo, (1, 2), {"b": 3, "f": 4, "a1": 5})
== "foo(c=1, a=2, b=3, f=4, a1=5)"
)
def test_varkwargs_are_sorted_and_after_real_kwargs():
def foo(d, e, f, **kwargs):
pass
assert (
repr_call(foo, (), {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6})
== "foo(d=4, e=5, f=6, a=1, b=2, c=3)"
)
def test_varargs_come_without_equals():
def foo(a, *args):
pass
assert repr_call(foo, (1, 2, 3, 4), {}) == "foo(2, 3, 4, a=1)"
def test_can_mix_varargs_and_varkwargs():
def foo(*args, **kwargs):
pass
assert repr_call(foo, (1, 2, 3), {"c": 7}) == "foo(1, 2, 3, c=7)"
def test_arg_string_does_not_include_unprovided_defaults():
def foo(a, b, c=9, d=10):
pass
assert repr_call(foo, (1,), {"b": 1, "d": 11}) == "foo(a=1, b=1, d=11)"
def universal_acceptor(*args, **kwargs):
return args, kwargs
def has_one_arg(hello):
pass
def has_two_args(hello, world):
pass
def has_a_default(x, y, z=1):
pass
def has_varargs(*args):
pass
def has_kwargs(**kwargs):
pass
@pytest.mark.parametrize("f", [has_one_arg, has_two_args, has_varargs, has_kwargs])
def test_copying_preserves_signature(f):
af = get_signature(f)
t = define_function_signature("foo", "docstring", af)(universal_acceptor)
at = get_signature(t)
assert af == at
def test_name_does_not_clash_with_function_names():
def f():
pass
@define_function_signature("f", "A docstring for f", signature(f))
def g():
pass
g()
def test_copying_sets_name():
f = define_function_signature(
"hello_world", "A docstring for hello_world", signature(has_two_args)
)(universal_acceptor)
assert f.__name__ == "hello_world"
def test_copying_sets_docstring():
f = define_function_signature(
"foo", "A docstring for foo", signature(has_two_args)
)(universal_acceptor)
assert f.__doc__ == "A docstring for foo"
def test_uses_defaults():
f = define_function_signature(
"foo", "A docstring for foo", signature(has_a_default)
)(universal_acceptor)
assert f(3, 2) == ((3, 2, 1), {})
def test_uses_varargs():
f = define_function_signature("foo", "A docstring for foo", signature(has_varargs))(
universal_acceptor
)
assert f(1, 2) == ((1, 2), {})
DEFINE_FOO_FUNCTION = """
def foo(x):
return x
"""
def test_exec_as_module_execs():
m = source_exec_as_module(DEFINE_FOO_FUNCTION)
assert m.foo(1) == 1
def test_exec_as_module_caches():
assert source_exec_as_module(DEFINE_FOO_FUNCTION) is source_exec_as_module(
DEFINE_FOO_FUNCTION
)
def test_exec_leaves_sys_path_unchanged():
old_path = deepcopy(sys.path)
source_exec_as_module("hello_world = 42")
assert sys.path == old_path
def test_define_function_signature_works_with_conflicts():
def accepts_everything(*args, **kwargs):
pass
define_function_signature(
"hello",
"A docstring for hello",
Signature(parameters=[Parameter("f", Parameter.POSITIONAL_OR_KEYWORD)]),
)(accepts_everything)(1)
define_function_signature(
"hello",
"A docstring for hello",
Signature(parameters=[Parameter("f", Parameter.VAR_POSITIONAL)]),
)(accepts_everything)(1)
define_function_signature(
"hello",
"A docstring for hello",
Signature(parameters=[Parameter("f", Parameter.VAR_KEYWORD)]),
)(accepts_everything)()
define_function_signature(
"hello",
"A docstring for hello",
Signature(
parameters=[
Parameter("f", Parameter.POSITIONAL_OR_KEYWORD),
Parameter("f_3", Parameter.POSITIONAL_OR_KEYWORD),
Parameter("f_1", Parameter.VAR_POSITIONAL),
Parameter("f_2", Parameter.VAR_KEYWORD),
]
),
)(accepts_everything)(1, 2)
def test_define_function_signature_validates_function_name():
define_function_signature("hello_world", None, Signature())
with raises(ValueError):
define_function_signature("hello world", None, Signature())
| Foo |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/dashboard.py | {
"start": 25395,
"end": 26560
} | class ____(CamelSnakeSerializer[Dashboard]):
is_editable_by_everyone = serializers.BooleanField(
help_text="Whether the dashboard is editable by everyone.",
)
teams_with_edit_access = serializers.ListField(
child=serializers.IntegerField(),
help_text="List of team IDs that have edit access to a dashboard.",
required=False,
default=list,
)
def validate(self, data):
if "teams_with_edit_access" in data:
team_ids = data["teams_with_edit_access"]
existing_team_ids = set(
Team.objects.filter(
id__in=team_ids, organization=self.context["organization"]
).values_list("id", flat=True)
)
invalid_team_ids = set(team_ids) - existing_team_ids
if invalid_team_ids:
invalid_team_ids_str = [str(id) for id in invalid_team_ids]
raise serializers.ValidationError(
f"Cannot update dashboard edit permissions. Teams with IDs {oxfordize_list(invalid_team_ids_str)} do not exist."
)
return data
| DashboardPermissionsSerializer |
python | walkccc__LeetCode | solutions/991. Broken Calculator/991.py | {
"start": 0,
"end": 253
} | class ____:
def brokenCalc(self, startValue: int, target: int) -> int:
ops = 0
while startValue < target:
if target % 2 == 0:
target //= 2
else:
target += 1
ops += 1
return ops + startValue - target
| Solution |
python | huggingface__transformers | tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py | {
"start": 31222,
"end": 32802
} | class ____(EncoderDecoderMixin, unittest.TestCase):
supports_sdpa = True # one submodel support SDPA
def get_encoder_decoder_model(self, config, decoder_config):
encoder_model = ViTModel(config).eval()
decoder_model = TrOCRForCausalLM(decoder_config).eval()
return encoder_model, decoder_model
def prepare_config_and_inputs(self):
model_tester_encoder = ViTModelTester(self, batch_size=13)
model_tester_decoder = TrOCRStandaloneDecoderModelTester(
self, batch_size=13, d_model=32, max_position_embeddings=512
)
encoder_config_and_inputs = model_tester_encoder.prepare_config_and_inputs()
decoder_config_and_inputs = model_tester_decoder.prepare_config_and_inputs()
config, pixel_values, _ = encoder_config_and_inputs
(decoder_config, decoder_input_ids, decoder_attention_mask, _) = decoder_config_and_inputs
# make sure that cross attention layers are added
decoder_config.add_cross_attention = True
# disable cache for now
decoder_config.use_cache = False
return {
"config": config,
"pixel_values": pixel_values,
"decoder_config": decoder_config,
"decoder_input_ids": decoder_input_ids,
"decoder_attention_mask": decoder_attention_mask,
"labels": decoder_input_ids,
}
@unittest.skip(reason="There are no published pretrained TrOCR checkpoints for now")
def test_real_model_save_load_from_pretrained(self):
pass
@require_torch
| ViT2TrOCR |
python | pallets__jinja | src/jinja2/runtime.py | {
"start": 3124,
"end": 3740
} | class ____:
"""The `self` in templates."""
def __init__(self, context: "Context") -> None:
self.__context = context
def __getitem__(self, name: str) -> t.Any:
blocks = self.__context.blocks[name]
return BlockReference(name, self.__context, blocks, 0)
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.__context.name!r}>"
def _dict_method_all(dict_method: F) -> F:
@functools.wraps(dict_method)
def f_all(self: "Context") -> t.Any:
return dict_method(self.get_all())
return t.cast(F, f_all)
@abc.Mapping.register
| TemplateReference |
python | xlwings__xlwings | xlwings/main.py | {
"start": 151371,
"end": 151668
} | class ____(Sheets):
def __init__(self):
pass
# override class name which appears in repr
_name = "Sheets"
@property
def impl(self):
return books.active.sheets.impl
apps = ActiveEngineApps()
books = ActiveAppBooks()
sheets = ActiveBookSheets()
| ActiveBookSheets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.