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
gevent__gevent
src/greentest/3.11/test_signal.py
{ "start": 12380, "end": 18253 }
class ____(unittest.TestCase): @unittest.skipIf(_testcapi is None, 'need _testcapi') def check_wakeup(self, test_body, *signals, ordered=True): # use a subprocess to have only one thread code = """if 1: import _testcapi import os import signal import struct signals = {!r} def handler(signum, frame): pass def check_signum(signals): data = os.read(read, len(signals)+1) raised = struct.unpack('%uB' % len(data), data) if not {!r}: raised = set(raised) signals = set(signals) if raised != signals: raise Exception("%r != %r" % (raised, signals)) {} signal.signal(signal.SIGALRM, handler) read, write = os.pipe() os.set_blocking(write, False) signal.set_wakeup_fd(write) test() check_signum(signals) os.close(read) os.close(write) """.format(tuple(map(int, signals)), ordered, test_body) assert_python_ok('-c', code) @unittest.skipIf(_testcapi is None, 'need _testcapi') @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") def test_wakeup_write_error(self): # Issue #16105: write() errors in the C signal handler should not # pass silently. # Use a subprocess to have only one thread. code = """if 1: import _testcapi import errno import os import signal import sys from test.support import captured_stderr def handler(signum, frame): 1/0 signal.signal(signal.SIGALRM, handler) r, w = os.pipe() os.set_blocking(r, False) # Set wakeup_fd a read-only file descriptor to trigger the error signal.set_wakeup_fd(r) try: with captured_stderr() as err: signal.raise_signal(signal.SIGALRM) except ZeroDivisionError: # An ignored exception should have been printed out on stderr err = err.getvalue() if ('Exception ignored when trying to write to the signal wakeup fd' not in err): raise AssertionError(err) if ('OSError: [Errno %d]' % errno.EBADF) not in err: raise AssertionError(err) else: raise AssertionError("ZeroDivisionError not raised") os.close(r) os.close(w) """ r, w = os.pipe() try: os.write(r, b'x') except OSError: pass else: self.skipTest("OS doesn't report write() error on the read end of a pipe") finally: os.close(r) os.close(w) assert_python_ok('-c', code) def test_wakeup_fd_early(self): self.check_wakeup("""def test(): import select import time TIMEOUT_FULL = 10 TIMEOUT_HALF = 5 class InterruptSelect(Exception): pass def handler(signum, frame): raise InterruptSelect signal.signal(signal.SIGALRM, handler) signal.alarm(1) # We attempt to get a signal during the sleep, # before select is called try: select.select([], [], [], TIMEOUT_FULL) except InterruptSelect: pass else: raise Exception("select() was not interrupted") before_time = time.monotonic() select.select([read], [], [], TIMEOUT_FULL) after_time = time.monotonic() dt = after_time - before_time if dt >= TIMEOUT_HALF: raise Exception("%s >= %s" % (dt, TIMEOUT_HALF)) """, signal.SIGALRM) def test_wakeup_fd_during(self): self.check_wakeup("""def test(): import select import time TIMEOUT_FULL = 10 TIMEOUT_HALF = 5 class InterruptSelect(Exception): pass def handler(signum, frame): raise InterruptSelect signal.signal(signal.SIGALRM, handler) signal.alarm(1) before_time = time.monotonic() # We attempt to get a signal during the select call try: select.select([read], [], [], TIMEOUT_FULL) except InterruptSelect: pass else: raise Exception("select() was not interrupted") after_time = time.monotonic() dt = after_time - before_time if dt >= TIMEOUT_HALF: raise Exception("%s >= %s" % (dt, TIMEOUT_HALF)) """, signal.SIGALRM) def test_signum(self): self.check_wakeup("""def test(): signal.signal(signal.SIGUSR1, handler) signal.raise_signal(signal.SIGUSR1) signal.raise_signal(signal.SIGALRM) """, signal.SIGUSR1, signal.SIGALRM) @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') def test_pending(self): self.check_wakeup("""def test(): signum1 = signal.SIGUSR1 signum2 = signal.SIGUSR2 signal.signal(signum1, handler) signal.signal(signum2, handler) signal.pthread_sigmask(signal.SIG_BLOCK, (signum1, signum2)) signal.raise_signal(signum1) signal.raise_signal(signum2) # Unblocking the 2 signals calls the C signal handler twice signal.pthread_sigmask(signal.SIG_UNBLOCK, (signum1, signum2)) """, signal.SIGUSR1, signal.SIGUSR2, ordered=False) @unittest.skipUnless(hasattr(socket, 'socketpair'), 'need socket.socketpair')
WakeupSignalTests
python
getsentry__sentry
tests/sentry/uptime/autodetect/test_notifications.py
{ "start": 657, "end": 9214 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.organization = self.create_organization() self.project = self.create_project(organization=self.organization) self.user1 = self.create_user("user1@example.com") self.user2 = self.create_user("user2@example.com") self.create_member(user=self.user1, organization=self.organization) self.create_member(user=self.user2, organization=self.organization) self.team = self.create_team( organization=self.organization, members=[self.user1, self.user2] ) self.project.add_team(self.team) self.features = {"organizations:uptime-auto-detected-monitor-emails": True} def create_test_detector( self, url: str = "https://example.com" ) -> tuple[Detector, UptimeSubscription]: uptime_subscription = self.create_uptime_subscription(url=url) detector = self.create_uptime_detector( project=self.project, mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE, uptime_subscription=uptime_subscription, ) return detector, uptime_subscription def test_get_user_emails_from_project(self) -> None: """Test that we get all project member emails.""" emails = set(get_user_emails_from_project(self.project)) assert emails == {"user1@example.com", "user2@example.com"} def test_get_user_emails_with_alternate_email(self) -> None: """Test that alternate project-specific emails are respected.""" with assume_test_silo_mode(SiloMode.CONTROL): UserEmail.objects.create( user=self.user1, email="alternate1@example.com", is_verified=True ) UserOption.objects.create( user=self.user1, key="mail:email", project_id=self.project.id, value="alternate1@example.com", ) emails = set(get_user_emails_from_project(self.project)) assert emails == {"alternate1@example.com", "user2@example.com"} def test_get_user_emails_skips_unverified(self) -> None: """Test that unverified alternate emails are not used.""" with assume_test_silo_mode(SiloMode.CONTROL): UserEmail.objects.create( user=self.user1, email="unverified@example.com", is_verified=False ) UserOption.objects.create( user=self.user1, key="mail:email", project_id=self.project.id, value="unverified@example.com", ) emails = set(get_user_emails_from_project(self.project)) assert emails == {"user2@example.com"} assert "unverified@example.com" not in emails def test_generate_uptime_monitor_overview_url(self) -> None: """Test URL generation for uptime monitoring overview.""" url = generate_uptime_monitor_overview_url(self.organization) assert f"/organizations/{self.organization.slug}/insights/uptime/" in url def test_generate_uptime_monitor_detail_url(self) -> None: """Test URL generation for specific detector details.""" detector, _ = self.create_test_detector() url = generate_uptime_monitor_detail_url(self.organization, self.project.slug, detector.id) assert f"/organizations/{self.organization.slug}/issues/alerts/rules/uptime/" in url assert f"/{self.project.slug}/{detector.id}/details/" in url @patch("sentry.uptime.autodetect.notifications.MessageBuilder") def test_send_auto_detected_notifications(self, mock_builder: Mock) -> None: """Test that email is sent to all project members on graduation.""" mock_builder.return_value.send_async = Mock() detector, uptime_subscription = self.create_test_detector(url="https://api.example.com") with self.feature(self.features): send_auto_detected_notifications(detector.id) assert mock_builder.call_count == 1 call_kwargs = mock_builder.call_args[1] assert call_kwargs["subject"] == "We've Created a Free Uptime Monitor for Your Project" assert call_kwargs["template"] == "sentry/emails/uptime/auto-detected-monitors.txt" assert call_kwargs["html_template"] == "sentry/emails/uptime/auto-detected-monitors.html" assert call_kwargs["type"] == "uptime.auto_detected_monitors" context = call_kwargs["context"] assert "monitor_url_display" in context assert "monitor_detail_url" in context assert "project_slug" in context assert "date_created" in context assert "view_monitors_link" in context assert context["monitor_url_display"] == uptime_subscription.url assert context["project_slug"] == self.project.slug assert ( f"/organizations/{self.organization.slug}/issues/alerts/rules/uptime/" in context["monitor_detail_url"] ) assert context["date_created"] == detector.date_added mock_builder.return_value.send_async.assert_called_once() email_recipients = mock_builder.return_value.send_async.call_args[0][0] assert set(email_recipients) == {"user1@example.com", "user2@example.com"} @patch("sentry.uptime.autodetect.notifications.MessageBuilder") def test_send_auto_detected_notifications_no_members(self, mock_builder: Mock) -> None: """Test that no email is sent if project has no members.""" empty_org = self.create_organization() empty_project = self.create_project(organization=empty_org) detector = self.create_uptime_detector( project=empty_project, mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE, ) with self.feature({"organizations:uptime-auto-detected-monitor-emails": True}): send_auto_detected_notifications(detector.id) mock_builder.return_value.send_async.assert_not_called() @patch("sentry.uptime.autodetect.notifications.MessageBuilder") def test_send_auto_detected_notifications_multiple_teams(self, mock_builder: Mock) -> None: """Test email sent to all members across multiple teams.""" mock_builder.return_value.send_async = Mock() user3 = self.create_user("user3@example.com") user4 = self.create_user("user4@example.com") self.create_member(user=user3, organization=self.organization) self.create_member(user=user4, organization=self.organization) team2 = self.create_team(organization=self.organization, members=[user3, user4]) self.project.add_team(team2) detector, _ = self.create_test_detector() with self.feature(self.features): send_auto_detected_notifications(detector.id) email_recipients = mock_builder.return_value.send_async.call_args[0][0] assert set(email_recipients) == { "user1@example.com", "user2@example.com", "user3@example.com", "user4@example.com", } @patch("sentry.uptime.autodetect.notifications.MessageBuilder") def test_send_auto_detected_notifications_excludes_non_team_members( self, mock_builder: Mock ) -> None: """Test that users not on project teams don't receive emails.""" mock_builder.return_value.send_async = Mock() user_not_in_team = self.create_user("outsider@example.com") self.create_member(user=user_not_in_team, organization=self.organization) detector, _ = self.create_test_detector() with self.feature(self.features): send_auto_detected_notifications(detector.id) email_recipients = mock_builder.return_value.send_async.call_args[0][0] assert set(email_recipients) == {"user1@example.com", "user2@example.com"} assert "outsider@example.com" not in email_recipients @patch("sentry.uptime.autodetect.notifications.MessageBuilder") def test_send_auto_detected_notifications_feature_flag_disabled( self, mock_builder: Mock ) -> None: """Test that no email is sent when feature flag is disabled.""" mock_builder.return_value.send_async = Mock() detector, _ = self.create_test_detector(url="https://api.example.com") with self.feature({"organizations:uptime-auto-detected-monitor-emails": False}): send_auto_detected_notifications(detector.id) mock_builder.return_value.send_async.assert_not_called()
UptimeAutoDetectedNotificationsTest
python
pdm-project__pdm
src/pdm/cli/commands/venv/remove.py
{ "start": 261, "end": 1280 }
class ____(BaseCommand): """Remove the virtualenv with the given name""" arguments = (verbose_option,) def add_arguments(self, parser: argparse.ArgumentParser) -> None: parser.add_argument( "-y", "--yes", action="store_true", help="Answer yes on the following question", ) parser.add_argument("env", help="The key of the virtualenv") def handle(self, project: Project, options: argparse.Namespace) -> None: project.core.ui.echo("Virtualenvs created with this project:") venv = get_venv_with_name(project, options.env) if options.yes or termui.confirm(f"[warning]Will remove: [success]{venv.root}[/], continue?", default=True): shutil.rmtree(venv.root) saved_python = project._saved_python if saved_python and Path(saved_python).parent.parent == venv.root: project._saved_python = None project.core.ui.echo("Removed successfully!")
RemoveCommand
python
doocs__leetcode
solution/2700-2799/2788.Split Strings by Separator/Solution.py
{ "start": 0, "end": 167 }
class ____: def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]: return [s for w in words for s in w.split(separator) if s]
Solution
python
keras-team__keras
keras/src/metrics/confusion_metrics.py
{ "start": 330, "end": 2938 }
class ____(Metric): """Calculates the number of the given confusion matrix condition. Args: confusion_matrix_cond: One of `metrics_utils.ConfusionMatrix` conditions. thresholds: (Optional) Defaults to `0.5`. A float value or a python list / tuple of float threshold values in `[0, 1]`. A threshold is compared with prediction values to determine the truth value of predictions (i.e., above the threshold is `True`, below is `False`). One metric value is generated for each threshold value. name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. """ def __init__( self, confusion_matrix_cond, thresholds=None, name=None, dtype=None ): super().__init__(name=name, dtype=dtype) self._confusion_matrix_cond = confusion_matrix_cond self.init_thresholds = thresholds self.thresholds = metrics_utils.parse_init_thresholds( thresholds, default_threshold=0.5 ) self._thresholds_distributed_evenly = ( metrics_utils.is_evenly_distributed_thresholds(self.thresholds) ) self.accumulator = self.add_variable( shape=(len(self.thresholds),), initializer=initializers.Zeros(), name="accumulator", ) def update_state(self, y_true, y_pred, sample_weight=None): """Accumulates the metric statistics. Args: y_true: The ground truth values. y_pred: The predicted values. sample_weight: Optional weighting of each example. Defaults to `1`. Can be a tensor whose rank is either 0, or the same rank as `y_true`, and must be broadcastable to `y_true`. """ return metrics_utils.update_confusion_matrix_variables( {self._confusion_matrix_cond: self.accumulator}, y_true, y_pred, thresholds=self.thresholds, thresholds_distributed_evenly=self._thresholds_distributed_evenly, sample_weight=sample_weight, ) def result(self): if len(self.thresholds) == 1: result = self.accumulator[0] else: result = self.accumulator return backend.convert_to_tensor(result) def get_config(self): config = {"thresholds": self.init_thresholds} base_config = super().get_config() return {**base_config, **config} @keras_export("keras.metrics.FalsePositives")
_ConfusionMatrixConditionCount
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/psycopg2.py
{ "start": 22225, "end": 31864 }
class ____(_PGDialect_common_psycopg): driver = "psycopg2" supports_statement_cache = True supports_server_side_cursors = True default_paramstyle = "pyformat" # set to true based on psycopg2 version supports_sane_multi_rowcount = False execution_ctx_cls = PGExecutionContext_psycopg2 preparer = PGIdentifierPreparer_psycopg2 psycopg2_version = (0, 0) use_insertmanyvalues_wo_returning = True returns_native_bytes = False _has_native_hstore = True colspecs = util.update_copy( _PGDialect_common_psycopg.colspecs, { JSON: _PGJSON, sqltypes.JSON: _PGJSON, JSONB: _PGJSONB, ranges.INT4RANGE: _Psycopg2NumericRange, ranges.INT8RANGE: _Psycopg2NumericRange, ranges.NUMRANGE: _Psycopg2NumericRange, ranges.DATERANGE: _Psycopg2DateRange, ranges.TSRANGE: _Psycopg2DateTimeRange, ranges.TSTZRANGE: _Psycopg2DateTimeTZRange, }, ) def __init__( self, executemany_mode="values_only", executemany_batch_page_size=100, **kwargs, ): _PGDialect_common_psycopg.__init__(self, **kwargs) if self._native_inet_types: raise NotImplementedError( "The psycopg2 dialect does not implement " "ipaddress type handling; native_inet_types cannot be set " "to ``True`` when using this dialect." ) # Parse executemany_mode argument, allowing it to be only one of the # symbol names self.executemany_mode = parse_user_argument_for_enum( executemany_mode, { EXECUTEMANY_VALUES: ["values_only"], EXECUTEMANY_VALUES_PLUS_BATCH: ["values_plus_batch"], }, "executemany_mode", ) self.executemany_batch_page_size = executemany_batch_page_size if self.dbapi and hasattr(self.dbapi, "__version__"): m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", self.dbapi.__version__) if m: self.psycopg2_version = tuple( int(x) for x in m.group(1, 2, 3) if x is not None ) if self.psycopg2_version < (2, 7): raise ImportError( "psycopg2 version 2.7 or higher is required." ) def initialize(self, connection): super().initialize(connection) self._has_native_hstore = ( self.use_native_hstore and self._hstore_oids(connection.connection.dbapi_connection) is not None ) self.supports_sane_multi_rowcount = ( self.executemany_mode is not EXECUTEMANY_VALUES_PLUS_BATCH ) @classmethod def import_dbapi(cls): import psycopg2 return psycopg2 @util.memoized_property def _psycopg2_extensions(cls): from psycopg2 import extensions return extensions @util.memoized_property def _psycopg2_extras(cls): from psycopg2 import extras return extras @util.memoized_property def _isolation_lookup(self): extensions = self._psycopg2_extensions return { "AUTOCOMMIT": extensions.ISOLATION_LEVEL_AUTOCOMMIT, "READ COMMITTED": extensions.ISOLATION_LEVEL_READ_COMMITTED, "READ UNCOMMITTED": extensions.ISOLATION_LEVEL_READ_UNCOMMITTED, "REPEATABLE READ": extensions.ISOLATION_LEVEL_REPEATABLE_READ, "SERIALIZABLE": extensions.ISOLATION_LEVEL_SERIALIZABLE, } def set_isolation_level(self, dbapi_connection, level): dbapi_connection.set_isolation_level(self._isolation_lookup[level]) def set_readonly(self, connection, value): connection.readonly = value def get_readonly(self, connection): return connection.readonly def set_deferrable(self, connection, value): connection.deferrable = value def get_deferrable(self, connection): return connection.deferrable def on_connect(self): extras = self._psycopg2_extras fns = [] if self.client_encoding is not None: def on_connect(dbapi_conn): dbapi_conn.set_client_encoding(self.client_encoding) fns.append(on_connect) if self.dbapi: def on_connect(dbapi_conn): extras.register_uuid(None, dbapi_conn) fns.append(on_connect) if self.dbapi and self.use_native_hstore: def on_connect(dbapi_conn): hstore_oids = self._hstore_oids(dbapi_conn) if hstore_oids is not None: oid, array_oid = hstore_oids kw = {"oid": oid} kw["array_oid"] = array_oid extras.register_hstore(dbapi_conn, **kw) fns.append(on_connect) if self.dbapi and self._json_deserializer: def on_connect(dbapi_conn): extras.register_default_json( dbapi_conn, loads=self._json_deserializer ) extras.register_default_jsonb( dbapi_conn, loads=self._json_deserializer ) fns.append(on_connect) if fns: def on_connect(dbapi_conn): for fn in fns: fn(dbapi_conn) return on_connect else: return None def do_executemany(self, cursor, statement, parameters, context=None): if self.executemany_mode is EXECUTEMANY_VALUES_PLUS_BATCH: if self.executemany_batch_page_size: kwargs = {"page_size": self.executemany_batch_page_size} else: kwargs = {} self._psycopg2_extras.execute_batch( cursor, statement, parameters, **kwargs ) else: cursor.executemany(statement, parameters) def do_begin_twophase(self, connection, xid): connection.connection.tpc_begin(xid) def do_prepare_twophase(self, connection, xid): connection.connection.tpc_prepare() def _do_twophase(self, dbapi_conn, operation, xid, recover=False): if recover: if dbapi_conn.status != self._psycopg2_extensions.STATUS_READY: dbapi_conn.rollback() operation(xid) else: operation() def do_rollback_twophase( self, connection, xid, is_prepared=True, recover=False ): dbapi_conn = connection.connection.dbapi_connection self._do_twophase( dbapi_conn, dbapi_conn.tpc_rollback, xid, recover=recover ) def do_commit_twophase( self, connection, xid, is_prepared=True, recover=False ): dbapi_conn = connection.connection.dbapi_connection self._do_twophase( dbapi_conn, dbapi_conn.tpc_commit, xid, recover=recover ) @util.memoized_instancemethod def _hstore_oids(self, dbapi_connection): extras = self._psycopg2_extras oids = extras.HstoreAdapter.get_oids(dbapi_connection) if oids is not None and oids[0]: return oids[0:2] else: return None def is_disconnect(self, e, connection, cursor): if isinstance(e, self.dbapi.Error): # check the "closed" flag. this might not be # present on old psycopg2 versions. Also, # this flag doesn't actually help in a lot of disconnect # situations, so don't rely on it. if getattr(connection, "closed", False): return True # checks based on strings. in the case that .closed # didn't cut it, fall back onto these. str_e = str(e).partition("\n")[0] for msg in self._is_disconnect_messages: idx = str_e.find(msg) if idx >= 0 and '"' not in str_e[:idx]: return True return False @util.memoized_property def _is_disconnect_messages(self): return ( # these error messages from libpq: interfaces/libpq/fe-misc.c # and interfaces/libpq/fe-secure.c. "terminating connection", "closed the connection", "connection not open", "could not receive data from server", "could not send data to server", # psycopg2 client errors, psycopg2/connection.h, # psycopg2/cursor.h "connection already closed", "cursor already closed", # not sure where this path is originally from, it may # be obsolete. It really says "losed", not "closed". "losed the connection unexpectedly", # these can occur in newer SSL "connection has been closed unexpectedly", "SSL error: decryption failed or bad record mac", "SSL SYSCALL error: Bad file descriptor", "SSL SYSCALL error: EOF detected", "SSL SYSCALL error: Operation timed out", "SSL SYSCALL error: Bad address", # This can occur in OpenSSL 1 when an unexpected EOF occurs. # https://www.openssl.org/docs/man1.1.1/man3/SSL_get_error.html#BUGS # It may also occur in newer OpenSSL for a non-recoverable I/O # error as a result of a system call that does not set 'errno' # in libc. "SSL SYSCALL error: Success", ) dialect = PGDialect_psycopg2
PGDialect_psycopg2
python
ray-project__ray
python/ray/_private/state.py
{ "start": 667, "end": 43929 }
class ____: """A class used to interface with the Ray control state. Attributes: global_state_accessor: The client used to query gcs table from gcs server. """ def __init__(self): """Create a GlobalState object.""" # Args used for lazy init of this object. self.gcs_options = None self._global_state_accessor = None self._init_lock = Lock() def _connect_and_get_accessor(self) -> GlobalStateAccessor: """ This lazily initializes clients needed for state accessors and returns a connected global state accessor. Returns: GlobalStateAccessor: A connected global state accessor. Raises: RuntimeError: An exception is raised if ray.init() has not been called yet. """ with self._init_lock: if self._global_state_accessor is not None: return self._global_state_accessor if self.gcs_options is None: raise ray.exceptions.RaySystemError( "Ray has not been started yet. Trying to use state API before ray.init() has been called." ) self._global_state_accessor = GlobalStateAccessor(self.gcs_options) connected = self._global_state_accessor.connect() if not connected: self._global_state_accessor = None raise ray.exceptions.RaySystemError( "Failed to connect to GCS. Please check if the GCS server is running " "and if this node can connect to the head node." ) return self._global_state_accessor def disconnect(self): """Disconnect global state from GCS.""" with self._init_lock: self.gcs_options = None if self._global_state_accessor is not None: self._global_state_accessor = None def _initialize_global_state(self, gcs_options): """Set args for lazily initialization of the GlobalState object. It's possible that certain keys in gcs kv may not have been fully populated yet. In this case, we will retry this method until they have been populated or we exceed a timeout. Args: gcs_options: The client options for gcs """ # Save args for lazy init of global state. This avoids opening extra # gcs connections from each worker until needed. with self._init_lock: self.gcs_options = gcs_options def actor_table( self, actor_id: Optional[str], job_id: Optional[ray.JobID] = None, actor_state_name: Optional[str] = None, ): """Fetch and parse the actor table information for a single actor ID. Args: actor_id: A hex string of the actor ID to fetch information about. If this is None, then the actor table is fetched. If this is not None, `job_id` and `actor_state_name` will not take effect. job_id: To filter actors by job_id, which is of type `ray.JobID`. You can use the `ray.get_runtime_context().job_id` function to get the current job ID actor_state_name: To filter actors based on actor state, which can be one of the following: "DEPENDENCIES_UNREADY", "PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD". Returns: Information from the actor table. """ accessor = self._connect_and_get_accessor() if actor_id is not None: actor_id = ray.ActorID(hex_to_binary(actor_id)) actor_info = accessor.get_actor_info(actor_id) if actor_info is None: return {} else: actor_table_data = gcs_pb2.ActorTableData.FromString(actor_info) return self._gen_actor_info(actor_table_data) else: validate_actor_state_name(actor_state_name) actor_table = accessor.get_actor_table(job_id, actor_state_name) results = {} for i in range(len(actor_table)): actor_table_data = gcs_pb2.ActorTableData.FromString(actor_table[i]) results[ binary_to_hex(actor_table_data.actor_id) ] = self._gen_actor_info(actor_table_data) return results def _gen_actor_info(self, actor_table_data): """Parse actor table data. Returns: Information from actor table. """ actor_info = { "ActorID": binary_to_hex(actor_table_data.actor_id), "ActorClassName": actor_table_data.class_name, "IsDetached": actor_table_data.is_detached, "Name": actor_table_data.name, "JobID": binary_to_hex(actor_table_data.job_id), "Address": { "IPAddress": actor_table_data.address.ip_address, "Port": actor_table_data.address.port, "NodeID": binary_to_hex(actor_table_data.address.node_id), }, "OwnerAddress": { "IPAddress": actor_table_data.owner_address.ip_address, "Port": actor_table_data.owner_address.port, "NodeID": binary_to_hex(actor_table_data.owner_address.node_id), }, "State": gcs_pb2.ActorTableData.ActorState.DESCRIPTOR.values_by_number[ actor_table_data.state ].name, "NumRestarts": actor_table_data.num_restarts, "Timestamp": actor_table_data.timestamp, "StartTime": actor_table_data.start_time, "EndTime": actor_table_data.end_time, "DeathCause": actor_table_data.death_cause, "Pid": actor_table_data.pid, } return actor_info def node_table(self): """Fetch and parse the Gcs node info table. Returns: Information about the node in the cluster. """ accessor = self._connect_and_get_accessor() return accessor.get_node_table() def job_table(self): """Fetch and parse the gcs job table. Returns: Information about the Ray jobs in the cluster, namely a list of dicts with keys: - "JobID" (identifier for the job), - "DriverIPAddress" (IP address of the driver for this job), - "DriverPid" (process ID of the driver for this job), - "StartTime" (UNIX timestamp of the start time of this job), - "StopTime" (UNIX timestamp of the stop time of this job, if any) """ accessor = self._connect_and_get_accessor() job_table = accessor.get_job_table( skip_submission_job_info_field=True, skip_is_running_tasks_field=True ) results = [] for i in range(len(job_table)): entry = gcs_pb2.JobTableData.FromString(job_table[i]) job_info = {} job_info["JobID"] = entry.job_id.hex() job_info["DriverIPAddress"] = entry.driver_address.ip_address job_info["DriverPid"] = entry.driver_pid job_info["Timestamp"] = entry.timestamp job_info["StartTime"] = entry.start_time job_info["EndTime"] = entry.end_time job_info["IsDead"] = entry.is_dead job_info["Entrypoint"] = entry.entrypoint results.append(job_info) return results def next_job_id(self): """Get next job id from GCS. Returns: Next job id in the cluster. """ accessor = self._connect_and_get_accessor() return ray.JobID.from_int(accessor.get_next_job_id()) def profile_events(self): """Retrieve and return task profiling events from GCS. Return: Profiling events by component id (e.g. worker id). { <component_id>: [ { event_type: <event name> , component_id: <i.e. worker id>, node_ip_address: <on which node profiling was done>, component_type: <i.e. worker/driver>, start_time: <unix timestamp in seconds>, end_time: <unix timestamp in seconds>, extra_data: <e.g. stack trace when error raised>, } ] } """ accessor = self._connect_and_get_accessor() result = defaultdict(list) task_events = accessor.get_task_events() for i in range(len(task_events)): event = gcs_pb2.TaskEvents.FromString(task_events[i]) profile = event.profile_events if not profile: continue component_type = profile.component_type component_id = binary_to_hex(profile.component_id) node_ip_address = profile.node_ip_address for event in profile.events: try: extra_data = json.loads(event.extra_data) except ValueError: extra_data = {} profile_event = { "event_type": event.event_name, "component_id": component_id, "node_ip_address": node_ip_address, "component_type": component_type, "start_time": event.start_time, "end_time": event.end_time, "extra_data": extra_data, } result[component_id].append(profile_event) return dict(result) def get_placement_group_by_name(self, placement_group_name, ray_namespace): accessor = self._connect_and_get_accessor() placement_group_info = accessor.get_placement_group_by_name( placement_group_name, ray_namespace ) if placement_group_info is None: return None else: placement_group_table_data = gcs_pb2.PlacementGroupTableData.FromString( placement_group_info ) return self._gen_placement_group_info(placement_group_table_data) def placement_group_table(self, placement_group_id=None): accessor = self._connect_and_get_accessor() if placement_group_id is not None: placement_group_id = ray.PlacementGroupID( hex_to_binary(placement_group_id.hex()) ) placement_group_info = accessor.get_placement_group_info(placement_group_id) if placement_group_info is None: return {} else: placement_group_info = gcs_pb2.PlacementGroupTableData.FromString( placement_group_info ) return self._gen_placement_group_info(placement_group_info) else: placement_group_table = accessor.get_placement_group_table() results = {} for placement_group_info in placement_group_table: placement_group_table_data = gcs_pb2.PlacementGroupTableData.FromString( placement_group_info ) placement_group_id = binary_to_hex( placement_group_table_data.placement_group_id ) results[placement_group_id] = self._gen_placement_group_info( placement_group_table_data ) return results def _gen_placement_group_info(self, placement_group_info): # This should be imported here, otherwise, it will error doc build. from ray.core.generated.common_pb2 import PlacementStrategy def get_state(state): if state == gcs_pb2.PlacementGroupTableData.PENDING: return "PENDING" elif state == gcs_pb2.PlacementGroupTableData.PREPARED: return "PREPARED" elif state == gcs_pb2.PlacementGroupTableData.CREATED: return "CREATED" elif state == gcs_pb2.PlacementGroupTableData.RESCHEDULING: return "RESCHEDULING" else: return "REMOVED" def get_strategy(strategy): if strategy == PlacementStrategy.PACK: return "PACK" elif strategy == PlacementStrategy.STRICT_PACK: return "STRICT_PACK" elif strategy == PlacementStrategy.STRICT_SPREAD: return "STRICT_SPREAD" elif strategy == PlacementStrategy.SPREAD: return "SPREAD" else: raise ValueError(f"Invalid strategy returned: {PlacementStrategy}") stats = placement_group_info.stats assert placement_group_info is not None return { "placement_group_id": binary_to_hex( placement_group_info.placement_group_id ), "name": placement_group_info.name, "bundles": { # The value here is needs to be dictionarified # otherwise, the payload becomes unserializable. bundle.bundle_id.bundle_index: message_to_dict(bundle)["unitResources"] for bundle in placement_group_info.bundles }, "bundles_to_node_id": { bundle.bundle_id.bundle_index: binary_to_hex(bundle.node_id) for bundle in placement_group_info.bundles }, "strategy": get_strategy(placement_group_info.strategy), "state": get_state(placement_group_info.state), "stats": { "end_to_end_creation_latency_ms": ( stats.end_to_end_creation_latency_us / 1000.0 ), "scheduling_latency_ms": (stats.scheduling_latency_us / 1000.0), "scheduling_attempt": stats.scheduling_attempt, "highest_retry_delay_ms": stats.highest_retry_delay_ms, "scheduling_state": gcs_pb2.PlacementGroupStats.SchedulingState.DESCRIPTOR.values_by_number[ # noqa: E501 stats.scheduling_state ].name, }, } def _nanoseconds_to_microseconds(self, time_in_nanoseconds): """A helper function for converting nanoseconds to microseconds.""" time_in_microseconds = time_in_nanoseconds / 1000 return time_in_microseconds # Colors are specified at # https://github.com/catapult-project/catapult/blob/master/tracing/tracing/base/color_scheme.html. # noqa: E501 _default_color_mapping = defaultdict( lambda: "generic_work", { "worker_idle": "cq_build_abandoned", "task": "rail_response", "task:deserialize_arguments": "rail_load", "task:execute": "rail_animation", "task:store_outputs": "rail_idle", "wait_for_function": "detailed_memory_dump", "ray.get": "good", "ray.put": "terrible", "ray.wait": "vsync_highlight_color", "submit_task": "background_memory_dump", "fetch_and_run_function": "detailed_memory_dump", "register_remote_function": "detailed_memory_dump", }, ) # These colors are for use in Chrome tracing. _chrome_tracing_colors = [ "thread_state_uninterruptible", "thread_state_iowait", "thread_state_running", "thread_state_runnable", "thread_state_sleeping", "thread_state_unknown", "background_memory_dump", "light_memory_dump", "detailed_memory_dump", "vsync_highlight_color", "generic_work", "good", "bad", "terrible", # "black", # "grey", # "white", "yellow", "olive", "rail_response", "rail_animation", "rail_idle", "rail_load", "startup", "heap_dump_stack_frame", "heap_dump_object_type", "heap_dump_child_node_arrow", "cq_build_running", "cq_build_passed", "cq_build_failed", "cq_build_abandoned", "cq_build_attempt_runnig", "cq_build_attempt_passed", "cq_build_attempt_failed", ] def chrome_tracing_dump(self, filename=None): """Return a list of profiling events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to enable "Flow events" in the "View Options" menu. Args: filename: If a filename is provided, the timeline is dumped to that file. Returns: If filename is not provided, this returns a list of profiling events. Each profile event is a dictionary. """ # TODO(rkn): Support including the task specification data in the # timeline. # TODO(rkn): This should support viewing just a window of time or a # limited number of events. self._connect_and_get_accessor() # Add a small delay to account for propagation delay of events to the GCS. # This should be harmless enough but prevents calls to timeline() from # missing recent timeline data. import time time.sleep(1) profile_events = self.profile_events() all_events = [] for component_id_hex, component_events in profile_events.items(): # Only consider workers and drivers. component_type = component_events[0]["component_type"] if component_type not in ["worker", "driver"]: continue for event in component_events: new_event = { # The category of the event. "cat": event["event_type"], # The string displayed on the event. "name": event["event_type"], # The identifier for the group of rows that the event # appears in. "pid": event["node_ip_address"], # The identifier for the row that the event appears in. "tid": event["component_type"] + ":" + event["component_id"], # The start time in microseconds. "ts": self._nanoseconds_to_microseconds(event["start_time"]), # The duration in microseconds. "dur": self._nanoseconds_to_microseconds( event["end_time"] - event["start_time"] ), # What is this? "ph": "X", # This is the name of the color to display the box in. "cname": self._default_color_mapping[event["event_type"]], # The extra user-defined data. "args": event["extra_data"], } # Modify the json with the additional user-defined extra data. # This can be used to add fields or override existing fields. if "cname" in event["extra_data"]: new_event["cname"] = event["extra_data"]["cname"] if "name" in event["extra_data"]: new_event["name"] = event["extra_data"]["name"] all_events.append(new_event) if not all_events: logger.warning( "No profiling events found. Ray profiling must be enabled " "by setting RAY_PROFILING=1, and make sure " "RAY_task_events_report_interval_ms=0." ) if filename is not None: with open(filename, "w") as outfile: json.dump(all_events, outfile) else: return all_events def chrome_tracing_object_transfer_dump(self, filename=None): """Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to enable "Flow events" in the "View Options" menu. Args: filename: If a filename is provided, the timeline is dumped to that file. Returns: If filename is not provided, this returns a list of profiling events. Each profile event is a dictionary. """ self._connect_and_get_accessor() node_id_to_address = {} for node_info in self.node_table(): node_id_to_address[node_info["NodeID"]] = "{}:{}".format( node_info["NodeManagerAddress"], node_info["ObjectManagerPort"] ) all_events = [] for key, items in self.profile_events().items(): # Only consider object manager events. if items[0]["component_type"] != "object_manager": continue for event in items: if event["event_type"] == "transfer_send": object_ref, remote_node_id, _, _ = event["extra_data"] elif event["event_type"] == "transfer_receive": object_ref, remote_node_id, _ = event["extra_data"] elif event["event_type"] == "receive_pull_request": object_ref, remote_node_id = event["extra_data"] else: assert False, "This should be unreachable." # Choose a color by reading the first couple of hex digits of # the object ref as an integer and turning that into a color. object_ref_int = int(object_ref[:2], 16) color = self._chrome_tracing_colors[ object_ref_int % len(self._chrome_tracing_colors) ] new_event = { # The category of the event. "cat": event["event_type"], # The string displayed on the event. "name": event["event_type"], # The identifier for the group of rows that the event # appears in. "pid": node_id_to_address[key], # The identifier for the row that the event appears in. "tid": node_id_to_address[remote_node_id], # The start time in microseconds. "ts": self._nanoseconds_to_microseconds(event["start_time"]), # The duration in microseconds. "dur": self._nanoseconds_to_microseconds( event["end_time"] - event["start_time"] ), # What is this? "ph": "X", # This is the name of the color to display the box in. "cname": color, # The extra user-defined data. "args": event["extra_data"], } all_events.append(new_event) # Add another box with a color indicating whether it was a send # or a receive event. if event["event_type"] == "transfer_send": additional_event = new_event.copy() additional_event["cname"] = "black" all_events.append(additional_event) elif event["event_type"] == "transfer_receive": additional_event = new_event.copy() additional_event["cname"] = "grey" all_events.append(additional_event) else: pass if filename is not None: with open(filename, "w") as outfile: json.dump(all_events, outfile) else: return all_events def workers(self): """Get a dictionary mapping worker ID to worker information.""" accessor = self._connect_and_get_accessor() # Get all data in worker table worker_table = accessor.get_worker_table() workers_data = {} for i in range(len(worker_table)): worker_table_data = gcs_pb2.WorkerTableData.FromString(worker_table[i]) if ( worker_table_data.is_alive and worker_table_data.worker_type == common_pb2.WORKER ): worker_id = binary_to_hex(worker_table_data.worker_address.worker_id) worker_info = worker_table_data.worker_info workers_data[worker_id] = { "node_ip_address": decode(worker_info[b"node_ip_address"]), "plasma_store_socket": decode(worker_info[b"plasma_store_socket"]), } if b"stderr_file" in worker_info: workers_data[worker_id]["stderr_file"] = decode( worker_info[b"stderr_file"] ) if b"stdout_file" in worker_info: workers_data[worker_id]["stdout_file"] = decode( worker_info[b"stdout_file"] ) return workers_data def add_worker(self, worker_id, worker_type, worker_info): """Add a worker to the cluster. Args: worker_id: ID of this worker. Type is bytes. worker_type: Type of this worker. Value is common_pb2.DRIVER or common_pb2.WORKER. worker_info: Info of this worker. Type is dict{str: str}. Returns: Is operation success """ accessor = self._connect_and_get_accessor() worker_data = gcs_pb2.WorkerTableData() worker_data.is_alive = True worker_data.worker_address.worker_id = worker_id worker_data.worker_type = worker_type for k, v in worker_info.items(): worker_data.worker_info[k] = bytes(v, encoding="utf-8") return accessor.add_worker_info(worker_data.SerializeToString()) def update_worker_debugger_port(self, worker_id, debugger_port): """Update the debugger port of a worker. Args: worker_id: ID of this worker. Type is bytes. debugger_port: Port of the debugger. Type is int. Returns: Is operation success """ accessor = self._connect_and_get_accessor() assert worker_id is not None, "worker_id is not valid" assert ( debugger_port is not None and debugger_port > 0 ), "debugger_port is not valid" return accessor.update_worker_debugger_port(worker_id, debugger_port) def get_worker_debugger_port(self, worker_id): """Get the debugger port of a worker. Args: worker_id: ID of this worker. Type is bytes. Returns: Debugger port of the worker. """ accessor = self._connect_and_get_accessor() assert worker_id is not None, "worker_id is not valid" return accessor.get_worker_debugger_port(worker_id) def update_worker_num_paused_threads(self, worker_id, num_paused_threads_delta): """Updates the number of paused threads of a worker. Args: worker_id: ID of this worker. Type is bytes. num_paused_threads_delta: The delta of the number of paused threads. Returns: Is operation success """ accessor = self._connect_and_get_accessor() assert worker_id is not None, "worker_id is not valid" assert num_paused_threads_delta is not None, "worker_id is not valid" return accessor.update_worker_num_paused_threads( worker_id, num_paused_threads_delta ) def cluster_resources(self): """Get the current total cluster resources. Note that this information can grow stale as nodes are added to or removed from the cluster. Returns: A dictionary mapping resource name to the total quantity of that resource in the cluster. """ self._connect_and_get_accessor() # Calculate total resources. total_resources = defaultdict(int) for node_total_resources in self.total_resources_per_node().values(): for resource_id, value in node_total_resources.items(): total_resources[resource_id] += value return dict(total_resources) def _live_node_ids(self): """Returns a set of node IDs corresponding to nodes still alive.""" return set(self.total_resources_per_node().keys()) def available_resources_per_node(self): """Returns a dictionary mapping node id to available resources.""" accessor = self._connect_and_get_accessor() available_resources_by_id = {} all_available_resources = accessor.get_all_available_resources() for available_resource in all_available_resources: message = gcs_pb2.AvailableResources.FromString(available_resource) # Calculate available resources for this node. dynamic_resources = {} for resource_id, capacity in message.resources_available.items(): dynamic_resources[resource_id] = capacity # Update available resources for this node. node_id = ray._common.utils.binary_to_hex(message.node_id) available_resources_by_id[node_id] = dynamic_resources return available_resources_by_id # returns a dict that maps node_id(hex string) to a dict of {resource_id: capacity} def total_resources_per_node(self) -> Dict[str, Dict[str, int]]: accessor = self._connect_and_get_accessor() total_resources_by_node = {} all_total_resources = accessor.get_all_total_resources() for node_total_resources in all_total_resources: message = gcs_pb2.TotalResources.FromString(node_total_resources) # Calculate total resources for this node. node_resources = {} for resource_id, capacity in message.resources_total.items(): node_resources[resource_id] = capacity # Update total resources for this node. node_id = ray._common.utils.binary_to_hex(message.node_id) total_resources_by_node[node_id] = node_resources return total_resources_by_node def available_resources(self): """Get the current available cluster resources. This is different from `cluster_resources` in that this will return idle (available) resources rather than total resources. Note that this information can grow stale as tasks start and finish. Returns: A dictionary mapping resource name to the total quantity of that resource in the cluster. Note that if a resource (e.g., "CPU") is currently not available (i.e., quantity is 0), it will not be included in this dictionary. """ self._connect_and_get_accessor() available_resources_by_id = self.available_resources_per_node() # Calculate total available resources. total_available_resources = defaultdict(int) for available_resources in available_resources_by_id.values(): for resource_id, num_available in available_resources.items(): total_available_resources[resource_id] += num_available return dict(total_available_resources) def get_system_config(self): """Get the system config of the cluster.""" accessor = self._connect_and_get_accessor() return json.loads(accessor.get_system_config()) def get_node_to_connect_for_driver(self, node_ip_address): """Get the node to connect for a Ray driver.""" accessor = self._connect_and_get_accessor() return accessor.get_node_to_connect_for_driver(node_ip_address) def get_node(self, node_id: str): """Get the node information for a node id.""" accessor = self._connect_and_get_accessor() return accessor.get_node(node_id) def get_draining_nodes(self) -> Dict[str, int]: """Get all the hex ids of nodes that are being drained and the corresponding draining deadline timestamps in ms. There is no deadline if the timestamp is 0. """ accessor = self._connect_and_get_accessor() return accessor.get_draining_nodes() def get_cluster_config(self) -> autoscaler_pb2.ClusterConfig: """Get the cluster config of the current cluster.""" accessor = self._connect_and_get_accessor() serialized_cluster_config = accessor.get_internal_kv( ray._raylet.GCS_AUTOSCALER_STATE_NAMESPACE.encode(), ray._raylet.GCS_AUTOSCALER_CLUSTER_CONFIG_KEY.encode(), ) if serialized_cluster_config: return autoscaler_pb2.ClusterConfig.FromString(serialized_cluster_config) return None @staticmethod def _calculate_max_resource_from_cluster_config( cluster_config: Optional[autoscaler_pb2.ClusterConfig], key: str ) -> Optional[int]: """Calculate the maximum available resources for a given resource type from cluster config. If the resource type is not available, return None. """ if cluster_config is None: return None max_value = 0 for node_group_config in cluster_config.node_group_configs: num_resources = node_group_config.resources.get(key, default=0) num_nodes = node_group_config.max_count if num_nodes == 0 or num_resources == 0: continue if num_nodes == -1 or num_resources == -1: return sys.maxsize max_value += num_nodes * num_resources if max_value == 0: return None max_value_limit = cluster_config.max_resources.get(key, default=sys.maxsize) return min(max_value, max_value_limit) def get_max_resources_from_cluster_config(self) -> Optional[Dict[str, int]]: """Get the maximum available resources for all resource types from cluster config. Returns: A dictionary mapping resource name to the maximum quantity of that resource that could be available in the cluster based on the cluster config. Returns None if the config is not available. Values in the dictionary default to 0 if there is no such resource. """ all_resource_keys = set() config = self.get_cluster_config() if config is None: return None if config.node_group_configs: for node_group_config in config.node_group_configs: all_resource_keys.update(node_group_config.resources.keys()) if len(all_resource_keys) == 0: return None result = {} for key in all_resource_keys: max_value = self._calculate_max_resource_from_cluster_config(config, key) result[key] = max_value if max_value is not None else 0 return result def get_actor_info(self, actor_id: ray.ActorID) -> Optional[str]: """Get the actor info for a actor id.""" accessor = self._connect_and_get_accessor() return accessor.get_actor_info(actor_id) state = GlobalState() """A global object used to access the cluster's global state.""" def jobs(): """Get a list of the jobs in the cluster (for debugging only). Returns: Information from the job table, namely a list of dicts with keys: - "JobID" (identifier for the job), - "DriverIPAddress" (IP address of the driver for this job), - "DriverPid" (process ID of the driver for this job), - "StartTime" (UNIX timestamp of the start time of this job), - "StopTime" (UNIX timestamp of the stop time of this job, if any) """ return state.job_table() def next_job_id(): """Get next job id from GCS. Returns: Next job id in integer representation in the cluster. """ return state.next_job_id() @DeveloperAPI @client_mode_hook def nodes(): """Get a list of the nodes in the cluster (for debugging only). Returns: Information about the Ray clients in the cluster. """ return state.node_table() def workers(): """Get a list of the workers in the cluster. Returns: Information about the Ray workers in the cluster. """ return state.workers() def current_node_id(): """Return the node id of the current node. For example, "node:172.10.5.34". This can be used as a custom resource, e.g., {node_id: 1} to reserve the whole node, or {node_id: 0.001} to just force placement on the node. Returns: Id of the current node. """ return NODE_ID_PREFIX + ray.util.get_node_ip_address() def node_ids(): """Get a list of the node ids in the cluster. For example, ["node:172.10.5.34", "node:172.42.3.77"]. These can be used as custom resources, e.g., {node_id: 1} to reserve the whole node, or {node_id: 0.001} to just force placement on the node. Returns: List of the node resource ids. """ node_ids = [] for node_total_resources in state.total_resources_per_node().values(): for resource_id in node_total_resources.keys(): if ( resource_id.startswith(NODE_ID_PREFIX) and resource_id != HEAD_NODE_RESOURCE_NAME ): node_ids.append(resource_id) return node_ids def actors( actor_id: Optional[str] = None, job_id: Optional[ray.JobID] = None, actor_state_name: Optional[str] = None, ): """Fetch actor info for one or more actor IDs (for debugging only). Args: actor_id: A hex string of the actor ID to fetch information about. If this is None, then all actor information is fetched. If this is not None, `job_id` and `actor_state_name` will not take effect. job_id: To filter actors by job_id, which is of type `ray.JobID`. You can use the `ray.get_runtime_context().job_id` function to get the current job ID actor_state_name: To filter actors based on actor state, which can be one of the following: "DEPENDENCIES_UNREADY", "PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD". Returns: Information about the actors. """ return state.actor_table( actor_id=actor_id, job_id=job_id, actor_state_name=actor_state_name ) @DeveloperAPI @client_mode_hook def timeline(filename=None): """Return a list of profiling events that can viewed as a timeline. Ray profiling must be enabled by setting the RAY_PROFILING=1 environment variable prior to starting Ray, and set RAY_task_events_report_interval_ms=0 To view this information as a timeline, simply dump it as a json file by passing in "filename" or using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Args: filename: If a filename is provided, the timeline is dumped to that file. Returns: If filename is not provided, this returns a list of profiling events. Each profile event is a dictionary. """ return state.chrome_tracing_dump(filename=filename) def object_transfer_timeline(filename=None): """Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to enable "Flow events" in the "View Options" menu. Args: filename: If a filename is provided, the timeline is dumped to that file. Returns: If filename is not provided, this returns a list of profiling events. Each profile event is a dictionary. """ return state.chrome_tracing_object_transfer_dump(filename=filename) @DeveloperAPI @client_mode_hook def cluster_resources(): """Get the current total cluster resources. Note that this information can grow stale as nodes are added to or removed from the cluster. Returns: A dictionary mapping resource name to the total quantity of that resource in the cluster. """ return state.cluster_resources() @DeveloperAPI @client_mode_hook def available_resources(): """Get the current available cluster resources. This is different from `cluster_resources` in that this will return idle (available) resources rather than total resources. Note that this information can grow stale as tasks start and finish. Returns: A dictionary mapping resource name to the total quantity of that resource in the cluster. Note that if a resource (e.g., "CPU") is currently not available (i.e., quantity is 0), it will not be included in this dictionary. """ return state.available_resources() @DeveloperAPI def available_resources_per_node(): """Get the current available resources of each live node. Note that this information can grow stale as tasks start and finish. Returns: A dictionary mapping node hex id to available resources dictionary. """ return state.available_resources_per_node() @DeveloperAPI def total_resources_per_node(): """Get the current total resources of each live node. Note that this information can grow stale as tasks start and finish. Returns: A dictionary mapping node hex id to total resources dictionary. """ return state.total_resources_per_node() def update_worker_debugger_port(worker_id, debugger_port): """Update the debugger port of a worker. Args: worker_id: ID of this worker. Type is bytes. debugger_port: Port of the debugger. Type is int. Returns: Is operation success """ return state.update_worker_debugger_port(worker_id, debugger_port) def update_worker_num_paused_threads(worker_id, num_paused_threads_delta): """Update the number of paused threads of a worker. Args: worker_id: ID of this worker. Type is bytes. num_paused_threads_delta: The delta of the number of paused threads. Returns: Is operation success """ return state.update_worker_num_paused_threads(worker_id, num_paused_threads_delta) def get_worker_debugger_port(worker_id): """Get the debugger port of a worker. Args: worker_id: ID of this worker. Type is bytes. Returns: Debugger port of the worker. """ return state.get_worker_debugger_port(worker_id)
GlobalState
python
django__django
tests/delete_regress/tests.py
{ "start": 11926, "end": 14357 }
class ____(TestCase): def test_meta_ordered_delete(self): # When a subquery is performed by deletion code, the subquery must be # cleared of all ordering. There was a but that caused _meta ordering # to be used. Refs #19720. h = House.objects.create(address="Foo") OrderedPerson.objects.create(name="Jack", lives_in=h) OrderedPerson.objects.create(name="Bob", lives_in=h) OrderedPerson.objects.filter(lives_in__address="Foo").delete() self.assertEqual(OrderedPerson.objects.count(), 0) def test_foreign_key_delete_nullifies_correct_columns(self): """ With a model (Researcher) that has two foreign keys pointing to the same model (Contact), deleting an instance of the target model (contact1) nullifies the correct fields of Researcher. """ contact1 = Contact.objects.create(label="Contact 1") contact2 = Contact.objects.create(label="Contact 2") researcher1 = Researcher.objects.create( primary_contact=contact1, secondary_contact=contact2, ) researcher2 = Researcher.objects.create( primary_contact=contact2, secondary_contact=contact1, ) contact1.delete() researcher1.refresh_from_db() researcher2.refresh_from_db() self.assertIsNone(researcher1.primary_contact) self.assertEqual(researcher1.secondary_contact, contact2) self.assertEqual(researcher2.primary_contact, contact2) self.assertIsNone(researcher2.secondary_contact) def test_self_reference_with_through_m2m_at_second_level(self): toy = Toy.objects.create(name="Paints") child = Child.objects.create(name="Juan") Book.objects.create(pagecount=500, owner=child) PlayedWith.objects.create(child=child, toy=toy, date=datetime.date.today()) with self.assertNumQueries(1) as ctx: Book.objects.filter( Exists( Book.objects.filter( pk=OuterRef("pk"), owner__toys=toy.pk, ), ) ).delete() self.assertIs(Book.objects.exists(), False) sql = ctx.captured_queries[0]["sql"].lower() if connection.features.delete_can_self_reference_subquery: self.assertEqual(sql.count("select"), 1)
DeleteTests
python
readthedocs__readthedocs.org
readthedocs/core/migrations/0007_historicaluser.py
{ "start": 312, "end": 5030 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("core", "0006_remove_userprofile_allow_email"), ] operations = [ migrations.CreateModel( name="HistoricalUser", fields=[ ( "id", models.IntegerField( auto_created=True, blank=True, db_index=True, verbose_name="ID" ), ), ("password", models.CharField(max_length=128, verbose_name="password")), ( "last_login", models.DateTimeField(blank=True, null=True, verbose_name="last login"), ), ( "is_superuser", models.BooleanField( default=False, help_text="Designates that this user has all permissions without explicitly assigning them.", verbose_name="superuser status", ), ), ( "username", models.CharField( db_index=True, error_messages={"unique": "A user with that username already exists."}, help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.", max_length=150, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name="username", ), ), ( "first_name", models.CharField(blank=True, max_length=30, verbose_name="first name"), ), ( "last_name", models.CharField(blank=True, max_length=150, verbose_name="last name"), ), ( "email", models.EmailField(blank=True, max_length=254, verbose_name="email address"), ), ( "is_staff", models.BooleanField( default=False, help_text="Designates whether the user can log into this admin site.", verbose_name="staff status", ), ), ( "is_active", models.BooleanField( default=True, help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.", verbose_name="active", ), ), ( "date_joined", models.DateTimeField( default=django.utils.timezone.now, verbose_name="date joined" ), ), ( "extra_history_user_id", models.IntegerField(blank=True, db_index=True, null=True, verbose_name="ID"), ), ( "extra_history_user_username", models.CharField( db_index=True, max_length=150, null=True, verbose_name="username", ), ), ("history_id", models.AutoField(primary_key=True, serialize=False)), ("history_date", models.DateTimeField()), ("history_change_reason", models.CharField(max_length=100, null=True)), ( "history_type", models.CharField( choices=[("+", "Created"), ("~", "Changed"), ("-", "Deleted")], max_length=1, ), ), ( "history_user", models.ForeignKey( null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="+", to=settings.AUTH_USER_MODEL, ), ), ], options={ "verbose_name": "historical user", "ordering": ("-history_date", "-history_id"), "get_latest_by": "history_date", }, bases=(simple_history.models.HistoricalChanges, models.Model), ), ]
Migration
python
Pylons__pyramid
tests/test_urldispatch.py
{ "start": 1628, "end": 11197 }
class ____(unittest.TestCase): def setUp(self): testing.setUp() def tearDown(self): testing.tearDown() def _getRequest(self, **kw): from pyramid.threadlocal import get_current_registry request = DummyRequest(**kw) reg = get_current_registry() request.registry = reg return request def _getTargetClass(self): from pyramid.urldispatch import RoutesMapper return RoutesMapper def _makeOne(self): klass = self._getTargetClass() return klass() def test_provides_IRoutesMapper(self): from zope.interface.verify import verifyObject from pyramid.interfaces import IRoutesMapper verifyObject(IRoutesMapper, self._makeOne()) def test_no_route_matches(self): mapper = self._makeOne() request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['match'], None) self.assertEqual(result['route'], None) def test_connect_name_exists_removes_old(self): mapper = self._makeOne() mapper.connect('foo', 'archives/:action/:article') mapper.connect('foo', 'archives/:action/:article2') self.assertEqual(len(mapper.routelist), 1) self.assertEqual(len(mapper.routes), 1) self.assertEqual( mapper.routes['foo'].pattern, 'archives/:action/:article2' ) self.assertEqual( mapper.routelist[0].pattern, 'archives/:action/:article2' ) def test_connect_static(self): mapper = self._makeOne() mapper.connect('foo', 'archives/:action/:article', static=True) self.assertEqual(len(mapper.routelist), 0) self.assertEqual(len(mapper.routes), 1) self.assertEqual( mapper.routes['foo'].pattern, 'archives/:action/:article' ) def test_connect_static_overridden(self): mapper = self._makeOne() mapper.connect('foo', 'archives/:action/:article', static=True) self.assertEqual(len(mapper.routelist), 0) self.assertEqual(len(mapper.routes), 1) self.assertEqual( mapper.routes['foo'].pattern, 'archives/:action/:article' ) mapper.connect('foo', 'archives/:action/:article2') self.assertEqual(len(mapper.routelist), 1) self.assertEqual(len(mapper.routes), 1) self.assertEqual( mapper.routes['foo'].pattern, 'archives/:action/:article2' ) self.assertEqual( mapper.routelist[0].pattern, 'archives/:action/:article2' ) def test___call__pathinfo_cant_be_decoded(self): from pyramid.exceptions import URLDecodeError from pyramid.threadlocal import get_current_registry class DummyRequest: @property def path_info(self): return b'\xff\xfe\xe6\x00'.decode('utf-8') mapper = self._makeOne() request = DummyRequest() request.registry = get_current_registry() self.assertRaises(URLDecodeError, mapper, request) def test___call__pathinfo_KeyError(self): from pyramid.threadlocal import get_current_registry class DummyRequest: @property def path_info(self): # if the PATH_INFO is missing from the environ raise KeyError mapper = self._makeOne() mapper.connect('root', '') request = DummyRequest() request.registry = get_current_registry() result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) def test___call__route_matches(self): mapper = self._makeOne() mapper.connect('foo', 'archives/:action/:article') request = self._getRequest(path_info='/archives/action1/article1') result = mapper(request) self.assertEqual(result['route'], mapper.routes['foo']) self.assertEqual(result['match']['action'], 'action1') self.assertEqual(result['match']['article'], 'article1') def test___call__route_matches_with_predicates(self): mapper = self._makeOne() mapper.connect( 'foo', 'archives/:action/:article', predicates=[lambda *arg: True] ) request = self._getRequest(path_info='/archives/action1/article1') result = mapper(request) self.assertEqual(result['route'], mapper.routes['foo']) self.assertEqual(result['match']['action'], 'action1') self.assertEqual(result['match']['article'], 'article1') def test___call__route_fails_to_match_with_predicates(self): mapper = self._makeOne() mapper.connect( 'foo', 'archives/:action/article1', predicates=[lambda *arg: True, lambda *arg: False], ) mapper.connect('bar', 'archives/:action/:article') request = self._getRequest(path_info='/archives/action1/article1') result = mapper(request) self.assertEqual(result['route'], mapper.routes['bar']) self.assertEqual(result['match']['action'], 'action1') self.assertEqual(result['match']['article'], 'article1') def test___call__custom_predicate_gets_info(self): mapper = self._makeOne() def pred(info, request): self.assertEqual(info['match'], {'action': 'action1'}) self.assertEqual(info['route'], mapper.routes['foo']) return True mapper.connect('foo', 'archives/:action/article1', predicates=[pred]) request = self._getRequest(path_info='/archives/action1/article1') mapper(request) def test_cc_bug(self): # "unordered" as reported in IRC by author of # http://labs.creativecommons.org/2010/01/13/cc-engine-and-web-non-frameworks/ mapper = self._makeOne() mapper.connect('rdf', 'licenses/:license_code/:license_version/rdf') mapper.connect( 'juri', 'licenses/:license_code/:license_version/:jurisdiction' ) request = self._getRequest(path_info='/licenses/1/v2/rdf') result = mapper(request) self.assertEqual(result['route'], mapper.routes['rdf']) self.assertEqual(result['match']['license_code'], '1') self.assertEqual(result['match']['license_version'], 'v2') request = self._getRequest(path_info='/licenses/1/v2/usa') result = mapper(request) self.assertEqual(result['route'], mapper.routes['juri']) self.assertEqual(result['match']['license_code'], '1') self.assertEqual(result['match']['license_version'], 'v2') self.assertEqual(result['match']['jurisdiction'], 'usa') def test___call__root_route_matches(self): mapper = self._makeOne() mapper.connect('root', '') request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) def test___call__root_route_matches2(self): mapper = self._makeOne() mapper.connect('root', '/') request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) def test___call__root_route_when_path_info_empty(self): mapper = self._makeOne() mapper.connect('root', '/') request = self._getRequest(path_info='') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) def test___call__root_route_when_path_info_notempty(self): mapper = self._makeOne() mapper.connect('root', '/') request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) def test___call__no_path_info(self): mapper = self._makeOne() mapper.connect('root', '/') request = self._getRequest(path_info='') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) def test_has_routes(self): mapper = self._makeOne() self.assertEqual(mapper.has_routes(), False) mapper.connect('whatever', 'archives/:action/:article') self.assertEqual(mapper.has_routes(), True) def test_get_routes(self): from pyramid.urldispatch import Route mapper = self._makeOne() self.assertEqual(mapper.get_routes(), []) mapper.connect('whatever', 'archives/:action/:article') routes = mapper.get_routes() self.assertEqual(len(routes), 1) self.assertEqual(routes[0].__class__, Route) def test_get_route_matches(self): mapper = self._makeOne() mapper.connect('whatever', 'archives/:action/:article') result = mapper.get_route('whatever') self.assertEqual(result.pattern, 'archives/:action/:article') def test_get_route_misses(self): mapper = self._makeOne() result = mapper.get_route('whatever') self.assertEqual(result, None) def test_generate(self): mapper = self._makeOne() def generator(kw): return 123 route = DummyRoute(generator) mapper.routes['abc'] = route self.assertEqual(mapper.generate('abc', {}), 123)
RoutesMapperTests
python
conda__conda
conda/models/enums.py
{ "start": 3477, "end": 4670 }
class ____(Enum): generic = "generic" python = "python" @staticmethod def coerce(val): # what a mess if isinstance(val, NoarchType): return val valtype = getattr(val, "type", None) if isinstance(valtype, NoarchType): # see issue #8311 return valtype if isinstance(val, bool): val = NoarchType.generic if val else None if isinstance(val, str): val = val.lower() if val == "python": val = NoarchType.python elif val == "generic": val = NoarchType.generic else: try: val = NoarchType.generic if boolify(val, nullable=True) else None except TypeCoercionError: raise CondaUpgradeError( dals( f""" The noarch type for this package is set to '{val}'. The current version of conda is too old to install this package. Please update conda. """ ) ) return val
NoarchType
python
bokeh__bokeh
tests/unit/bokeh/plotting/test__stack.py
{ "start": 4766, "end": 9021 }
class ____: def test_raises_when_spec_in_kwargs(self) -> None: with pytest.raises(ValueError) as e: bps.double_stack(['a', 'b'], 'foo', 'bar', foo=10) assert str(e.value).endswith("Stack property 'foo' cannot appear in keyword args") with pytest.raises(ValueError) as e: bps.double_stack(['a', 'b'], 'foo', 'bar', bar=10) assert str(e.value).endswith("Stack property 'bar' cannot appear in keyword args") def test_raises_when_kwargs_list_lengths_differ(self) -> None: with pytest.raises(ValueError) as e: bps.double_stack(['a', 'b'], 'foo', 'bar', baz=[1, 2], quux=[3,4,5]) assert str(e.value).endswith("Keyword argument sequences for broadcasting must all be the same lengths. Got lengths: [2, 3]") def test_raises_when_kwargs_list_lengths_and_stackers_lengths_differ(self) -> None: with pytest.raises(ValueError) as e: bps.double_stack(['a', 'b', 'c'], 'foo', 'bar', baz=[1, 2], quux=[3,4]) assert str(e.value).endswith("Keyword argument sequences for broadcasting must be the same length as stackers") def test_broadcast_with_no_kwargs(self) -> None: stackers = ['a', 'b', 'c', 'd'] kws = bps.double_stack(stackers, 'start', 'end') assert len(kws) == len(stackers) for i, kw in enumerate(kws): assert {"start", "end", "name"} == set(kw.keys()) assert list(kw["start"]["expr"].fields) == stackers[:i] assert list(kw["end"]["expr"].fields) == stackers[: (i + 1)] def test_broadcast_with_scalar_kwargs(self) -> None: stackers = ['a', 'b', 'c', 'd'] kws = bps.double_stack(stackers, 'start', 'end', foo=10, bar="baz") assert len(kws) == len(stackers) for i, kw in enumerate(kws): assert {"start", "end", "foo", "bar", "name"} == set(kw.keys()) assert list(kw["start"]["expr"].fields) == stackers[:i] assert list(kw["end"]["expr"].fields) == stackers[: (i + 1)] assert kw["foo"] == 10 assert kw["bar"] == "baz" assert kw["name"] == stackers[i] def test_broadcast_with_list_kwargs(self) -> None: stackers = ['a', 'b', 'c', 'd'] kws = bps.double_stack(stackers, 'start', 'end', foo=[10, 20, 30, 40], bar="baz") assert len(kws) == len(stackers) for i, kw in enumerate(kws): assert {"start", "end", "foo", "bar", "name"} == set(kw.keys()) assert list(kw["start"]["expr"].fields) == stackers[:i] assert list(kw["end"]["expr"].fields) == stackers[: (i + 1)] assert kw["foo"] == [10, 20, 30, 40][i] assert kw["bar"] == "baz" assert kw["name"] == stackers[i] def test_broadcast_name_scalar_overrides(self) -> None: stackers = ['a', 'b', 'c', 'd'] kws = bps.double_stack(stackers, 'start', 'end', foo=[10, 20, 30, 40], bar="baz", name="name") assert len(kws) == len(stackers) for i, kw in enumerate(kws): assert {"start", "end", "foo", "bar", "name"} == set(kw.keys()) assert list(kw["start"]["expr"].fields) == stackers[:i] assert list(kw["end"]["expr"].fields) == stackers[: (i + 1)] assert kw["foo"] == [10, 20, 30, 40][i] assert kw["bar"] == "baz" assert kw["name"] == "name" def test_broadcast_name_list_overrides(self) -> None: names = ["aa", "bb", "cc", "dd"] stackers = ['a', 'b', 'c', 'd'] kws = bps.double_stack(stackers, 'start', 'end', foo=[10, 20, 30, 40], bar="baz", name=names) assert len(kws) == len(stackers) for i, kw in enumerate(kws): assert {"start", "end", "foo", "bar", "name"} == set(kw.keys()) assert list(kw["start"]["expr"].fields) == stackers[:i] assert list(kw["end"]["expr"].fields) == stackers[: (i + 1)] assert kw["foo"] == [10, 20, 30, 40][i] assert kw["bar"] == "baz" assert kw["name"] == names[i] #----------------------------------------------------------------------------- # Private API #-----------------------------------------------------------------------------
Test_double_stack
python
huggingface__transformers
src/transformers/models/longcat_flash/modeling_longcat_flash.py
{ "start": 28611, "end": 31854 }
class ____(LongcatFlashPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} _keys_to_ignore_on_load_unexpected = [r"model\.mtp.*"] def __init__(self, config): super().__init__(config) self.model = LongcatFlashModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" Example: ```python >>> from transformers import AutoTokenizer, LongcatFlashForCausalLM >>> model = LongcatFlashForCausalLM.from_pretrained("meta-longcat_flash/LongcatFlash-2-7b-hf") >>> tokenizer = AutoTokenizer.from_pretrained("meta-longcat_flash/LongcatFlash-2-7b-hf") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = ["LongcatFlashPreTrainedModel", "LongcatFlashModel", "LongcatFlashForCausalLM"]
LongcatFlashForCausalLM
python
huggingface__transformers
src/transformers/models/convnext/modeling_convnext.py
{ "start": 6756, "end": 8227 }
class ____(nn.Module): """ConvNeXT stage, consisting of an optional downsampling layer + multiple residual blocks. Args: config ([`ConvNextConfig`]): Model configuration class. in_channels (`int`): Number of input channels. out_channels (`int`): Number of output channels. depth (`int`): Number of residual blocks. drop_path_rates(`list[float]`): Stochastic depth rates for each layer. """ def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None): super().__init__() if in_channels != out_channels or stride > 1: self.downsampling_layer = nn.ModuleList( [ ConvNextLayerNorm(in_channels, eps=1e-6, data_format="channels_first"), nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride), ] ) else: self.downsampling_layer = nn.ModuleList() drop_path_rates = drop_path_rates or [0.0] * depth self.layers = nn.ModuleList( [ConvNextLayer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)] ) def forward(self, features: torch.Tensor) -> torch.Tensor: for layer in self.downsampling_layer: features = layer(features) for layer in self.layers: features = layer(features) return features
ConvNextStage
python
pytorch__pytorch
test/inductor/test_pallas.py
{ "start": 22570, "end": 23669 }
class ____(PallasTestsMixin, TestCase): DEVICE = "cpu" @mock.patch("torch._inductor.codegen.pallas.has_tpu_pallas", return_value=False) def test_tpu_not_available_raises_error(self, mock_has_tpu_pallas): def fn(a, b): return a + b with self.assertRaisesRegex( RuntimeError, ( "PALLAS_TARGET_TPU is set, but no TPU device was found. " "Please make sure that you have a TPU available and that JAX is configured correctly." ), ): torch.compile(fn, backend="inductor", options={"cpu_backend": "pallas"})( torch.randn(16), torch.randn(16) ) if test_torchinductor.HAS_CPU and HAS_PALLAS: make_pallas(test_torchinductor.SweepInputsCpuTest) # make_pallas(test_torchinductor.CpuTests) if test_torchinductor.HAS_GPU and HAS_PALLAS: # make_pallas(test_torchinductor.SweepInputsGPUTest) # make_pallas(test_torchinductor.GPUTests) pass if __name__ == "__main__": if HAS_PALLAS: run_tests(needs="filelock")
PallasTestsTPU
python
scipy__scipy
scipy/stats/tests/test_generation/reference_distributions.py
{ "start": 14006, "end": 14095 }
class ____(ReferenceDistribution): def _pdf(self, x): return mp.npdf(x)
Normal
python
eriklindernoren__ML-From-Scratch
mlfromscratch/unsupervised_learning/generative_adversarial_network.py
{ "start": 495, "end": 5842 }
class ____(): """A Generative Adversarial Network with deep fully-connected neural nets as Generator and Discriminator. Training Data: MNIST Handwritten Digits (28x28 images) """ def __init__(self): self.img_rows = 28 self.img_cols = 28 self.img_dim = self.img_rows * self.img_cols self.latent_dim = 100 optimizer = Adam(learning_rate=0.0002, b1=0.5) loss_function = CrossEntropy # Build the discriminator self.discriminator = self.build_discriminator(optimizer, loss_function) # Build the generator self.generator = self.build_generator(optimizer, loss_function) # Build the combined model self.combined = NeuralNetwork(optimizer=optimizer, loss=loss_function) self.combined.layers.extend(self.generator.layers) self.combined.layers.extend(self.discriminator.layers) print () self.generator.summary(name="Generator") self.discriminator.summary(name="Discriminator") def build_generator(self, optimizer, loss_function): model = NeuralNetwork(optimizer=optimizer, loss=loss_function) model.add(Dense(256, input_shape=(self.latent_dim,))) model.add(Activation('leaky_relu')) model.add(BatchNormalization(momentum=0.8)) model.add(Dense(512)) model.add(Activation('leaky_relu')) model.add(BatchNormalization(momentum=0.8)) model.add(Dense(1024)) model.add(Activation('leaky_relu')) model.add(BatchNormalization(momentum=0.8)) model.add(Dense(self.img_dim)) model.add(Activation('tanh')) return model def build_discriminator(self, optimizer, loss_function): model = NeuralNetwork(optimizer=optimizer, loss=loss_function) model.add(Dense(512, input_shape=(self.img_dim,))) model.add(Activation('leaky_relu')) model.add(Dropout(0.5)) model.add(Dense(256)) model.add(Activation('leaky_relu')) model.add(Dropout(0.5)) model.add(Dense(2)) model.add(Activation('softmax')) return model def train(self, n_epochs, batch_size=128, save_interval=50): mnist = fetch_mldata('MNIST original') X = mnist.data y = mnist.target # Rescale [-1, 1] X = (X.astype(np.float32) - 127.5) / 127.5 half_batch = int(batch_size / 2) for epoch in range(n_epochs): # --------------------- # Train Discriminator # --------------------- self.discriminator.set_trainable(True) # Select a random half batch of images idx = np.random.randint(0, X.shape[0], half_batch) imgs = X[idx] # Sample noise to use as generator input noise = np.random.normal(0, 1, (half_batch, self.latent_dim)) # Generate a half batch of images gen_imgs = self.generator.predict(noise) # Valid = [1, 0], Fake = [0, 1] valid = np.concatenate((np.ones((half_batch, 1)), np.zeros((half_batch, 1))), axis=1) fake = np.concatenate((np.zeros((half_batch, 1)), np.ones((half_batch, 1))), axis=1) # Train the discriminator d_loss_real, d_acc_real = self.discriminator.train_on_batch(imgs, valid) d_loss_fake, d_acc_fake = self.discriminator.train_on_batch(gen_imgs, fake) d_loss = 0.5 * (d_loss_real + d_loss_fake) d_acc = 0.5 * (d_acc_real + d_acc_fake) # --------------------- # Train Generator # --------------------- # We only want to train the generator for the combined model self.discriminator.set_trainable(False) # Sample noise and use as generator input noise = np.random.normal(0, 1, (batch_size, self.latent_dim)) # The generator wants the discriminator to label the generated samples as valid valid = np.concatenate((np.ones((batch_size, 1)), np.zeros((batch_size, 1))), axis=1) # Train the generator g_loss, g_acc = self.combined.train_on_batch(noise, valid) # Display the progress print ("%d [D loss: %f, acc: %.2f%%] [G loss: %f, acc: %.2f%%]" % (epoch, d_loss, 100*d_acc, g_loss, 100*g_acc)) # If at save interval => save generated image samples if epoch % save_interval == 0: self.save_imgs(epoch) def save_imgs(self, epoch): r, c = 5, 5 # Grid size noise = np.random.normal(0, 1, (r * c, self.latent_dim)) # Generate images and reshape to image shape gen_imgs = self.generator.predict(noise).reshape((-1, self.img_rows, self.img_cols)) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(r, c) plt.suptitle("Generative Adversarial Network") cnt = 0 for i in range(r): for j in range(c): axs[i,j].imshow(gen_imgs[cnt,:,:], cmap='gray') axs[i,j].axis('off') cnt += 1 fig.savefig("mnist_%d.png" % epoch) plt.close() if __name__ == '__main__': gan = GAN() gan.train(n_epochs=200000, batch_size=64, save_interval=400)
GAN
python
sympy__sympy
sympy/printing/codeprinter.py
{ "start": 549, "end": 966 }
class ____: """ Decorator for registering requirements on print methods. """ def __init__(self, **kwargs): self._req = kwargs def __call__(self, method): def _method_wrapper(self_, *args, **kwargs): for k, v in self._req.items(): getattr(self_, k).update(v) return method(self_, *args, **kwargs) return wraps(method)(_method_wrapper)
requires
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 32622, "end": 33027 }
class ____(unittest.TestCase): """Test az_AZ date_time provider methods""" def setUp(self): self.fake = Faker("az_AZ") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in AzAzProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in AzAzProvider.MONTH_NAMES.values()
TestAzAz
python
joke2k__faker
tests/providers/test_internet.py
{ "start": 32817, "end": 33282 }
class ____: """Test ro_RO internet provider methods""" def test_free_email_domain(self, faker): domain = faker.free_email_domain() assert domain in RoRoInternetProvider.free_email_domains def test_tld(self, faker): tld = faker.tld() assert tld in PlPlInternetProvider.tlds def test_slug(self, faker): num_of_samples = 100 for _ in range(num_of_samples): assert faker.slug() != ""
TestRoRo
python
pytorch__pytorch
torch/onnx/_internal/exporter/_onnx_program.py
{ "start": 6655, "end": 18565 }
class ____: """A class to represent an ONNX program that is callable with torch tensors. Attributes: model: The ONNX model as an ONNX IR model object. exported_program: The exported program that produced the ONNX model. """ def __init__( self, model: ir.Model, exported_program: torch.export.ExportedProgram | None ) -> None: """Initialize the ONNX program with the specified model and exported program. Args: model: The ONNX model. exported_program: The exported program that produced the ONNX model. Optional. """ self.model: ir.Model = model self.exported_program = exported_program self._inference_session: ort.InferenceSession | None = None self._tempdir: tempfile.TemporaryDirectory | None = None # Strategy used to capture the exported program self._capture_strategy: str | None = None def __repr__(self) -> str: return f"""\ ONNXProgram( model= {textwrap.indent(str(self.model), " " * 8)} , exported_program= {textwrap.indent(str(self.exported_program), " " * 8)} ) """ def __call__(self, *args, **kwargs) -> Sequence[torch.Tensor]: """Run the ONNX model with the same arguments you would provide to the GraphModule.""" import onnxruntime as ort flatten_args = _process_args(args, kwargs) if self._inference_session is None: self.initialize_inference_session() assert self._inference_session is not None ort_input = { k.name: _to_ort_value(v) for k, v in zip(self.model.graph.inputs, flatten_args) } run_options = ort.RunOptions() run_options.log_severity_level = 3 # 3: Error logger.debug("Running the inference session with %s arguments.", len(ort_input)) # pyrefly: ignore [missing-attribute] outputs = self._inference_session.run_with_ort_values( None, ort_input, run_options=run_options ) logger.debug("Inference session run completed.") return tuple(_from_ort_value(output) for output in outputs) def call_reference(self, *args, **kwargs) -> Sequence[torch.Tensor]: """Run the ONNX model using the reference backend.""" import onnx.reference evaluator = onnx.reference.ReferenceEvaluator(self.model_proto) flatten_args = _process_args(args, kwargs) ref_input = { k.name: _to_numpy_array(v) for k, v in zip(self.model.graph.inputs, flatten_args) } outputs = evaluator.run(None, ref_input) # type: ignore[arg-type] assert isinstance(outputs, Sequence) return tuple(_from_numpy_array(output) for output in outputs) def compute_values( self, value_names: Sequence[str], args=(), kwargs=None ) -> Sequence[torch.Tensor]: """Compute the values of the specified names in the ONNX model. This method is used to compute the values of the specified names in the ONNX model. The values are returned as a dictionary mapping names to tensors. Args: value_names: The names of the values to compute. Returns: A dictionary mapping names to tensors. """ if kwargs is None: kwargs = {} self.release() values = _create_value_mapping(self.model.graph) for name in value_names: if name not in values: raise ValueError( f"Value '{name}' not found in the model. " "Please provide a valid value name." ) temporary_outputs = [values[name] for name in value_names] with _set_graph_outputs(self.model.graph, temporary_outputs): try: result = self(*args, **kwargs) finally: self.release() return result @property def model_proto(self) -> onnx.ModelProto: """Return the ONNX ``ModelProto`` object.""" return ir.serde.serialize_model(self.model) def optimize(self) -> None: """Optimize the ONNX model. This method optimizes the ONNX model by performing constant folding and eliminating redundancies in the graph. The optimization is done in-place. """ self.model = onnxscript_apis.optimize(self.model) def save( self, destination: str | os.PathLike, *, include_initializers: bool = True, keep_initializers_as_inputs: bool = False, external_data: bool | None = None, ) -> None: """Save the ONNX model to the specified destination. When ``external_data`` is ``True`` or the model is larger than 2GB, the weights are saved as external data in a separate file. Initializer (model weights) serialization behaviors: * ``include_initializers=True``, ``keep_initializers_as_inputs=False`` (default): The initializers are included in the saved model. * ``include_initializers=True``, ``keep_initializers_as_inputs=True``: The initializers are included in the saved model and kept as model inputs. Choose this option if you want the ability to override the model weights during inference. * ``include_initializers=False``, ``keep_initializers_as_inputs=False``: The initializers are not included in the saved model and are not listed as model inputs. Choose this option if you want to attach the initializers to the ONNX model in a separate, post-processing, step. * ``include_initializers=False``, ``keep_initializers_as_inputs=True``: The initializers are not included in the saved model but are listed as model inputs. Choose this option if you want to supply the initializers during inference and want to minimize the size of the saved model. Args: destination: The path to save the ONNX model to. include_initializers: Whether to include the initializers in the saved model. keep_initializers_as_inputs: Whether to keep the initializers as inputs in the saved model. If `True`, the initializers are added as inputs to the model which means they can be overwritten. by providing the initializers as model inputs. external_data: Whether to save the weights as external data in a separate file. Raises: TypeError: If ``external_data`` is ``True`` and ``destination`` is not a file path. """ original_initializers = copy.copy(self.model.graph.initializers) original_inputs = copy.copy(self.model.graph.inputs) # Adjust the model based on options if not include_initializers: self.model.graph.initializers.clear() if keep_initializers_as_inputs: self.model.graph.inputs.extend(original_initializers.values()) # type: ignore[arg-type] try: # Save the model to disk if ( external_data or _count_initializer_size(self.model.graph) > _LARGE_MODEL_THRESHOLD ): onnxscript_apis.save_model_with_external_data(self.model, destination) else: ir.save(self.model, destination) finally: # Revert the changes to the model if not include_initializers: self.model.graph.initializers.update(original_initializers) if keep_initializers_as_inputs: self.model.graph.inputs.clear() self.model.graph.inputs.extend(original_inputs) def apply_weights(self, state_dict: dict[str, torch.Tensor]) -> None: """Apply the weights from the specified state dict to the ONNX model. Use this method to replace FakeTensors or other weights. Args: state_dict: The state dict containing the weights to apply to the ONNX model. """ from torch.onnx._internal.exporter import _core for name, tensor in state_dict.items(): if name in self.model.graph.initializers: self.model.graph.initializers[name].const_value = _core.TorchTensor( tensor, name ) else: warnings.warn( f"Weight '{name}' not found in the model. Skipped applying.", category=torch.onnx.errors.OnnxExporterWarning, stacklevel=1, ) def initialize_inference_session( self, initializer: Callable[ [str | bytes], ort.InferenceSession ] = _ort_session_initializer, ) -> None: """Initialize the ONNX Runtime inference session. Args: initializer: The function to initialize the ONNX Runtime inference session with the specified model. By default, it uses the :func:`_ort_session_initializer` function. """ # TODO(justinchuby): Allow different inference options logger.debug("Initializing the inference session.") if ( byte_size := _count_initializer_size(self.model.graph) ) > _LARGE_MODEL_THRESHOLD: logger.debug("The model initializers is larger than 1.5GB (%s).", byte_size) # Save the model to a temporary file if too large self._tempdir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) model_path = os.path.join(self._tempdir.name, "model.onnx") self.save(model_path, external_data=True) model = model_path else: model = self.model_proto.SerializeToString() # type: ignore[assignment] self._inference_session = initializer(model) logger.debug("Inference session initialized.") def release(self) -> None: """Release the inference session. You may call this method to release the resources used by the inference session. """ # Release the inference session first so that the model file can be deleted if self._inference_session is not None: self._inference_session = None gc.collect() if self._tempdir is not None: self._tempdir.cleanup() self._tempdir = None def _rename_dynamic_axes( self, dynamic_shapes: dict[str, Any] | tuple[Any, ...] | list[Any], ) -> None: """Rename dynamic axes in a model according to the specified dynamic_axes names.""" rename_mapping = _dynamic_shapes.create_rename_mapping( self.model.graph.inputs, dynamic_shapes ) _ir_passes.rename_axis(self.model, rename_mapping) def _process_args(args, kwargs) -> tuple[torch.Tensor, ...]: """Process input arguments for the ONNX model.""" args = _flatten_inputs(args, kwargs) args = _remove_none_from_inputs(args) args = _convert_complex_to_real_representation(args) return args def _flatten_inputs(model_args, model_kwargs): flattened_args, _ = _pytree.tree_flatten((model_args, model_kwargs)) return flattened_args def _remove_none_from_inputs(model_args): return tuple(arg for arg in model_args if arg is not None) def _convert_complex_to_real_representation(model_args): """Convert complex dtype tensors to real representation tensors. ONNX does not support complex dtype tensors. Thus, we convert complex dtype tensors to real representation tensors (i.e., float dtype tensors with an extra dimension representing the real and imaginary parts of the complex number). """ return tuple( torch.view_as_real(arg.resolve_conj()) if isinstance(arg, torch.Tensor) and arg.is_complex() else arg for arg in model_args )
ONNXProgram
python
pytorch__pytorch
torch/_inductor/codegen/triton.py
{ "start": 9340, "end": 10338 }
class ____: index_str: str mask_vars: OrderedSet[str] expand_str: Optional[str] _has_rindex: bool index: sympy.Expr expand_shape: Optional[Sequence[Union[int, str]]] def has_mask(self) -> bool: return bool(self.mask_vars) def has_indirect(self) -> bool: return free_symbol_is_type(self.index, SymT.TMP) def has_rindex(self) -> bool: return self._has_rindex def has_tmpmask(self) -> bool: return any(str(mask).startswith("tmp") for mask in self.mask_vars) def has_rmask(self) -> bool: return any(str(mask).startswith("r") for mask in self.mask_vars) @property def mask_str(self) -> str: # The sorted call is added to make sure the order is still # deterministic if self.mask_vars contains mix of string # and TritonCSEVariable return ( " & ".join(sorted(map(str, self.mask_vars))) if self.mask_vars else "None" ) @dataclasses.dataclass
IndexingOptions
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py
{ "start": 12087, "end": 12561 }
class ____(nn.Module): def __init__(self, config: Dinov2WithRegistersConfig): super().__init__() self.attention = Dinov2WithRegistersSelfAttention(config) self.output = Dinov2WithRegistersSelfOutput(config) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: self_attn_output, _ = self.attention(hidden_states) output = self.output(self_attn_output, hidden_states) return output
Dinov2WithRegistersAttention
python
dask__distributed
distributed/client.py
{ "start": 26825, "end": 197629 }
class ____(SyncMethodMixin): """Connect to and submit computation to a Dask cluster The Client connects users to a Dask cluster. It provides an asynchronous user interface around functions and futures. This class resembles executors in ``concurrent.futures`` but also allows ``Future`` objects within ``submit/map`` calls. When a Client is instantiated it takes over all ``dask.compute`` and ``dask.persist`` calls by default. It is also common to create a Client without specifying the scheduler address , like ``Client()``. In this case the Client creates a :class:`LocalCluster` in the background and connects to that. Any extra keywords are passed from Client to LocalCluster in this case. See the LocalCluster documentation for more information. Parameters ---------- address: string, or Cluster This can be the address of a ``Scheduler`` server like a string ``'127.0.0.1:8786'`` or a cluster object like ``LocalCluster()`` loop The event loop timeout: int (defaults to configuration ``distributed.comm.timeouts.connect``) Timeout duration for initial connection to the scheduler set_as_default: bool (True) Use this Client as the global dask scheduler scheduler_file: string (optional) Path to a file with scheduler information if available security: Security or bool, optional Optional security information. If creating a local cluster can also pass in ``True``, in which case temporary self-signed credentials will be created automatically. asynchronous: bool (False by default) Set to True if using this client within async/await functions or within Tornado gen.coroutines. Otherwise this should remain False for normal use. name: string (optional) Gives the client a name that will be included in logs generated on the scheduler for matters relating to this client heartbeat_interval: int (optional) Time in milliseconds between heartbeats to scheduler serializers Iterable of approaches to use when serializing the object. See :ref:`serialization` for more. deserializers Iterable of approaches to use when deserializing the object. See :ref:`serialization` for more. extensions : list The extensions direct_to_workers: bool (optional) Whether or not to connect directly to the workers, or to ask the scheduler to serve as intermediary. connection_limit : int The number of open comms to maintain at once in the connection pool **kwargs: If you do not pass a scheduler address, Client will create a ``LocalCluster`` object, passing any extra keyword arguments. Examples -------- Provide cluster's scheduler node address on initialization: >>> client = Client('127.0.0.1:8786') # doctest: +SKIP Use ``submit`` method to send individual computations to the cluster >>> a = client.submit(add, 1, 2) # doctest: +SKIP >>> b = client.submit(add, 10, 20) # doctest: +SKIP Continue using submit or map on results to build up larger computations >>> c = client.submit(add, a, b) # doctest: +SKIP Gather results with the ``gather`` method. >>> client.gather(c) # doctest: +SKIP 33 You can also call Client with no arguments in order to create your own local cluster. >>> client = Client() # makes your own local "cluster" # doctest: +SKIP Extra keywords will be passed directly to LocalCluster >>> client = Client(n_workers=2, threads_per_worker=4) # doctest: +SKIP See Also -------- distributed.scheduler.Scheduler: Internal scheduler distributed.LocalCluster: """ _is_finalizing: staticmethod[[], bool] = staticmethod(sys.is_finalizing) _instances: ClassVar[weakref.WeakSet[Client]] = weakref.WeakSet() _default_event_handlers = {"print": _handle_print, "warn": _handle_warn} preloads: preloading.PreloadManager __loop: IOLoop | None = None def __init__( self, address=None, loop=None, timeout=no_default, set_as_default=True, scheduler_file=None, security=None, asynchronous=False, name=None, heartbeat_interval=None, serializers=None, deserializers=None, extensions=DEFAULT_EXTENSIONS, direct_to_workers=None, connection_limit=512, **kwargs, ): if timeout is no_default: timeout = dask.config.get("distributed.comm.timeouts.connect") timeout = parse_timedelta(timeout, "s") if timeout is None: raise ValueError("None is an invalid value for global client timeout") self._timeout = timeout self.futures = dict() self.refcount = defaultdict(int) self._handle_report_task = None if name is None: name = dask.config.get("client-name", None) self.id = ( type(self).__name__ + ("-" + name + "-" if name else "-") + str(uuid.uuid1(clock_seq=os.getpid())) ) self.generation = 0 self.status = "newly-created" self._pending_msg_buffer = [] self.extensions = {} self.scheduler_file = scheduler_file self._startup_kwargs = kwargs self.cluster = None self.scheduler = None self._scheduler_identity = {} # A reentrant-lock on the refcounts for futures associated with this # client. Should be held by individual operations modifying refcounts, # or any bulk operation that needs to ensure the set of futures doesn't # change during operation. self._refcount_lock = threading.RLock() self.datasets = Datasets(self) self._serializers = serializers if deserializers is None: deserializers = serializers self._deserializers = deserializers if direct_to_workers is None: direct_to_workers = dask.config.get("distributed.client.direct-to-workers") self.direct_to_workers = direct_to_workers self._previous_as_current = None # Communication self.scheduler_comm = None if address is None: address = dask.config.get("scheduler-address", None) if address: logger.info("Config value `scheduler-address` found: %s", address) if address is not None and kwargs: raise ValueError(f"Unexpected keyword arguments: {sorted(kwargs)}") if isinstance(address, (rpc, PooledRPCCall)): self.scheduler = address elif isinstance(getattr(address, "scheduler_address", None), str): # It's a LocalCluster or LocalCluster-compatible object self.cluster = address status = self.cluster.status if status in (Status.closed, Status.closing): raise RuntimeError( f"Trying to connect to an already closed or closing Cluster {self.cluster}." ) with suppress(AttributeError): loop = address.loop if security is None: security = getattr(self.cluster, "security", None) elif address is not None and not isinstance(address, str): raise TypeError( f"Scheduler address must be a string or a Cluster instance, got {type(address)}" ) # If connecting to an address and no explicit security is configured, attempt # to load security credentials with a security loader (if configured). if security is None and isinstance(address, str): security = _maybe_call_security_loader(address) if security is None or security is False: security = Security() elif isinstance(security, dict): security = Security(**security) elif security is True: security = Security.temporary() self._startup_kwargs["security"] = security elif not isinstance(security, Security): # pragma: no cover raise TypeError("security must be a Security object") self.security = security if name == "worker": self.connection_args = self.security.get_connection_args("worker") else: self.connection_args = self.security.get_connection_args("client") self._asynchronous = asynchronous self._loop_runner = LoopRunner(loop=loop, asynchronous=asynchronous) self._connecting_to_scheduler = False self._gather_keys = None self._gather_future = None if heartbeat_interval is None: heartbeat_interval = dask.config.get("distributed.client.heartbeat") heartbeat_interval = parse_timedelta(heartbeat_interval, default="ms") scheduler_info_interval = parse_timedelta( dask.config.get("distributed.client.scheduler-info-interval", default="ms") ) self._periodic_callbacks = dict() self._periodic_callbacks["scheduler-info"] = PeriodicCallback( self._update_scheduler_info, scheduler_info_interval * 1000 ) self._periodic_callbacks["heartbeat"] = PeriodicCallback( self._heartbeat, heartbeat_interval * 1000 ) self._start_arg = address self._set_as_default = set_as_default if set_as_default: self._set_config = dask.config.set(scheduler="dask.distributed") self._event_handlers = {} self._stream_handlers = { "key-in-memory": self._handle_key_in_memory, "lost-data": self._handle_lost_data, "cancelled-keys": self._handle_cancelled_keys, "task-retried": self._handle_retried_key, "task-erred": self._handle_task_erred, "restart": self._handle_restart, "error": self._handle_error, "event": self._handle_event, "adjust-heartbeat-interval": self._adjust_heartbeat_intervals, } self._state_handlers = { "memory": self._handle_key_in_memory, "lost": self._handle_lost_data, "erred": self._handle_task_erred, } self.rpc = ConnectionPool( limit=connection_limit, serializers=serializers, deserializers=deserializers, deserialize=True, connection_args=self.connection_args, timeout=timeout, server=self, ) self.extensions = { name: extension(self) for name, extension in extensions.items() } preload = dask.config.get("distributed.client.preload") preload_argv = dask.config.get("distributed.client.preload-argv") self.preloads = preloading.process_preloads(self, preload, preload_argv) self.start(timeout=timeout) Client._instances.add(self) from distributed.recreate_tasks import ReplayTaskClient ReplayTaskClient(self) @property def io_loop(self) -> IOLoop | None: warnings.warn( "The io_loop property is deprecated", DeprecationWarning, stacklevel=2 ) return self.loop @io_loop.setter def io_loop(self, value: IOLoop) -> None: warnings.warn( "The io_loop property is deprecated", DeprecationWarning, stacklevel=2 ) self.loop = value @property def loop(self) -> IOLoop | None: loop = self.__loop if loop is None: # If the loop is not running when this is called, the LoopRunner.loop # property will raise a DeprecationWarning # However subsequent calls might occur - eg atexit, where a stopped # loop is still acceptable - so we cache access to the loop. self.__loop = loop = self._loop_runner.loop return loop @loop.setter def loop(self, value: IOLoop) -> None: warnings.warn( "setting the loop property is deprecated", DeprecationWarning, stacklevel=2 ) self.__loop = value @contextmanager def as_current(self): """Thread-local, Task-local context manager that causes the Client.current class method to return self. Any Future objects deserialized inside this context manager will be automatically attached to this Client. """ tok = _current_client.set(self) with dask.config.set(scheduler="dask.distributed"): try: yield finally: _current_client.reset(tok) @classmethod def current(cls, allow_global=True): """When running within the context of `as_client`, return the context-local current client. Otherwise, return the latest initialised Client. If no Client instances exist, raise ValueError. If allow_global is set to False, raise ValueError if running outside of the `as_client` context manager. Parameters ---------- allow_global : bool If True returns the default client Returns ------- Client The current client Raises ------ ValueError If there is no client set, a ValueError is raised See also -------- default_client """ out = _current_client.get() if out: return out if allow_global: return default_client() raise ValueError("Not running inside the `as_current` context manager") @property def dashboard_link(self): """Link to the scheduler's dashboard. Returns ------- str Dashboard URL. Examples -------- Opening the dashboard in your default web browser: >>> import webbrowser >>> from distributed import Client >>> client = Client() >>> webbrowser.open(client.dashboard_link) """ try: return self.cluster.dashboard_link except AttributeError: scheduler, info = self._get_scheduler_info(n_workers=0) if scheduler is None: return None else: protocol, rest = scheduler.address.split("://") port = info["services"]["dashboard"] if protocol == "inproc": host = "localhost" else: host = rest.split(":")[0] return format_dashboard_link(host, port) def _get_scheduler_info(self, n_workers): from distributed.scheduler import Scheduler if ( self.cluster and hasattr(self.cluster, "scheduler") and isinstance(self.cluster.scheduler, Scheduler) ): info = self.cluster.scheduler.identity(n_workers=n_workers) scheduler = self.cluster.scheduler elif ( self._loop_runner.is_started() and self.scheduler and not self.asynchronous ): info = sync(self.loop, self.scheduler.identity, n_workers=n_workers) scheduler = self.scheduler else: info = self._scheduler_identity scheduler = self.scheduler return scheduler, SchedulerInfo(info) def __repr__(self): # Note: avoid doing I/O here... info = self._scheduler_identity addr = info.get("address") if addr: nworkers = info.get("n_workers", 0) nthreads = info.get("total_threads", 0) text = "<%s: %r processes=%d threads=%d" % ( self.__class__.__name__, addr, nworkers, nthreads, ) memory = info.get("total_memory", 0) text += ", memory=" + format_bytes(memory) text += ">" return text elif self.scheduler is not None: return f"<{self.__class__.__name__}: scheduler={self.scheduler.address!r}>" else: return f"<{self.__class__.__name__}: No scheduler connected>" def _repr_html_(self): try: dle_version = parse_version(version("dask-labextension")) JUPYTERLAB = False if dle_version < parse_version("6.0.0") else True except PackageNotFoundError: JUPYTERLAB = False scheduler, info = self._get_scheduler_info(n_workers=5) return get_template("client.html.j2").render( id=self.id, scheduler=scheduler, info=info, cluster=self.cluster, scheduler_file=self.scheduler_file, dashboard_link=self.dashboard_link, jupyterlab=JUPYTERLAB, ) def start(self, **kwargs): """Start scheduler running in separate thread""" if self.status != "newly-created": return self._loop_runner.start() if self._set_as_default: _set_global_client(self) if self.asynchronous: self._started = asyncio.ensure_future(self._start(**kwargs)) else: sync(self.loop, self._start, **kwargs) def __await__(self): if hasattr(self, "_started"): return self._started.__await__() else: async def _(): return self return _().__await__() def _send_to_scheduler_safe(self, msg): if self.status in ("running", "closing"): try: self.scheduler_comm.send(msg) except (CommClosedError, AttributeError): if self.status == "running": raise elif self.status in ("connecting", "newly-created"): self._pending_msg_buffer.append(msg) def _send_to_scheduler(self, msg): if self.status in ("running", "closing", "connecting", "newly-created"): self.loop.add_callback(self._send_to_scheduler_safe, msg) else: raise ClosedClientError( f"Client is {self.status}. Can't send {msg['op']} message." ) async def _start(self, timeout=no_default, **kwargs): self.status = "connecting" await self.rpc.start() if timeout is no_default: timeout = self._timeout timeout = parse_timedelta(timeout, "s") address = self._start_arg if self.cluster is not None: # Ensure the cluster is started (no-op if already running) try: await self.cluster except Exception: logger.info( "Tried to start cluster and received an error. Proceeding.", exc_info=True, ) address = self.cluster.scheduler_address elif self.scheduler_file is not None: while not os.path.exists(self.scheduler_file): await asyncio.sleep(0.01) for _ in range(10): try: with open(self.scheduler_file) as f: cfg = json.load(f) address = cfg["address"] break except (ValueError, KeyError): # JSON file not yet flushed await asyncio.sleep(0.01) elif self._start_arg is None: from distributed.deploy import LocalCluster self.cluster = await LocalCluster( loop=self.loop, asynchronous=self._asynchronous, **self._startup_kwargs, ) address = self.cluster.scheduler_address self._gather_semaphore = asyncio.Semaphore(5) if self.scheduler is None: self.scheduler = self.rpc(address) self.scheduler_comm = None try: await self._ensure_connected(timeout=timeout) except (OSError, ImportError): await self._close() raise for pc in self._periodic_callbacks.values(): pc.start() for topic, handler in Client._default_event_handlers.items(): self.subscribe_topic(topic, handler) await self.preloads.start() self._handle_report_task = asyncio.create_task(self._handle_report()) return self @log_errors async def _reconnect(self): assert self.scheduler_comm.comm.closed() self.status = "connecting" self.scheduler_comm = None for st in self.futures.values(): st.cancel( reason="scheduler-connection-lost", msg=( "Client lost the connection to the scheduler. " "Please check your connection and re-run your work." ), ) self.futures.clear() timeout = self._timeout deadline = time() + timeout while timeout > 0 and self.status == "connecting": try: await self._ensure_connected(timeout=timeout) break except OSError: # Wait a bit before retrying await asyncio.sleep(0.1) timeout = deadline - time() except ImportError: await self._close() break else: logger.error( "Failed to reconnect to scheduler after %.2f " "seconds, closing client", self._timeout, ) await self._close() async def _ensure_connected(self, timeout=None): if ( self.scheduler_comm and not self.scheduler_comm.closed() or self._connecting_to_scheduler or self.scheduler is None ): return self._connecting_to_scheduler = True try: comm = await connect( self.scheduler.address, timeout=timeout, **self.connection_args ) comm.name = "Client->Scheduler" if timeout is not None: await wait_for(self._update_scheduler_info(), timeout) else: await self._update_scheduler_info() await comm.write( { "op": "register-client", "client": self.id, "reply": False, "versions": version_module.get_versions(), } ) except Exception: if self.status == "closed": return else: raise finally: self._connecting_to_scheduler = False if timeout is not None: msg = await wait_for(comm.read(), timeout) else: msg = await comm.read() assert len(msg) == 1 assert msg[0]["op"] == "stream-start" if msg[0].get("error"): raise ImportError(msg[0]["error"]) if msg[0].get("warning"): warnings.warn(version_module.VersionMismatchWarning(msg[0]["warning"])) bcomm = BatchedSend(interval="10ms", loop=self.loop) bcomm.start(comm) self.scheduler_comm = bcomm self.status = "running" for msg in self._pending_msg_buffer: self._send_to_scheduler(msg) del self._pending_msg_buffer[:] logger.debug("Started scheduling coroutines. Synchronized") async def _update_scheduler_info(self, n_workers=5): if self.status not in ("running", "connecting") or self.scheduler is None: return try: self._scheduler_identity = SchedulerInfo( await self.scheduler.identity(n_workers=n_workers) ) except OSError: logger.debug("Not able to query scheduler for identity") async def _wait_for_workers( self, n_workers: int, timeout: float | None = None ) -> None: info = await self.scheduler.identity(n_workers=-1) self._scheduler_identity = SchedulerInfo(info) if timeout: deadline = time() + parse_timedelta(timeout) else: deadline = None def running_workers(info): return len( [ ws for ws in info["workers"].values() if ws["status"] == Status.running.name ] ) while running_workers(info) < n_workers: if deadline and time() > deadline: assert timeout is not None raise WorkerStartTimeoutError(running_workers(info), n_workers, timeout) await asyncio.sleep(0.1) info = await self.scheduler.identity(n_workers=-1) self._scheduler_identity = SchedulerInfo(info) def wait_for_workers(self, n_workers: int, timeout: float | None = None) -> None: """Blocking call to wait for n workers before continuing Parameters ---------- n_workers : int The number of workers timeout : number, optional Time in seconds after which to raise a ``dask.distributed.TimeoutError`` """ if not isinstance(n_workers, int) or n_workers < 1: raise ValueError( f"`n_workers` must be a positive integer. Instead got {n_workers}." ) if self.cluster and hasattr(self.cluster, "wait_for_workers"): return self.cluster.wait_for_workers(n_workers, timeout) return self.sync(self._wait_for_workers, n_workers, timeout=timeout) def _adjust_heartbeat_intervals(self, interval): """Adjust the heartbeat intervals for the client and scheduler""" self._periodic_callbacks["heartbeat"].callback_time = interval * 1000 self._periodic_callbacks["scheduler-info"].callback_time = interval * 1000 def _heartbeat(self): # Don't send heartbeat if scheduler comm or cluster are already closed if self.scheduler_comm is not None and not ( self.scheduler_comm.comm.closed() or (self.cluster and self.cluster.status in (Status.closed, Status.closing)) ): self.scheduler_comm.send({"op": "heartbeat-client"}) def __enter__(self): if not self._loop_runner.is_started(): self.start() if self._set_as_default: self._previous_as_current = _current_client.set(self) return self async def __aenter__(self): await self if self._set_as_default: self._previous_as_current = _current_client.set(self) return self async def __aexit__(self, exc_type, exc_value, traceback): if self._previous_as_current: try: _current_client.reset(self._previous_as_current) except ValueError as e: if not e.args[0].endswith(" was created in a different Context"): raise # pragma: nocover warnings.warn( "It is deprecated to enter and exit the Client context " "manager from different tasks", DeprecationWarning, stacklevel=2, ) await self._close( # if we're handling an exception, we assume that it's more # important to deliver that exception than shutdown gracefully. fast=(exc_type is not None) ) def __exit__(self, exc_type, exc_value, traceback): if self._previous_as_current: try: _current_client.reset(self._previous_as_current) except ValueError as e: if not e.args[0].endswith(" was created in a different Context"): raise # pragma: nocover warnings.warn( "It is deprecated to enter and exit the Client context " "manager from different threads", DeprecationWarning, stacklevel=2, ) self.close() def __del__(self): # If the loop never got assigned, we failed early in the constructor, # nothing to do if self.__loop is not None: self.close() def _inc_ref(self, key): with self._refcount_lock: self.refcount[key] += 1 def _dec_ref(self, key): with self._refcount_lock: self.refcount[key] -= 1 if self.refcount[key] == 0: del self.refcount[key] self._release_key(key) def _release_key(self, key): """Release key from distributed memory""" logger.debug("Release key %s", key) st = self.futures.pop(key, None) if st is not None: st.cancel() if self.status != "closed": self._send_to_scheduler( {"op": "client-releases-keys", "keys": [key], "client": self.id} ) @log_errors async def _handle_report(self): """Listen to scheduler""" try: while True: if self.scheduler_comm is None: break try: msgs = await self.scheduler_comm.comm.read() except CommClosedError: if self._is_finalizing(): return if self.status == "running": if self.cluster and self.cluster.status in ( Status.closed, Status.closing, ): # Don't attempt to reconnect if cluster are already closed. # Instead close down the client. await self._close() return logger.info("Client report stream closed to scheduler") logger.info("Reconnecting...") self.status = "connecting" await self._reconnect() continue else: break if not isinstance(msgs, (list, tuple)): msgs = (msgs,) breakout = False for msg in msgs: logger.debug("Client %s receives message %s", self.id, msg) if "status" in msg and "error" in msg["status"]: typ, exc, tb = clean_exception(**msg) raise exc.with_traceback(tb) op = msg.pop("op") if op == "close" or op == "stream-closed": breakout = True break try: handler = self._stream_handlers[op] result = handler(**msg) if inspect.isawaitable(result): await result except Exception as e: logger.exception(e) if breakout: break except (CancelledError, asyncio.CancelledError): pass def _handle_key_in_memory(self, key=None, type=None, workers=None): state = self.futures.get(key) if state is not None: if type and not state.type: # Type exists and not yet set try: type = loads(type) except Exception: type = None # Here, `type` may be a str if actual type failed # serializing in Worker else: type = None state.finish(type) def _handle_lost_data(self, key=None): state = self.futures.get(key) if state is not None: state.lose() def _handle_cancelled_keys(self, keys, reason=None, msg=None): for key in keys: state = self.futures.get(key) if state is not None: state.cancel(reason=reason, msg=msg) def _handle_retried_key(self, key=None): state = self.futures.get(key) if state is not None: state.retry() def _handle_task_erred(self, key=None, exception=None, traceback=None): state = self.futures.get(key) if state is not None: state.set_error(exception, traceback) def _handle_restart(self): logger.info("Receive restart signal from scheduler") for state in self.futures.values(): state.cancel( reason="scheduler-restart", msg="Scheduler has restarted. Please re-run your work.", ) self.futures.clear() self.generation += 1 with self._refcount_lock: self.refcount.clear() def _handle_error(self, exception=None): logger.warning("Scheduler exception:") logger.exception(exception) @asynccontextmanager async def _wait_for_handle_report_task(self, fast=False): current_task = asyncio.current_task() handle_report_task = self._handle_report_task # Give the scheduler 'stream-closed' message 100ms to come through # This makes the shutdown slightly smoother and quieter should_wait = ( handle_report_task is not None and handle_report_task is not current_task ) if should_wait: with suppress(asyncio.CancelledError, TimeoutError): await wait_for(asyncio.shield(handle_report_task), 0.1) yield if should_wait: with suppress(TimeoutError, asyncio.CancelledError): await wait_for(handle_report_task, 0 if fast else 2) @log_errors async def _close(self, fast: bool = False) -> None: """Send close signal and wait until scheduler completes If fast is True, the client will close forcefully, by cancelling tasks the background _handle_report_task. """ # TODO: close more forcefully by aborting the RPC and cancelling all # background tasks. # See https://trio.readthedocs.io/en/stable/reference-io.html#trio.aclose_forcefully if self.status == "closed": return self.status = "closing" await self.preloads.teardown() with suppress(AttributeError): for pc in self._periodic_callbacks.values(): pc.stop() _del_global_client(self) self._scheduler_identity = {} if self._set_as_default and not _get_global_client(): with suppress(AttributeError): # clear the dask.config set keys with self._set_config: pass if self.get == dask.config.get("get", None): del dask.config.config["get"] if ( self.scheduler_comm and self.scheduler_comm.comm and not self.scheduler_comm.comm.closed() ): self._send_to_scheduler({"op": "close-client"}) self._send_to_scheduler({"op": "close-stream"}) async with self._wait_for_handle_report_task(fast=fast): if ( self.scheduler_comm and self.scheduler_comm.comm and not self.scheduler_comm.comm.closed() ): await self.scheduler_comm.close() for key in list(self.futures): self._release_key(key=key) if self._start_arg is None: with suppress(AttributeError): await self.cluster.close() await self.rpc.close() self.status = "closed" if _get_global_client() is self: _set_global_client(None) with suppress(AttributeError): await self.scheduler.close_rpc() self.scheduler = None self.status = "closed" def close(self, timeout=no_default): """Close this client Clients will also close automatically when your Python session ends If you started a client without arguments like ``Client()`` then this will also close the local cluster that was started at the same time. Parameters ---------- timeout : number Time in seconds after which to raise a ``dask.distributed.TimeoutError`` See Also -------- Client.restart """ if timeout is no_default: timeout = self._timeout * 2 # XXX handling of self.status here is not thread-safe if self.status in ["closed", "newly-created"]: if self.asynchronous: return NoOpAwaitable() return self.status = "closing" with suppress(AttributeError): for pc in self._periodic_callbacks.values(): pc.stop() if self.asynchronous: coro = self._close() if timeout: coro = wait_for(coro, timeout) return coro sync(self.loop, self._close, fast=True, callback_timeout=timeout) assert self.status == "closed" if not self._is_finalizing(): self._loop_runner.stop() async def _shutdown(self): logger.info("Shutting down scheduler from Client") self.status = "closing" for pc in self._periodic_callbacks.values(): pc.stop() async with self._wait_for_handle_report_task(): if self.cluster: await self.cluster.close() else: with suppress(CommClosedError): await self.scheduler.terminate() await self._close() def shutdown(self): """Shut down the connected scheduler and workers Note, this may disrupt other clients that may be using the same scheduler and workers. See Also -------- Client.close : close only this client """ return self.sync(self._shutdown) def get_executor(self, **kwargs): """ Return a concurrent.futures Executor for submitting tasks on this Client Parameters ---------- **kwargs Any submit()- or map()- compatible arguments, such as `workers` or `resources`. Returns ------- ClientExecutor An Executor object that's fully compatible with the concurrent.futures API. """ return ClientExecutor(self, **kwargs) def submit( self, func: Callable[..., _T], *args, key=None, workers=None, resources=None, retries=None, priority=0, fifo_timeout="100 ms", allow_other_workers=False, actor=False, actors=False, pure=True, **kwargs, ) -> Future[_T]: """Submit a function application to the scheduler Parameters ---------- func : callable Callable to be scheduled as ``func(*args **kwargs)``. If ``func`` returns a coroutine, it will be run on the main event loop of a worker. Otherwise ``func`` will be run in a worker's task executor pool (see ``Worker.executors`` for more information.) *args : tuple Optional positional arguments key : str Unique identifier for the task. Defaults to function-name and hash workers : string or iterable of strings A set of worker addresses or hostnames on which computations may be performed. Leave empty to default to all workers (common case) resources : dict (defaults to {}) Defines the ``resources`` each instance of this mapped task requires on the worker; e.g. ``{'GPU': 2}``. See :doc:`worker resources <resources>` for details on defining resources. retries : int (default to 0) Number of allowed automatic retries if the task fails priority : Number Optional prioritization of task. Zero is default. Higher priorities take precedence fifo_timeout : str timedelta (default '100ms') Allowed amount of time between calls to consider the same priority allow_other_workers : bool (defaults to False) Used with ``workers``. Indicates whether or not the computations may be performed on workers that are not in the `workers` set(s). actor : bool (default False) Whether this task should exist on the worker as a stateful actor. See :doc:`actors` for additional details. actors : bool (default False) Alias for `actor` pure : bool (defaults to True) Whether or not the function is pure. Set ``pure=False`` for impure functions like ``np.random.random``. Note that if both ``actor`` and ``pure`` kwargs are set to True, then the value of ``pure`` will be reverted to False, since an actor is stateful. See :ref:`pure functions` for more details. **kwargs Examples -------- >>> c = client.submit(add, a, b) # doctest: +SKIP Notes ----- The current implementation of a task graph resolution searches for occurrences of ``key`` and replaces it with a corresponding ``Future`` result. That can lead to unwanted substitution of strings passed as arguments to a task if these strings match some ``key`` that already exists on a cluster. To avoid these situations it is required to use unique values if a ``key`` is set manually. See https://github.com/dask/dask/issues/9969 to track progress on resolving this issue. Returns ------- Future If running in asynchronous mode, returns the future. Otherwise returns the concrete value Raises ------ TypeError If 'func' is not callable, a TypeError is raised ValueError If 'allow_other_workers'is True and 'workers' is None, a ValueError is raised See Also -------- Client.map : Submit on many arguments at once """ if not callable(func): raise TypeError("First input to submit must be a callable function") actor = actor or actors if actor: pure = not actor if allow_other_workers not in (True, False, None): raise TypeError("allow_other_workers= must be True or False") if key is None: if pure: key = funcname(func) + "-" + tokenize(func, kwargs, *args) else: key = funcname(func) + "-" + str(uuid.uuid4()) with self._refcount_lock: if key in self.futures: return Future(key, self) if allow_other_workers and workers is None: raise ValueError("Only use allow_other_workers= if using workers=") if isinstance(workers, (str, Number)): workers = [workers] expr = LLGExpr( { key: Task( key, func, *(parse_input(a) for a in args), **{k: parse_input(v) for k, v in kwargs.items()}, # type: ignore ) }, # We'd like to avoid hashing/tokenizing all of the above. # The LLGExpr in this situation is as unique as it'll get. _determ_token=uuid.uuid4().hex, ) futures = self._graph_to_futures( expr, [key], workers=workers, allow_other_workers=allow_other_workers, internal_priority={key: 0}, user_priority=priority, resources=resources, retries=retries, fifo_timeout=fifo_timeout, actors=actor, span_metadata=SpanMetadata(collections=[{"type": "Future"}]), ) logger.debug("Submit %s(...), %s", funcname(func), key) return futures[key] def map( self, func: Callable[..., _T], *iterables: Collection, key: str | list | None = None, workers: str | Iterable[str] | None = None, retries: int | None = None, resources: dict[str, Any] | None = None, priority: int = 0, allow_other_workers: bool = False, fifo_timeout: str = "100 ms", actor: bool = False, actors: bool = False, pure: bool = True, batch_size=None, **kwargs, ) -> list[Future[_T]]: """Map a function on a sequence of arguments Arguments can be normal objects or Futures Parameters ---------- func : callable Callable to be scheduled for execution. If ``func`` returns a coroutine, it will be run on the main event loop of a worker. Otherwise ``func`` will be run in a worker's task executor pool (see ``Worker.executors`` for more information.) iterables : Iterables List-like objects to map over. They should have the same length. key : str, list Prefix for task names if string. Explicit names if list. workers : string or iterable of strings A set of worker hostnames on which computations may be performed. Leave empty to default to all workers (common case) retries : int (default to 0) Number of allowed automatic retries if a task fails resources : dict (defaults to {}) Defines the `resources` each instance of this mapped task requires on the worker; e.g. ``{'GPU': 2}``. See :doc:`worker resources <resources>` for details on defining resources. priority : Number Optional prioritization of task. Zero is default. Higher priorities take precedence allow_other_workers : bool (defaults to False) Used with `workers`. Indicates whether or not the computations may be performed on workers that are not in the `workers` set(s). fifo_timeout : str timedelta (default '100ms') Allowed amount of time between calls to consider the same priority actor : bool (default False) Whether these tasks should exist on the worker as stateful actors. See :doc:`actors` for additional details. actors : bool (default False) Alias for `actor` pure : bool (defaults to True) Whether or not the function is pure. Set ``pure=False`` for impure functions like ``np.random.random``. Note that if both ``actor`` and ``pure`` kwargs are set to True, then the value of ``pure`` will be reverted to False, since an actor is stateful. See :ref:`pure functions` for more details. batch_size : int, optional (default: just one batch whose size is the entire iterable) Submit tasks to the scheduler in batches of (at most) ``batch_size``. The tradeoff in batch size is that large batches avoid more per-batch overhead, but batches that are too big can take a long time to submit and unreasonably delay the cluster from starting its processing. **kwargs : dict Extra keyword arguments to send to the function. Large values will be included explicitly in the task graph. Examples -------- >>> L = client.map(func, sequence) # doctest: +SKIP Notes ----- The current implementation of a task graph resolution searches for occurrences of ``key`` and replaces it with a corresponding ``Future`` result. That can lead to unwanted substitution of strings passed as arguments to a task if these strings match some ``key`` that already exists on a cluster. To avoid these situations it is required to use unique values if a ``key`` is set manually. See https://github.com/dask/dask/issues/9969 to track progress on resolving this issue. Returns ------- List, iterator, or Queue of futures, depending on the type of the inputs. See Also -------- Client.submit : Submit a single function """ if not callable(func): raise TypeError("First input to map must be a callable function") if all(isinstance(it, pyQueue) for it in iterables) or all( isinstance(i, Iterator) for i in iterables ): raise TypeError( "Dask no longer supports mapping over Iterators or Queues." "Consider using a normal for loop and Client.submit" ) total_length = sum(len(x) for x in iterables) if batch_size and batch_size > 1 and total_length > batch_size: batches = list( zip(*(partition_all(batch_size, iterable) for iterable in iterables)) ) keys: list[list[Any]] | list[Any] if isinstance(key, list): keys = [list(element) for element in partition_all(batch_size, key)] else: keys = [key for _ in range(len(batches))] return list( flatten( self.map( func, *batch, key=key, workers=workers, retries=retries, priority=priority, allow_other_workers=allow_other_workers, fifo_timeout=fifo_timeout, resources=resources, actor=actor, actors=actors, pure=pure, **kwargs, ) for key, batch in zip(keys, batches) ) ) key = key or funcname(func) actor = actor or actors if actor: pure = not actor if allow_other_workers and workers is None: raise ValueError("Only use allow_other_workers= if using workers=") expr = _MapExpr( func, iterables, key=key, pure=pure, annotations={}, kwargs=kwargs, ) keys = list(expr.keys) if isinstance(workers, (str, Number)): workers = [workers] if workers is not None and not isinstance(workers, (list, set)): raise TypeError("Workers must be a list or set of workers or None") internal_priority = dict(zip(keys, range(len(keys)))) futures = self._graph_to_futures( expr, keys, workers=workers, allow_other_workers=allow_other_workers, internal_priority=internal_priority, resources=resources, retries=retries, user_priority=priority, fifo_timeout=fifo_timeout, actors=actor, span_metadata=SpanMetadata(collections=[{"type": "Future"}]), ) # make sure the graph is not materialized logger.debug("map(%s, ...)", funcname(func)) return [futures[k] for k in keys] async def _gather(self, futures, errors="raise", direct=None, local_worker=None): unpacked, future_set = unpack_remotedata(futures, byte_keys=True) mismatched_futures = [f for f in future_set if f.client is not self] if mismatched_futures: raise ValueError( "Cannot gather Futures created by another client. " f"These are the {len(mismatched_futures)} (out of {len(futures)}) " f"mismatched Futures and their client IDs (this client is {self.id}): " f"{ {f: f.client.id for f in mismatched_futures} }" ) keys = [future.key for future in future_set] bad_data = dict() data = {} if direct is None: direct = self.direct_to_workers if direct is None: try: w = get_worker() except Exception: direct = False else: if w.scheduler.address == self.scheduler.address: direct = True async def wait(k): """Want to stop the All(...) early if we find an error""" try: st = self.futures[k] except KeyError: raise AllExit() else: await st.wait() if st.status != "finished" and errors == "raise": raise AllExit() while True: logger.debug("Waiting on futures to clear before gather") with suppress(AllExit): await distributed.utils.All( [wait(key) for key in keys if key in self.futures], quiet_exceptions=AllExit, ) failed = ("error", "cancelled") exceptions = set() bad_keys = set() for future in future_set: key = future.key if key not in self.futures or future.status in failed: exceptions.add(key) if errors == "raise": st = future._state exception = st.exception traceback = st.traceback raise exception.with_traceback(traceback) if errors == "skip": bad_keys.add(key) bad_data[key] = None else: # pragma: no cover raise ValueError("Bad value, `errors=%s`" % errors) keys = [k for k in keys if k not in bad_keys and k not in data] if local_worker: # look inside local worker data.update( {k: local_worker.data[k] for k in keys if k in local_worker.data} ) keys = [k for k in keys if k not in data] # We now do an actual remote communication with workers or scheduler if self._gather_future: # attach onto another pending gather request self._gather_keys |= set(keys) response = await self._gather_future else: # no one waiting, go ahead self._gather_keys = set(keys) future = asyncio.ensure_future( self._gather_remote(direct, local_worker) ) if self._gather_keys is None: self._gather_future = None else: self._gather_future = future response = await future if response["status"] == "error": log = logger.warning if errors == "raise" else logger.debug log( "Couldn't gather %s keys, rescheduling %s", len(response["keys"]), response["keys"], ) for key in response["keys"]: self._send_to_scheduler({"op": "report-key", "key": key}) for key in response["keys"]: try: self.futures[key].reset() except KeyError: # TODO: verify that this is safe pass else: # pragma: no cover break if bad_data and errors == "skip" and isinstance(unpacked, list): unpacked = [f for f in unpacked if f not in bad_data] data.update(response["data"]) result = pack_data(unpacked, merge(data, bad_data)) return result async def _gather_remote(self, direct: bool, local_worker: bool) -> dict[str, Any]: """Perform gather with workers or scheduler This method exists to limit and batch many concurrent gathers into a few. In controls access using a Tornado semaphore, and picks up keys from other requests made recently. """ async with self._gather_semaphore: keys = list(self._gather_keys) self._gather_keys = None # clear state, these keys are being sent off self._gather_future = None if direct or local_worker: # gather directly from workers who_has = await retry_operation(self.scheduler.who_has, keys=keys) data, missing_keys, failed_keys, _ = await gather_from_workers( who_has, rpc=self.rpc ) response: dict[str, Any] = {"status": "OK", "data": data} if missing_keys or failed_keys: response = await retry_operation( self.scheduler.gather, keys=missing_keys + failed_keys ) if response["status"] == "OK": response["data"].update(data) else: # ask scheduler to gather data for us response = await retry_operation(self.scheduler.gather, keys=keys) return response def gather(self, futures, errors="raise", direct=None, asynchronous=None): """Gather futures from distributed memory Accepts a future, nested container of futures, iterator, or queue. The return type will match the input type. Parameters ---------- futures : Collection of futures This can be a possibly nested collection of Future objects. Collections can be lists, sets, or dictionaries errors : string Either 'raise' or 'skip' if we should raise if a future has erred or skip its inclusion in the output collection direct : boolean Whether or not to connect directly to the workers, or to ask the scheduler to serve as intermediary. This can also be set when creating the Client. asynchronous: bool If True the client is in asynchronous mode Returns ------- results: a collection of the same type as the input, but now with gathered results rather than futures Examples -------- >>> from operator import add # doctest: +SKIP >>> c = Client('127.0.0.1:8787') # doctest: +SKIP >>> x = c.submit(add, 1, 2) # doctest: +SKIP >>> c.gather(x) # doctest: +SKIP 3 >>> c.gather([x, [x], x]) # support lists and dicts # doctest: +SKIP [3, [3], 3] See Also -------- Client.scatter : Send data out to cluster """ if isinstance(futures, pyQueue): raise TypeError( "Dask no longer supports gathering over Iterators and Queues. " "Consider using a normal for loop and Client.submit/gather" ) if isinstance(futures, Iterator): return (self.gather(f, errors=errors, direct=direct) for f in futures) try: local_worker = get_worker() except ValueError: local_worker = None with shorten_traceback(): return self.sync( self._gather, futures, errors=errors, direct=direct, local_worker=local_worker, asynchronous=asynchronous, ) async def _scatter( self, data, workers=None, broadcast=False, direct=None, local_worker=None, timeout=no_default, hash=True, ): if timeout is no_default: timeout = self._timeout if isinstance(workers, (str, Number)): workers = [workers] if isinstance(data, type(range(0))): data = list(data) input_type = type(data) names = False unpack = False if isinstance(data, Iterator): data = list(data) if isinstance(data, (set, frozenset)): data = list(data) if not isinstance(data, (dict, list, tuple, set, frozenset)): unpack = True data = [data] if isinstance(data, (list, tuple)): if hash: names = [type(x).__name__ + "-" + tokenize(x) for x in data] else: names = [type(x).__name__ + "-" + uuid.uuid4().hex for x in data] data = dict(zip(names, data)) assert isinstance(data, dict) types = valmap(type, data) if direct is None: direct = self.direct_to_workers if direct is None: try: w = get_worker() except Exception: direct = False else: if w.scheduler.address == self.scheduler.address: direct = True if local_worker: # running within task local_worker.update_data(data=data) await self.scheduler.update_data( who_has={key: [local_worker.address] for key in data}, nbytes=valmap(sizeof, data), client=self.id, ) else: data2 = valmap(to_serialize, data) if direct: nthreads = None start = time() while not nthreads: if nthreads is not None: await asyncio.sleep(0.1) if time() > start + timeout: raise TimeoutError("No valid workers found") # Exclude paused and closing_gracefully workers nthreads = await self.scheduler.ncores_running(workers=workers) if not nthreads: # pragma: no cover raise ValueError("No valid workers found") workers = list(nthreads.keys()) _, who_has, nbytes = await scatter_to_workers(workers, data2, self.rpc) await self.scheduler.update_data( who_has=who_has, nbytes=nbytes, client=self.id ) else: await self.scheduler.scatter( data=data2, workers=workers, client=self.id, broadcast=broadcast, timeout=timeout, ) out = {k: Future(k, self) for k in data} for key, typ in types.items(): self.futures[key].finish(type=typ) if direct and broadcast: n = None if broadcast is True else broadcast await self._replicate(list(out.values()), workers=workers, n=n) if issubclass(input_type, (list, tuple, set, frozenset)): out = input_type(out[k] for k in names) if unpack: assert len(out) == 1 out = list(out.values())[0] return out def scatter( self, data, workers=None, broadcast=False, direct=None, hash=True, timeout=no_default, asynchronous=None, ): """Scatter data into distributed memory This moves data from the local client process into the workers of the distributed scheduler. Note that it is often better to submit jobs to your workers to have them load the data rather than loading data locally and then scattering it out to them. Parameters ---------- data : list, dict, or object Data to scatter out to workers. Output type matches input type. workers : list of tuples (optional) Optionally constrain locations of data. Specify workers as hostname/port pairs, e.g. ``('127.0.0.1', 8787)``. broadcast : bool (defaults to False) Whether to send each data element to all workers. By default we round-robin based on number of cores. .. note:: Setting this flag to True is incompatible with the Active Memory Manager's :ref:`ReduceReplicas` policy. If you wish to use it, you must first disable the policy or disable the AMM entirely. direct : bool (defaults to automatically check) Whether or not to connect directly to the workers, or to ask the scheduler to serve as intermediary. This can also be set when creating the Client. hash : bool (optional) Whether or not to hash data to determine key. If False then this uses a random key timeout : number, optional Time in seconds after which to raise a ``dask.distributed.TimeoutError`` asynchronous: bool If True the client is in asynchronous mode Returns ------- List, dict, iterator, or queue of futures matching the type of input. Examples -------- >>> c = Client('127.0.0.1:8787') # doctest: +SKIP >>> c.scatter(1) # doctest: +SKIP <Future: status: finished, key: c0a8a20f903a4915b94db8de3ea63195> >>> c.scatter([1, 2, 3]) # doctest: +SKIP [<Future: status: finished, key: c0a8a20f903a4915b94db8de3ea63195>, <Future: status: finished, key: 58e78e1b34eb49a68c65b54815d1b158>, <Future: status: finished, key: d3395e15f605bc35ab1bac6341a285e2>] >>> c.scatter({'x': 1, 'y': 2, 'z': 3}) # doctest: +SKIP {'x': <Future: status: finished, key: x>, 'y': <Future: status: finished, key: y>, 'z': <Future: status: finished, key: z>} Constrain location of data to subset of workers >>> c.scatter([1, 2, 3], workers=[('hostname', 8788)]) # doctest: +SKIP Broadcast data to all workers >>> [future] = c.scatter([element], broadcast=True) # doctest: +SKIP Send scattered data to parallelized function using client futures interface >>> data = c.scatter(data, broadcast=True) # doctest: +SKIP >>> res = [c.submit(func, data, i) for i in range(100)] Notes ----- Scattering a dictionary uses ``dict`` keys to create ``Future`` keys. The current implementation of a task graph resolution searches for occurrences of ``key`` and replaces it with a corresponding ``Future`` result. That can lead to unwanted substitution of strings passed as arguments to a task if these strings match some ``key`` that already exists on a cluster. To avoid these situations it is required to use unique values if a ``key`` is set manually. See https://github.com/dask/dask/issues/9969 to track progress on resolving this issue. See Also -------- Client.gather : Gather data back to local process """ if timeout is no_default: timeout = self._timeout if isinstance(data, pyQueue) or isinstance(data, Iterator): raise TypeError( "Dask no longer supports mapping over Iterators or Queues." "Consider using a normal for loop and Client.submit" ) try: local_worker = get_worker() except ValueError: local_worker = None return self.sync( self._scatter, data, workers=workers, broadcast=broadcast, direct=direct, local_worker=local_worker, timeout=timeout, asynchronous=asynchronous, hash=hash, ) async def _cancel(self, futures, reason=None, msg=None, force=False): # FIXME: This method is asynchronous since interacting with the FutureState below requires an event loop. keys = list({f.key for f in futures_of(futures)}) self._send_to_scheduler( { "op": "cancel-keys", "keys": keys, "force": force, "reason": reason, "msg": msg, } ) for k in keys: st = self.futures.pop(k, None) if st is not None: st.cancel(reason=reason, msg=msg) def cancel(self, futures, asynchronous=None, force=False, reason=None, msg=None): """ Cancel running futures This stops future tasks from being scheduled if they have not yet run and deletes them if they have already run. After calling, this result and all dependent results will no longer be accessible Parameters ---------- futures : List[Future] The list of Futures asynchronous: bool If True the client is in asynchronous mode force : boolean (False) Cancel this future even if other clients desire it reason: str Reason for cancelling the futures msg : str Message that will be attached to the cancelled future """ return self.sync( self._cancel, futures, asynchronous=asynchronous, force=force, msg=msg, reason=reason, ) async def _retry(self, futures): keys = list({f.key for f in futures_of(futures)}) response = await self.scheduler.retry(keys=keys, client=self.id) for key in response: st = self.futures[key] st.retry() def retry(self, futures, asynchronous=None): """ Retry failed futures Parameters ---------- futures : list of Futures The list of Futures asynchronous: bool If True the client is in asynchronous mode """ return self.sync(self._retry, futures, asynchronous=asynchronous) @log_errors async def _publish_dataset(self, *args, name=None, override=False, **kwargs): coroutines = [] uid = uuid.uuid4().hex self._send_to_scheduler({"op": "publish_flush_batched_send", "uid": uid}) def add_coro(name, data): keys = [f.key for f in futures_of(data)] async def _(): await self.scheduler.publish_wait_flush(uid=uid) await self.scheduler.publish_put( keys=keys, name=name, data=to_serialize(data), override=override, client=self.id, ) coroutines.append(_()) if name: if len(args) == 0: raise ValueError( "If name is provided, expecting call signature like" " publish_dataset(df, name='ds')" ) # in case this is a singleton, collapse it elif len(args) == 1: args = args[0] add_coro(name, args) for name, data in kwargs.items(): add_coro(name, data) await asyncio.gather(*coroutines) def publish_dataset(self, *args, **kwargs): """ Publish named datasets to scheduler This stores a named reference to a dask collection or list of futures on the scheduler. These references are available to other Clients which can download the collection or futures with ``get_dataset``. Datasets are not immediately computed. You may wish to call ``Client.persist`` prior to publishing a dataset. Parameters ---------- args : list of objects to publish as name kwargs : dict named collections to publish on the scheduler Examples -------- Publishing client: >>> df = dd.read_csv('s3://...') # doctest: +SKIP >>> df = c.persist(df) # doctest: +SKIP >>> c.publish_dataset(my_dataset=df) # doctest: +SKIP Alternative invocation >>> c.publish_dataset(df, name='my_dataset') Receiving client: >>> c.list_datasets() # doctest: +SKIP ['my_dataset'] >>> df2 = c.get_dataset('my_dataset') # doctest: +SKIP Returns ------- None See Also -------- Client.list_datasets Client.get_dataset Client.unpublish_dataset Client.persist """ return self.sync(self._publish_dataset, *args, **kwargs) def unpublish_dataset(self, name, **kwargs): """ Remove named datasets from scheduler Parameters ---------- name : str The name of the dataset to unpublish Examples -------- >>> c.list_datasets() # doctest: +SKIP ['my_dataset'] >>> c.unpublish_dataset('my_dataset') # doctest: +SKIP >>> c.list_datasets() # doctest: +SKIP [] See Also -------- Client.publish_dataset """ return self.sync(self.scheduler.publish_delete, name=name, **kwargs) def list_datasets(self, **kwargs): """ List named datasets available on the scheduler See Also -------- Client.publish_dataset Client.get_dataset """ return self.sync(self.scheduler.publish_list, **kwargs) async def _get_dataset(self, name, default=no_default): with self.as_current(): out = await self.scheduler.publish_get(name=name, client=self.id) if out is None: if default is no_default: raise KeyError(f"Dataset '{name}' not found") else: return default for fut in futures_of(out["data"]): fut.bind_client(self) self._inform_scheduler_of_futures() return out["data"] def get_dataset(self, name, default=no_default, **kwargs): """ Get named dataset from the scheduler if present. Return the default or raise a KeyError if not present. Parameters ---------- name : str name of the dataset to retrieve default : str optional, not set by default If set, do not raise a KeyError if the name is not present but return this default kwargs : dict additional keyword arguments to _get_dataset Returns ------- The dataset from the scheduler, if present See Also -------- Client.publish_dataset Client.list_datasets """ return self.sync(self._get_dataset, name, default=default, **kwargs) async def _run_on_scheduler(self, function, *args, wait=True, **kwargs): response = await self.scheduler.run_function( function=dumps(function), args=dumps(args), kwargs=dumps(kwargs), wait=wait, ) if response["status"] == "error": typ, exc, tb = clean_exception(**response) raise exc.with_traceback(tb) else: return response["result"] def run_on_scheduler(self, function, *args, **kwargs): """Run a function on the scheduler process This is typically used for live debugging. The function should take a keyword argument ``dask_scheduler=``, which will be given the scheduler object itself. Parameters ---------- function : callable The function to run on the scheduler process *args : tuple Optional arguments for the function **kwargs : dict Optional keyword arguments for the function Examples -------- >>> def get_number_of_tasks(dask_scheduler=None): ... return len(dask_scheduler.tasks) >>> client.run_on_scheduler(get_number_of_tasks) # doctest: +SKIP 100 Run asynchronous functions in the background: >>> async def print_state(dask_scheduler): # doctest: +SKIP ... while True: ... print(dask_scheduler.status) ... await asyncio.sleep(1) >>> c.run(print_state, wait=False) # doctest: +SKIP See Also -------- Client.run : Run a function on all workers """ return self.sync(self._run_on_scheduler, function, *args, **kwargs) async def _run( self, function, *args, nanny: bool = False, workers: list[str] | None = None, wait: bool = True, on_error: Literal["raise", "return", "ignore"] = "raise", **kwargs, ): responses = await self.scheduler.broadcast( msg=dict( op="run", function=dumps(function), args=dumps(args), wait=wait, kwargs=dumps(kwargs), ), workers=workers, nanny=nanny, on_error="return_pickle", ) results = {} for key, resp in responses.items(): if isinstance(resp, bytes): # Pickled RPC exception exc = loads(resp) assert isinstance(exc, Exception) elif resp["status"] == "error": # Exception raised by the remote function _, exc, tb = clean_exception(**resp) exc = exc.with_traceback(tb) else: assert resp["status"] == "OK" results[key] = resp["result"] continue if on_error == "raise": raise exc elif on_error == "return": results[key] = exc elif on_error != "ignore": raise ValueError( "on_error must be 'raise', 'return', or 'ignore'; " f"got {on_error!r}" ) if wait: return results def run( self, function, *args, workers: list[str] | None = None, wait: bool = True, nanny: bool = False, on_error: Literal["raise", "return", "ignore"] = "raise", **kwargs, ): """ Run a function on all workers outside of task scheduling system This calls a function on all currently known workers immediately, blocks until those results come back, and returns the results asynchronously as a dictionary keyed by worker address. This method is generally used for side effects such as collecting diagnostic information or installing libraries. If your function takes an input argument named ``dask_worker`` then that variable will be populated with the worker itself. Parameters ---------- function : callable The function to run *args : tuple Optional arguments for the remote function **kwargs : dict Optional keyword arguments for the remote function workers : list Workers on which to run the function. Defaults to all known workers. wait : boolean (optional) If the function is asynchronous whether or not to wait until that function finishes. nanny : bool, default False Whether to run ``function`` on the nanny. By default, the function is run on the worker process. If specified, the addresses in ``workers`` should still be the worker addresses, not the nanny addresses. on_error: "raise" | "return" | "ignore" If the function raises an error on a worker: raise (default) Re-raise the exception on the client. The output from other workers will be lost. return Return the Exception object instead of the function output for the worker ignore Ignore the exception and remove the worker from the result dict Examples -------- >>> c.run(os.getpid) # doctest: +SKIP {'192.168.0.100:9000': 1234, '192.168.0.101:9000': 4321, '192.168.0.102:9000': 5555} Restrict computation to particular workers with the ``workers=`` keyword argument. >>> c.run(os.getpid, workers=['192.168.0.100:9000', ... '192.168.0.101:9000']) # doctest: +SKIP {'192.168.0.100:9000': 1234, '192.168.0.101:9000': 4321} >>> def get_status(dask_worker): ... return dask_worker.status >>> c.run(get_status) # doctest: +SKIP {'192.168.0.100:9000': 'running', '192.168.0.101:9000': 'running} Run asynchronous functions in the background: >>> async def print_state(dask_worker): # doctest: +SKIP ... while True: ... print(dask_worker.status) ... await asyncio.sleep(1) >>> c.run(print_state, wait=False) # doctest: +SKIP """ return self.sync( self._run, function, *args, workers=workers, wait=wait, nanny=nanny, on_error=on_error, **kwargs, ) @staticmethod def _get_computation_code( stacklevel: int | None = None, nframes: int = 1 ) -> tuple[SourceCode, ...]: """Walk up the stack to the user code and extract the code surrounding the compute/submit/persist call. All modules encountered which are ignored through the option `distributed.diagnostics.computations.ignore-modules` will be ignored. This can be used to exclude commonly used libraries which wrap dask/distributed compute calls. ``stacklevel`` may be used to explicitly indicate from which frame on the stack to get the source code. """ if nframes <= 0: return () ignore_modules = dask.config.get( "distributed.diagnostics.computations.ignore-modules" ) if not isinstance(ignore_modules, list): raise TypeError( "Ignored modules must be a list. Instead got " f"({type(ignore_modules)}, {ignore_modules})" ) ignore_files = dask.config.get( "distributed.diagnostics.computations.ignore-files" ) if not isinstance(ignore_files, list): raise TypeError( "Ignored files must be a list. Instead got " f"({type(ignore_files)}, {ignore_files})" ) mod_pattern: re.Pattern | None = None fname_pattern: re.Pattern | None = None if stacklevel is None: if ignore_modules: mod_pattern = re.compile( "|".join([f"(?:{mod})" for mod in ignore_modules]) ) if ignore_files: fname_pattern = re.compile( r".*[\\/](" + "|".join(mod for mod in ignore_files) + r")([\\/]|$)" ) else: # stacklevel 0 or less - shows dask internals which likely isn't helpful stacklevel = stacklevel if stacklevel > 0 else 1 code: list[SourceCode] = [] for i, (fr, lineno_frame) in enumerate( traceback.walk_stack(sys._getframe().f_back), 1 ): if len(code) >= nframes: break if stacklevel is not None and i != stacklevel: continue if fr.f_code.co_name in ("<listcomp>", "<dictcomp>"): continue if mod_pattern and mod_pattern.match(fr.f_globals.get("__name__", "")): continue if fname_pattern and fname_pattern.match(fr.f_code.co_filename): continue kwargs = dict( lineno_frame=lineno_frame, lineno_relative=lineno_frame - fr.f_code.co_firstlineno, filename=fr.f_code.co_filename, ) try: code.append(SourceCode(code=inspect.getsource(fr), **kwargs)) # type: ignore except OSError: try: from IPython import get_ipython ip = get_ipython() if ip is not None: # The current cell code.append(SourceCode(code=ip.history_manager._i00, **kwargs)) # type: ignore except ImportError: pass # No IPython break if hasattr(fr.f_back, "f_globals"): module_name = fr.f_back.f_globals["__name__"] # type: ignore if module_name == "__channelexec__": break # execnet; pytest-xdist # pragma: nocover try: module_name = sys.modules[module_name].__name__ except KeyError: # Ignore pathological cases where the module name isn't in `sys.modules` break # Ignore IPython related wrapping functions to user code if module_name.endswith("interactiveshell"): break return tuple(reversed(code)) def _inform_scheduler_of_futures(self): self._send_to_scheduler( { "op": "client-desires-keys", "keys": list(self.refcount), } ) def _graph_to_futures( self, expr, keys, span_metadata, workers=None, allow_other_workers=None, internal_priority=None, user_priority=0, resources=None, retries=None, fifo_timeout=0, actors=None, ): with self._refcount_lock: if actors is not None and actors is not True and actors is not False: actors = list(self._expand_key(actors)) annotations = {} if user_priority: annotations["priority"] = user_priority if workers: if not isinstance(workers, (list, tuple, set)): workers = [workers] annotations["workers"] = workers if retries: annotations["retries"] = retries if allow_other_workers not in (True, False, None): raise TypeError("allow_other_workers= must be True, False, or None") if allow_other_workers: annotations["allow_other_workers"] = allow_other_workers if resources: annotations["resources"] = resources # Merge global and local annotations annotations = merge(dask.get_annotations(), annotations) # Pack the high level graph before sending it to the scheduler keyset = set(keys) # Validate keys for key in keyset: validate_key(key) # Create futures before sending graph (helps avoid contention) futures = {key: Future(key, self) for key in keyset} # This is done manually here to get better exception messages on # scheduler side and be able to produce the below warning about # serialized size expr_ser = Serialized(*serialize(to_serialize(expr), on_error="raise")) pickled_size = sum(map(nbytes, [expr_ser.header] + expr_ser.frames)) if pickled_size > parse_bytes( dask.config.get("distributed.admin.large-graph-warning-threshold") ): warnings.warn( f"Sending large graph of size {format_bytes(pickled_size)}.\n" "This may cause some slowdown.\n" "Consider loading the data with Dask directly\n or using futures or " "delayed objects to embed the data into the graph without repetition.\n" "See also https://docs.dask.org/en/stable/best-practices.html#load-data-with-dask for more information." ) computations = self._get_computation_code( nframes=dask.config.get("distributed.diagnostics.computations.nframes") ) self._send_to_scheduler( { "op": "update-graph", "expr_ser": expr_ser, "keys": set(keys), "internal_priority": internal_priority, "submitting_task": getattr(thread_state, "key", None), "fifo_timeout": fifo_timeout, "actors": actors, "code": ToPickle(computations), "annotations": ToPickle(annotations), "span_metadata": ToPickle(span_metadata), } ) return futures def get( self, dsk, keys, workers=None, allow_other_workers=None, resources=None, sync=True, asynchronous=None, direct=None, retries=None, priority=0, fifo_timeout="60s", actors=None, **kwargs, ): """Compute dask graph Parameters ---------- dsk : dict keys : object, or nested lists of objects workers : string or iterable of strings A set of worker addresses or hostnames on which computations may be performed. Leave empty to default to all workers (common case) allow_other_workers : bool (defaults to False) Used with ``workers``. Indicates whether or not the computations may be performed on workers that are not in the `workers` set(s). resources : dict (defaults to {}) Defines the ``resources`` each instance of this mapped task requires on the worker; e.g. ``{'GPU': 2}``. See :doc:`worker resources <resources>` for details on defining resources. sync : bool (optional) Returns Futures if False or concrete values if True (default). asynchronous: bool If True the client is in asynchronous mode direct : bool Whether or not to connect directly to the workers, or to ask the scheduler to serve as intermediary. This can also be set when creating the Client. retries : int (default to 0) Number of allowed automatic retries if computing a result fails priority : Number Optional prioritization of task. Zero is default. Higher priorities take precedence fifo_timeout : timedelta str (defaults to '60s') Allowed amount of time between calls to consider the same priority actors : bool or dict (default None) Whether these tasks should exist on the worker as stateful actors. Specified on a global (True/False) or per-task (``{'x': True, 'y': False}``) basis. See :doc:`actors` for additional details. Returns ------- results If 'sync' is True, returns the results. Otherwise, returns the known data packed If 'sync' is False, returns the known data. Otherwise, returns the results Examples -------- >>> from operator import add # doctest: +SKIP >>> c = Client('127.0.0.1:8787') # doctest: +SKIP >>> c.get({'x': (add, 1, 2)}, 'x') # doctest: +SKIP 3 See Also -------- Client.compute : Compute asynchronous collections """ if isinstance(dsk, dict): dsk = LLGExpr(dsk) elif isinstance(dsk, HighLevelGraph): dsk = HLGExpr(dsk) futures = self._graph_to_futures( expr=dsk, keys=set(flatten([keys])), workers=workers, allow_other_workers=allow_other_workers, resources=resources, fifo_timeout=fifo_timeout, retries=retries, user_priority=priority, actors=actors, span_metadata=SpanMetadata(collections=[{"type": "low-level-graph"}]), ) packed = pack_data(keys, futures) if sync: if getattr(thread_state, "key", False): try: secede() should_rejoin = True except Exception: should_rejoin = False try: results = self.gather(packed, asynchronous=asynchronous, direct=direct) finally: for f in futures.values(): f.release() if getattr(thread_state, "key", False) and should_rejoin: rejoin() return results return packed def _optimize_insert_futures(self, dsk, keys): """Replace known keys in dask graph with Futures When given a Dask graph that might have overlapping keys with our known results we replace the values of that graph with futures. This can be used as an optimization to avoid recomputation. This returns the same graph if unchanged but a new graph if any changes were necessary. """ with self._refcount_lock: changed = False for key in list(dsk): if key in self.futures: if not changed: changed = True dsk = ensure_dict(dsk) dsk[key] = Future(key, self) if changed: dsk, _ = dask.optimization.cull(dsk, keys) return dsk def normalize_collection(self, collection): """ Replace collection's tasks by already existing futures if they exist This normalizes the tasks within a collections task graph against the known futures within the scheduler. It returns a copy of the collection with a task graph that includes the overlapping futures. Parameters ---------- collection : dask object Collection like dask.array or dataframe or dask.value objects Returns ------- collection : dask object Collection with its tasks replaced with any existing futures. Examples -------- >>> len(x.__dask_graph__()) # x is a dask collection with 100 tasks # doctest: +SKIP 100 >>> set(client.futures).intersection(x.__dask_graph__()) # some overlap exists # doctest: +SKIP 10 >>> x = client.normalize_collection(x) # doctest: +SKIP >>> len(x.__dask_graph__()) # smaller computational graph # doctest: +SKIP 20 See Also -------- Client.persist : trigger computation of collection's tasks """ dsk_orig = collection.__dask_graph__() dsk = self._optimize_insert_futures(dsk_orig, collection.__dask_keys__()) if dsk is dsk_orig: return collection else: return redict_collection(collection, dsk) def compute( self, collections, sync=False, optimize_graph=True, workers=None, allow_other_workers=False, resources=None, retries=0, priority=0, fifo_timeout="60s", actors=None, traverse=True, **kwargs, ): """Compute dask collections on cluster Parameters ---------- collections : iterable of dask objects or single dask object Collections like dask.array or dataframe or dask.value objects sync : bool (optional) Returns Futures if False (default) or concrete values if True optimize_graph : bool Whether or not to optimize the underlying graphs workers : string or iterable of strings A set of worker hostnames on which computations may be performed. Leave empty to default to all workers (common case) allow_other_workers : bool (defaults to False) Used with `workers`. Indicates whether or not the computations may be performed on workers that are not in the `workers` set(s). retries : int (default to 0) Number of allowed automatic retries if computing a result fails priority : Number Optional prioritization of task. Zero is default. Higher priorities take precedence fifo_timeout : timedelta str (defaults to '60s') Allowed amount of time between calls to consider the same priority traverse : bool (defaults to True) By default dask traverses builtin python collections looking for dask objects passed to ``compute``. For large collections this can be expensive. If none of the arguments contain any dask objects, set ``traverse=False`` to avoid doing this traversal. resources : dict (defaults to {}) Defines the `resources` each instance of this mapped task requires on the worker; e.g. ``{'GPU': 2}``. See :doc:`worker resources <resources>` for details on defining resources. actors : bool or dict (default None) Whether these tasks should exist on the worker as stateful actors. Specified on a global (True/False) or per-task (``{'x': True, 'y': False}``) basis. See :doc:`actors` for additional details. **kwargs Options to pass to the graph optimize calls Returns ------- List of Futures if input is a sequence, or a single future otherwise Examples -------- >>> from dask import delayed >>> from operator import add >>> x = delayed(add)(1, 2) >>> y = delayed(add)(x, x) >>> xx, yy = client.compute([x, y]) # doctest: +SKIP >>> xx # doctest: +SKIP <Future: status: finished, key: add-8f6e709446674bad78ea8aeecfee188e> >>> xx.result() # doctest: +SKIP 3 >>> yy.result() # doctest: +SKIP 6 Also support single arguments >>> xx = client.compute(x) # doctest: +SKIP See Also -------- Client.get : Normal synchronous dask.get function """ if isinstance(collections, (list, tuple, set, frozenset)): singleton = False else: collections = [collections] singleton = True if traverse: collections = tuple( ( dask.delayed(a) if isinstance(a, (list, set, tuple, dict, Iterator)) else a ) for a in collections ) variables = [a for a in collections if dask.is_dask_collection(a)] metadata = SpanMetadata( collections=[get_collections_metadata(v) for v in variables] ) futures_dict = {} if variables: expr = collections_to_expr(variables, optimize_graph, **kwargs) from dask._expr import FinalizeCompute expr = FinalizeCompute(expr) expr = expr.optimize() names = list(flatten(expr.__dask_keys__())) futures_dict = self._graph_to_futures( expr, names, workers=workers, allow_other_workers=allow_other_workers, resources=resources, retries=retries, user_priority=priority, fifo_timeout=fifo_timeout, actors=actors, span_metadata=metadata, ) i = 0 futures = [] for arg in collections: if dask.is_dask_collection(arg): futures.append(futures_dict[names[i]]) i += 1 else: futures.append(arg) if sync: result = self.gather(futures) else: result = futures if singleton: return first(result) else: return result def persist( self, collections, optimize_graph=True, workers=None, allow_other_workers=None, resources=None, retries=None, priority=0, fifo_timeout="60s", actors=None, **kwargs, ): """Persist dask collections on cluster Starts computation of the collection on the cluster in the background. Provides a new dask collection that is semantically identical to the previous one, but now based off of futures currently in execution. Parameters ---------- collections : sequence or single dask object Collections like dask.array or dataframe or dask.value objects optimize_graph : bool Whether or not to optimize the underlying graphs workers : string or iterable of strings A set of worker hostnames on which computations may be performed. Leave empty to default to all workers (common case) allow_other_workers : bool (defaults to False) Used with `workers`. Indicates whether or not the computations may be performed on workers that are not in the `workers` set(s). retries : int (default to 0) Number of allowed automatic retries if computing a result fails priority : Number Optional prioritization of task. Zero is default. Higher priorities take precedence fifo_timeout : timedelta str (defaults to '60s') Allowed amount of time between calls to consider the same priority resources : dict (defaults to {}) Defines the `resources` each instance of this mapped task requires on the worker; e.g. ``{'GPU': 2}``. See :doc:`worker resources <resources>` for details on defining resources. actors : bool or dict (default None) Whether these tasks should exist on the worker as stateful actors. Specified on a global (True/False) or per-task (``{'x': True, 'y': False}``) basis. See :doc:`actors` for additional details. Returns ------- List of collections, or single collection, depending on type of input. Examples -------- >>> xx = client.persist(x) # doctest: +SKIP >>> xx, yy = client.persist([x, y]) # doctest: +SKIP See Also -------- Client.compute """ if isinstance(collections, (tuple, list, set, frozenset)): singleton = False else: singleton = True collections = [collections] assert all(map(dask.is_dask_collection, collections)) metadata = SpanMetadata( collections=[get_collections_metadata(v) for v in collections] ) expr = collections_to_expr(collections, optimize_graph) expr2 = expr.optimize() keys = expr2.__dask_keys__() futures = self._graph_to_futures( expr2, list(flatten(keys)), workers=workers, allow_other_workers=allow_other_workers, resources=resources, retries=retries, user_priority=priority, fifo_timeout=fifo_timeout, actors=actors, span_metadata=metadata, ) postpersists = [c.__dask_postpersist__() for c in collections] assert len(postpersists) == len(keys) result = [ func({k: futures[k] for k in flatten(ks)}, *args) for (func, args), ks in zip(postpersists, keys) ] if singleton: return result[0] return result async def _restart( self, timeout: str | int | float | NoDefault, wait_for_workers: bool ) -> None: if timeout is no_default: timeout = self._timeout * 4 timeout = parse_timedelta(cast("str|int|float", timeout), "s") await self.scheduler.restart( timeout=timeout, wait_for_workers=wait_for_workers, stimulus_id=f"client-restart-{time()}", ) def restart( self, timeout: str | int | float | NoDefault = no_default, wait_for_workers: bool = True, ): """ Restart all workers. Reset local state. Optionally wait for workers to return. Workers without nannies are shut down, hoping an external deployment system will restart them. Therefore, if not using nannies and your deployment system does not automatically restart workers, ``restart`` will just shut down all workers, then time out! After ``restart``, all connected workers are new, regardless of whether ``TimeoutError`` was raised. Any workers that failed to shut down in time are removed, and may or may not shut down on their own in the future. Parameters ---------- timeout: How long to wait for workers to shut down and come back, if ``wait_for_workers`` is True, otherwise just how long to wait for workers to shut down. Raises ``asyncio.TimeoutError`` if this is exceeded. wait_for_workers: Whether to wait for all workers to reconnect, or just for them to shut down (default True). Use ``restart(wait_for_workers=False)`` combined with :meth:`Client.wait_for_workers` for granular control over how many workers to wait for. See also -------- Scheduler.restart Client.restart_workers """ return self.sync( self._restart, timeout=timeout, wait_for_workers=wait_for_workers ) async def _restart_workers( self, workers: list[str], timeout: str | int | float | NoDefault, raise_for_error: bool, ) -> dict[str, Literal["OK", "removed", "timed out"]]: if timeout is no_default: timeout = self._timeout * 4 timeout = parse_timedelta(cast("str|int|float", timeout), "s") info = self.scheduler_info() name_to_addr = {meta["name"]: addr for addr, meta in info["workers"].items()} worker_addrs = [name_to_addr.get(w, w) for w in workers] out: dict[str, Literal["OK", "removed", "timed out"]] = ( await self.scheduler.restart_workers( workers=worker_addrs, timeout=timeout, on_error="raise" if raise_for_error else "return", stimulus_id=f"client-restart-workers-{time()}", ) ) # Map keys back to original `workers` input names/addresses out = {w: out[w_addr] for w, w_addr in zip(workers, worker_addrs)} if raise_for_error: assert all(v == "OK" for v in out.values()), out return out def restart_workers( self, workers: list[str], timeout: str | int | float | NoDefault = no_default, raise_for_error: bool = True, ): """Restart a specified set of workers .. note:: Only workers being monitored by a :class:`distributed.Nanny` can be restarted. See ``Nanny.restart`` for more details. Parameters ---------- workers : list[str] Workers to restart. This can be a list of worker addresses, names, or a both. timeout : int | float | None Number of seconds to wait raise_for_error: bool (default True) Whether to raise a :py:class:`TimeoutError` if restarting worker(s) doesn't finish within ``timeout``, or another exception caused from restarting worker(s). Returns ------- dict[str, "OK" | "removed" | "timed out"] Mapping of worker and restart status, the keys will match the original values passed in via ``workers``. Notes ----- This method differs from :meth:`Client.restart` in that this method simply restarts the specified set of workers, while ``Client.restart`` will restart all workers and also reset local state on the cluster (e.g. all keys are released). Additionally, this method does not gracefully handle tasks that are being executed when a worker is restarted. These tasks may fail or have their suspicious count incremented. Examples -------- You can get information about active workers using the following: >>> workers = client.scheduler_info()['workers'] From that list you may want to select some workers to restart >>> client.restart_workers(workers=['tcp://address:port', ...]) See Also -------- Client.restart """ info = self.scheduler_info() for worker, meta in info["workers"].items(): if (worker in workers or meta["name"] in workers) and meta["nanny"] is None: raise ValueError( f"Restarting workers requires a nanny to be used. Worker " f"{worker} has type {info['workers'][worker]['type']}." ) return self.sync( self._restart_workers, workers=workers, timeout=timeout, raise_for_error=raise_for_error, ) async def _upload_large_file(self, local_filename, remote_filename=None): if remote_filename is None: remote_filename = os.path.split(local_filename)[1] with open(local_filename, "rb") as f: data = f.read() [future] = await self._scatter([data]) key = future.key await self._replicate(future) def dump_to_file(dask_worker=None): if not os.path.isabs(remote_filename): fn = os.path.join(dask_worker.local_directory, remote_filename) else: fn = remote_filename with open(fn, "wb") as f: f.write(dask_worker.data[key]) return len(dask_worker.data[key]) response = await self._run(dump_to_file) assert all(len(data) == v for v in response.values()) def upload_file(self, filename, load: bool = True): """Upload local package to scheduler and workers This sends a local file up to the scheduler and all worker nodes. This file is placed into the working directory of each node, see config option ``temporary-directory`` (defaults to :py:func:`tempfile.gettempdir`). This directory will be added to the Python's system path so any ``.py``, ``.egg`` or ``.zip`` files will be importable. Parameters ---------- filename : string Filename of ``.py``, ``.egg``, or ``.zip`` file to send to workers load : bool, optional Whether or not to import the module as part of the upload process. Defaults to ``True``. Examples -------- >>> client.upload_file('mylibrary.egg') # doctest: +SKIP >>> from mylibrary import myfunc # doctest: +SKIP >>> L = client.map(myfunc, seq) # doctest: +SKIP >>> >>> # Where did that file go? Use `dask_worker.local_directory`. >>> def where_is_mylibrary(dask_worker): >>> path = pathlib.Path(dask_worker.local_directory) / 'mylibrary.egg' >>> assert path.exists() >>> return str(path) >>> >>> client.run(where_is_mylibrary) # doctest: +SKIP """ name = filename + str(uuid.uuid4()) async def _(): results = await asyncio.gather( self.register_plugin( SchedulerUploadFile(filename, load=load), name=name ), # FIXME: Make scheduler plugin responsible for (de)registering worker plugin self.register_plugin(UploadFile(filename, load=load), name=name), ) return results[1] # Results from workers upload return self.sync(_) async def _rebalance(self, futures=None, workers=None): if futures is not None: await _wait(futures) keys = list({f.key for f in self.futures_of(futures)}) else: keys = None result = await self.scheduler.rebalance(keys=keys, workers=workers) if result["status"] == "partial-fail": raise KeyError(f"Could not rebalance keys: {result['keys']}") assert result["status"] == "OK", result def rebalance(self, futures=None, workers=None, **kwargs): """Rebalance data within network Move data between workers to roughly balance memory burden. This either affects a subset of the keys/workers or the entire network, depending on keyword arguments. For details on the algorithm and configuration options, refer to the matching scheduler-side method :meth:`~distributed.scheduler.Scheduler.rebalance`. .. warning:: This operation is generally not well tested against normal operation of the scheduler. It is not recommended to use it while waiting on computations. Parameters ---------- futures : list, optional A list of futures to balance, defaults all data workers : list, optional A list of workers on which to balance, defaults to all workers **kwargs : dict Optional keyword arguments for the function """ return self.sync(self._rebalance, futures, workers, **kwargs) async def _replicate(self, futures, n=None, workers=None, branching_factor=2): futures = self.futures_of(futures) await _wait(futures) keys = {f.key for f in futures} await self.scheduler.replicate( keys=list(keys), n=n, workers=workers, branching_factor=branching_factor ) def replicate(self, futures, n=None, workers=None, branching_factor=2, **kwargs): """Set replication of futures within network Copy data onto many workers. This helps to broadcast frequently accessed data and can improve resilience. This performs a tree copy of the data throughout the network individually on each piece of data. This operation blocks until complete. It does not guarantee replication of data to future workers. .. note:: This method is incompatible with the Active Memory Manager's :ref:`ReduceReplicas` policy. If you wish to use it, you must first disable the policy or disable the AMM entirely. Parameters ---------- futures : list of futures Futures we wish to replicate n : int, optional Number of processes on the cluster on which to replicate the data. Defaults to all. workers : list of worker addresses Workers on which we want to restrict the replication. Defaults to all. branching_factor : int, optional The number of workers that can copy data in each generation **kwargs : dict Optional keyword arguments for the remote function Examples -------- >>> x = c.submit(func, *args) # doctest: +SKIP >>> c.replicate([x]) # send to all workers # doctest: +SKIP >>> c.replicate([x], n=3) # send to three workers # doctest: +SKIP >>> c.replicate([x], workers=['alice', 'bob']) # send to specific # doctest: +SKIP >>> c.replicate([x], n=1, workers=['alice', 'bob']) # send to one of specific workers # doctest: +SKIP >>> c.replicate([x], n=1) # reduce replications # doctest: +SKIP See Also -------- Client.rebalance """ return self.sync( self._replicate, futures, n=n, workers=workers, branching_factor=branching_factor, **kwargs, ) def nthreads(self, workers=None, **kwargs): """The number of threads/cores available on each worker node Parameters ---------- workers : list (optional) A list of workers that we care about specifically. Leave empty to receive information about all workers. **kwargs : dict Optional keyword arguments for the remote function Examples -------- >>> c.nthreads() # doctest: +SKIP {'192.168.1.141:46784': 8, '192.167.1.142:47548': 8, '192.167.1.143:47329': 8, '192.167.1.144:37297': 8} See Also -------- Client.who_has Client.has_what """ if isinstance(workers, tuple) and all( isinstance(i, (str, tuple)) for i in workers ): workers = list(workers) if workers is not None and not isinstance(workers, (tuple, list, set)): workers = [workers] return self.sync(self.scheduler.ncores, workers=workers, **kwargs) ncores = nthreads def who_has(self, futures=None, **kwargs): """The workers storing each future's data Parameters ---------- futures : list (optional) A list of futures, defaults to all data **kwargs : dict Optional keyword arguments for the remote function Examples -------- >>> x, y, z = c.map(inc, [1, 2, 3]) # doctest: +SKIP >>> wait([x, y, z]) # doctest: +SKIP >>> c.who_has() # doctest: +SKIP {'inc-1c8dd6be1c21646c71f76c16d09304ea': ['192.168.1.141:46784'], 'inc-1e297fc27658d7b67b3a758f16bcf47a': ['192.168.1.141:46784'], 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b': ['192.168.1.141:46784']} >>> c.who_has([x, y]) # doctest: +SKIP {'inc-1c8dd6be1c21646c71f76c16d09304ea': ['192.168.1.141:46784'], 'inc-1e297fc27658d7b67b3a758f16bcf47a': ['192.168.1.141:46784']} See Also -------- Client.has_what Client.nthreads """ if futures is not None: futures = self.futures_of(futures) keys = list({f.key for f in futures}) else: keys = None async def _(): return WhoHas(await self.scheduler.who_has(keys=keys, **kwargs)) return self.sync(_) def has_what(self, workers=None, **kwargs): """Which keys are held by which workers This returns the keys of the data that are held in each worker's memory. Parameters ---------- workers : list (optional) A list of worker addresses, defaults to all **kwargs : dict Optional keyword arguments for the remote function Examples -------- >>> x, y, z = c.map(inc, [1, 2, 3]) # doctest: +SKIP >>> wait([x, y, z]) # doctest: +SKIP >>> c.has_what() # doctest: +SKIP {'192.168.1.141:46784': ['inc-1c8dd6be1c21646c71f76c16d09304ea', 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b', 'inc-1e297fc27658d7b67b3a758f16bcf47a']} See Also -------- Client.who_has Client.nthreads Client.processing """ if isinstance(workers, tuple) and all( isinstance(i, (str, tuple)) for i in workers ): workers = list(workers) if workers is not None and not isinstance(workers, (tuple, list, set)): workers = [workers] async def _(): return HasWhat(await self.scheduler.has_what(workers=workers, **kwargs)) return self.sync(_) def processing(self, workers=None): """The tasks currently running on each worker Parameters ---------- workers : list (optional) A list of worker addresses, defaults to all Examples -------- >>> x, y, z = c.map(inc, [1, 2, 3]) # doctest: +SKIP >>> c.processing() # doctest: +SKIP {'192.168.1.141:46784': ['inc-1c8dd6be1c21646c71f76c16d09304ea', 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b', 'inc-1e297fc27658d7b67b3a758f16bcf47a']} See Also -------- Client.who_has Client.has_what Client.nthreads """ if isinstance(workers, tuple) and all( isinstance(i, (str, tuple)) for i in workers ): workers = list(workers) if workers is not None and not isinstance(workers, (tuple, list, set)): workers = [workers] return self.sync(self.scheduler.processing, workers=workers) def nbytes(self, keys=None, summary=True, **kwargs): """The bytes taken up by each key on the cluster This is as measured by ``sys.getsizeof`` which may not accurately reflect the true cost. Parameters ---------- keys : list (optional) A list of keys, defaults to all keys summary : boolean, (optional) Summarize keys into key types **kwargs : dict Optional keyword arguments for the remote function Examples -------- >>> x, y, z = c.map(inc, [1, 2, 3]) # doctest: +SKIP >>> c.nbytes(summary=False) # doctest: +SKIP {'inc-1c8dd6be1c21646c71f76c16d09304ea': 28, 'inc-1e297fc27658d7b67b3a758f16bcf47a': 28, 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b': 28} >>> c.nbytes(summary=True) # doctest: +SKIP {'inc': 84} See Also -------- Client.who_has """ return self.sync(self.scheduler.nbytes, keys=keys, summary=summary, **kwargs) def call_stack(self, futures=None, keys=None): """The actively running call stack of all relevant keys You can specify data of interest either by providing futures or collections in the ``futures=`` keyword or a list of explicit keys in the ``keys=`` keyword. If neither are provided then all call stacks will be returned. Parameters ---------- futures : list (optional) List of futures, defaults to all data keys : list (optional) List of key names, defaults to all data Examples -------- >>> df = dd.read_parquet(...).persist() # doctest: +SKIP >>> client.call_stack(df) # call on collections >>> client.call_stack() # Or call with no arguments for all activity # doctest: +SKIP """ keys = keys or [] if futures is not None: futures = self.futures_of(futures) keys += list({f.key for f in futures}) return self.sync(self.scheduler.call_stack, keys=keys or None) def profile( self, key=None, start=None, stop=None, workers=None, merge_workers=True, plot=False, filename=None, server=False, scheduler=False, ): """Collect statistical profiling information about recent work Parameters ---------- key : str Key prefix to select, this is typically a function name like 'inc' Leave as None to collect all data start : time stop : time workers : list List of workers to restrict profile information server : bool If true, return the profile of the worker's administrative thread rather than the worker threads. This is useful when profiling Dask itself, rather than user code. scheduler : bool If true, return the profile information from the scheduler's administrative thread rather than the workers. This is useful when profiling Dask's scheduling itself. plot : boolean or string Whether or not to return a plot object filename : str Filename to save the plot Examples -------- >>> client.profile() # call on collections >>> client.profile(filename='dask-profile.html') # save to html file """ return self.sync( self._profile, key=key, workers=workers, merge_workers=merge_workers, start=start, stop=stop, plot=plot, filename=filename, server=server, scheduler=scheduler, ) async def _profile( self, key=None, start=None, stop=None, workers=None, merge_workers=True, plot=False, filename=None, server=False, scheduler=False, ): if isinstance(workers, (str, Number)): workers = [workers] state = await self.scheduler.profile( key=key, workers=workers, merge_workers=merge_workers, start=start, stop=stop, server=server, scheduler=scheduler, ) if filename: plot = True if plot: from distributed import profile data = profile.plot_data(state) figure, source = profile.plot_figure(data, sizing_mode="stretch_both") if plot == "save" and not filename: filename = "dask-profile.html" if filename: from bokeh.plotting import output_file, save output_file(filename=filename, title="Dask Profile") save(figure, filename=filename) return (state, figure) else: return state def scheduler_info(self, n_workers: int = 5, **kwargs: Any) -> SchedulerInfo: """Basic information about the workers in the cluster Parameters ---------- n_workers: int The number of workers for which to fetch information. To fetch all, use -1. **kwargs : dict Optional keyword arguments for the remote function Examples -------- >>> c.scheduler_info() # doctest: +SKIP {'id': '2de2b6da-69ee-11e6-ab6a-e82aea155996', 'services': {}, 'type': 'Scheduler', 'workers': {'127.0.0.1:40575': {'active': 0, 'last-seen': 1472038237.4845693, 'name': '127.0.0.1:40575', 'services': {}, 'stored': 0, 'time-delay': 0.0061032772064208984}}} """ if not self.asynchronous: self.sync(self._update_scheduler_info, n_workers=n_workers) return self._scheduler_identity def dump_cluster_state( self, filename: str = "dask-cluster-dump", write_from_scheduler: bool | None = None, exclude: Collection[str] = (), format: Literal["msgpack", "yaml"] = "msgpack", **storage_options, ): """Extract a dump of the entire cluster state and persist to disk or a URL. This is intended for debugging purposes only. Warning: Memory usage on the scheduler (and client, if writing the dump locally) can be large. On a large or long-running cluster, this can take several minutes. The scheduler may be unresponsive while the dump is processed. Results will be stored in a dict:: { "scheduler": {...}, # scheduler state "workers": { worker_addr: {...}, # worker state ... } "versions": { "scheduler": {...}, "workers": { worker_addr: {...}, ... } } } Parameters ---------- filename: The path or URL to write to. The appropriate file suffix (``.msgpack.gz`` or ``.yaml``) will be appended automatically. Must be a path supported by :func:`fsspec.open` (like ``s3://my-bucket/cluster-dump``, or ``cluster-dumps/dump``). See ``write_from_scheduler`` to control whether the dump is written directly to ``filename`` from the scheduler, or sent back to the client over the network, then written locally. write_from_scheduler: If None (default), infer based on whether ``filename`` looks like a URL or a local path: True if the filename contains ``://`` (like ``s3://my-bucket/cluster-dump``), False otherwise (like ``local_dir/cluster-dump``). If True, write cluster state directly to ``filename`` from the scheduler. If ``filename`` is a local path, the dump will be written to that path on the *scheduler's* filesystem, so be careful if the scheduler is running on ephemeral hardware. Useful when the scheduler is attached to a network filesystem or persistent disk, or for writing to buckets. If False, transfer cluster state from the scheduler back to the client over the network, then write it to ``filename``. This is much less efficient for large dumps, but useful when the scheduler doesn't have access to any persistent storage. exclude: A collection of attribute names which are supposed to be excluded from the dump, e.g. to exclude code, tracebacks, logs, etc. Defaults to exclude ``run_spec``, which is the serialized user code. This is typically not required for debugging. To allow serialization of this, pass an empty tuple. format: Either ``"msgpack"`` or ``"yaml"``. If msgpack is used (default), the output will be stored in a gzipped file as msgpack. To read:: import gzip, msgpack with gzip.open("filename") as fd: state = msgpack.unpack(fd) or:: import yaml try: from yaml import CLoader as Loader except ImportError: from yaml import Loader with open("filename") as fd: state = yaml.load(fd, Loader=Loader) **storage_options: Any additional arguments to :func:`fsspec.open` when writing to a URL. """ return self.sync( self._dump_cluster_state, filename=filename, write_from_scheduler=write_from_scheduler, exclude=exclude, format=format, **storage_options, ) async def _dump_cluster_state( self, filename: str = "dask-cluster-dump", write_from_scheduler: bool | None = None, exclude: Collection[str] = cluster_dump.DEFAULT_CLUSTER_DUMP_EXCLUDE, format: Literal["msgpack", "yaml"] = cluster_dump.DEFAULT_CLUSTER_DUMP_FORMAT, **storage_options, ): filename = str(filename) if write_from_scheduler is None: write_from_scheduler = "://" in filename if write_from_scheduler: await self.scheduler.dump_cluster_state_to_url( url=filename, exclude=exclude, format=format, **storage_options, ) else: await cluster_dump.write_state( partial(self.scheduler.get_cluster_state, exclude=exclude), filename, format, **storage_options, ) def write_scheduler_file(self, scheduler_file): """Write the scheduler information to a json file. This facilitates easy sharing of scheduler information using a file system. The scheduler file can be used to instantiate a second Client using the same scheduler. Parameters ---------- scheduler_file : str Path to a write the scheduler file. Examples -------- >>> client = Client() # doctest: +SKIP >>> client.write_scheduler_file('scheduler.json') # doctest: +SKIP # connect to previous client's scheduler >>> client2 = Client(scheduler_file='scheduler.json') # doctest: +SKIP """ if self.scheduler_file: raise ValueError("Scheduler file already set") else: self.scheduler_file = scheduler_file with open(self.scheduler_file, "w") as f: json.dump(self.scheduler_info(), f, indent=2) def get_metadata(self, keys, default=no_default): """Get arbitrary metadata from scheduler See set_metadata for the full docstring with examples Parameters ---------- keys : key or list Key to access. If a list then gets within a nested collection default : optional If the key does not exist then return this value instead. If not provided then this raises a KeyError if the key is not present See Also -------- Client.set_metadata """ if not isinstance(keys, (list, tuple)): keys = (keys,) return self.sync(self.scheduler.get_metadata, keys=keys, default=default) def get_scheduler_logs(self, n=None): """Get logs from scheduler Parameters ---------- n : int Number of logs to retrieve. Maxes out at 10000 by default, configurable via the ``distributed.admin.log-length`` configuration value. Returns ------- Logs in reversed order (newest first) """ return self.sync(self.scheduler.logs, n=n) def get_worker_logs(self, n=None, workers=None, nanny=False): """Get logs from workers Parameters ---------- n : int Number of logs to retrieve. Maxes out at 10000 by default, configurable via the ``distributed.admin.log-length`` configuration value. workers : iterable List of worker addresses to retrieve. Gets all workers by default. nanny : bool, default False Whether to get the logs from the workers (False) or the nannies (True). If specified, the addresses in `workers` should still be the worker addresses, not the nanny addresses. Returns ------- Dictionary mapping worker address to logs. Logs are returned in reversed order (newest first) """ return self.sync(self.scheduler.worker_logs, n=n, workers=workers, nanny=nanny) def benchmark_hardware(self) -> dict: """ Run a benchmark on the workers for memory, disk, and network bandwidths Returns ------- result: dict A dictionary mapping the names "disk", "memory", and "network" to dictionaries mapping sizes to bandwidths. These bandwidths are averaged over many workers running computations across the cluster. """ return self.sync(self.scheduler.benchmark_hardware) def log_event(self, topic: str | Collection[str], msg: Any): """Log an event under a given topic Parameters ---------- topic : str, list[str] Name of the topic under which to log an event. To log the same event under multiple topics, pass a list of topic names. msg Event message to log. Note this must be msgpack serializable. Examples -------- >>> from time import time >>> client.log_event("current-time", time()) """ if not _is_dumpable(msg): raise TypeError( f"Message must be msgpack serializable. Got {type(msg)=} instead." ) return self.sync(self.scheduler.log_event, topic=topic, msg=msg) def get_events(self, topic: str | None = None): """Retrieve structured topic logs Parameters ---------- topic : str, optional Name of topic log to retrieve events for. If no ``topic`` is provided, then logs for all topics will be returned. """ return self.sync(self.scheduler.events, topic=topic) async def _handle_event(self, topic, event): if topic not in self._event_handlers: self.unsubscribe_topic(topic) return handler = self._event_handlers[topic] ret = handler(event) if inspect.isawaitable(ret): await ret def subscribe_topic(self, topic, handler): """Subscribe to a topic and execute a handler for every received event Parameters ---------- topic: str The topic name handler: callable or coroutine function A handler called for every received event. The handler must accept a single argument `event` which is a tuple `(timestamp, msg)` where timestamp refers to the clock on the scheduler. Examples -------- >>> import logging >>> logger = logging.getLogger("myLogger") # Log config not shown >>> client.subscribe_topic("topic-name", lambda: logger.info) See Also -------- dask.distributed.Client.unsubscribe_topic dask.distributed.Client.get_events dask.distributed.Client.log_event """ if topic in self._event_handlers: logger.info("Handler for %s already set. Overwriting.", topic) self._event_handlers[topic] = handler msg = {"op": "subscribe-topic", "topic": topic, "client": self.id} self._send_to_scheduler(msg) def unsubscribe_topic(self, topic): """Unsubscribe from a topic and remove event handler See Also -------- dask.distributed.Client.subscribe_topic dask.distributed.Client.get_events dask.distributed.Client.log_event """ if topic in self._event_handlers: msg = {"op": "unsubscribe-topic", "topic": topic, "client": self.id} self._send_to_scheduler(msg) else: raise ValueError(f"No event handler known for topic {topic}.") def retire_workers( self, workers: list[str] | None = None, close_workers: bool = True, **kwargs ): """Retire certain workers on the scheduler See :meth:`distributed.Scheduler.retire_workers` for the full docstring. Parameters ---------- workers close_workers **kwargs : dict Optional keyword arguments for the remote function Examples -------- You can get information about active workers using the following: >>> workers = client.scheduler_info()['workers'] From that list you may want to select some workers to close >>> client.retire_workers(workers=['tcp://address:port', ...]) See Also -------- dask.distributed.Scheduler.retire_workers """ return self.sync( self.scheduler.retire_workers, workers=workers, close_workers=close_workers, **kwargs, ) def set_metadata(self, key, value): """Set arbitrary metadata in the scheduler This allows you to store small amounts of data on the central scheduler process for administrative purposes. Data should be msgpack serializable (ints, strings, lists, dicts) If the key corresponds to a task then that key will be cleaned up when the task is forgotten by the scheduler. If the key is a list then it will be assumed that you want to index into a nested dictionary structure using those keys. For example if you call the following:: >>> client.set_metadata(['a', 'b', 'c'], 123) Then this is the same as setting >>> scheduler.task_metadata['a']['b']['c'] = 123 The lower level dictionaries will be created on demand. Examples -------- >>> client.set_metadata('x', 123) # doctest: +SKIP >>> client.get_metadata('x') # doctest: +SKIP 123 >>> client.set_metadata(['x', 'y'], 123) # doctest: +SKIP >>> client.get_metadata('x') # doctest: +SKIP {'y': 123} >>> client.set_metadata(['x', 'w', 'z'], 456) # doctest: +SKIP >>> client.get_metadata('x') # doctest: +SKIP {'y': 123, 'w': {'z': 456}} >>> client.get_metadata(['x', 'w']) # doctest: +SKIP {'z': 456} See Also -------- get_metadata """ if not isinstance(key, list): key = (key,) return self.sync(self.scheduler.set_metadata, keys=key, value=value) def get_versions( self, check: bool = False, packages: Sequence[str] | None = None ) -> VersionsDict | Coroutine[Any, Any, VersionsDict]: """Return version info for the scheduler, all workers and myself Parameters ---------- check raise ValueError if all required & optional packages do not match packages Extra package names to check Examples -------- >>> c.get_versions() # doctest: +SKIP >>> c.get_versions(packages=['sklearn', 'geopandas']) # doctest: +SKIP """ return self.sync(self._get_versions, check=check, packages=packages or []) async def _get_versions( self, check: bool = False, packages: Sequence[str] | None = None ) -> VersionsDict: packages = packages or [] client = version_module.get_versions(packages=packages) scheduler = await self.scheduler.versions(packages=packages) workers = await self.scheduler.broadcast( msg={"op": "versions", "packages": packages}, on_error="ignore", ) result = VersionsDict(scheduler=scheduler, workers=workers, client=client) if check: msg = version_module.error_message(scheduler, workers, client) if msg["warning"]: warnings.warn(msg["warning"]) if msg["error"]: raise ValueError(msg["error"]) return result def futures_of(self, futures): """Wrapper method of futures_of Parameters ---------- futures : tuple The futures """ return futures_of(futures, client=self) @classmethod def _expand_key(cls, k): """ Expand a user-provided task key specification, e.g. in a resources or retries dictionary. """ if not isinstance(k, tuple): k = (k,) for kk in k: if dask.is_dask_collection(kk): yield from kk.__dask_keys__() else: yield kk async def _story(self, *keys_or_stimuli: str, on_error="raise"): assert on_error in ("raise", "ignore") try: flat_stories = await self.scheduler.get_story( keys_or_stimuli=keys_or_stimuli ) flat_stories = [("scheduler", *msg) for msg in flat_stories] except Exception: if on_error == "raise": raise elif on_error == "ignore": flat_stories = [] else: raise ValueError(f"on_error not in {'raise', 'ignore'}") responses = await self.scheduler.broadcast( msg={"op": "get_story", "keys_or_stimuli": keys_or_stimuli}, on_error=on_error, ) for worker, stories in responses.items(): flat_stories.extend((worker, *msg) for msg in stories) return flat_stories def story(self, *keys_or_stimuli, on_error="raise"): """Returns a cluster-wide story for the given keys or stimulus_id's""" return self.sync(self._story, *keys_or_stimuli, on_error=on_error) def get_task_stream( self, start=None, stop=None, count=None, plot=False, filename="task-stream.html", bokeh_resources=None, ): """Get task stream data from scheduler This collects the data present in the diagnostic "Task Stream" plot on the dashboard. It includes the start, stop, transfer, and deserialization time of every task for a particular duration. Note that the task stream diagnostic does not run by default. You may wish to call this function once before you start work to ensure that things start recording, and then again after you have completed. Parameters ---------- start : Number or string When you want to start recording If a number it should be the result of calling time() If a string then it should be a time difference before now, like '60s' or '500 ms' stop : Number or string When you want to stop recording count : int The number of desired records, ignored if both start and stop are specified plot : boolean, str If true then also return a Bokeh figure If plot == 'save' then save the figure to a file filename : str (optional) The filename to save to if you set ``plot='save'`` bokeh_resources : bokeh.resources.Resources (optional) Specifies if the resource component is INLINE or CDN Examples -------- >>> client.get_task_stream() # prime plugin if not already connected >>> x.compute() # do some work >>> client.get_task_stream() [{'task': ..., 'type': ..., 'thread': ..., ...}] Pass the ``plot=True`` or ``plot='save'`` keywords to get back a Bokeh figure >>> data, figure = client.get_task_stream(plot='save', filename='myfile.html') Alternatively consider the context manager >>> from dask.distributed import get_task_stream >>> with get_task_stream() as ts: ... x.compute() >>> ts.data [...] Returns ------- L: List[Dict] See Also -------- get_task_stream : a context manager version of this method """ return self.sync( self._get_task_stream, start=start, stop=stop, count=count, plot=plot, filename=filename, bokeh_resources=bokeh_resources, ) async def _get_task_stream( self, start=None, stop=None, count=None, plot=False, filename="task-stream.html", bokeh_resources=None, ): msgs = await self.scheduler.get_task_stream(start=start, stop=stop, count=count) if plot: from distributed.diagnostics.task_stream import rectangles rects = rectangles(msgs) from distributed.dashboard.components.scheduler import task_stream_figure source, figure = task_stream_figure(sizing_mode="stretch_both") source.data.update(rects) if plot == "save": from bokeh.plotting import output_file, save output_file(filename=filename, title="Dask Task Stream") save(figure, filename=filename, resources=bokeh_resources) return (msgs, figure) else: return msgs def register_plugin( self, plugin: NannyPlugin | SchedulerPlugin | WorkerPlugin, name: str | None = None, idempotent: bool | None = None, ): """Register a plugin. See https://distributed.readthedocs.io/en/latest/plugins.html Parameters ---------- plugin : A nanny, scheduler, or worker plugin to register. name : Name for the plugin; if None, a name is taken from the plugin instance or automatically generated if not present. idempotent : Do not re-register if a plugin of the given name already exists. If None, ``plugin.idempotent`` is taken if defined, False otherwise. """ if name is None: name = _get_plugin_name(plugin) assert name if idempotent is not None: warnings.warn( "The `idempotent` argument is deprecated and will be removed in a " "future version. Please mark your plugin as idempotent by setting its " "`.idempotent` attribute to `True`.", FutureWarning, stacklevel=2, ) else: idempotent = getattr(plugin, "idempotent", False) assert isinstance(idempotent, bool) return self._register_plugin(plugin, name, idempotent) @singledispatchmethod def _register_plugin( self, plugin: NannyPlugin | SchedulerPlugin | WorkerPlugin, name: str, idempotent: bool, ): if isinstance(plugin, type): raise TypeError("Please provide an instance of a plugin, not a type.") if any( "dask.distributed.diagnostics.plugin" in str(c) for c in plugin.__class__.__bases__ ): raise TypeError( "Importing plugin base classes from `dask.distributed.diagnostics.plugin` is not supported. " "Please import directly from `distributed.diagnostics.plugin` instead." ) raise TypeError( "Registering duck-typed plugins is not allowed. Please inherit from " "NannyPlugin, WorkerPlugin, or SchedulerPlugin to create a plugin." ) @_register_plugin.register def _(self, plugin: SchedulerPlugin, name: str, idempotent: bool): return self.sync( self._register_scheduler_plugin, plugin=plugin, name=name, idempotent=idempotent, ) @_register_plugin.register def _( self, plugin: NannyPlugin, name: str, idempotent: bool ) -> dict[str, OKMessage]: return self.sync( self._register_nanny_plugin, plugin=plugin, name=name, idempotent=idempotent, ) @_register_plugin.register def _(self, plugin: WorkerPlugin, name: str, idempotent: bool): return self.sync( self._register_worker_plugin, plugin=plugin, name=name, idempotent=idempotent, ) async def _register_scheduler_plugin( self, plugin: SchedulerPlugin, name: str, idempotent: bool ): return await self.scheduler.register_scheduler_plugin( plugin=dumps(plugin), name=name, idempotent=idempotent, ) def register_scheduler_plugin( self, plugin: SchedulerPlugin, name: str | None = None, idempotent: bool | None = None, ): """ Register a scheduler plugin. .. deprecated:: 2023.9.2 Use :meth:`Client.register_plugin` instead. See https://distributed.readthedocs.io/en/latest/plugins.html#scheduler-plugins Parameters ---------- plugin : SchedulerPlugin SchedulerPlugin instance to pass to the scheduler. name : str Name for the plugin; if None, a name is taken from the plugin instance or automatically generated if not present. idempotent : bool Do not re-register if a plugin of the given name already exists. """ warnings.warn( "`Client.register_scheduler_plugin` has been deprecated; " "please `Client.register_plugin` instead", DeprecationWarning, stacklevel=2, ) return cast(OKMessage, self.register_plugin(plugin, name, idempotent)) async def _unregister_scheduler_plugin(self, name): return await self.scheduler.unregister_scheduler_plugin(name=name) def unregister_scheduler_plugin(self, name): """Unregisters a scheduler plugin See https://distributed.readthedocs.io/en/latest/plugins.html#scheduler-plugins Parameters ---------- name : str Name of the plugin to unregister. See the :meth:`Client.register_scheduler_plugin` docstring for more information. Examples -------- >>> class MyPlugin(SchedulerPlugin): ... def __init__(self, *args, **kwargs): ... pass # the constructor is up to you ... async def start(self, scheduler: Scheduler) -> None: ... pass ... async def before_close(self) -> None: ... pass ... async def close(self) -> None: ... pass ... def restart(self, scheduler: Scheduler) -> None: ... pass >>> plugin = MyPlugin(1, 2, 3) >>> client.register_plugin(plugin, name='foo') >>> client.unregister_scheduler_plugin(name='foo') See Also -------- register_scheduler_plugin """ return self.sync(self._unregister_scheduler_plugin, name=name) def register_worker_callbacks(self, setup=None): """ Registers a setup callback function for all current and future workers. This registers a new setup function for workers in this cluster. The function will run immediately on all currently connected workers. It will also be run upon connection by any workers that are added in the future. Multiple setup functions can be registered - these will be called in the order they were added. If the function takes an input argument named ``dask_worker`` then that variable will be populated with the worker itself. Parameters ---------- setup : callable(dask_worker: Worker) -> None Function to register and run on all workers """ return self.register_plugin(_WorkerSetupPlugin(setup)) async def _register_worker_plugin( self, plugin: WorkerPlugin, name: str, idempotent: bool ) -> dict[str, OKMessage]: responses = await self.scheduler.register_worker_plugin( plugin=dumps(plugin), name=name, idempotent=idempotent ) for response in responses.values(): if response["status"] == "error": _, exc, tb = clean_exception( response["exception"], response["traceback"] ) assert exc raise exc.with_traceback(tb) return cast(dict[str, OKMessage], responses) async def _register_nanny_plugin( self, plugin: NannyPlugin, name: str, idempotent: bool ) -> dict[str, OKMessage]: responses = await self.scheduler.register_nanny_plugin( plugin=dumps(plugin), name=name, idempotent=idempotent ) for response in responses.values(): if response["status"] == "error": _, exc, tb = clean_exception( response["exception"], response["traceback"] ) assert exc raise exc.with_traceback(tb) return cast(dict[str, OKMessage], responses) def register_worker_plugin( self, plugin: NannyPlugin | WorkerPlugin, name: str | None = None, nanny: bool | None = None, ): """ Registers a lifecycle worker plugin for all current and future workers. .. deprecated:: 2023.9.2 Use :meth:`Client.register_plugin` instead. This registers a new object to handle setup, task state transitions and teardown for workers in this cluster. The plugin will instantiate itself on all currently connected workers. It will also be run on any worker that connects in the future. The plugin may include methods ``setup``, ``teardown``, ``transition``, and ``release_key``. See the ``dask.distributed.WorkerPlugin`` class or the examples below for the interface and docstrings. It must be serializable with the pickle or cloudpickle modules. If the plugin has a ``name`` attribute, or if the ``name=`` keyword is used then that will control idempotency. If a plugin with that name has already been registered, then it will be removed and replaced by the new one. For alternatives to plugins, you may also wish to look into preload scripts. Parameters ---------- plugin : WorkerPlugin or NannyPlugin WorkerPlugin or NannyPlugin instance to register. name : str, optional A name for the plugin. Registering a plugin with the same name will have no effect. If plugin has no name attribute a random name is used. nanny : bool, optional Whether to register the plugin with workers or nannies. Examples -------- >>> class MyPlugin(WorkerPlugin): ... def __init__(self, *args, **kwargs): ... pass # the constructor is up to you ... def setup(self, worker: dask.distributed.Worker): ... pass ... def teardown(self, worker: dask.distributed.Worker): ... pass ... def transition(self, key: str, start: str, finish: str, ... **kwargs): ... pass ... def release_key(self, key: str, state: str, cause: str | None, reason: None, report: bool): ... pass >>> plugin = MyPlugin(1, 2, 3) >>> client.register_plugin(plugin) You can get access to the plugin with the ``get_worker`` function >>> client.register_plugin(other_plugin, name='my-plugin') >>> def f(): ... worker = get_worker() ... plugin = worker.plugins['my-plugin'] ... return plugin.my_state >>> future = client.run(f) See Also -------- distributed.WorkerPlugin unregister_worker_plugin """ warnings.warn( "`Client.register_worker_plugin` has been deprecated; " "please use `Client.register_plugin` instead", DeprecationWarning, stacklevel=2, ) if name is None: name = _get_plugin_name(plugin) assert name method: Callable if isinstance(plugin, WorkerPlugin): method = self._register_worker_plugin if nanny is True: warnings.warn( "Registering a `WorkerPlugin` as a nanny plugin is not " "allowed, registering as a worker plugin instead. " "To register as a nanny plugin, inherit from `NannyPlugin`.", UserWarning, stacklevel=2, ) elif isinstance(plugin, NannyPlugin): method = self._register_nanny_plugin if nanny is False: warnings.warn( "Registering a `NannyPlugin` as a worker plugin is not " "allowed, registering as a nanny plugin instead. " "To register as a worker plugin, inherit from `WorkerPlugin`.", UserWarning, stacklevel=2, ) elif isinstance(plugin, SchedulerPlugin): # type: ignore[unreachable] if nanny: warnings.warn( "Registering a `SchedulerPlugin` as a nanny plugin is not " "allowed, registering as a scheduler plugin instead. " "To register as a nanny plugin, inherit from `NannyPlugin`.", UserWarning, stacklevel=2, ) else: warnings.warn( "Registering a `SchedulerPlugin` as a worker plugin is not " "allowed, registering as a scheduler plugin instead. " "To register as a worker plugin, inherit from `WorkerPlugin`.", UserWarning, stacklevel=2, ) method = self._register_scheduler_plugin else: warnings.warn( "Registering duck-typed plugins has been deprecated. " "Please make sure your plugin inherits from `NannyPlugin` " "or `WorkerPlugin`.", DeprecationWarning, stacklevel=2, ) if nanny is True: method = self._register_nanny_plugin else: method = self._register_worker_plugin return self.sync(method, plugin=plugin, name=name, idempotent=False) async def _unregister_worker_plugin(self, name, nanny=None): if nanny: responses = await self.scheduler.unregister_nanny_plugin(name=name) else: responses = await self.scheduler.unregister_worker_plugin(name=name) for response in responses.values(): if response["status"] == "error": _, exc, tb = clean_exception(**response) raise exc.with_traceback(tb) return responses def unregister_worker_plugin(self, name, nanny=None): """Unregisters a lifecycle worker plugin This unregisters an existing worker plugin. As part of the unregistration process the plugin's ``teardown`` method will be called. Parameters ---------- name : str Name of the plugin to unregister. See the :meth:`Client.register_plugin` docstring for more information. Examples -------- >>> class MyPlugin(WorkerPlugin): ... def __init__(self, *args, **kwargs): ... pass # the constructor is up to you ... def setup(self, worker: dask.distributed.Worker): ... pass ... def teardown(self, worker: dask.distributed.Worker): ... pass ... def transition(self, key: str, start: str, finish: str, **kwargs): ... pass ... def release_key(self, key: str, state: str, cause: str | None, reason: None, report: bool): ... pass >>> plugin = MyPlugin(1, 2, 3) >>> client.register_plugin(plugin, name='foo') >>> client.unregister_worker_plugin(name='foo') See Also -------- register_plugin """ return self.sync(self._unregister_worker_plugin, name=name, nanny=nanny) @property def amm(self): """Convenience accessors for the :doc:`active_memory_manager`""" from distributed.active_memory_manager import AMMClientProxy return AMMClientProxy(self) def _handle_forwarded_log_record(self, event): _, record_attrs = event record = logging.makeLogRecord(record_attrs) dest_logger = logging.getLogger(record.name) dest_logger.handle(record) def forward_logging(self, logger_name=None, level=logging.NOTSET): """ Begin forwarding the given logger (by default the root) and all loggers under it from worker tasks to the client process. Whenever the named logger handles a LogRecord on the worker-side, the record will be serialized, sent to the client, and handled by the logger with the same name on the client-side. Note that worker-side loggers will only handle LogRecords if their level is set appropriately, and the client-side logger will only emit the forwarded LogRecord if its own level is likewise set appropriately. For example, if your submitted task logs a DEBUG message to logger "foo", then in order for ``forward_logging()`` to cause that message to be emitted in your client session, you must ensure that the logger "foo" have its level set to DEBUG (or lower) in the worker process *and* in the client process. Parameters ---------- logger_name : str, optional The name of the logger to begin forwarding. The usual rules of the ``logging`` module's hierarchical naming system apply. For example, if ``name`` is ``"foo"``, then not only ``"foo"``, but also ``"foo.bar"``, ``"foo.baz"``, etc. will be forwarded. If ``name`` is ``None``, this indicates the root logger, and so *all* loggers will be forwarded. Note that a logger will only forward a given LogRecord if the logger's level is sufficient for the LogRecord to be handled at all. level : str | int, optional Optionally restrict forwarding to LogRecords of this level or higher, even if the forwarded logger's own level is lower. Examples -------- For purposes of the examples, suppose we configure client-side logging as a user might: with a single StreamHandler attached to the root logger with an output level of INFO and a simple output format:: import logging import distributed import io, yaml TYPICAL_LOGGING_CONFIG = ''' version: 1 handlers: console: class : logging.StreamHandler formatter: default level : INFO formatters: default: format: '%(asctime)s %(levelname)-8s [worker %(worker)s] %(name)-15s %(message)s' datefmt: '%Y-%m-%d %H:%M:%S' root: handlers: - console ''' config = yaml.safe_load(io.StringIO(TYPICAL_LOGGING_CONFIG)) logging.config.dictConfig(config) Now create a client and begin forwarding the root logger from workers back to our local client process. >>> client = distributed.Client() >>> client.forward_logging() # forward the root logger at any handled level Then submit a task that does some error logging on a worker. We see output from the client-side StreamHandler. >>> def do_error(): ... logging.getLogger("user.module").error("Hello error") ... return 42 >>> client.submit(do_error).result() 2022-11-09 03:43:25 ERROR [worker tcp://127.0.0.1:34783] user.module Hello error 42 Note how an attribute ``"worker"`` is also added by dask to the forwarded LogRecord, which our custom formatter uses. This is useful for identifying exactly which worker logged the error. One nuance worth highlighting: even though our client-side root logger is configured with a level of INFO, the worker-side root loggers still have their default level of ERROR because we haven't done any explicit logging configuration on the workers. Therefore worker-side INFO logs will *not* be forwarded because they never even get handled in the first place. >>> def do_info_1(): ... # no output on the client side ... logging.getLogger("user.module").info("Hello info the first time") ... return 84 >>> client.submit(do_info_1).result() 84 It is necessary to set the client-side logger's level to INFO before the info message will be handled and forwarded to the client. In other words, the "effective" level of the client-side forwarded logging is the maximum of each logger's client-side and worker-side levels. >>> def do_info_2(): ... logger = logging.getLogger("user.module") ... logger.setLevel(logging.INFO) ... # now produces output on the client side ... logger.info("Hello info the second time") ... return 84 >>> client.submit(do_info_2).result() 2022-11-09 03:57:39 INFO [worker tcp://127.0.0.1:42815] user.module Hello info the second time 84 """ plugin_name = f"forward-logging-{logger_name or '<root>'}" topic = f"{TOPIC_PREFIX_FORWARDED_LOG_RECORD}-{plugin_name}" # note that subscription is idempotent self.subscribe_topic(topic, self._handle_forwarded_log_record) # note that any existing plugin with the same name will automatically be # removed and torn down (see distributed.worker.Worker.plugin_add()), so # this is effectively idempotent, i.e., forwarding the same logger twice # won't cause every LogRecord to be forwarded twice return self.register_plugin( ForwardLoggingPlugin(logger_name, level, topic), plugin_name ) def unforward_logging(self, logger_name=None): """ Stop forwarding the given logger (default root) from worker tasks to the client process. """ plugin_name = f"forward-logging-{logger_name or '<root>'}" topic = f"{TOPIC_PREFIX_FORWARDED_LOG_RECORD}-{plugin_name}" self.unsubscribe_topic(topic) return self.unregister_worker_plugin(plugin_name) def _convert_dask_keys(keys: NestedKeys) -> List: assert isinstance(keys, list) new_keys: list[List | TaskRef] = [] for key in keys: if isinstance(key, list): new_keys.append(_convert_dask_keys(key)) else: new_keys.append(TaskRef(key)) return List(*new_keys)
Client
python
PyCQA__pylint
tests/functional/n/non_ascii_name_class/non_ascii_name_class_method.py
{ "start": 38, "end": 333 }
class ____: """We need a class docstring?""" def public(self): """Say something""" print(self) @classmethod def umlaut_ä(cls): # [non-ascii-name] """do something""" return "ä" # Usage should not raise a second error OkayClass.umlaut_ä()
OkayClass
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/decorators/decorator_assets_definition_builder.py
{ "start": 10976, "end": 30621 }
class ____: def __init__( self, *, named_ins_by_asset_key: Mapping[AssetKey, NamedIn], named_outs_by_asset_key: Mapping[AssetKey, NamedOut], internal_deps: Mapping[AssetKey, set[AssetKey]], op_name: str, args: DecoratorAssetsDefinitionBuilderArgs, fn: Callable[..., Any], ) -> None: self.named_outs_by_asset_key = named_outs_by_asset_key self.internal_deps = internal_deps self.op_name = op_name self.args = args self.fn = fn self.named_ins_by_asset_key = ( ( { **named_ins_by_asset_key, **build_subsettable_named_ins( named_ins_by_asset_key, named_outs_by_asset_key, self.internal_deps.values(), ), } ) if self.args.can_subset and self.internal_deps else named_ins_by_asset_key ) @staticmethod def for_multi_asset( *, fn: Callable[..., Any], args: DecoratorAssetsDefinitionBuilderArgs ) -> "DecoratorAssetsDefinitionBuilder": op_name = args.name or fn.__name__ if args.asset_out_map and args.specs: raise DagsterInvalidDefinitionError("Must specify only outs or specs but not both.") if args.compute_kind and args.specs and any(spec.kinds for spec in args.specs): raise DagsterInvalidDefinitionError( "Can not specify compute_kind on both the @multi_asset and kinds on AssetSpecs." ) if args.specs: check.invariant( args.decorator_name == "@multi_asset", "Only hit this code path in multi_asset." ) if args.upstream_asset_deps: raise DagsterInvalidDefinitionError( "Can not pass deps and specs to @multi_asset, specify deps on the AssetSpecs" " directly." ) if args.asset_deps: raise DagsterInvalidDefinitionError( "Can not pass internal_asset_deps and specs to @multi_asset, specify deps on" " the AssetSpecs directly." ) return DecoratorAssetsDefinitionBuilder.from_multi_asset_specs( fn=fn, op_name=op_name, passed_args=args, asset_specs=args.specs, can_subset=args.can_subset, asset_in_map=args.asset_in_map, ) return DecoratorAssetsDefinitionBuilder.from_asset_outs_in_asset_centric_decorator( fn=fn, op_name=op_name, asset_in_map=args.asset_in_map, asset_out_map=args.asset_out_map, asset_deps=args.asset_deps, upstream_asset_deps=args.upstream_asset_deps, passed_args=args, ) @staticmethod def from_multi_asset_specs( *, fn: Callable[..., Any], op_name: str, asset_specs: Sequence[AssetSpec], can_subset: bool, asset_in_map: Mapping[str, AssetIn], passed_args: DecoratorAssetsDefinitionBuilderArgs, ) -> "DecoratorAssetsDefinitionBuilder": check.param_invariant(passed_args.specs, "passed_args", "Must use specs in this codepath") named_outs_by_asset_key: Mapping[AssetKey, NamedOut] = {} for asset_spec in asset_specs: output_name = asset_spec.key.to_python_identifier() if SYSTEM_METADATA_KEY_DAGSTER_TYPE in asset_spec.metadata: dagster_type = asset_spec.metadata[SYSTEM_METADATA_KEY_DAGSTER_TYPE] elif asset_spec.metadata.get(SYSTEM_METADATA_KEY_IO_MANAGER_KEY): dagster_type = DagsterAny else: dagster_type = Nothing named_outs_by_asset_key[asset_spec.key] = NamedOut( output_name, Out( dagster_type=dagster_type, is_required=not (can_subset or asset_spec.skippable), description=asset_spec.description, code_version=asset_spec.code_version, metadata=asset_spec.metadata, io_manager_key=asset_spec.metadata.get(SYSTEM_METADATA_KEY_IO_MANAGER_KEY), ), ) upstream_deps = {} for spec in asset_specs: for dep in spec.deps: if dep.asset_key not in named_outs_by_asset_key: upstream_deps[dep.asset_key] = dep if dep.asset_key in named_outs_by_asset_key and dep.partition_mapping is not None: # self-dependent asset also needs to be considered an upstream_key upstream_deps[dep.asset_key] = dep # get which asset keys have inputs set named_ins_by_asset_key = build_and_validate_named_ins( fn, upstream_deps.values(), asset_in_map ) # We expect that asset_ins are a subset of asset_deps. The reason we do not check this in # `build_and_validate_named_ins` is because in other decorator pathways, we allow for argument-based # dependencies which are not specified in deps (such as the asset decorator). validate_named_ins_subset_of_deps(named_ins_by_asset_key, upstream_deps) internal_deps = { spec.key: {dep.asset_key for dep in spec.deps} for spec in asset_specs if spec.deps is not None } if not passed_args.allow_arbitrary_check_specs: _validate_check_specs_target_relevant_asset_keys( passed_args.check_specs, [spec.key for spec in asset_specs] ) return DecoratorAssetsDefinitionBuilder( named_ins_by_asset_key=named_ins_by_asset_key, named_outs_by_asset_key=named_outs_by_asset_key, internal_deps=internal_deps, op_name=op_name, args=passed_args, fn=fn, ) @staticmethod def from_asset_outs_in_asset_centric_decorator( *, fn: Callable[..., Any], op_name: str, asset_in_map: Mapping[str, AssetIn], asset_out_map: Mapping[str, AssetOut], asset_deps: Mapping[str, set[AssetKey]], upstream_asset_deps: Optional[Iterable[AssetDep]], passed_args: DecoratorAssetsDefinitionBuilderArgs, ): check.param_invariant( not passed_args.specs, "args", "This codepath for non-spec based create" ) named_ins_by_asset_key = build_and_validate_named_ins( fn, upstream_asset_deps or set(), asset_in_map, ) named_outs_by_asset_key = build_named_outs(asset_out_map) # validate that the asset_ins are a subset of the upstream asset_deps. upstream_internal_asset_keys = set().union(*asset_deps.values()) asset_in_keys = set(named_ins_by_asset_key.keys()) if asset_deps and not asset_in_keys.issubset(upstream_internal_asset_keys): invalid_asset_in_keys = asset_in_keys - upstream_internal_asset_keys check.failed( f"Invalid asset dependencies: `{invalid_asset_in_keys}` specified as asset" " inputs, but are not specified in `internal_asset_deps`. Asset inputs must" " be associated with an output produced by the asset." ) # validate that the asset_deps make sense valid_asset_deps = asset_in_keys | set(named_outs_by_asset_key.keys()) for out_name, asset_keys in asset_deps.items(): if asset_out_map and out_name not in asset_out_map: check.failed( f"Invalid out key '{out_name}' supplied to `internal_asset_deps` argument" f" for multi-asset {op_name}. Must be one of the outs for this multi-asset" f" {list(asset_out_map.keys())[:20]}.", ) invalid_asset_deps = asset_keys.difference(valid_asset_deps) check.invariant( not invalid_asset_deps, f"Invalid asset dependencies: {invalid_asset_deps} specified in" f" `internal_asset_deps` argument for multi-asset '{op_name}' on key" f" '{out_name}'. Each specified asset key must be associated with an input to" " the asset or produced by this asset. Valid keys:" f" {list(valid_asset_deps)[:20]}", ) keys_by_output_name = make_keys_by_output_name(named_outs_by_asset_key) internal_deps = {keys_by_output_name[name]: asset_deps[name] for name in asset_deps} _validate_check_specs_target_relevant_asset_keys( passed_args.check_specs, list(named_outs_by_asset_key.keys()) ) return DecoratorAssetsDefinitionBuilder( named_ins_by_asset_key=named_ins_by_asset_key, named_outs_by_asset_key=named_outs_by_asset_key, internal_deps=internal_deps, op_name=op_name, args=passed_args, fn=fn, ) @property def group_name(self) -> Optional[str]: return self.args.group_name @cached_property def outs_by_output_name(self) -> Mapping[str, Out]: return dict(self.named_outs_by_asset_key.values()) @cached_property def asset_keys_by_input_name(self) -> Mapping[str, AssetKey]: return { in_mapping.input_name: asset_key for asset_key, in_mapping in self.named_ins_by_asset_key.items() } @cached_property def asset_keys_by_output_name(self) -> Mapping[str, AssetKey]: return { out_mapping.output_name: asset_key for asset_key, out_mapping in self.named_outs_by_asset_key.items() } @cached_property def asset_keys(self) -> set[AssetKey]: return set(self.named_outs_by_asset_key.keys()) @cached_property def check_specs_by_output_name(self) -> Mapping[str, AssetCheckSpec]: return self.args.check_specs_by_output_name @cached_property def check_outs_by_output_name(self) -> Mapping[str, Out]: return { output_name: Out(dagster_type=None, is_required=not self.args.can_subset) for output_name in self.check_specs_by_output_name.keys() } @cached_property def combined_outs_by_output_name(self) -> Mapping[str, Out]: return { **self.outs_by_output_name, **self.check_outs_by_output_name, } @cached_property def overlapping_output_names(self) -> set[str]: return set(self.outs_by_output_name.keys()) & set(self.check_outs_by_output_name.keys()) @cached_property def ins_by_input_names(self) -> Mapping[str, In]: return {in_name: in_obj for in_name, in_obj in self.named_ins_by_asset_key.values()} @cached_property def asset_keys_by_input_names(self) -> Mapping[str, AssetKey]: return { in_mapping.input_name: asset_key for asset_key, in_mapping in self.named_ins_by_asset_key.items() } @cached_property def partition_mappings(self) -> Mapping[AssetKey, PartitionMapping]: partition_mappings = { self.asset_keys_by_input_names[input_name]: asset_in.partition_mapping for input_name, asset_in in self.args.asset_in_map.items() if asset_in.partition_mapping is not None } if not self.args.upstream_asset_deps: return partition_mappings return get_partition_mappings_from_deps( partition_mappings=partition_mappings, deps=self.args.upstream_asset_deps, asset_name=self.op_name, ) @cached_property def required_resource_keys(self) -> AbstractSet[str]: return compute_required_resource_keys( required_resource_keys=self.args.required_resource_keys, resource_defs=self.args.op_def_resource_defs, fn=self.fn, decorator_name=self.args.decorator_name, ) def create_op_definition(self) -> OpDefinition: return _Op( name=self.op_name, description=self.args.op_description, ins=self.ins_by_input_names, out=self.combined_outs_by_output_name, required_resource_keys=self.required_resource_keys, tags={ **({COMPUTE_KIND_TAG: self.args.compute_kind} if self.args.compute_kind else {}), **(self.args.op_tags or {}), }, config_schema=self.args.config_schema, retry_policy=self.args.retry_policy, code_version=self.args.code_version, pool=self.args.pool, )(self.fn) def create_assets_definition(self) -> AssetsDefinition: return AssetsDefinition.dagster_internal_init( keys_by_input_name=self.asset_keys_by_input_names, keys_by_output_name=self.asset_keys_by_output_name, node_def=self.create_op_definition(), can_subset=self.args.can_subset, resource_defs=self.args.assets_def_resource_defs, backfill_policy=self.args.backfill_policy, check_specs_by_output_name=self.check_specs_by_output_name, specs=self.specs, hook_defs=self.args.hooks, is_subset=False, selected_asset_keys=None, # not a subset so this is None selected_asset_check_keys=None, # not a subset so this is none execution_type=self.args.execution_type, ) @cached_property def specs(self) -> Sequence[AssetSpec]: if self.args.specs: specs = self.args.specs self._validate_spec_partitions_defs(specs, self.args.partitions_def) else: specs = self._synthesize_specs() check.invariant( not self.group_name or all( (spec.group_name is None or spec.group_name == self.group_name) for spec in specs ), "Cannot set group_name parameter on multi_asset if one or more of the" " AssetSpecs/AssetOuts supplied to this multi_asset have a group_name defined.", ) if not self.group_name and not self.args.partitions_def: return specs return [ spec.replace_attributes( group_name=spec.group_name or self.group_name, partitions_def=spec.partitions_def or self.args.partitions_def, ) for spec in specs ] def _validate_spec_partitions_defs( self, specs: Sequence[AssetSpec], partitions_def: Optional[PartitionsDefinition] ) -> Optional[PartitionsDefinition]: any_spec_has_partitions_def = False any_spec_has_no_partitions_def = False if partitions_def is not None: for spec in specs: if spec.partitions_def is not None and spec.partitions_def != partitions_def: check.failed( f"AssetSpec for {spec.key.to_user_string()} has partitions_def " f"(type={type(spec.partitions_def)}) which is different than the " f"partitions_def provided to AssetsDefinition (type={type(partitions_def)}).", ) any_spec_has_partitions_def = ( any_spec_has_partitions_def or spec.partitions_def is not None ) any_spec_has_no_partitions_def = ( any_spec_has_no_partitions_def or spec.partitions_def is None ) if ( partitions_def is not None and any_spec_has_partitions_def and any_spec_has_no_partitions_def ): check.failed( "If partitions_def is provided, then either all specs must have that PartitionsDefinition or none." ) def _synthesize_specs(self) -> Sequence[AssetSpec]: resolved_specs = [] input_deps_by_key = { key: AssetDep(asset=key, partition_mapping=self.partition_mappings.get(key)) for key in self.asset_keys_by_input_names.values() } input_deps = list(input_deps_by_key.values()) for output_name, asset_out in self.args.asset_out_map.items(): key = self.asset_keys_by_output_name[output_name] if self.args.asset_deps: deps = [ input_deps_by_key.get( dep_key, AssetDep( asset=dep_key, partition_mapping=self.partition_mappings.get(key), ), ) for dep_key in self.args.asset_deps.get(output_name, []) ] else: deps = input_deps resolved_specs.append( asset_out.to_spec(key, deps=deps, partitions_def=self.args.partitions_def) ) specs = resolved_specs return specs def validate_and_assign_output_names_to_check_specs( check_specs: Optional[Sequence[AssetCheckSpec]], valid_asset_keys: Sequence[AssetKey] ) -> Mapping[str, AssetCheckSpec]: _validate_check_specs_target_relevant_asset_keys(check_specs, valid_asset_keys) return create_check_specs_by_output_name(check_specs) def create_check_specs_by_output_name( check_specs: Optional[Sequence[AssetCheckSpec]], ) -> Mapping[str, AssetCheckSpec]: checks_by_output_name = { spec.get_python_identifier(): spec for spec in check.opt_sequence_param(check_specs, "check_specs", of_type=AssetCheckSpec) } if check_specs and len(checks_by_output_name) != len(check_specs): duplicates = { item: count for item, count in Counter( [(spec.asset_key, spec.name) for spec in check_specs] ).items() if count > 1 } raise DagsterInvalidDefinitionError(f"Duplicate check specs: {duplicates}") return checks_by_output_name def _validate_check_specs_target_relevant_asset_keys( check_specs: Optional[Sequence[AssetCheckSpec]], valid_asset_keys: Sequence[AssetKey] ) -> None: for spec in check_specs or []: if spec.asset_key not in valid_asset_keys: raise DagsterInvalidDefinitionError( f"Invalid asset key {spec.asset_key} in check spec {spec.name}. Must be one of" f" {valid_asset_keys}" ) def validate_named_ins_subset_of_deps( named_ins_per_key: Mapping[AssetKey, NamedIn], asset_deps_by_key: Mapping[AssetKey, AssetDep], ) -> None: """Validates that the asset_ins are a subset of the asset_deps. This is a common validation that we need to do in multiple places, so we've factored it out into a helper function. """ asset_dep_keys = set(asset_deps_by_key.keys()) asset_in_keys = set(named_ins_per_key.keys()) if asset_in_keys - asset_dep_keys: invalid_asset_in_keys = asset_in_keys - asset_dep_keys raise DagsterInvalidDefinitionError( f"Invalid asset dependencies: `{invalid_asset_in_keys}` specified as AssetIns, but" " are not specified as `AssetDep` objects on any constituent AssetSpec objects. Asset inputs must be associated with an" " output produced by the asset." )
DecoratorAssetsDefinitionBuilder
python
streamlit__streamlit
lib/streamlit/elements/write.py
{ "start": 1505, "end": 1550 }
class ____(list[Any]): pass
StreamingOutput
python
dagster-io__dagster
python_modules/libraries/dagster-managed-elements/dagster_managed_elements_tests/example_reconciler.py
{ "start": 157, "end": 568 }
class ____(ManagedElementReconciler): def __init__(self, diff: ManagedElementDiff, apply_diff: Optional[ManagedElementDiff] = None): self._diff = diff self._apply_diff = apply_diff or diff def check(self, **kwargs) -> ManagedElementCheckResult: return self._diff def apply(self, **kwargs) -> ManagedElementCheckResult: return self._apply_diff
MyManagedElementReconciler
python
keon__algorithms
tests/test_set.py
{ "start": 72, "end": 324 }
class ____(unittest.TestCase): def test_find_keyboard_row(self): self.assertEqual(["Alaska", "Dad"], find_keyboard_row(["Hello", "Alaska", "Dad", "Peace"]))
TestFindKeyboardRow
python
great-expectations__great_expectations
tests/core/test_expectation_validation_result.py
{ "start": 20268, "end": 23043 }
class ____: @pytest.mark.unit def test_hash_consistency_with_equality(self): config1 = ExpectationConfiguration( type="expect_column_values_to_not_be_null", kwargs={"column": "test_column"} ) config2 = ExpectationConfiguration( type="expect_column_values_to_not_be_null", kwargs={"column": "test_column"} ) result1 = ExpectationValidationResult( success=True, expectation_config=config1, result={"observed_value": 100}, meta={"test": "value"}, exception_info={"raised_exception": False}, ) result2 = ExpectationValidationResult( success=True, expectation_config=config2, result={"observed_value": 100}, meta={"test": "value"}, exception_info={"raised_exception": False}, ) assert result1 == result2 assert hash(result1) == hash(result2) @pytest.mark.unit def test_hash_different_for_different_success(self): config = ExpectationConfiguration( type="expect_column_values_to_not_be_null", kwargs={"column": "test_column"} ) result1 = ExpectationValidationResult( success=True, expectation_config=config, result={"observed_value": 100} ) result2 = ExpectationValidationResult( success=False, expectation_config=config, result={"observed_value": 100} ) assert result1 != result2 assert hash(result1) != hash(result2) @pytest.mark.unit def test_hash_different_for_different_results(self): config = ExpectationConfiguration( type="expect_column_values_to_not_be_null", kwargs={"column": "test_column"} ) result1 = ExpectationValidationResult( success=True, expectation_config=config, result={"observed_value": 100} ) result2 = ExpectationValidationResult( success=True, expectation_config=config, result={"observed_value": 200} ) assert result1 != result2 assert hash(result1) != hash(result2) @pytest.mark.unit def test_hash_stable_across_runs(self): config = ExpectationConfiguration( type="expect_column_values_to_not_be_null", kwargs={"column": "test_column"} ) result = ExpectationValidationResult( success=True, expectation_config=config, result={"observed_value": 100}, meta={"test": "value"}, exception_info={"raised_exception": False}, ) hash1 = hash(result) hash2 = hash(result) hash3 = hash(result) assert hash1 == hash2 == hash3
TestExpectationValidationResultHash
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 23380, "end": 23895 }
class ____(_FilterTestCommon): """Apply a filter to an expression. ``name`` is the name of the filter, the other fields are the same as :class:`Call`. If ``node`` is ``None``, the filter is being used in a filter block and is applied to the content of the block. """ node: Expr | None # type: ignore def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any: if self.node is None: raise Impossible() return super().as_const(eval_ctx=eval_ctx)
Filter
python
ray-project__ray
rllib/examples/_old_api_stack/models/mobilenet_v2_encoder.py
{ "start": 1094, "end": 1659 }
class ____(TorchModel, Encoder): """A MobileNet v2 encoder for RLlib.""" def __init__(self, config): super().__init__(config) self.net = torch.hub.load( "pytorch/vision:v0.6.0", "mobilenet_v2", pretrained=True ) if config.freeze: # We don't want to train this encoder, so freeze its parameters! for p in self.net.parameters(): p.requires_grad = False def _forward(self, input_dict, **kwargs): return {ENCODER_OUT: (self.net(input_dict["obs"]))}
MobileNetV2Encoder
python
huggingface__transformers
tests/models/seed_oss/test_modeling_seed_oss.py
{ "start": 1274, "end": 1483 }
class ____(CausalLMModelTest, unittest.TestCase): model_tester_class = SeedOssModelTester _is_stateful = True model_split_percents = [0.5, 0.6] @slow @require_torch_large_accelerator
SeedOssModelTest
python
PyCQA__pylint
tests/functional/a/assigning/assigning_non_slot.py
{ "start": 370, "end": 518 }
class ____: """ missing not in slots. """ __slots__ = ['member'] def __init__(self): self.missing = 42 # [assigning-non-slot]
Bad
python
crytic__slither
slither/detectors/functions/external_function.py
{ "start": 703, "end": 12476 }
class ____(AbstractDetector): """ Detect public function that could be declared as external IMPROVEMENT: Add InternalDynamicCall check https://github.com/trailofbits/slither/pull/53#issuecomment-432809950 """ ARGUMENT = "external-function" HELP = "Public function that could be declared external" IMPACT = DetectorClassification.OPTIMIZATION CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-external" WIKI_TITLE = "Public function that could be declared external" WIKI_DESCRIPTION = "`public` functions that are never called by the contract should be declared `external`, and its immutable parameters should be located in `calldata` to save gas." WIKI_RECOMMENDATION = "Use the `external` attribute for functions never called from the contract, and change the location of immutable parameters to `calldata` to save gas." VULNERABLE_SOLC_VERSIONS = ( ALL_SOLC_VERSIONS_04 + ALL_SOLC_VERSIONS_05 + make_solc_versions(6, 0, 8) ) @staticmethod def detect_functions_called(contract: Contract) -> List[Function]: """Returns a list of InternallCall, SolidityCall calls made in a function Returns: (list): List of all InternallCall, SolidityCall """ result = [] # Obtain all functions reachable by this contract. for func in contract.all_functions_called: if not isinstance(func, Function): continue # Loop through all internal and solidity calls in the function, add them to a list. for ir in func.internal_calls + func.solidity_calls: result.append(ir.function) return result @staticmethod def _contains_internal_dynamic_call(contract: Contract) -> bool: """ Checks if a contract contains a dynamic call either in a direct definition, or through inheritance. Returns: (boolean): True if this contract contains a dynamic call (including through inheritance). """ for func in contract.all_functions_called: if not isinstance(func, Function): continue for node in func.nodes: for ir in node.irs: if isinstance(ir, (InternalDynamicCall)): return True return False @staticmethod def get_base_most_function(function: FunctionContract) -> FunctionContract: """ Obtains the base function definition for the provided function. This could be used to obtain the original definition of a function, if the provided function is an override. Returns: (function): Returns the base-most function of a provided function. (The original definition). """ # Loop through the list of inherited contracts and this contract, to find the first function instance which # matches this function's signature. Note here that `inheritance` is in order from most basic to most extended. for contract in function.contract.inheritance + [function.contract]: # Loop through the functions not inherited (explicitly defined in this contract). for f in contract.functions_declared: # If it matches names, this is the base most function. if f.full_name == function.full_name: return f # Somehow we couldn't resolve it, which shouldn't happen, as the provided function should be found if we could # not find some any more basic. # pylint: disable=broad-exception-raised raise Exception("Could not resolve the base-most function for the provided function.") @staticmethod def get_all_function_definitions( base_most_function: FunctionContract, ) -> List[FunctionContract]: """ Obtains all function definitions given a base-most function. This includes the provided function, plus any overrides of that function. Returns: (list): Returns any the provided function and any overriding functions defined for it. """ # We assume the provided function is the base-most function, so we check all derived contracts # for a redefinition return [base_most_function] + [ function for derived_contract in base_most_function.contract.derived_contracts for function in derived_contract.functions if function.full_name == base_most_function.full_name and isinstance(function, FunctionContract) ] @staticmethod def function_parameters_written(function: Function) -> bool: return any(p in function.variables_written for p in function.parameters) @staticmethod def is_reference_type(parameter: Variable) -> bool: parameter_type = parameter.type if isinstance(parameter_type, ArrayType): return True if isinstance(parameter_type, UserDefinedType) and isinstance( parameter_type.type, Structure ): return True if str(parameter_type) in ["bytes", "string"]: return True return False def _detect(self) -> List[Output]: # pylint: disable=too-many-locals,too-many-branches results: List[Output] = [] # Create a set to track contracts with dynamic calls. All contracts with dynamic calls could potentially be # calling functions internally, and thus we can't assume any function in such contracts isn't called by them. dynamic_call_contracts: Set[Contract] = set() # Create a completed functions set to skip over functions already processed (any functions which are the base # of, or override hierarchically are processed together). completed_functions: Set[Function] = set() # First we build our set of all contracts with dynamic calls for contract in self.contracts: if self._contains_internal_dynamic_call(contract): dynamic_call_contracts.add(contract) # Loop through all contracts for contract in self.contracts: # Filter false-positives: Immediately filter this contract if it's in blacklist if contract in dynamic_call_contracts: continue # Next we'll want to loop through all functions defined directly in this contract. for function in contract.functions_declared: # If all of the function arguments are non-reference type or calldata, we skip it. reference_args = [] for arg in function.parameters: if self.is_reference_type(arg) and arg.location == "memory": reference_args.append(arg) if len(reference_args) == 0: continue # If the function is a constructor, or is public, we skip it. if function.is_constructor or function.visibility != "public": continue # Optimization: If this function has already been processed, we stop. if function in completed_functions: continue # If the function has parameters which are written-to in function body, we skip # because parameters of external functions will be allocated in calldata region which is immutable if self.function_parameters_written(function): continue # Get the base-most function to know our origin of this function. base_most_function = self.get_base_most_function(function) # Get all possible contracts which can call this function (or an override). all_possible_sources = [ base_most_function.contract ] + base_most_function.contract.derived_contracts # Get all function signatures (overloaded and not), mark as completed and we process them now. # Note: We mark all function definitions as the same, as they must all share visibility to override. all_function_definitions = set( self.get_all_function_definitions(base_most_function) ) completed_functions = completed_functions.union(all_function_definitions) # Filter false-positives: Determine if any of these sources have dynamic calls, if so, flag all of these # function definitions, and then flag all functions in all contracts that make dynamic calls. sources_with_dynamic_calls = set(all_possible_sources) & dynamic_call_contracts if sources_with_dynamic_calls: functions_in_dynamic_call_sources = { f for dyn_contract in sources_with_dynamic_calls for f in dyn_contract.functions if not f.is_constructor } completed_functions = completed_functions.union( functions_in_dynamic_call_sources ) continue # Detect all functions called in each source, if any match our current signature, we skip # otherwise, this is a candidate (in all sources) to be changed visibility for. is_called = False for possible_source in all_possible_sources: functions_called = self.detect_functions_called(possible_source) if set(functions_called) & all_function_definitions: is_called = True break # If any of this function's definitions are called, we skip it. if is_called: continue # As we collect all shadowed functions in get_all_function_definitions # Some function coming from a base might already been declared as external all_function_definitions: List[FunctionContract] = [ f for f in all_function_definitions if isinstance(f, FunctionContract) and f.visibility == "public" and f.contract == f.contract_declarer ] if all_function_definitions: all_function_definitions = sorted( all_function_definitions, key=lambda x: x.canonical_name ) function_definition = all_function_definitions[0] all_function_definitions = all_function_definitions[1:] info = [f"{function_definition.full_name} should be declared external:\n"] info += ["\t- ", function_definition, "\n"] if self.compilation_unit.solc_version >= "0.5.": info += [ "Moreover, the following function parameters should change its data location:\n" ] for reference_arg in reference_args: info += [f"{reference_arg} location should be calldata\n"] for other_function_definition in all_function_definitions: info += ["\t- ", other_function_definition, "\n"] res = self.generate_result(info) results.append(res) return results @staticmethod def _format(slither, result): custom_format(slither, result)
ExternalFunction
python
pytorch__pytorch
torch/_dynamo/utils.py
{ "start": 140676, "end": 144825 }
class ____(Generic[_P, R]): """Implements dunder methods for tnp.ndarray via functions from the operator library""" def __init__(self, op: Callable[..., Any]) -> None: self.op = op self.__name__ = f"wrapped_{op.__name__}" def __repr__(self) -> str: return f"<Wrapped operator <original {self.__name__}>>" def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any: assert not kwargs # pyrefly: ignore [bad-assignment] args = ( tnp.ndarray(arg) if isinstance(arg, torch.Tensor) else arg for arg in args ) out = self.op(*args) return numpy_to_tensor(out) def defake(x: Any) -> Any: if not isinstance(x, FakeTensor): return x size: torch._prims_common.ShapeType stride: torch._prims_common.StrideType if x._has_symbolic_sizes_strides: size = [] for s in x.size(): if isinstance(s, torch.SymInt): size.append(s.node.shape_env.size_hint(s.node.expr)) else: size.append(s) stride = [] for s in x.stride(): if isinstance(s, torch.SymInt): stride.append(s.node.shape_env.size_hint(s.node.expr)) else: stride.append(s) else: size = x.size() stride = x.stride() y = torch.empty_strided( size, stride, dtype=x.dtype, device=x.device, requires_grad=x.requires_grad, ) y.zero_() return y def _disable_side_effect_safety_checks_for_current_subtracer( fn: Callable[_P, R], *args: _P.args, **kwargs: _P.kwargs ) -> R: return fn(*args, **kwargs) def is_utils_checkpoint(obj: Any) -> bool: # Lazy import to avoid circular dependencies import torch.utils.checkpoint return obj is torch.utils.checkpoint.checkpoint def is_invoke_subgraph(obj: Any) -> bool: from torch._higher_order_ops.invoke_subgraph import invoke_subgraph_placeholder return obj is invoke_subgraph_placeholder def build_invoke_subgraph_variable(**options: Any) -> Any: from .variables.higher_order_ops import TorchHigherOrderOperatorVariable return TorchHigherOrderOperatorVariable.make( torch._higher_order_ops.invoke_subgraph, **options, ) def build_checkpoint_variable(**options: Any) -> Any: import torch._higher_order_ops.wrap as higher_order_ops from .variables.higher_order_ops import TorchHigherOrderOperatorVariable # TODO - This is a temporary situation where we have two versions of # checkpointing implementation. We will converge on one and remove the other. activation_checkpoint_op: torch._ops.HigherOrderOperator = ( higher_order_ops.tag_activation_checkpoint ) if torch._functorch.config.functionalize_rng_ops: activation_checkpoint_op = higher_order_ops.wrap_activation_checkpoint return TorchHigherOrderOperatorVariable.make( activation_checkpoint_op, **options, ) def is_compile_supported(device_type: DeviceLikeType) -> Any: from .eval_frame import is_dynamo_supported type = torch.device(device_type).type compile_supported = is_dynamo_supported() if type == "cpu": pass elif type in ["cuda", "xpu", "mtia"] and compile_supported: compile_supported = has_triton() else: compile_supported = False return compile_supported # The following 3.11 source code functions are adapted from # https://github.com/python/cpython/blob/v3.11.4/Lib/traceback.py # in order to output source code corresponding to bytecode in 3.11+. # We need our own versions since we want to support multiline expressions. def _fix_offset(str: str, offset: int) -> int: """ Convert byte offset `offset` of `str` into character offset. Byte offset is used for 3.11+ instruction column data. Takes things like unicode characters into consideration. Unchanged from CPython implementation. """ as_utf8 = str.encode("utf-8") return len(as_utf8[:offset].decode("utf-8", errors="replace")) @dataclasses.dataclass
numpy_operator_wrapper
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 202444, "end": 202951 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "pull_request_review", "review_edge") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") pull_request_review = sgqlc.types.Field( "PullRequestReview", graphql_name="pullRequestReview" ) review_edge = sgqlc.types.Field("PullRequestReviewEdge", graphql_name="reviewEdge")
AddPullRequestReviewPayload
python
pytorch__pytorch
test/package/common.py
{ "start": 172, "end": 1288 }
class ____(TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._temporary_files = [] def temp(self): t = NamedTemporaryFile() name = t.name if IS_WINDOWS: t.close() # can't read an open file in windows else: self._temporary_files.append(t) return name def setUp(self): """Add test/package/ to module search path. This ensures that importing our fake packages via, e.g. `import package_a` will always work regardless of how we invoke the test. """ super().setUp() self.package_test_dir = os.path.dirname(os.path.realpath(__file__)) self.orig_sys_path = sys.path.copy() sys.path.append(self.package_test_dir) torch.package.package_exporter._gate_torchscript_serialization = False def tearDown(self): super().tearDown() sys.path = self.orig_sys_path # remove any temporary files for t in self._temporary_files: t.close() self._temporary_files = []
PackageTestCase
python
sympy__sympy
sympy/printing/numpy.py
{ "start": 14025, "end": 19166 }
class ____(NumPyPrinter): _kf = {**NumPyPrinter._kf, **_scipy_known_functions} _kc = {**NumPyPrinter._kc, **_scipy_known_constants} def __init__(self, settings=None): super().__init__(settings=settings) self.language = "Python with SciPy and NumPy" def _print_SparseRepMatrix(self, expr): i, j, data = [], [], [] for (r, c), v in expr.todok().items(): i.append(r) j.append(c) data.append(v) return "{name}(({data}, ({i}, {j})), shape={shape})".format( name=self._module_format('scipy.sparse.coo_matrix'), data=data, i=i, j=j, shape=expr.shape ) _print_ImmutableSparseMatrix = _print_SparseRepMatrix # SciPy's lpmv has a different order of arguments from assoc_legendre def _print_assoc_legendre(self, expr): return "{0}({2}, {1}, {3})".format( self._module_format('scipy.special.lpmv'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) def _print_lowergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammainc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_uppergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammaincc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_betainc(self, expr): betainc = self._module_format('scipy.special.betainc') beta = self._module_format('scipy.special.beta') args = [self._print(arg) for arg in expr.args] return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \ * {beta}({args[0]}, {args[1]})" def _print_betainc_regularized(self, expr): return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format( self._module_format('scipy.special.betainc'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2]), self._print(expr.args[3])) def _print_fresnels(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_fresnelc(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_airyai(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airyaiprime(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybi(self, expr): return "{}({})[2]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybiprime(self, expr): return "{}({})[3]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_bernoulli(self, expr): # scipy's bernoulli is inconsistent with SymPy's so rewrite return self._print(expr._eval_rewrite_as_zeta(*expr.args)) def _print_harmonic(self, expr): return self._print(expr._eval_rewrite_as_zeta(*expr.args)) def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) if len(limits) == 1: # nicer (but not necessary) to prefer quad over nquad for 1D case module_str = self._module_format("scipy.integrate.quad") limit_str = "%s, %s" % tuple(map(self._print, limits[0])) else: module_str = self._module_format("scipy.integrate.nquad") limit_str = "({})".format(", ".join( "(%s, %s)" % tuple(map(self._print, l)) for l in limits)) return "{}(lambda {}: {}, {})[0]".format( module_str, ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), limit_str) def _print_Si(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.sici"), self._print(expr.args[0])) def _print_Ci(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.sici"), self._print(expr.args[0])) for func in _scipy_known_functions: setattr(SciPyPrinter, f'_print_{func}', _print_known_func) for const in _scipy_known_constants: setattr(SciPyPrinter, f'_print_{const}', _print_known_const) _cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()} _cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()}
SciPyPrinter
python
numba__numba
numba/np/ufunc/ufuncbuilder.py
{ "start": 11282, "end": 14610 }
class ____(_BaseUFuncBuilder): # TODO handle scalar def __init__(self, py_func, signature, identity=None, cache=False, targetoptions=None, writable_args=()): if targetoptions is None: targetoptions = {} self.py_func = py_func self.identity = parse_identity(identity) with _suppress_deprecation_warning_nopython_not_supplied(): self.nb_func = jit(_target='npyufunc', cache=cache)(py_func) self.signature = signature self.sin, self.sout = parse_signature(signature) self.targetoptions = targetoptions self.cache = cache self._sigs = [] self._cres = {} transform_arg = _get_transform_arg(py_func) self.writable_args = tuple([transform_arg(a) for a in writable_args]) def _finalize_signature(self, cres, args, return_type): if not cres.objectmode and cres.signature.return_type != types.void: raise TypeError("gufunc kernel must have void return type") if return_type is None: return_type = types.void return return_type(*args) @global_compiler_lock def build_ufunc(self): type_list = [] func_list = [] if not self.nb_func: raise TypeError("No definition") # Get signature in the order they are added keepalive = [] for sig in self._sigs: cres = self._cres[sig] dtypenums, ptr, env = self.build(cres) type_list.append(dtypenums) func_list.append(int(ptr)) keepalive.append((cres.library, env)) datalist = [None] * len(func_list) nin = len(self.sin) nout = len(self.sout) # Pass envs to fromfuncsig to bind to the lifetime of the ufunc object ufunc = _internal.fromfunc( self.py_func.__name__, self.py_func.__doc__, func_list, type_list, nin, nout, datalist, keepalive, self.identity, self.signature, self.writable_args ) return ufunc def build(self, cres): """ Returns (dtype numbers, function ptr, EnvironmentObject) """ # Builder wrapper for ufunc entry point signature = cres.signature info = build_gufunc_wrapper( self.py_func, cres, self.sin, self.sout, cache=self.cache, is_parfors=False, ) env = info.env ptr = info.library.get_pointer_to_function(info.name) # Get dtypes dtypenums = [] for a in signature.args: if isinstance(a, types.Array): ty = a.dtype else: ty = a dtypenums.append(as_dtype(ty).num) return dtypenums, ptr, env def _get_transform_arg(py_func): """Return function that transform arg into index""" args = inspect.getfullargspec(py_func).args pos_by_arg = {arg: i for i, arg in enumerate(args)} def transform_arg(arg): if isinstance(arg, int): return arg try: return pos_by_arg[arg] except KeyError: msg = (f"Specified writable arg {arg} not found in arg list " f"{args} for function {py_func.__qualname__}") raise RuntimeError(msg) return transform_arg
GUFuncBuilder
python
pypa__setuptools
setuptools/_vendor/jaraco/collections/__init__.py
{ "start": 15539, "end": 15872 }
class ____(dict): """ A dictionary that by default maps each key to itself, but otherwise acts like a normal dictionary. >>> d = IdentityOverrideMap() >>> d[42] 42 >>> d['speed'] = 'speedo' >>> print(d['speed']) speedo """ def __missing__(self, key): return key
IdentityOverrideMap
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 11869, "end": 13289 }
class ____(BaseField): """Floating point number field.""" def __init__(self, min_value=None, max_value=None, **kwargs): """ :param min_value: (optional) A min value that will be applied during validation :param max_value: (optional) A max value that will be applied during validation :param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.BaseField` """ self.min_value, self.max_value = min_value, max_value super().__init__(**kwargs) def to_python(self, value): try: value = float(value) except ValueError: pass return value def validate(self, value): if isinstance(value, int): try: value = float(value) except OverflowError: self.error("The value is too large to be converted to float") if not isinstance(value, float): self.error("FloatField only accepts float and integer values") if self.min_value is not None and value < self.min_value: self.error("Float value is too small") if self.max_value is not None and value > self.max_value: self.error("Float value is too large") def prepare_query_value(self, op, value): if value is None: return value return super().prepare_query_value(op, float(value))
FloatField
python
wandb__wandb
wandb/_pydantic/pagination.py
{ "start": 427, "end": 559 }
class ____(GQLResult): typename__: Literal["PageInfo"] = "PageInfo" end_cursor: Optional[str] has_next_page: bool
PageInfo
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/compute_log_manager.py
{ "start": 3891, "end": 5555 }
class ____: def __init__( self, manager: "ComputeLogManager[T_DagsterInstance]", log_key: Sequence[str], cursor: Optional[str], ): self._manager = manager self._log_key = log_key self._cursor = cursor self._observer: Optional[Callable[[CapturedLogData], None]] = None self.is_complete = False def __call__(self, observer: Optional[Callable[[CapturedLogData], None]]) -> Self: self._observer = observer self.fetch() if self._manager.is_capture_complete(self._log_key): self.complete() return self @property def log_key(self) -> Sequence[str]: return self._log_key def dispose(self) -> None: self._observer = None self._manager.unsubscribe(self) def fetch(self) -> None: if not self._observer: return should_fetch = True while should_fetch: log_data = self._manager.get_log_data( self._log_key, self._cursor, max_bytes=MAX_BYTES_CHUNK_READ, ) if not self._cursor or log_data.cursor != self._cursor: self._observer(log_data) self._cursor = log_data.cursor should_fetch = _has_max_data(log_data.stdout) or _has_max_data(log_data.stderr) def complete(self) -> None: self.is_complete = True def _has_max_data(chunk: Optional[bytes]) -> bool: # function is used as predicate but does not actually return a boolean return chunk and len(chunk) >= MAX_BYTES_CHUNK_READ # type: ignore @public
CapturedLogSubscription
python
pyqtgraph__pyqtgraph
pyqtgraph/GraphicsScene/mouseEvents.py
{ "start": 5629, "end": 8718 }
class ____(object): """ Instances of this class are delivered to items in a :class:`GraphicsScene <pyqtgraph.GraphicsScene>` via their mouseClickEvent() method when the item is clicked. """ def __init__(self, pressEvent, double=False): self.accepted = False self.currentItem = None self._double = double self._scenePos = pressEvent.scenePos() self._screenPos = pressEvent.screenPos() self._button = pressEvent.button() self._buttons = pressEvent.buttons() self._modifiers = pressEvent.modifiers() self._time = perf_counter() self.acceptedItem = None def accept(self): """An item should call this method if it can handle the event. This will prevent the event being delivered to any other items.""" self.accepted = True self.acceptedItem = self.currentItem def ignore(self): """An item should call this method if it cannot handle the event. This will allow the event to be delivered to other items.""" self.accepted = False def isAccepted(self): return self.accepted def scenePos(self): """Return the current scene position of the mouse.""" return Point(self._scenePos) def screenPos(self): """Return the current screen position (pixels relative to widget) of the mouse.""" return Point(self._screenPos) def buttons(self): """ Return the buttons currently pressed on the mouse. (see QGraphicsSceneMouseEvent::buttons in the Qt documentation) """ return self._buttons def button(self): """Return the mouse button that generated the click event. (see QGraphicsSceneMouseEvent::button in the Qt documentation) """ return self._button def double(self): """Return True if this is a double-click.""" return self._double def pos(self): """ Return the current position of the mouse in the coordinate system of the item that the event was delivered to. """ return Point(self.currentItem.mapFromScene(self._scenePos)) def lastPos(self): """ Return the previous position of the mouse in the coordinate system of the item that the event was delivered to. """ return Point(self.currentItem.mapFromScene(self._lastScenePos)) def modifiers(self): """Return any keyboard modifiers currently pressed. (see QGraphicsSceneMouseEvent::modifiers in the Qt documentation) """ return self._modifiers def __repr__(self): try: if self.currentItem is None: p = self._scenePos else: p = self.pos() return "<MouseClickEvent (%g,%g) button=%s>" % (p.x(), p.y(), str(self.button())) except: return "<MouseClickEvent button=%s>" % (str(self.button())) def time(self): return self._time
MouseClickEvent
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/frontend_widget.py
{ "start": 3368, "end": 34821 }
class ____(HistoryConsoleWidget, BaseFrontendMixin): """ A Qt frontend for a generic Python kernel. """ # The text to show when the kernel is (re)started. banner = Unicode(config=True) kernel_banner = Unicode() # Whether to show the banner _display_banner = Bool(False) # An option and corresponding signal for overriding the default kernel # interrupt behavior. custom_interrupt = Bool(False) custom_interrupt_requested = QtCore.Signal() # An option and corresponding signals for overriding the default kernel # restart behavior. custom_restart = Bool(False) custom_restart_kernel_died = QtCore.Signal(float) custom_restart_requested = QtCore.Signal() # Whether to automatically show calltips on open-parentheses. enable_calltips = Bool(True, config=True, help="Whether to draw information calltips on open-parentheses.") clear_on_kernel_restart = Bool(True, config=True, help="Whether to clear the console when the kernel is restarted") confirm_restart = Bool(True, config=True, help="Whether to ask for user confirmation when restarting kernel") lexer_class = DottedObjectName(config=True, help="The pygments lexer class to use." ) def _lexer_class_changed(self, name, old, new): lexer_class = import_item(new) self.lexer = lexer_class() def _lexer_class_default(self): return 'pygments.lexers.Python3Lexer' lexer = Any() def _lexer_default(self): lexer_class = import_item(self.lexer_class) return lexer_class() # Emitted when a user visible 'execute_request' has been submitted to the # kernel from the FrontendWidget. Contains the code to be executed. executing = QtCore.Signal(object) # Emitted when a user-visible 'execute_reply' has been received from the # kernel and processed by the FrontendWidget. Contains the response message. executed = QtCore.Signal(object) # Emitted when an exit request has been received from the kernel. exit_requested = QtCore.Signal(object) _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos']) _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'code', 'pos']) _ExecutionRequest = namedtuple( '_ExecutionRequest', ['id', 'kind', 'hidden']) _local_kernel = False _highlighter = Instance(FrontendHighlighter, allow_none=True) # ------------------------------------------------------------------------- # 'Object' interface # ------------------------------------------------------------------------- def __init__(self, local_kernel=_local_kernel, *args, **kw): super().__init__(*args, **kw) # FrontendWidget protected variables. self._bracket_matcher = BracketMatcher(self._control) self._call_tip_widget = CallTipWidget(self._control) self._copy_raw_action = QtWidgets.QAction('Copy (Raw Text)', None) self._highlighter = FrontendHighlighter(self, lexer=self.lexer) self._kernel_manager = None self._kernel_client = None self._request_info = {} self._request_info['execute'] = {} self._callback_dict = {} self._display_banner = True # Configure the ConsoleWidget. self.tab_width = 4 self._set_continuation_prompt('... ') # Configure the CallTipWidget. self._call_tip_widget.setFont(self.font) self.font_changed.connect(self._call_tip_widget.setFont) # Configure actions. action = self._copy_raw_action action.setEnabled(False) action.setShortcut(QtGui.QKeySequence("Ctrl+Shift+C")) action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) action.triggered.connect(self.copy_raw) self.copy_available.connect(action.setEnabled) self.addAction(action) # Connect signal handlers. document = self._control.document() document.contentsChange.connect(self._document_contents_change) # Set flag for whether we are connected via localhost. self._local_kernel = local_kernel # Whether or not a clear_output call is pending new output. self._pending_clearoutput = False #--------------------------------------------------------------------------- # 'ConsoleWidget' public interface #--------------------------------------------------------------------------- def copy(self): """ Copy the currently selected text to the clipboard, removing prompts. """ if self._page_control is not None and self._page_control.hasFocus(): self._page_control.copy() elif self._control.hasFocus(): text = self._control.textCursor().selection().toPlainText() if text: first_line_selection, *remaining_lines = text.splitlines() # Get preceding text cursor = self._control.textCursor() cursor.setPosition(cursor.selectionStart()) cursor.setPosition(cursor.block().position(), QtGui.QTextCursor.KeepAnchor) preceding_text = cursor.selection().toPlainText() def remove_prompts(line): """Remove all prompts from line.""" line = self._highlighter.transform_classic_prompt(line) return self._highlighter.transform_ipy_prompt(line) # Get first line promp len first_line = preceding_text + first_line_selection len_with_prompt = len(first_line) first_line = remove_prompts(first_line) prompt_len = len_with_prompt - len(first_line) # Remove not selected part if prompt_len < len(preceding_text): first_line = first_line[len(preceding_text) - prompt_len:] # Remove partial prompt last line if len(remaining_lines) > 0 and remaining_lines[-1]: cursor = self._control.textCursor() cursor.setPosition(cursor.selectionEnd()) block = cursor.block() start_pos = block.position() length = block.length() cursor.setPosition(start_pos) cursor.setPosition(start_pos + length - 1, QtGui.QTextCursor.KeepAnchor) last_line_full = cursor.selection().toPlainText() prompt_len = ( len(last_line_full) - len(remove_prompts(last_line_full))) if len(remaining_lines[-1]) < prompt_len: # This is a partial prompt remaining_lines[-1] = "" # Remove prompts for other lines. remaining_lines = map(remove_prompts, remaining_lines) text = '\n'.join([first_line, *remaining_lines]) # Needed to prevent errors when copying the prompt. # See issue 264 try: was_newline = text[-1] == '\n' except IndexError: was_newline = False if was_newline: # user doesn't need newline text = text[:-1] QtWidgets.QApplication.clipboard().setText(text) else: self.log.debug("frontend widget : unknown copy target") #--------------------------------------------------------------------------- # 'ConsoleWidget' abstract interface #--------------------------------------------------------------------------- def _execute(self, source, hidden): """ Execute 'source'. If 'hidden', do not show any output. See parent class :meth:`execute` docstring for full details. """ msg_id = self.kernel_client.execute(source, hidden) self._request_info['execute'][msg_id] = self._ExecutionRequest( msg_id, 'user', hidden) if not hidden: self.executing.emit(source) def _prompt_started_hook(self): """ Called immediately after a new prompt is displayed. """ if not self._reading: self._highlighter.highlighting_on = True def _prompt_finished_hook(self): """ Called immediately after a prompt is finished, i.e. when some input will be processed and a new prompt displayed. """ if not self._reading: self._highlighter.highlighting_on = False def _tab_pressed(self): """ Called when the tab key is pressed. Returns whether to continue processing the event. """ # Perform tab completion if: # 1) The cursor is in the input buffer. # 2) There is a non-whitespace character before the cursor. # 3) There is no active selection. text = self._get_input_buffer_cursor_line() if text is None: return False non_ws_before = bool(text[:self._get_input_buffer_cursor_column()].strip()) complete = non_ws_before and self._get_cursor().selectedText() == '' if complete: self._complete() return not complete #--------------------------------------------------------------------------- # 'ConsoleWidget' protected interface #--------------------------------------------------------------------------- def _context_menu_make(self, pos): """ Reimplemented to add an action for raw copy. """ menu = super()._context_menu_make(pos) for before_action in menu.actions(): if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ QtGui.QKeySequence.ExactMatch: menu.insertAction(before_action, self._copy_raw_action) break return menu def request_interrupt_kernel(self): if self._executing: self.interrupt_kernel() def request_restart_kernel(self): message = 'Are you sure you want to restart the kernel?' self.restart_kernel(message, now=False) def _event_filter_console_keypress(self, event): """ Reimplemented for execution interruption and smart backspace. """ key = event.key() if self._control_key_down(event.modifiers(), include_command=False): if key == QtCore.Qt.Key_C and self._executing: # If text is selected, the user probably wants to copy it. if self.can_copy() and event.matches(QtGui.QKeySequence.Copy): self.copy() else: self.request_interrupt_kernel() return True elif key == QtCore.Qt.Key_Period: self.request_restart_kernel() return True elif not event.modifiers() & QtCore.Qt.AltModifier: # Smart backspace: remove four characters in one backspace if: # 1) everything left of the cursor is whitespace # 2) the four characters immediately left of the cursor are spaces if key == QtCore.Qt.Key_Backspace: col = self._get_input_buffer_cursor_column() cursor = self._control.textCursor() if col > 3 and not cursor.hasSelection(): text = self._get_input_buffer_cursor_line()[:col] if text.endswith(' ') and not text.strip(): cursor.movePosition(QtGui.QTextCursor.Left, QtGui.QTextCursor.KeepAnchor, 4) cursor.removeSelectedText() return True return super()._event_filter_console_keypress(event) #--------------------------------------------------------------------------- # 'BaseFrontendMixin' abstract interface #--------------------------------------------------------------------------- def _handle_clear_output(self, msg): """Handle clear output messages.""" if self.include_output(msg): wait = msg['content'].get('wait', True) if wait: self._pending_clearoutput = True else: self.clear_output() def _silent_exec_callback(self, expr, callback): """Silently execute `expr` in the kernel and call `callback` with reply the `expr` is evaluated silently in the kernel (without) output in the frontend. Call `callback` with the `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument Parameters ---------- expr : string valid string to be executed by the kernel. callback : function function accepting one argument, as a string. The string will be the `repr` of the result of evaluating `expr` The `callback` is called with the `repr()` of the result of `expr` as first argument. To get the object, do `eval()` on the passed value. See Also -------- _handle_exec_callback : private method, deal with calling callback with reply """ # generate uuid, which would be used as an indication of whether or # not the unique request originated from here (can use msg id ?) local_uuid = str(uuid.uuid1()) msg_id = self.kernel_client.execute('', silent=True, user_expressions={ local_uuid:expr }) self._callback_dict[local_uuid] = callback self._request_info['execute'][msg_id] = self._ExecutionRequest( msg_id, 'silent_exec_callback', False) def _handle_exec_callback(self, msg): """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback`` Parameters ---------- msg : raw message send by the kernel containing an `user_expressions` and having a 'silent_exec_callback' kind. Notes ----- This function will look for a `callback` associated with the corresponding message id. Association has been made by `_silent_exec_callback`. `callback` is then called with the `repr()` of the value of corresponding `user_expressions` as argument. `callback` is then removed from the known list so that any message coming again with the same id won't trigger it. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._callback_dict: self._callback_dict.pop(expression)(user_exp[expression]) def _handle_execute_reply(self, msg): """ Handles replies for code execution. """ self.log.debug("execute_reply: %s", msg.get('content', '')) msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False # Note: If info is NoneType, this is ignored if not info or info.hidden: return if info.kind == 'user': # Make sure that all output from the SUB channel has been processed # before writing a new prompt. if not self.kernel_client.iopub_channel.closed(): self.kernel_client.iopub_channel.flush() # Reset the ANSI style information to prevent bad text in stdout # from messing up our colors. We're not a true terminal so we're # allowed to do this. if self.ansi_codes: self._ansi_processor.reset_sgr() content = msg['content'] status = content['status'] if status == 'ok': self._process_execute_ok(msg) elif status == 'aborted': self._process_execute_abort(msg) self._show_interpreter_prompt_for_reply(msg) self.executed.emit(msg) self._request_info['execute'].pop(msg_id) elif info.kind == 'silent_exec_callback': self._handle_exec_callback(msg) self._request_info['execute'].pop(msg_id) else: raise RuntimeError("Unknown handler for %s" % info.kind) def _handle_error(self, msg): """ Handle error messages. """ self._process_execute_error(msg) def _handle_input_request(self, msg): """ Handle requests for raw_input. """ self.log.debug("input: %s", msg.get('content', '')) msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) if info and info.hidden: raise RuntimeError('Request for raw input during hidden execution.') # Make sure that all output from the SUB channel has been processed # before entering readline mode. if not self.kernel_client.iopub_channel.closed(): self.kernel_client.iopub_channel.flush() def callback(line): self._finalize_input_request() self.kernel_client.input(line) if self._reading: self.log.debug("Got second input request, assuming first was interrupted.") self._reading = False self._readline(msg['content']['prompt'], callback=callback, password=msg['content']['password']) def _kernel_restarted_message(self, died=True): msg = "Kernel died, restarting" if died else "Kernel restarting" self._append_html("<br>%s<hr><br>" % msg, before_prompt=False ) def _handle_kernel_died(self, since_last_heartbeat): """Handle the kernel's death (if we do not own the kernel). """ self.log.warning("kernel died: %s", since_last_heartbeat) if self.custom_restart: self.custom_restart_kernel_died.emit(since_last_heartbeat) else: self._kernel_restarted_message(died=True) self.reset() def _handle_kernel_restarted(self, died=True): """Notice that the autorestarter restarted the kernel. There's nothing to do but show a message. """ self.log.warning("kernel restarted") self._kernel_restarted_message(died=died) # This resets the autorestart counter so that the kernel can be # auto-restarted before the next time it's polled to see if it's alive. if self.kernel_manager: self.kernel_manager.reset_autorestart_count() self.reset() def _handle_inspect_reply(self, rep): """Handle replies for call tips.""" self.log.debug("oinfo: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): content = rep['content'] if content.get('status') == 'ok' and content.get('found', False): self._call_tip_widget.show_inspect_data(content) def _handle_execute_result(self, msg): """ Handle display hook output. """ self.log.debug("execute_result: %s", msg.get('content', '')) if self.include_output(msg): self.flush_clearoutput() text = msg['content']['data'] self._append_plain_text(text + '\n', before_prompt=True) def _handle_stream(self, msg): """ Handle stdout, stderr, and stdin. """ self.log.debug("stream: %s", msg.get('content', '')) if self.include_output(msg): self.flush_clearoutput() self.append_stream(msg['content']['text']) def _handle_shutdown_reply(self, msg): """ Handle shutdown signal, only if from other console. """ self.log.debug("shutdown: %s", msg.get('content', '')) restart = msg.get('content', {}).get('restart', False) if msg['parent_header']: msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) if info and info.hidden: return if not self.from_here(msg): # got shutdown reply, request came from session other than ours if restart: # someone restarted the kernel, handle it self._handle_kernel_restarted(died=False) else: # kernel was shutdown permanently # this triggers exit_requested if the kernel was local, # and a dialog if the kernel was remote, # so we don't suddenly clear the qtconsole without asking. if self._local_kernel: self.exit_requested.emit(self) else: title = self.window().windowTitle() reply = QtWidgets.QMessageBox.question(self, title, "Kernel has been shutdown permanently. " "Close the Console?", QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self.exit_requested.emit(self) def _handle_status(self, msg): """Handle status message""" # This is where a busy/idle indicator would be triggered, # when we make one. state = msg['content'].get('execution_state', '') if state == 'starting': # kernel started while we were running if self._executing: self._handle_kernel_restarted(died=True) elif state == 'idle': pass elif state == 'busy': pass def _started_channels(self): """ Called when the KernelManager channels have started listening or when the frontend is assigned an already listening KernelManager. """ self.reset(clear=True) #--------------------------------------------------------------------------- # 'FrontendWidget' public interface #--------------------------------------------------------------------------- def copy_raw(self): """ Copy the currently selected text to the clipboard without attempting to remove prompts or otherwise alter the text. """ self._control.copy() def interrupt_kernel(self): """ Attempts to interrupt the running kernel. Also unsets _reading flag, to avoid runtime errors if raw_input is called again. """ if self.custom_interrupt: self._reading = False self.custom_interrupt_requested.emit() elif self.kernel_manager: self._reading = False self.kernel_manager.interrupt_kernel() else: self._append_plain_text('Cannot interrupt a kernel I did not start.\n') def reset(self, clear=False): """ Resets the widget to its initial state if ``clear`` parameter is True, otherwise prints a visual indication of the fact that the kernel restarted, but does not clear the traces from previous usage of the kernel before it was restarted. With ``clear=True``, it is similar to ``%clear``, but also re-writes the banner and aborts execution if necessary. """ if self._executing: self._executing = False self._request_info['execute'] = {} self._reading = False self._highlighter.highlighting_on = False if clear: self._control.clear() if self._display_banner: self._append_plain_text(self.banner) if self.kernel_banner: self._append_plain_text(self.kernel_banner) # update output marker for stdout/stderr, so that startup # messages appear after banner: self._show_interpreter_prompt() def restart_kernel(self, message, now=False): """ Attempts to restart the running kernel. """ # FIXME: now should be configurable via a checkbox in the dialog. Right # now at least the heartbeat path sets it to True and the manual restart # to False. But those should just be the pre-selected states of a # checkbox that the user could override if so desired. But I don't know # enough Qt to go implementing the checkbox now. if self.custom_restart: self.custom_restart_requested.emit() return if self.kernel_manager: # Pause the heart beat channel to prevent further warnings. self.kernel_client.hb_channel.pause() # Prompt the user to restart the kernel. Un-pause the heartbeat if # they decline. (If they accept, the heartbeat will be un-paused # automatically when the kernel is restarted.) if self.confirm_restart: buttons = QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No result = QtWidgets.QMessageBox.question(self, 'Restart kernel?', message, buttons) do_restart = result == QtWidgets.QMessageBox.Yes else: # confirm_restart is False, so we don't need to ask user # anything, just do the restart do_restart = True if do_restart: try: self.kernel_manager.restart_kernel(now=now) except RuntimeError as e: self._append_plain_text( 'Error restarting kernel: %s\n' % e, before_prompt=True ) else: self._append_html("<br>Restarting kernel...\n<hr><br>", before_prompt=True, ) else: self.kernel_client.hb_channel.unpause() else: self._append_plain_text( 'Cannot restart a Kernel I did not start\n', before_prompt=True ) def append_stream(self, text): """Appends text to the output stream.""" self._append_plain_text(text, before_prompt = True) def flush_clearoutput(self): """If a clearoutput is pending, execute it.""" if self._pending_clearoutput: self._pending_clearoutput = False self.clear_output() def clear_output(self): """Clears the current line of output.""" cursor = self._control.textCursor() cursor.beginEditBlock() cursor.movePosition(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor) cursor.insertText('') cursor.endEditBlock() #--------------------------------------------------------------------------- # 'FrontendWidget' protected interface #--------------------------------------------------------------------------- def _auto_call_tip(self): """Trigger call tip automatically on open parenthesis Call tips can be requested explcitly with `_call_tip`. """ cursor = self._get_cursor() cursor.movePosition(QtGui.QTextCursor.Left) if cursor.document().characterAt(cursor.position()) == '(': # trigger auto call tip on open paren self._call_tip() def _call_tip(self): """Shows a call tip, if appropriate, at the current cursor location.""" # Decide if it makes sense to show a call tip if not self.enable_calltips or not self.kernel_client.shell_channel.is_alive(): return False cursor_pos = self._get_input_buffer_cursor_pos() code = self.input_buffer # Send the metadata request to the kernel msg_id = self.kernel_client.inspect(code, cursor_pos) pos = self._get_cursor().position() self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) return True def _complete(self): """ Performs completion at the current cursor location. """ code = self.input_buffer cursor_pos = self._get_input_buffer_cursor_pos() # Send the completion request to the kernel msg_id = self.kernel_client.complete(code=code, cursor_pos=cursor_pos) info = self._CompletionRequest(msg_id, code, cursor_pos) self._request_info['complete'] = info def _process_execute_abort(self, msg): """ Process a reply for an aborted execution request. """ self._append_plain_text("ERROR: execution aborted\n") def _process_execute_error(self, msg): """ Process a reply for an execution request that resulted in an error. """ content = msg['content'] # If a SystemExit is passed along, this means exit() was called - also # all the ipython %exit magic syntax of '-k' to be used to keep # the kernel running if content['ename']=='SystemExit': keepkernel = content['evalue']=='-k' or content['evalue']=='True' self._keep_kernel_on_exit = keepkernel self.exit_requested.emit(self) else: traceback = ''.join(content['traceback']) self._append_plain_text(traceback) def _process_execute_ok(self, msg): """ Process a reply for a successful execution request. """ payload = msg['content'].get('payload', []) for item in payload: if not self._process_execute_payload(item): warning = 'Warning: received unknown payload of type %s' print(warning % repr(item['source'])) def _process_execute_payload(self, item): """ Process a single payload item from the list of payload items in an execution reply. Returns whether the payload was handled. """ # The basic FrontendWidget doesn't handle payloads, as they are a # mechanism for going beyond the standard Python interpreter model. return False def _show_interpreter_prompt(self): """ Shows a prompt for the interpreter. """ self._show_prompt('>>> ') def _show_interpreter_prompt_for_reply(self, msg): """ Shows a prompt for the interpreter given an 'execute_reply' message. """ self._show_interpreter_prompt() #------ Signal handlers ---------------------------------------------------- def _document_contents_change(self, position, removed, added): """ Called whenever the document's content changes. Display a call tip if appropriate. """ # Calculate where the cursor should be *after* the change: position += added if position == self._get_cursor().position(): self._auto_call_tip() #------ Trait default initializers ----------------------------------------- @default('banner') def _banner_default(self): """ Returns the standard Python banner. """ banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \ '"license" for more information.' return banner % (sys.version, sys.platform)
FrontendWidget
python
conda__conda
conda/activate.py
{ "start": 38865, "end": 39581 }
class ____(_Activator): pathsep_join = '" "'.join sep = "/" path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) script_extension = ".fish" tempfile_extension = None # output to stdout command_join = ";\n" needs_line_ending_fix = True unset_var_tmpl = "set -e %s || true" export_var_tmpl = 'set -gx %s "%s"' path_var_tmpl = 'set -gx %s (cygpath "%s")' if on_win else export_var_tmpl set_var_tmpl = 'set -g %s "%s"' run_script_tmpl = 'source "%s"' hook_source_path = Path( CONDA_PACKAGE_ROOT, "shell", "etc", "fish", "conf.d", "conda.fish", ) inline_hook_source = True
FishActivator
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 508848, "end": 511172 }
class ____(sgqlc.types.Interface): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "id", "project", "projects", "projects_resource_path", "projects_url", "viewer_can_create_projects", ) id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") project = sgqlc.types.Field( "Project", graphql_name="project", args=sgqlc.types.ArgDict( ( ( "number", sgqlc.types.Arg( sgqlc.types.non_null(Int), graphql_name="number", default=None ), ), ) ), ) projects = sgqlc.types.Field( sgqlc.types.non_null(ProjectConnection), graphql_name="projects", args=sgqlc.types.ArgDict( ( ( "order_by", sgqlc.types.Arg(ProjectOrder, graphql_name="orderBy", default=None), ), ( "search", sgqlc.types.Arg(String, graphql_name="search", default=None), ), ( "states", sgqlc.types.Arg( sgqlc.types.list_of(sgqlc.types.non_null(ProjectState)), graphql_name="states", default=None, ), ), ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ( "before", sgqlc.types.Arg(String, graphql_name="before", default=None), ), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) projects_resource_path = sgqlc.types.Field( sgqlc.types.non_null(URI), graphql_name="projectsResourcePath" ) projects_url = sgqlc.types.Field( sgqlc.types.non_null(URI), graphql_name="projectsUrl" ) viewer_can_create_projects = sgqlc.types.Field( sgqlc.types.non_null(Boolean), graphql_name="viewerCanCreateProjects" )
ProjectOwner
python
google__jax
tests/array_interoperability_test.py
{ "start": 10079, "end": 15487 }
class ____(jtu.JaxTestCase): @jtu.skip_on_devices("cuda") def testCudaArrayInterfaceOnNonCudaFails(self): x = jnp.arange(5) self.assertFalse(hasattr(x, "__cuda_array_interface__")) with self.assertRaisesRegex( AttributeError, "__cuda_array_interface__ is only defined for NVidia GPU buffers.", ): _ = x.__cuda_array_interface__ @jtu.run_on_devices("cuda") def testCudaArrayInterfaceOnShardedArrayFails(self): devices = jax.local_devices() if len(devices) <= 1: raise unittest.SkipTest("Test requires 2 or more devices") mesh = jax.sharding.Mesh(np.array(devices), ("x",)) sharding = jax.sharding.NamedSharding(mesh, P("x")) x = jnp.arange(16) x = jax.device_put(x, sharding) self.assertFalse(hasattr(x, "__cuda_array_interface__")) with self.assertRaisesRegex( AttributeError, "__cuda_array_interface__ is only supported for unsharded arrays.", ): _ = x.__cuda_array_interface__ @jtu.sample_product( shape=all_shapes, dtype=cuda_array_interface_dtypes, ) @jtu.run_on_devices("cuda") def testCudaArrayInterfaceWorks(self, shape, dtype): rng = jtu.rand_default(self.rng()) x = rng(shape, dtype) y = jnp.array(x) z = np.asarray(y) a = y.__cuda_array_interface__ self.assertEqual(shape, a["shape"]) self.assertEqual(z.__array_interface__["typestr"], a["typestr"]) @jtu.run_on_devices("cuda") def testCudaArrayInterfaceBfloat16Fails(self): rng = jtu.rand_default(self.rng()) x = rng((2, 2), jnp.bfloat16) y = jnp.array(x) with self.assertRaisesRegex(AttributeError, ".*not supported for BF16.*"): _ = y.__cuda_array_interface__ @jtu.sample_product( shape=all_shapes, dtype=cuda_array_interface_dtypes, ) @unittest.skipIf(not cupy, "Test requires CuPy") @jtu.run_on_devices("cuda") def testJaxToCuPy(self, shape, dtype): rng = jtu.rand_default(self.rng()) x = rng(shape, dtype) y = jnp.array(x) # TODO(parkers): Remove after setting 'stream' properly. jax.block_until_ready(y) z = cupy.asarray(y) self.assertEqual(y.__cuda_array_interface__["data"][0], z.__cuda_array_interface__["data"][0]) self.assertAllClose(x, cupy.asnumpy(z)) @jtu.sample_product( shape=all_shapes, dtype=jtu.dtypes.supported(cuda_array_interface_dtypes), ) @unittest.skipIf(not cupy, "Test requires CuPy") @jtu.run_on_devices("cuda") def testCuPyToJax(self, shape, dtype): rng = jtu.rand_default(self.rng()) x = rng(shape, dtype) y = cupy.asarray(x) z = jnp.array(y, copy=False) # this conversion uses dlpack protocol self.assertEqual(z.dtype, dtype) self.assertEqual(y.__cuda_array_interface__["data"][0], z.__cuda_array_interface__["data"][0]) self.assertAllClose(np.asarray(z), cupy.asnumpy(y)) @jtu.sample_product( shape=all_shapes, dtype=jtu.dtypes.supported(cuda_array_interface_dtypes), ) @jtu.run_on_devices("cuda") def testCaiToJax(self, shape, dtype): dtype = np.dtype(dtype) rng = jtu.rand_default(self.rng()) x = rng(shape, dtype) # using device with highest device_id for testing the correctness # of detecting the device id from a pointer value device = jax.devices('cuda')[-1] with jax.default_device(device): y = jnp.array(x, dtype=dtype) # TODO(parkers): Remove after setting 'stream' properly below. jax.block_until_ready(y) self.assertEqual(y.dtype, dtype) # Using a jax array CAI provider support to construct an object # that implements the CUDA Array Interface, versions 2 and 3. cai = y.__cuda_array_interface__ stream = tuple(y.devices())[0].get_stream_for_external_ready_events() class CAIWithoutStridesV2: __cuda_array_interface__ = cai.copy() __cuda_array_interface__["version"] = 2 # CAI version 2 may not define strides and does not define stream __cuda_array_interface__.pop("strides", None) __cuda_array_interface__.pop("stream", None) class CAIWithoutStrides: __cuda_array_interface__ = cai.copy() __cuda_array_interface__["version"] = 3 __cuda_array_interface__["strides"] = None __cuda_array_interface__["stream"] = None # default stream class CAIWithStrides: __cuda_array_interface__ = cai.copy() __cuda_array_interface__["version"] = 3 strides = (dtype.itemsize,) if shape else () for s in reversed(shape[1:]): strides = (strides[0] * s, *strides) __cuda_array_interface__['strides'] = strides __cuda_array_interface__["stream"] = stream for CAIObject in [CAIWithoutStridesV2, CAIWithoutStrides, CAIWithStrides]: z = jnp.array(CAIObject(), copy=False) self.assertEqual(y.__cuda_array_interface__["data"][0], z.__cuda_array_interface__["data"][0]) self.assertAllClose(x, z) if 0 in shape: # the device id detection from a zero pointer value is not # possible pass else: self.assertEqual(y.devices(), z.devices()) z = jnp.array(CAIObject(), copy=True) if 0 not in shape: self.assertNotEqual(y.__cuda_array_interface__["data"][0], z.__cuda_array_interface__["data"][0]) self.assertAllClose(x, z)
CudaArrayInterfaceTest
python
Textualize__textual
src/textual/color.py
{ "start": 1600, "end": 2140 }
class ____(NamedTuple): """A color in HSL (Hue, Saturation, Lightness) format.""" h: float """Hue in range 0 to 1.""" s: float """Saturation in range 0 to 1.""" l: float """Lightness in range 0 to 1.""" @property def css(self) -> str: """HSL in css format.""" h, s, l = self def as_str(number: float) -> str: """Format a float.""" return f"{number:.1f}".rstrip("0").rstrip(".") return f"hsl({as_str(h*360)},{as_str(s*100)}%,{as_str(l*100)}%)"
HSL
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 12079, "end": 12301 }
class ____(PrefectBaseModel): """Filter by `TaskRun.state_type`.""" any_: Optional[List[StateType]] = Field( default=None, description="A list of task run state types to include" )
TaskRunFilterStateType
python
huggingface__transformers
src/transformers/models/t5gemma/modeling_t5gemma.py
{ "start": 20316, "end": 23699 }
class ____(GradientCheckpointingLayer): """Decoder sub-layer: an extra cross-attention layer.""" def __init__(self, config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.config = config self.layer_idx = layer_idx self.attention_type = config.layer_types[layer_idx] self.self_attn = T5GemmaSelfAttention( config=config, layer_idx=layer_idx, ) self.pre_self_attn_layernorm = T5GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_self_attn_layernorm = T5GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.mlp = T5GemmaMLP(config) self.pre_feedforward_layernorm = T5GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_feedforward_layernorm = T5GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.dropout = nn.Dropout(config.dropout_rate) self.cross_attn = T5GemmaCrossAttention(config=config, layer_idx=layer_idx) self.pre_cross_attn_layernorm = T5GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_cross_attn_layernorm = T5GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) def forward( self, hidden_states: torch.Tensor, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[EncoderDecoderCache] = None, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> torch.FloatTensor: residual = hidden_states hidden_states = self.pre_self_attn_layernorm(hidden_states) hidden_states, _ = self.self_attn( hidden_states=hidden_states, position_embeddings=position_embeddings, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values.self_attention_cache if past_key_values is not None else None, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = self.post_self_attn_layernorm(hidden_states) hidden_states = residual + self.dropout(hidden_states) residual = hidden_states hidden_states = self.pre_cross_attn_layernorm(hidden_states) hidden_states, _ = self.cross_attn( hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=encoder_attention_mask, past_key_values=past_key_values, use_cache=use_cache, **kwargs, ) hidden_states = self.post_cross_attn_layernorm(hidden_states) hidden_states = residual + self.dropout(hidden_states) residual = hidden_states hidden_states = self.pre_feedforward_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = self.post_feedforward_layernorm(hidden_states) hidden_states = residual + self.dropout(hidden_states) return hidden_states
T5GemmaDecoderLayer
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/footsies/footsies_env.py
{ "start": 713, "end": 10329 }
class ____(MultiAgentEnv): metadata = {"render.modes": ["human"]} SPECIAL_CHARGE_FRAMES = 60 GUARD_BREAK_REWARD = 0.3 observation_space = spaces.Dict( { agent: spaces.Box( low=-np.inf, high=np.inf, shape=(constants.OBSERVATION_SPACE_SIZE,), ) for agent in ["p1", "p2"] } ) action_space = spaces.Dict( { agent: spaces.Discrete( len( [ constants.EnvActions.NONE, constants.EnvActions.BACK, constants.EnvActions.FORWARD, constants.EnvActions.ATTACK, constants.EnvActions.BACK_ATTACK, constants.EnvActions.FORWARD_ATTACK, # This is a special input that holds down # attack for 60 frames. It's just too long of a sequence # to easily learn by holding ATTACK for so long. constants.EnvActions.SPECIAL_CHARGE, ] ) ) for agent in ["p1", "p2"] } ) def __init__(self, config: EnvContext, port: int): super().__init__() if config is None: config = {} self.config = config self.port = port self.footsies_process_pid = ( None # Store PID of the running footsies process (we assume one per env) ) self.agents: list[AgentID] = ["p1", "p2"] self.possible_agents: list[AgentID] = self.agents.copy() self._agent_ids: set[AgentID] = set(self.agents) self.t: int = 0 self.max_t: int = config.get("max_t", 1000) self.frame_skip = config.get("frame_skip", 4) observation_delay = config.get("observation_delay", 16) assert ( observation_delay % self.frame_skip == 0 ), "observation_delay must be divisible by frame_skip" self.encoder = FootsiesEncoder( observation_delay=observation_delay // self.frame_skip ) # start the game server before initializing the communication between the # game server and the Python harness via gRPC self._prepare_and_start_game_server() self.game = FootsiesGame( host=config["host"], port=self.port, ) self.last_game_state = None self.special_charge_queue = { "p1": -1, "p2": -1, } @staticmethod def _convert_to_charge_action(action: int) -> int: if action == constants.EnvActions.BACK: return constants.EnvActions.BACK_ATTACK elif action == constants.EnvActions.FORWARD: return constants.EnvActions.FORWARD_ATTACK else: return constants.EnvActions.ATTACK def close(self): """Terminate Footsies game server process. Run to ensure no game servers are left running. """ timeout = 2 try: logger.info( f"RLlib {self.__class__.__name__}: Terminating Footsies " f"game server process with PID: {self.footsies_process_pid}..." ) p = psutil.Process(self.footsies_process_pid) p.terminate() p.wait(timeout=timeout) except psutil.NoSuchProcess: logger.info( f"RLlib {self.__class__.__name__}: Process with PID {self.footsies_process_pid} not found, " f"it might have been already terminated." ) except psutil.TimeoutExpired: logger.warning( f"RLlib {self.__class__.__name__}: Process with PID {self.footsies_process_pid} did not terminate " f"within {timeout} seconds. " f"Sending SIGKILL signal instead.", ) p.kill() p.wait(timeout=timeout) def get_infos(self): return {agent: {} for agent in self.agents} def get_obs(self, game_state): return self.encoder.encode(game_state) def reset( self, *, seed: Optional[int] = None, options: Optional[dict] = None, ) -> tuple[dict[AgentID, ObsType], dict[AgentID, Any]]: """Resets the environment to the starting state and returns the initial observations for all agents. :return: Tuple of observations and infos for each agent. :rtype: tuple[dict[AgentID, ObsType], dict[AgentID, Any]] """ self.t = 0 self.game.reset_game() self.game.start_game() self.encoder.reset() self.last_game_state = self.game.get_state() observations = self.get_obs(self.last_game_state) return observations, {agent: {} for agent in self.agents} def step( self, actions: dict[AgentID, ActionType] ) -> tuple[ dict[AgentID, ObsType], dict[AgentID, float], dict[AgentID, bool], dict[AgentID, bool], dict[AgentID, dict[str, Any]], ]: """Step the environment with the provided actions for all agents. :param actions: Dictionary mapping agent ids to their actions for this step. :type actions: dict[AgentID, ActionType] :return: Tuple of observations, rewards, terminates, truncateds and infos for all agents. :rtype: tuple[ dict[AgentID, ObsType], dict[AgentID, float], dict[AgentID, bool], dict[AgentID, bool], dict[AgentID, dict[str, Any]], ] """ self.t += 1 for agent_id in self.agents: empty_queue = self.special_charge_queue[agent_id] < 0 action_is_special_charge = ( actions[agent_id] == constants.EnvActions.SPECIAL_CHARGE ) # Refill the charge queue only if we're not already in a special charge. if action_is_special_charge and empty_queue: self.special_charge_queue[ agent_id ] = self._build_charged_special_queue() if self.special_charge_queue[agent_id] >= 0: self.special_charge_queue[agent_id] -= 1 actions[agent_id] = self._convert_to_charge_action(actions[agent_id]) p1_action = self.game.action_to_bits(actions["p1"], is_player_1=True) p2_action = self.game.action_to_bits(actions["p2"], is_player_1=False) game_state = self.game.step_n_frames( p1_action=p1_action, p2_action=p2_action, n_frames=self.frame_skip ) observations = self.get_obs(game_state) terminated = game_state.player1.is_dead or game_state.player2.is_dead # Zero-sum game: 1 if other player is dead, -1 if you're dead: rewards = { "p1": int(game_state.player2.is_dead) - int(game_state.player1.is_dead), "p2": int(game_state.player1.is_dead) - int(game_state.player2.is_dead), } if self.config.get("reward_guard_break", False): p1_prev_guard_health = self.last_game_state.player1.guard_health p2_prev_guard_health = self.last_game_state.player2.guard_health p1_guard_health = game_state.player1.guard_health p2_guard_health = game_state.player2.guard_health if p2_guard_health < p2_prev_guard_health: rewards["p1"] += self.GUARD_BREAK_REWARD rewards["p2"] -= self.GUARD_BREAK_REWARD if p1_guard_health < p1_prev_guard_health: rewards["p2"] += self.GUARD_BREAK_REWARD rewards["p1"] -= self.GUARD_BREAK_REWARD terminateds = { "p1": terminated, "p2": terminated, "__all__": terminated, } truncated = self.t >= self.max_t truncateds = { "p1": truncated, "p2": truncated, "__all__": truncated, } self.last_game_state = game_state return observations, rewards, terminateds, truncateds, self.get_infos() def _build_charged_special_queue(self): assert self.SPECIAL_CHARGE_FRAMES % self.frame_skip == 0 steps_to_apply_attack = int(self.SPECIAL_CHARGE_FRAMES // self.frame_skip) return steps_to_apply_attack def _prepare_and_start_game_server(self): fb = FootsiesBinary(config=self.config, port=self.port) self.footsies_process_pid = fb.start_game_server() def env_creator(env_config: EnvContext) -> FootsiesEnv: """Creates the Footsies environment Ensure that each game server runs on a unique port. Training and evaluation env runners have separate port ranges. Helper function to create the FootsiesEnv with a unique port based on the worker index and vector index. It's usually passed to the `register_env()`, like this: register_env(name="FootsiesEnv", env_creator=env_creator). """ if env_config.get("env-for-evaluation", False): port = ( env_config["eval_start_port"] - 1 # "-1" to start with eval_start_port as the first port (eval worker index starts at 1) + int(env_config.worker_index) * env_config.get("num_envs_per_worker", 1) + env_config.get("vector_index", 0) ) else: port = ( env_config["train_start_port"] + int(env_config.worker_index) * env_config.get("num_envs_per_worker", 1) + env_config.get("vector_index", 0) ) return FootsiesEnv(config=env_config, port=port)
FootsiesEnv
python
scrapy__scrapy
tests/test_command_fetch.py
{ "start": 177, "end": 1161 }
class ____: def test_output(self, mockserver: MockServer) -> None: _, out, _ = proc("fetch", mockserver.url("/text")) assert out.strip() == "Works" def test_redirect_default(self, mockserver: MockServer) -> None: _, out, _ = proc("fetch", mockserver.url("/redirect")) assert out.strip() == "Redirected here" def test_redirect_disabled(self, mockserver: MockServer) -> None: _, _, err = proc( "fetch", "--no-redirect", mockserver.url("/redirect-no-meta-refresh") ) err = err.strip() assert "downloader/response_status_count/302" in err assert "downloader/response_status_count/200" not in err def test_headers(self, mockserver: MockServer) -> None: _, out, _ = proc("fetch", mockserver.url("/text"), "--headers") out = out.replace("\r", "") # required on win32 assert "Server: TwistedWeb" in out assert "Content-Type: text/plain" in out
TestFetchCommand
python
sympy__sympy
sympy/core/multidimensional.py
{ "start": 1508, "end": 4233 }
class ____: """ Generalizes a function taking scalars to accept multidimensional arguments. Examples ======== >>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh')) >>> @vectorize(0) ... def vsin(x): ... return sin(x) >>> vsin([1, x, y]) [sin(1), sin(x), sin(y)] >>> @vectorize(0, 1) ... def vdiff(f, y): ... return diff(f, y) >>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z]) [[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]] """ def __init__(self, *mdargs): """ The given numbers and strings characterize the arguments that will be treated as data structures, where the decorated function will be applied to every single element. If no argument is given, everything is treated multidimensional. """ for a in mdargs: if not isinstance(a, (int, str)): raise TypeError("a is of invalid type") self.mdargs = mdargs def __call__(self, f): """ Returns a wrapper for the one-dimensional function that can handle multidimensional arguments. """ @wraps(f) def wrapper(*args, **kwargs): # Get arguments that should be treated multidimensional if self.mdargs: mdargs = self.mdargs else: mdargs = range(len(args)) + kwargs.keys() arglength = len(args) for n in mdargs: if isinstance(n, int): if n >= arglength: continue entry = args[n] is_arg = True elif isinstance(n, str): try: entry = kwargs[n] except KeyError: continue is_arg = False if hasattr(entry, "__iter__"): # Create now a copy of the given array and manipulate then # the entries directly. if is_arg: args = list(args) args[n] = structure_copy(entry) else: kwargs[n] = structure_copy(entry) result = apply_on_element(wrapper, args, kwargs, n) return result return f(*args, **kwargs) return wrapper
vectorize
python
RaRe-Technologies__gensim
gensim/test/test_corpora.py
{ "start": 18253, "end": 20025 }
class ____(TestLowCorpus): TEST_CORPUS = [[(1, 1)], [], [(0, 2), (2, 1)], []] CORPUS_LINE = '#3 lang mom wash window window was washed' def setUp(self): self.corpus_class = malletcorpus.MalletCorpus self.file_extension = '.mallet' def test_load_with_metadata(self): fname = datapath('testcorpus.' + self.file_extension.lstrip('.')) corpus = self.corpus_class(fname) corpus.metadata = True self.assertEqual(len(corpus), 9) docs = list(corpus) self.assertEqual(len(docs), 9) for i, docmeta in enumerate(docs): doc, metadata = docmeta self.assertEqual(metadata[0], str(i + 1)) self.assertEqual(metadata[1], 'en') def test_line2doc(self): # case with metadata=False (by default) super(TestMalletCorpus, self).test_line2doc() # case with metadata=True fname = datapath('testcorpus.' + self.file_extension.lstrip('.')) id2word = {1: 'mom', 2: 'window'} corpus = self.corpus_class(fname, id2word=id2word, metadata=True) # should return all words in doc corpus.use_wordids = False doc, (docid, doclang) = corpus.line2doc(self.CORPUS_LINE) self.assertEqual(docid, '#3') self.assertEqual(doclang, 'lang') self.assertEqual( sorted(doc), [('mom', 1), ('was', 1), ('wash', 1), ('washed', 1), ('window', 2)]) # should return words in word2id corpus.use_wordids = True doc, (docid, doclang) = corpus.line2doc(self.CORPUS_LINE) self.assertEqual(docid, '#3') self.assertEqual(doclang, 'lang') self.assertEqual( sorted(doc), [(1, 1), (2, 2)])
TestMalletCorpus
python
PrefectHQ__prefect
tests/server/orchestration/api/test_task_runs.py
{ "start": 25046, "end": 27140 }
class ____: async def test_delete_task_runs(self, task_run, hosted_api_client, session): # delete the task run response = await hosted_api_client.delete(f"/task_runs/{task_run.id}") assert response.status_code == status.HTTP_204_NO_CONTENT # make sure it's deleted task_run_id = task_run.id session.expire_all() run = await models.task_runs.read_task_run( session=session, task_run_id=task_run_id ) assert run is None response = await hosted_api_client.get(f"/task_runs/{task_run_id}") assert response.status_code == status.HTTP_404_NOT_FOUND async def test_delete_task_run_returns_404_if_does_not_exist( self, hosted_api_client ): response = await hosted_api_client.delete(f"/task_runs/{uuid4()}") assert response.status_code == status.HTTP_404_NOT_FOUND async def test_delete_task_run_deletes_logs( self, task_run, logs, hosted_api_client, session ): # make sure we have task run logs task_run_logs = [log for log in logs if log.task_run_id is not None] assert len(task_run_logs) > 0 # delete the task run response = await hosted_api_client.delete(f"/task_runs/{task_run.id}") assert response.status_code == status.HTTP_204_NO_CONTENT, response.text async def read_logs(): # because deletion happens in the background, # loop until we get what we expect or we time out while True: # make sure we no longer have task run logs post_delete_logs = await models.logs.read_logs( session=session, log_filter=None, ) # we should get back our non task run logs if len(post_delete_logs) == len(logs) - len(task_run_logs): return post_delete_logs asyncio.sleep(1) logs = await asyncio.wait_for(read_logs(), 10) assert all([log.task_run_id is None for log in logs])
TestDeleteTaskRuns
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 889, "end": 1013 }
class ____(serializers.ModelSerializer): class Meta: model = BasicModel fields = '__all__'
BasicSerializer
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/declarative_automation/sensors/custom_condition.py
{ "start": 91, "end": 610 }
class ____(dg.AutomationCondition): def evaluate(self, context: dg.AutomationContext) -> dg.AutomationResult: if is_company_holiday(context.evaluation_time): true_subset = context.candidate_subset else: true_subset = context.get_empty_subset() return dg.AutomationResult(true_subset, context=context) # end_custom_condition # start_conditional import dagster as dg condition = dg.AutomationCondition.eager() & ~IsCompanyHoliday() # end_conditional
IsCompanyHoliday
python
django__django
tests/queries/models.py
{ "start": 4571, "end": 4744 }
class ____(models.Model): z = models.ForeignKey("self", models.CASCADE) class Meta: ordering = ["z"] # A model and custom default manager combination.
LoopZ
python
pypa__warehouse
tests/common/db/accounts.py
{ "start": 2858, "end": 3276 }
class ____(WarehouseFactory): class Meta: model = Email user = factory.SubFactory(UserFactory) # TODO: Replace when factory_boy supports `unique`. # See https://github.com/FactoryBoy/factory_boy/pull/997 email = factory.Sequence(lambda _: fake.unique.safe_email()) verified = True primary = True public = False unverify_reason = None transient_bounces = 0
EmailFactory
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 10927, "end": 11298 }
class ____(TestBase): def testFieldDictFieldExclude(self): reversion.register(TestModel, exclude=("name",)) with reversion.create_revision(): obj = TestModel.objects.create() self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, { "id": obj.pk, "related": [], })
FieldDictExcludeTest
python
walkccc__LeetCode
solutions/1152. Analyze User Website Visit Pattern/1152.py
{ "start": 0, "end": 675 }
class ____: def mostVisitedPattern( self, username: list[str], timestamp: list[int], website: list[str], ) -> list[str]: userToSites = collections.defaultdict(list) # Sort websites of each user by timestamp. for user, _, site in sorted( zip(username, timestamp, website), key=lambda x: x[1]): userToSites[user].append(site) # For each of three websites, count its frequency. patternCount = collections.Counter() for user, sites in userToSites.items(): patternCount.update(Counter(set(itertools.combinations(sites, 3)))) return max(sorted(patternCount), key=patternCount.get)
Solution
python
PyCQA__pyflakes
pyflakes/test/test_other.py
{ "start": 43753, "end": 48916 }
class ____(TestCase): def test_f_string_without_placeholders(self): self.flakes("f'foo'", m.FStringMissingPlaceholders) self.flakes(''' f"""foo bar """ ''', m.FStringMissingPlaceholders) self.flakes(''' print( f'foo' f'bar' ) ''', m.FStringMissingPlaceholders) # this is an "escaped placeholder" but not a placeholder self.flakes("f'{{}}'", m.FStringMissingPlaceholders) # ok: f-string with placeholders self.flakes(''' x = 5 print(f'{x}') ''') # ok: f-string with format specifiers self.flakes(''' x = 'a' * 90 print(f'{x:.8}') ''') # ok: f-string with multiple format specifiers self.flakes(''' x = y = 5 print(f'{x:>2} {y:>2}') ''') @skipIf(version_info < (3, 14), 'new in Python 3.14') def test_t_string_missing_placeholders(self): self.flakes("t'foo'", m.TStringMissingPlaceholders) # make sure this does not trigger the f-string placeholder error self.flakes(''' x = y = 5 tmpl = t'{x:0{y}}' ''') def test_invalid_dot_format_calls(self): self.flakes(''' '{'.format(1) ''', m.StringDotFormatInvalidFormat) self.flakes(''' '{} {1}'.format(1, 2) ''', m.StringDotFormatMixingAutomatic) self.flakes(''' '{0} {}'.format(1, 2) ''', m.StringDotFormatMixingAutomatic) self.flakes(''' '{}'.format(1, 2) ''', m.StringDotFormatExtraPositionalArguments) self.flakes(''' '{}'.format(1, bar=2) ''', m.StringDotFormatExtraNamedArguments) self.flakes(''' '{} {}'.format(1) ''', m.StringDotFormatMissingArgument) self.flakes(''' '{2}'.format() ''', m.StringDotFormatMissingArgument) self.flakes(''' '{bar}'.format() ''', m.StringDotFormatMissingArgument) # too much string recursion (placeholder-in-placeholder) self.flakes(''' '{:{:{}}}'.format(1, 2, 3) ''', m.StringDotFormatInvalidFormat) # ok: dotted / bracketed names need to handle the param differently self.flakes("'{.__class__}'.format('')") self.flakes("'{foo[bar]}'.format(foo={'bar': 'barv'})") # ok: placeholder-placeholders self.flakes(''' print('{:{}} {}'.format(1, 15, 2)) ''') # ok: not a placeholder-placeholder self.flakes(''' print('{:2}'.format(1)) ''') # ok: not mixed automatic self.flakes(''' '{foo}-{}'.format(1, foo=2) ''') # ok: we can't determine statically the format args self.flakes(''' a = () "{}".format(*a) ''') self.flakes(''' k = {} "{foo}".format(**k) ''') def test_invalid_percent_format_calls(self): self.flakes(''' '%(foo)' % {'foo': 'bar'} ''', m.PercentFormatInvalidFormat) self.flakes(''' '%s %(foo)s' % {'foo': 'bar'} ''', m.PercentFormatMixedPositionalAndNamed) self.flakes(''' '%(foo)s %s' % {'foo': 'bar'} ''', m.PercentFormatMixedPositionalAndNamed) self.flakes(''' '%j' % (1,) ''', m.PercentFormatUnsupportedFormatCharacter) self.flakes(''' '%s %s' % (1,) ''', m.PercentFormatPositionalCountMismatch) self.flakes(''' '%s %s' % (1, 2, 3) ''', m.PercentFormatPositionalCountMismatch) self.flakes(''' '%(bar)s' % {} ''', m.PercentFormatMissingArgument,) self.flakes(''' '%(bar)s' % {'bar': 1, 'baz': 2} ''', m.PercentFormatExtraNamedArguments) self.flakes(''' '%(bar)s' % (1, 2, 3) ''', m.PercentFormatExpectedMapping) self.flakes(''' '%s %s' % {'k': 'v'} ''', m.PercentFormatExpectedSequence) self.flakes(''' '%(bar)*s' % {'bar': 'baz'} ''', m.PercentFormatStarRequiresSequence) # ok: single %s with mapping self.flakes(''' '%s' % {'foo': 'bar', 'baz': 'womp'} ''') # ok: does not cause a MemoryError (the strings aren't evaluated) self.flakes(''' "%1000000000000f" % 1 ''') # ok: %% should not count towards placeholder count self.flakes(''' '%% %s %% %s' % (1, 2) ''') # ok: * consumes one positional argument self.flakes(''' '%.*f' % (2, 1.1234) '%*.*f' % (5, 2, 3.1234) ''') def test_ok_percent_format_cannot_determine_element_count(self): self.flakes(''' a = [] '%s %s' % [*a] '%s %s' % (*a,) ''') self.flakes(''' k = {} '%(k)s' % {**k} ''')
TestStringFormatting
python
apache__airflow
dev/breeze/src/airflow_breeze/prepare_providers/provider_documentation.py
{ "start": 5502, "end": 5633 }
class ____(Exception): """Raised when error occurred when preparing packages changes."""
PrepareReleaseDocsErrorOccurredException
python
pydata__xarray
xarray/namedarray/utils.py
{ "start": 9796, "end": 10485 }
class ____: """Object that prints as the given value, for use with sentinel values.""" __slots__ = ("_value",) _value: str def __init__(self, value: str): self._value = value def __repr__(self) -> str: return self._value def __eq__(self, other: ReprObject | Any) -> bool: # TODO: What type can other be? ArrayLike? return self._value == other._value if isinstance(other, ReprObject) else False def __hash__(self) -> int: return hash((type(self), self._value)) def __dask_tokenize__(self) -> object: from dask.base import normalize_token return normalize_token((type(self), self._value))
ReprObject
python
openai__openai-python
src/openai/types/shared_params/function_definition.py
{ "start": 290, "end": 1510 }
class ____(TypedDict, total=False): name: Required[str] """The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. """ description: str """ A description of what the function does, used by the model to choose when and how to call the function. """ parameters: FunctionParameters """The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. Omitting `parameters` defines a function with an empty parameter list. """ strict: Optional[bool] """Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](https://platform.openai.com/docs/guides/function-calling). """
FunctionDefinition
python
getsentry__sentry
src/sentry/lang/dart/apps.py
{ "start": 36, "end": 240 }
class ____(AppConfig): name = "sentry.lang.dart" def ready(self) -> None: from sentry.plugins.base import register from .plugin import DartPlugin register(DartPlugin)
Config
python
pytorch__pytorch
test/dynamo/test_guard_manager.py
{ "start": 33839, "end": 34175 }
class ____(torch._dynamo.test_case.TestCase): def setUp(self): self._prev = torch._dynamo.config.use_recursive_dict_tags_for_guards torch._dynamo.config.use_recursive_dict_tags_for_guards = True def tearDown(self): torch._dynamo.config.use_recursive_dict_tags_for_guards = self._prev
RecursiveDictTagTests
python
numba__numba
numba/tests/test_function_type.py
{ "start": 34568, "end": 35378 }
class ____(MemoryLeakMixin, TestCase): def test_base(self): # The test is adapted from https://github.com/numba/numba/issues/9071 nb_array = typeof(np.ones(2)) callee_int_type = types.FunctionType(int64(int64)) sig_int = int64(callee_int_type, int64) callee_array_type = types.FunctionType(float64(nb_array)) sig_array = float64(callee_array_type, nb_array) @njit([sig_int, sig_array]) def caller(callee, a): return callee(a) @njit def callee_int(b): return b @njit def callee_array(c): return c.sum() b = 1 c = np.ones(2) self.assertEqual(caller(callee_int, b), b) self.assertEqual(caller(callee_array, c), c.sum())
TestMultiFunctionType
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 554310, "end": 554651 }
class ____(sgqlc.types.Type): """Autogenerated return type of DeleteEnvironment""" __schema__ = github_schema __field_names__ = ("client_mutation_id",) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
DeleteEnvironmentPayload
python
pytorch__pytorch
torch/_inductor/cpu_vec_isa.py
{ "start": 6024, "end": 6664 }
class ____(VecISA): # this function can be repurposed for SVE with variable vec length _bit_width = 256 _macro = [ "CPU_CAPABILITY_SVE", "CPU_CAPABILITY_SVE256", "AT_BUILD_ARM_VEC256_WITH_SLEEF", "__ARM_FEATURE_BF16", ] _arch_flags = "-march=armv8-a+sve+bf16 -msve-vector-bits=256" _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16} def __str__(self) -> str: if config.is_fbcode(): return "neon" return "asimd" __hash__: Callable[[VecISA], Any] = VecISA.__hash__ # type: ignore[assignment] @dataclasses.dataclass
VecSVE256
python
plotly__plotly.py
plotly/graph_objs/treemap/pathbar/_textfont.py
{ "start": 233, "end": 17161 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "treemap.pathbar" _path_str = "treemap.pathbar.textfont" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", "sizesrc", "style", "stylesrc", "textcase", "textcasesrc", "variant", "variantsrc", "weight", "weightsrc", } @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def colorsrc(self): """ Sets the source reference on Chart Studio Cloud for `color`. The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["colorsrc"] @colorsrc.setter def colorsrc(self, val): self["colorsrc"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def familysrc(self): """ Sets the source reference on Chart Studio Cloud for `family`. The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["familysrc"] @familysrc.setter def familysrc(self, val): self["familysrc"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def linepositionsrc(self): """ Sets the source reference on Chart Studio Cloud for `lineposition`. The 'linepositionsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["linepositionsrc"] @linepositionsrc.setter def linepositionsrc(self, val): self["linepositionsrc"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def shadowsrc(self): """ Sets the source reference on Chart Studio Cloud for `shadow`. The 'shadowsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["shadowsrc"] @shadowsrc.setter def shadowsrc(self, val): self["shadowsrc"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def sizesrc(self): """ Sets the source reference on Chart Studio Cloud for `size`. The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["sizesrc"] @sizesrc.setter def sizesrc(self, val): self["sizesrc"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def stylesrc(self): """ Sets the source reference on Chart Studio Cloud for `style`. The 'stylesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["stylesrc"] @stylesrc.setter def stylesrc(self, val): self["stylesrc"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def textcasesrc(self): """ Sets the source reference on Chart Studio Cloud for `textcase`. The 'textcasesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textcasesrc"] @textcasesrc.setter def textcasesrc(self, val): self["textcasesrc"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def variantsrc(self): """ Sets the source reference on Chart Studio Cloud for `variant`. The 'variantsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["variantsrc"] @variantsrc.setter def variantsrc(self, val): self["variantsrc"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|numpy.ndarray """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def weightsrc(self): """ Sets the source reference on Chart Studio Cloud for `weight`. The 'weightsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["weightsrc"] @weightsrc.setter def weightsrc(self, val): self["weightsrc"] = val @property def _prop_descriptions(self): return """\ color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. """ def __init__( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, lineposition=None, linepositionsrc=None, shadow=None, shadowsrc=None, size=None, sizesrc=None, style=None, stylesrc=None, textcase=None, textcasesrc=None, variant=None, variantsrc=None, weight=None, weightsrc=None, **kwargs, ): """ Construct a new Textfont object Sets the font used inside `pathbar`. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.treemap.pathbar.Textfont` color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. Returns ------- Textfont """ super().__init__("textfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.treemap.pathbar.Textfont constructor must be a dict or an instance of :class:`plotly.graph_objs.treemap.pathbar.Textfont`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("colorsrc", arg, colorsrc) self._set_property("family", arg, family) self._set_property("familysrc", arg, familysrc) self._set_property("lineposition", arg, lineposition) self._set_property("linepositionsrc", arg, linepositionsrc) self._set_property("shadow", arg, shadow) self._set_property("shadowsrc", arg, shadowsrc) self._set_property("size", arg, size) self._set_property("sizesrc", arg, sizesrc) self._set_property("style", arg, style) self._set_property("stylesrc", arg, stylesrc) self._set_property("textcase", arg, textcase) self._set_property("textcasesrc", arg, textcasesrc) self._set_property("variant", arg, variant) self._set_property("variantsrc", arg, variantsrc) self._set_property("weight", arg, weight) self._set_property("weightsrc", arg, weightsrc) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Textfont
python
apache__airflow
airflow-core/src/airflow/metrics/base_stats_logger.py
{ "start": 2175, "end": 3098 }
class ____: """If no StatsLogger is configured, NoStatsLogger is used as a fallback.""" @classmethod def incr(cls, stat: str, count: int = 1, rate: int = 1, *, tags: dict[str, str] | None = None) -> None: """Increment stat.""" @classmethod def decr(cls, stat: str, count: int = 1, rate: int = 1, *, tags: dict[str, str] | None = None) -> None: """Decrement stat.""" @classmethod def gauge( cls, stat: str, value: int, rate: int = 1, delta: bool = False, *, tags: dict[str, str] | None = None, ) -> None: """Gauge stat.""" @classmethod def timing(cls, stat: str, dt: DeltaType, *, tags: dict[str, str] | None = None) -> None: """Stats timing.""" @classmethod def timer(cls, *args, **kwargs) -> Timer: """Timer metric that can be cancelled.""" return Timer()
NoStatsLogger
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/index1.py
{ "start": 1741, "end": 1898 }
class ____: __slots__ = ["x"] def func3(g: ClassG): reveal_type(g.x, expected_text="Unbound") reveal_type(g.x[0], expected_text="Unknown")
ClassG
python
RaRe-Technologies__gensim
gensim/test/test_similarities.py
{ "start": 32704, "end": 34883 }
class ____(unittest.TestCase): def setUp(self): try: import nmslib # noqa:F401 except ImportError as e: raise unittest.SkipTest("NMSLIB library is not available: %s" % e) from gensim.similarities.nmslib import NmslibIndexer self.model = doc2vec.Doc2Vec(SENTENCES, min_count=1) self.index = NmslibIndexer(self.model) self.vector = self.model.dv.get_normed_vectors()[0] def test_document_is_similar_to_itself(self): approx_neighbors = self.index.most_similar(self.vector, 1) doc, similarity = approx_neighbors[0] self.assertEqual(doc, 0) self.assertAlmostEqual(similarity, 1.0, places=2) def test_approx_neighbors_match_exact(self): approx_neighbors = self.model.dv.most_similar([self.vector], topn=5, indexer=self.index) exact_neighbors = self.model.dv.most_similar([self.vector], topn=5) approx_tags = [tag for tag, similarity in approx_neighbors] exact_tags = [tag for tag, similarity in exact_neighbors] self.assertEqual(approx_tags, exact_tags) def test_save(self): fname = get_tmpfile('gensim_similarities.tst.pkl') self.index.save(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(fname + '.d')) def test_load_not_exist(self): from gensim.similarities.nmslib import NmslibIndexer self.assertRaises(IOError, NmslibIndexer.load, fname='test-index') def test_save_load(self): from gensim.similarities.nmslib import NmslibIndexer fname = get_tmpfile('gensim_similarities.tst.pkl') self.index.save(fname) self.index2 = NmslibIndexer.load(fname) self.index2.model = self.model self.assertEqual(self.index.labels, self.index2.labels) self.assertEqual(self.index.index_params, self.index2.index_params) self.assertEqual(self.index.query_time_params, self.index2.query_time_params) @pytest.mark.skipif( sys.version_info[:2] != (3, 9) or int(numpy.__version__.split('.')[0]) != 2, reason="Skip if not on Python 3.9 or numpy 2.x" )
TestDoc2VecNmslibIndexer
python
RaRe-Technologies__gensim
gensim/test/test_hdpmodel.py
{ "start": 618, "end": 1703 }
class ____(unittest.TestCase, basetmtests.TestBaseTopicModel): def setUp(self): self.corpus = mmcorpus.MmCorpus(datapath('testcorpus.mm')) self.class_ = hdpmodel.HdpModel self.model = self.class_(corpus, id2word=dictionary, random_state=np.random.seed(0)) def test_topic_values(self): """ Check show topics method """ results = self.model.show_topics()[0] expected_prob, expected_word = '0.264', 'trees ' prob, word = results[1].split('+')[0].split('*') self.assertEqual(results[0], 0) self.assertEqual(prob, expected_prob) self.assertEqual(word, expected_word) return def test_ldamodel(self): """ Create ldamodel object, and check if the corresponding alphas are equal. """ ldam = self.model.suggested_lda_model() self.assertEqual(ldam.alpha[0], self.model.lda_alpha[0]) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG) unittest.main()
TestHdpModel
python
ansible__ansible
test/integration/targets/ignore_unreachable/fake_connectors/bad_put_file.py
{ "start": 210, "end": 435 }
class ____(ansible_local.Connection): def put_file(self, in_path, out_path): display.debug('Intercepted call to send data') raise AnsibleConnectionFailure('BADLOCAL Error: this is supposed to fail')
Connection
python
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/schemas/role_and_permission_schema.py
{ "start": 1907, "end": 2144 }
class ____(SQLAlchemySchema): """Role item schema.""" class Meta: """Meta.""" model = Role name = auto_field() permissions = fields.List(fields.Nested(ActionResourceSchema), data_key="actions")
RoleSchema
python
pypa__pipenv
pipenv/vendor/tomlkit/source.py
{ "start": 1779, "end": 4877 }
class ____(str): EOF = TOMLChar("\0") def __init__(self, _: str) -> None: super().__init__() # Collection of TOMLChars self._chars = iter([(i, TOMLChar(c)) for i, c in enumerate(self)]) self._idx = 0 self._marker = 0 self._current = TOMLChar("") self._state = _StateHandler(self) self.inc() def reset(self): # initialize both idx and current self.inc() # reset marker self.mark() @property def state(self) -> _StateHandler: return self._state @property def idx(self) -> int: return self._idx @property def current(self) -> TOMLChar: return self._current @property def marker(self) -> int: return self._marker def extract(self) -> str: """ Extracts the value between marker and index """ return self[self._marker : self._idx] def inc(self, exception: type[ParseError] | None = None) -> bool: """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) return True except StopIteration: self._idx = len(self) self._current = self.EOF if exception: raise self.parse_error(exception) from None return False def inc_n(self, n: int, exception: type[ParseError] | None = None) -> bool: """ Increments the parser by n characters if the end of the input has not been reached. """ return all(self.inc(exception=exception) for _ in range(n)) def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ while self.current in chars and max != 0: min -= 1 max -= 1 if not self.inc(): break # failed to consume minimum number of characters if min > 0: raise self.parse_error(UnexpectedCharError, self.current) def end(self) -> bool: """ Returns True if the parser has reached the end of the input. """ return self._current is self.EOF def mark(self) -> None: """ Sets the marker to the index's current position """ self._marker = self._idx def parse_error( self, exception: type[ParseError] = ParseError, *args: Any, **kwargs: Any, ) -> ParseError: """ Creates a generic "parse error" at the current position. """ line, col = self._to_linecol() return exception(line, col, *args, **kwargs) def _to_linecol(self) -> tuple[int, int]: cur = 0 for i, line in enumerate(self.splitlines()): if cur + len(line) + 1 > self.idx: return (i + 1, self.idx - cur) cur += len(line) + 1 return len(self.splitlines()), 0
Source
python
allegroai__clearml
clearml/backend_api/services/v2_23/auth.py
{ "start": 5623, "end": 7022 }
class ____(Request): """ Creates a new set of credentials for the authenticated user. New key/secret is returned. Note: Secret will never be returned in any other API call. If a secret is lost or compromised, the key should be revoked and a new set of credentials can be created. :param label: Optional credentials label :type label: str """ _service = "auth" _action = "create_credentials" _version = "2.23" _schema = { "additionalProperties": False, "definitions": {}, "properties": { "label": { "description": "Optional credentials label", "type": ["string", "null"], } }, "type": "object", } def __init__(self, label: Optional[str] = None, **kwargs: Any) -> None: super(CreateCredentialsRequest, self).__init__(**kwargs) self.label = label @schema_property("label") def label(self) -> Optional[str]: return self._property_label @label.setter def label(self, value: Optional[str]) -> None: if value is None: self._property_label = None return self.assert_isinstance(value, "label", six.string_types) self._property_label = value
CreateCredentialsRequest
python
tensorflow__tensorflow
tensorflow/python/ops/gradients_test.py
{ "start": 63708, "end": 66079 }
class ____(test_util.TensorFlowTestCase): @test_util.run_v1_only("b/120545219") def test_gradients_v1(self): x = variable_scope.get_variable( name="x", shape=(), initializer=init_ops.constant_initializer(1.0), use_resource=True) z = variable_scope.get_variable( name="z", shape=(), initializer=init_ops.constant_initializer(3.0), use_resource=True) # Verify that assign op is not differentiable y = state_ops.assign(x, z**2) grads = gradients.gradients(y, z) self.assertIsNone(grads[0]) # Verify that when the (non differentiable) assign op is wrapped with # grad_pass_through, gradients are correctly forwarded to the inputs. # Form an input as quadratic function of variable z and check that the # gradient of output wrt to z is correct. y = custom_gradient.grad_pass_through( lambda v: state_ops.assign(x, v))(z**2) grads = gradients.gradients(y, z) with self.cached_session(): self.evaluate(variables.global_variables_initializer()) self.assertAllClose(grads[0], 6.0) # Verify that variables involved in the wrapped op do not receive gradients. y = custom_gradient.grad_pass_through(lambda v: x * v)(z) grads = gradients.gradients(y, x) self.assertIsNone(grads[0]) @test_util.run_v2_only def test_gradients_v2(self): x = variables.Variable(1.0, name="x") z = variables.Variable(3.0, name="z") # Verify that assign op is not differentiable with backprop.GradientTape() as tape: y = x.assign(z**2) grads = tape.gradient(y, z) self.assertIsNone(grads) # Verify that when the (non differentiable) assign op is wrapped with # grad_pass_through, gradients are correctly forwarded to the inputs. # Form an input as quadratic function of variable z and check that the # gradient of output wrt to z is correct. with backprop.GradientTape() as tape: y = custom_gradient.grad_pass_through(x.assign)(z**2) grads = tape.gradient(y, z) self.assertAllClose(grads, 6.0) # Verify that variables involved in the wrapped op do not receive gradients. with backprop.GradientTape() as tape: y = custom_gradient.grad_pass_through(lambda v: x * v)(z) grads = tape.gradient(y, x) self.assertIsNone(grads) if __name__ == "__main__": googletest.main()
GradPassThroughTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py
{ "start": 42375, "end": 43150 }
class ____(BulkSalesforceStream, IncrementalRestSalesforceStream): state_checkpoint_interval = None def request_params( self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> MutableMapping[str, Any]: start_date = stream_slice["start_date"] end_date = stream_slice["end_date"] select_fields = self.get_query_select_fields() table_name = self.name where_conditions = [f"{self.cursor_field} >= {start_date}", f"{self.cursor_field} < {end_date}"] where_clause = f"WHERE {' AND '.join(where_conditions)}" query = f"SELECT {select_fields} FROM {table_name} {where_clause}" return {"q": query}
BulkIncrementalSalesforceStream
python
mlflow__mlflow
mlflow/genai/evaluation/entities.py
{ "start": 5048, "end": 6221 }
class ____: """Holds the result of the evaluation for an eval item.""" eval_item: EvalItem """A collection of assessments from scorers.""" assessments: list[Feedback] = field(default_factory=list) """Error message encountered in processing the eval item.""" eval_error: str | None = None def to_pd_series(self) -> pd.Series: """Converts the EvalResult to a flattened pd.Series.""" inputs = self.eval_item.to_dict() assessments = self.get_assessments_dict() # Merge dictionaries and convert to pd.Series return pd.Series(inputs | assessments) def get_assessments_dict(self) -> dict[str, Any]: result = {} for assessment in self.assessments: if not isinstance(assessment, Feedback): continue result |= { f"{assessment.name}/value": assessment.value, f"{assessment.name}/rationale": assessment.rationale, f"{assessment.name}/error_message": assessment.error_message, f"{assessment.name}/error_code": assessment.error_code, } return result @dataclass
EvalResult
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py
{ "start": 1295, "end": 1516 }
class ____(BaseSettings): mutable_default: list[int] = [] immutable_annotation: Sequence[int] = [] without_annotation = [] class_variable: ClassVar[list[int]] = [] final_variable: Final[list[int]] = []
F
python
ansible__ansible
lib/ansible/modules/group.py
{ "start": 14107, "end": 16460 }
class ____(Group): """ This is a Mac macOS Darwin Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() group manipulation are done using dseditgroup(1). """ platform = 'Darwin' distribution = None def group_add(self, **kwargs): cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'create'] if self.gid is not None: cmd += ['-i', str(self.gid)] elif 'system' in kwargs and kwargs['system'] is True: gid = self.get_lowest_available_system_gid() if gid is not False: self.gid = str(gid) cmd += ['-i', str(self.gid)] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) def group_del(self): cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'delete'] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) def group_mod(self, gid=None): info = self.group_info() if self.gid is not None and int(self.gid) != info[2]: cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'edit'] if gid is not None: cmd += ['-i', str(gid)] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) return (None, '', '') def get_lowest_available_system_gid(self): # check for lowest available system gid (< 500) try: cmd = [self.module.get_bin_path('dscl', True)] cmd += ['/Local/Default', '-list', '/Groups', 'PrimaryGroupID'] (rc, out, err) = self.execute_command(cmd) lines = out.splitlines() highest = 0 for group_info in lines: parts = group_info.split(' ') if len(parts) > 1: gid = int(parts[-1]) if gid > highest and gid < 500: highest = gid if highest == 0 or highest == 499: return False return (highest + 1) except Exception: return False
DarwinGroup
python
ray-project__ray
python/ray/train/v2/_internal/exceptions.py
{ "start": 3773, "end": 3935 }
class ____(RayTrainError): """Exception raised when an internal Ray Train collective operation of the worker group times out. """
CollectiveTimeoutError
python
kamyu104__LeetCode-Solutions
Python/meeting-scheduler.py
{ "start": 55, "end": 713 }
class ____(object): def minAvailableDuration(self, slots1, slots2, duration): """ :type slots1: List[List[int]] :type slots2: List[List[int]] :type duration: int :rtype: List[int] """ min_heap = list(filter(lambda slot: slot[1] - slot[0] >= duration, slots1 + slots2)) heapq.heapify(min_heap) # Time: O(n) while len(min_heap) > 1: left = heapq.heappop(min_heap) # Time: O(logn) right = min_heap[0] if left[1]-right[0] >= duration: return [right[0], right[0]+duration] return [] # Time: O(nlogn) # Space: O(n)
Solution
python
facebook__pyre-check
client/command_arguments.py
{ "start": 1873, "end": 3637 }
class ____: local_configuration: Optional[str] = None version: VersionKind = VersionKind.NONE debug: bool = False sequential: bool = False strict: bool = False show_error_traces: bool = False output: str = TEXT enable_profiling: bool = False enable_memory_profiling: bool = False noninteractive: bool = False logging_sections: Optional[str] = None log_identifier: Optional[str] = None logger: Optional[str] = None no_logger: bool = False targets: List[str] = field(default_factory=list) source_directories: List[str] = field(default_factory=list) only_check_paths: List[str] = field(default_factory=list) buck_mode: Optional[str] = None no_saved_state: bool = False search_path: List[str] = field(default_factory=list) optional_search_path: List[str] = field(default_factory=list) binary: Optional[str] = None exclude: List[str] = field(default_factory=list) typeshed: Optional[str] = None save_initial_state_to: Optional[str] = None load_initial_state_from: Optional[str] = None changed_files_path: Optional[str] = None dot_pyre_directory: Optional[Path] = None isolation_prefix: Optional[str] = None python_version: Optional[str] = None system_platform: Optional[str] = None shared_memory_heap_size: Optional[int] = None shared_memory_dependency_table_power: Optional[int] = None shared_memory_hash_table_power: Optional[int] = None number_of_workers: Optional[int] = None max_number_of_workers: Optional[int] = None enable_unawaited_awaitable_analysis: Optional[bool] = None include_suppressed_errors: Optional[bool] = None only_privacy_errors: Optional[bool] = None @dataclass(frozen=True)
CommandArguments
python
walkccc__LeetCode
solutions/253. Meeting Rooms II/253-2.py
{ "start": 0, "end": 388 }
class ____: def minMeetingRooms(self, intervals: list[list[int]]) -> int: n = len(intervals) ans = 0 starts = [] ends = [] for start, end in intervals: starts.append(start) ends.append(end) starts.sort() ends.sort() j = 0 for i in range(n): if starts[i] < ends[j]: ans += 1 else: j += 1 return ans
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 902153, "end": 921373 }
class ____(PositionDef): r""" PositionFieldDef schema wrapper. Parameters ---------- shorthand : str, dict, Sequence[str], :class:`RepeatRef` shorthand for field, aggregate, and type aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb'] Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, ``"min"``, ``"max"``, ``"count"``). **Default value:** ``undefined`` (None) **See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__ documentation. axis : dict, :class:`Axis`, None An object defining properties of axis's gridlines, ticks and labels. If ``null``, the axis for the encoding channel will be removed. **Default value:** If undefined, default `axis properties <https://vega.github.io/vega-lite/docs/axis.html>`__ are applied. **See also:** `axis <https://vega.github.io/vega-lite/docs/axis.html>`__ documentation. bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to ``0``, and at the middle of the band if set to ``0.5``. bin : bool, dict, Literal['binned'], :class:`BinParams`, None A flag for binning a ``quantitative`` field, `an object defining binning parameters <https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating that the data for ``x`` or ``y`` channel are binned before they are imported into Vega-Lite (``"binned"``). * If ``true``, default `binning parameters <https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be applied. * If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are already binned. You can map the bin-start field to ``x`` (or ``y``) and the bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also set the axis's `tickMinStep <https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property. **Default value:** ``false`` **See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__ documentation. field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef` **Required.** A string defining the name of the field from which to pull a data value or an object defining iterated values from the `repeat <https://vega.github.io/vega-lite/docs/repeat.html>`__ operator. **See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__ documentation. **Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If field names contain dots or brackets but are not nested, you can use ``\\`` to escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details about escaping in the `field documentation <https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required if ``aggregate`` is ``count``. impute : dict, :class:`ImputeParams`, None An object defining the properties of the Impute Operation to be applied. The field value of the other positional channel is taken as ``key`` of the ``Impute`` Operation. The field of the ``color`` channel if specified is used as ``groupby`` of the ``Impute`` Operation. **See also:** `impute <https://vega.github.io/vega-lite/docs/impute.html>`__ documentation. scale : dict, :class:`Scale`, None An object defining properties of the channel's scale, which is the function that transforms values in the data domain (numbers, dates, strings, etc) to visual values (pixels, colors, sizes) of the encoding channels. If ``null``, the scale will be `disabled and the data value will be directly encoded <https://vega.github.io/vega-lite/docs/scale.html#disable>`__. **Default value:** If undefined, default `scale properties <https://vega.github.io/vega-lite/docs/scale.html>`__ are applied. **See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__ documentation. sort : dict, :class:`Sort`, Sequence[str], Sequence[bool], Sequence[float], :class:`SortArray`, :class:`SortOrder`, :class:`AllSortString`, :class:`SortByChannel`, :class:`SortByEncoding`, :class:`EncodingSortField`, :class:`SortByChannelDesc`, Sequence[dict, :class:`DateTime`], Literal['-x', '-y', '-color', '-fill', '-stroke', '-strokeWidth', '-size', '-shape', '-fillOpacity', '-strokeOpacity', '-opacity', '-text', 'ascending', 'descending', 'x', 'y', 'color', 'fill', 'stroke', 'strokeWidth', 'size', 'shape', 'fillOpacity', 'strokeOpacity', 'opacity', 'text'], None Sort order for the encoded field. For continuous fields (quantitative or temporal), ``sort`` can be either ``"ascending"`` or ``"descending"``. For discrete fields, ``sort`` can be one of the following: * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in JavaScript. * `A string indicating an encoding channel name to sort by <https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__ (e.g., ``"x"`` or ``"y"``) with an optional minus prefix for descending sort (e.g., ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a sort-by-encoding definition <https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__. For example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": "descending"}``. * `A sort field definition <https://vega.github.io/vega-lite/docs/sort.html#sort-field>`__ for sorting by another field. * `An array specifying the field values in preferred order <https://vega.github.io/vega-lite/docs/sort.html#sort-array>`__. In this case, the sort order will obey the values in the array, followed by any unspecified values in their original order. For discrete time field, values in the sort array can be `date-time definition objects <https://vega.github.io/vega-lite/docs/datetime.html>`__. In addition, for time units ``"month"`` and ``"day"``, the values can be the month or day names (case insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"``). * ``null`` indicating no sort. **Default value:** ``"ascending"`` **Note:** ``null`` and sorting by another channel is not supported for ``row`` and ``column``. **See also:** `sort <https://vega.github.io/vega-lite/docs/sort.html>`__ documentation. stack : bool, :class:`StackOffset`, Literal['zero', 'center', 'normalize'], None Type of stacking offset if the field should be stacked. ``stack`` is only applicable for ``x``, ``y``, ``theta``, and ``radius`` channels with continuous domains. For example, ``stack`` of ``y`` can be used to customize stacking for a vertical bar chart. ``stack`` can be one of the following values: * ``"zero"`` or ``true``: stacking with baseline offset at zero value of the scale (for creating typical stacked `bar <https://vega.github.io/vega-lite/docs/stack.html#bar>`__ and `area <https://vega.github.io/vega-lite/docs/stack.html#area>`__ chart). * ``"normalize"`` - stacking with normalized domain (for creating `normalized stacked bar and area charts <https://vega.github.io/vega-lite/docs/stack.html#normalized>`__ and pie charts `with percentage tooltip <https://vega.github.io/vega-lite/docs/arc.html#tooltip>`__). * ``"center"`` - stacking with center baseline (for `streamgraph <https://vega.github.io/vega-lite/docs/stack.html#streamgraph>`__). * ``null`` or ``false`` - No-stacking. This will produce layered `bar <https://vega.github.io/vega-lite/docs/stack.html#layered-bar-chart>`__ and area chart. **Default value:** ``zero`` for plots with all of the following conditions are true: (1) the mark is ``bar``, ``area``, or ``arc``; (2) the stacked measure channel (x or y) has a linear scale; (3) At least one of non-position channels mapped to an unaggregated field that is different from x and y. Otherwise, ``null`` by default. **See also:** `stack <https://vega.github.io/vega-lite/docs/stack.html>`__ documentation. timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', 'utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds'] Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal field. or `a temporal field that gets casted as ordinal <https://vega.github.io/vega-lite/docs/type.html#cast>`__. **Default value:** ``undefined`` (None) **See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__ documentation. title : str, :class:`Text`, Sequence[str], None A title for the field. If ``null``, the title will be removed. **Default value:** derived from the field's name and transformation function (``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function, the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the field is binned or has a time unit applied, the applied function is shown in parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``). Otherwise, the title is simply the field name. **Notes**: 1) You can customize the default field title format by providing the `fieldTitle <https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle function via the compile function's options <https://vega.github.io/vega-lite/usage/compile.html#field-title>`__. 2) If both field definition's ``title`` and axis, header, or legend ``title`` are defined, axis/header/legend title will be used. type : :class:`StandardType`, Literal['quantitative', 'ordinal', 'temporal', 'nominal'] The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or ``"nominal"``) for the encoded field or constant value (``datum``). It can also be a ``"geojson"`` type for encoding `'geoshape' <https://vega.github.io/vega-lite/docs/geoshape.html>`__. Vega-Lite automatically infers data types in many cases as discussed below. However, type is required for a field if: (1) the field is not nominal and the field encoding has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal scale for a field with ``bin`` or ``timeUnit``. **Default value:** 1) For a data ``field``, ``"nominal"`` is the default data type unless the field encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or ``timeUnit`` that satisfies the following criteria: * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__. * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` or (2) the specified scale type is a time or utc scale * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort order <https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__, (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding channel is ``order``. 2) For a constant value in data domain (``datum``): * ``"quantitative"`` if the datum is a number * ``"nominal"`` if the datum is a string * ``"temporal"`` if the datum is `a date time object <https://vega.github.io/vega-lite/docs/datetime.html>`__ **Note:** * Data ``type`` describes the semantics of the data rather than the primitive data types (number, string, etc.). The same primitive data type can have different types of measurement. For example, numeric data can represent quantitative, ordinal, or nominal data. * Data values for a temporal field can be either a date-time string (e.g., ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a timestamp number (e.g., ``1552199579097``). * When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) or `"ordinal" (for using an ordinal bin scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" (for using an ordinal scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property refers to the post-aggregation data type. For example, we can calculate count ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have ``type`` as they must have exactly the same type as their primary channels (e.g., ``x``, ``y``). **See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__ documentation. """ _schema = {"$ref": "#/definitions/PositionFieldDef"} def __init__( self, shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined, aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined, axis: Optional[SchemaBase | Map | None] = Undefined, bandPosition: Optional[float] = Undefined, bin: Optional[bool | SchemaBase | Literal["binned"] | Map | None] = Undefined, field: Optional[str | SchemaBase | Map] = Undefined, impute: Optional[SchemaBase | Map | None] = Undefined, scale: Optional[SchemaBase | Map | None] = Undefined, sort: Optional[ SchemaBase | Sequence[str] | Sequence[bool] | Sequence[float] | Sequence[Temporal | SchemaBase | Map] | Map | AllSortString_T | None ] = Undefined, stack: Optional[bool | SchemaBase | StackOffset_T | None] = Undefined, timeUnit: Optional[ SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T ] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, type: Optional[SchemaBase | StandardType_T] = Undefined, **kwds, ): super().__init__( shorthand=shorthand, aggregate=aggregate, axis=axis, bandPosition=bandPosition, bin=bin, field=field, impute=impute, scale=scale, sort=sort, stack=stack, timeUnit=timeUnit, title=title, type=type, **kwds, )
PositionFieldDef
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0092_add_new_fields.py
{ "start": 149, "end": 871 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0091_upate_meta_options"), ] operations = [ migrations.AddField( model_name="domain", name="skip_validation", field=models.BooleanField( default=False, null=True, verbose_name="Skip validation process." ), ), migrations.AddField( model_name="domain", name="validation_process_start", field=models.DateTimeField( auto_now_add=True, null=True, verbose_name="Start date of the validation process.", ), ), ]
Migration
python
wandb__wandb
wandb/apis/internal.py
{ "start": 125, "end": 7611 }
class ____: """Internal proxy to the official internal API.""" # TODO: Move these methods to PublicApi. def __init__(self, *args: Any, **kwargs: Any) -> None: self._api_args = args self._api_kwargs = kwargs self._api = None def __getstate__(self): """Use for serializing. self._api is not serializable, so it's dropped """ state = self.__dict__.copy() del state["_api"] return state def __setstate__(self, state): """Used for deserializing. Don't need to set self._api because it's constructed when needed. """ self.__dict__.update(state) self._api = None @property def api(self) -> InternalApi: # This is a property in order to delay construction of Internal API # for as long as possible. If constructed in constructor, then the # whole InternalAPI is started when simply importing wandb. if self._api is None: self._api = InternalApi(*self._api_args, **self._api_kwargs) return self._api @property def api_key(self): return self.api.api_key @property def is_authenticated(self): return self.api.access_token is not None or self.api.api_key is not None @property def api_url(self): return self.api.api_url @property def app_url(self): return self.api.app_url @property def default_entity(self): return self.api.default_entity def validate_api_key(self) -> bool: """Returns whether the API key stored on initialization is valid.""" return self.api.validate_api_key() def file_current(self, *args): return self.api.file_current(*args) def download_file(self, *args, **kwargs): return self.api.download_file(*args, **kwargs) def download_write_file(self, *args, **kwargs): return self.api.download_write_file(*args, **kwargs) def set_current_run_id(self, run_id): return self.api.set_current_run_id(run_id) def viewer(self): return self.api.viewer() def max_cli_version(self): return self.api.max_cli_version() def viewer_server_info(self): return self.api.viewer_server_info() def list_projects(self, entity=None): return self.api.list_projects(entity=entity) def format_project(self, project): return self.api.format_project(project) def upsert_project(self, project, id=None, description=None, entity=None): return self.api.upsert_project( project, id=id, description=description, entity=entity ) def upsert_run(self, *args, **kwargs): return self.api.upsert_run(*args, **kwargs) def settings(self, *args, **kwargs): return self.api.settings(*args, **kwargs) def clear_setting( self, key: str, globally: bool = False, persist: bool = False ) -> None: return self.api.clear_setting(key, globally, persist) def set_setting( self, key: str, value: Any, globally: bool = False, persist: bool = False ) -> None: return self.api.set_setting(key, value, globally, persist) def parse_slug(self, *args, **kwargs): return self.api.parse_slug(*args, **kwargs) def download_url(self, *args, **kwargs): return self.api.download_url(*args, **kwargs) def download_urls(self, *args, **kwargs): return self.api.download_urls(*args, **kwargs) def push(self, *args, **kwargs): return self.api.push(*args, **kwargs) def sweep(self, *args, **kwargs): return self.api.sweep(*args, **kwargs) def upsert_sweep(self, *args, **kwargs): return self.api.upsert_sweep(*args, **kwargs) def set_sweep_state(self, *args, **kwargs): return self.api.set_sweep_state(*args, **kwargs) def get_sweep_state(self, *args, **kwargs): return self.api.get_sweep_state(*args, **kwargs) def stop_sweep(self, *args, **kwargs): return self.api.stop_sweep(*args, **kwargs) def cancel_sweep(self, *args, **kwargs): return self.api.cancel_sweep(*args, **kwargs) def pause_sweep(self, *args, **kwargs): return self.api.pause_sweep(*args, **kwargs) def resume_sweep(self, *args, **kwargs): return self.api.resume_sweep(*args, **kwargs) def register_agent(self, *args, **kwargs): return self.api.register_agent(*args, **kwargs) def agent_heartbeat(self, *args, **kwargs): return self.api.agent_heartbeat(*args, **kwargs) def use_artifact(self, *args, **kwargs): return self.api.use_artifact(*args, **kwargs) def create_artifact(self, *args, **kwargs): return self.api.create_artifact(*args, **kwargs) def complete_multipart_upload_artifact(self, *args, **kwargs): return self.api.complete_multipart_upload_artifact(*args, **kwargs) def run_config(self, *args, **kwargs): return self.api.run_config(*args, **kwargs) def upload_file_retry(self, *args, **kwargs): return self.api.upload_file_retry(*args, **kwargs) def upload_multipart_file_chunk_retry(self, *args, **kwargs): return self.api.upload_multipart_file_chunk_retry(*args, **kwargs) def get_run_info(self, *args, **kwargs): return self.api.get_run_info(*args, **kwargs) def get_run_state(self, *args, **kwargs): return self.api.get_run_state(*args, **kwargs) def entity_is_team(self, *args, **kwargs): return self.api.entity_is_team(*args, **kwargs) def get_project_run_queues(self, *args, **kwargs): return self.api.get_project_run_queues(*args, **kwargs) def push_to_run_queue(self, *args, **kwargs): return self.api.push_to_run_queue(*args, **kwargs) def pop_from_run_queue(self, *args, **kwargs): return self.api.pop_from_run_queue(*args, **kwargs) def ack_run_queue_item(self, *args, **kwargs): return self.api.ack_run_queue_item(*args, **kwargs) def create_launch_agent(self, *args, **kwargs): return self.api.create_launch_agent(*args, **kwargs) def create_default_resource_config(self, *args, **kwargs): return self.api.create_default_resource_config(*args, **kwargs) def create_run_queue(self, *args, **kwargs): return self.api.create_run_queue(*args, **kwargs) def upsert_run_queue(self, *args, **kwargs): return self.api.upsert_run_queue(*args, **kwargs) def create_custom_chart(self, *args, **kwargs): return self.api.create_custom_chart(*args, **kwargs) def update_launch_agent_status(self, *args, **kwargs): return self.api.update_launch_agent_status(*args, **kwargs) def launch_agent_introspection(self, *args, **kwargs): return self.api.launch_agent_introspection(*args, **kwargs) def fail_run_queue_item_introspection(self, *args, **kwargs): return self.api.fail_run_queue_item_introspection(*args, **kwargs) def fail_run_queue_item(self, *args, **kwargs): return self.api.fail_run_queue_item(*args, **kwargs) def update_run_queue_item_warning(self, *args, **kwargs): return self.api.update_run_queue_item_warning(*args, **kwargs) def get_launch_agent(self, *args, **kwargs): return self.api.get_launch_agent(*args, **kwargs) def stop_run(self, *args, **kwargs): return self.api.stop_run(*args, **kwargs) __all__ = ["Api"]
Api
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 10035, "end": 10105 }
class ____(sqltypes.Boolean): render_bind_cast = True
AsyncpgBoolean
python
matplotlib__matplotlib
lib/matplotlib/tri/_triinterpolate.py
{ "start": 9204, "end": 11481 }
class ____(TriInterpolator): """ Linear interpolator on a triangular grid. Each triangle is represented by a plane so that an interpolated value at point (x, y) lies on the plane of the triangle containing (x, y). Interpolated values are therefore continuous across the triangulation, but their first derivatives are discontinuous at edges between triangles. Parameters ---------- triangulation : `~matplotlib.tri.Triangulation` The triangulation to interpolate over. z : (npoints,) array-like Array of values, defined at grid points, to interpolate between. trifinder : `~matplotlib.tri.TriFinder`, optional If this is not specified, the Triangulation's default TriFinder will be used by calling `.Triangulation.get_trifinder`. Methods ------- `__call__` (x, y) : Returns interpolated values at (x, y) points. `gradient` (x, y) : Returns interpolated derivatives at (x, y) points. """ def __init__(self, triangulation, z, trifinder=None): super().__init__(triangulation, z, trifinder) # Store plane coefficients for fast interpolation calculations. self._plane_coefficients = \ self._triangulation.calculate_plane_coefficients(self._z) def __call__(self, x, y): return self._interpolate_multikeys(x, y, tri_index=None, return_keys=('z',))[0] __call__.__doc__ = TriInterpolator._docstring__call__ def gradient(self, x, y): return self._interpolate_multikeys(x, y, tri_index=None, return_keys=('dzdx', 'dzdy')) gradient.__doc__ = TriInterpolator._docstringgradient def _interpolate_single_key(self, return_key, tri_index, x, y): _api.check_in_list(['z', 'dzdx', 'dzdy'], return_key=return_key) if return_key == 'z': return (self._plane_coefficients[tri_index, 0]*x + self._plane_coefficients[tri_index, 1]*y + self._plane_coefficients[tri_index, 2]) elif return_key == 'dzdx': return self._plane_coefficients[tri_index, 0] else: # 'dzdy' return self._plane_coefficients[tri_index, 1]
LinearTriInterpolator
python
mlflow__mlflow
tests/pyfunc/sample_code/python_model.py
{ "start": 76, "end": 224 }
class ____(PythonModel): def predict(self, context, model_input): return f"This was the input: {model_input}" set_model(MyModel())
MyModel
python
spack__spack
lib/spack/spack/cray_manifest.py
{ "start": 10189, "end": 10375 }
class ____(spack.error.SpackError): """Raised if a compiler, listed in the Cray manifest, cannot be detected correctly based on the paths provided. """
CrayCompilerDetectionError
python
networkx__networkx
networkx/generators/tests/test_line.py
{ "start": 115, "end": 2999 }
class ____: def test_star(self): G = nx.star_graph(5) L = nx.line_graph(G) assert nx.is_isomorphic(L, nx.complete_graph(5)) def test_path(self): G = nx.path_graph(5) L = nx.line_graph(G) assert nx.is_isomorphic(L, nx.path_graph(4)) def test_cycle(self): G = nx.cycle_graph(5) L = nx.line_graph(G) assert nx.is_isomorphic(L, G) def test_digraph1(self): G = nx.DiGraph([(0, 1), (0, 2), (0, 3)]) L = nx.line_graph(G) # no edge graph, but with nodes assert L.adj == {(0, 1): {}, (0, 2): {}, (0, 3): {}} def test_multigraph1(self): G = nx.MultiGraph([(0, 1), (0, 1), (1, 0), (0, 2), (2, 0), (0, 3)]) L = nx.line_graph(G) # no edge graph, but with nodes assert edges_equal( L.edges(), [ ((0, 3, 0), (0, 1, 0)), ((0, 3, 0), (0, 2, 0)), ((0, 3, 0), (0, 2, 1)), ((0, 3, 0), (0, 1, 1)), ((0, 3, 0), (0, 1, 2)), ((0, 1, 0), (0, 1, 1)), ((0, 1, 0), (0, 2, 0)), ((0, 1, 0), (0, 1, 2)), ((0, 1, 0), (0, 2, 1)), ((0, 1, 1), (0, 1, 2)), ((0, 1, 1), (0, 2, 0)), ((0, 1, 1), (0, 2, 1)), ((0, 1, 2), (0, 2, 0)), ((0, 1, 2), (0, 2, 1)), ((0, 2, 0), (0, 2, 1)), ], ) def test_multigraph2(self): G = nx.MultiGraph([(1, 2), (2, 1)]) L = nx.line_graph(G) assert edges_equal(L.edges(), [((1, 2, 0), (1, 2, 1))]) def test_multidigraph1(self): G = nx.MultiDiGraph([(1, 2), (2, 1)]) L = nx.line_graph(G) assert edges_equal( L.edges(), [((1, 2, 0), (2, 1, 0)), ((2, 1, 0), (1, 2, 0))], directed=True ) def test_multidigraph2(self): G = nx.MultiDiGraph([(0, 1), (0, 1), (0, 1), (1, 2)]) L = nx.line_graph(G) assert edges_equal( L.edges(), [((0, 1, 0), (1, 2, 0)), ((0, 1, 1), (1, 2, 0)), ((0, 1, 2), (1, 2, 0))], directed=True, ) def test_digraph2(self): G = nx.DiGraph([(0, 1), (1, 2), (2, 3)]) L = nx.line_graph(G) assert edges_equal( L.edges(), [((0, 1), (1, 2)), ((1, 2), (2, 3))], directed=True ) def test_create1(self): G = nx.DiGraph([(0, 1), (1, 2), (2, 3)]) L = nx.line_graph(G, create_using=nx.Graph()) assert edges_equal(L.edges(), [((0, 1), (1, 2)), ((1, 2), (2, 3))]) def test_create2(self): G = nx.Graph([(0, 1), (1, 2), (2, 3)]) L = nx.line_graph(G, create_using=nx.DiGraph()) assert edges_equal( L.edges(), [((0, 1), (1, 2)), ((1, 2), (2, 3))], directed=True )
TestGeneratorLine
python
ZoranPandovski__al-go-rithms
data_structures/Linked_list/Python/double_linked_list_test.py
{ "start": 47, "end": 498 }
class ____(unittest.TestCase): def testNoRepeated(self): l=List() l.insert(None, Node(4)) l.insert(l.head,Node(6)) l.insert(l.head,Node(8)) self.assertEqual(l.removeRepeated().toNativeList(), [4,8,6]) def testRepeated(self): l=List() l.insert(None, Node(4)) l.insert(l.head,Node(6)) l.insert(l.head,Node(8)) l.insert(l.head,Node(6)) self.assertEqual(l.removeRepeated().toNativeList(), [4,6,8]) unittest.main()
TestMyMethods
python
getsentry__sentry
tests/sentry/integrations/slack/test_link_team.py
{ "start": 1006, "end": 4283 }
class ____(TestCase): url: str def setUp(self) -> None: super().setUp() self.login_as(self.user) self.external_id = "new-slack-id" self.channel_name = "my-channel" self.channel_id = "my-channel_id" self.response_url = "http://example.slack.com/response_url" self.integration = install_slack(self.organization) self.idp = add_identity(self.integration, self.user, self.external_id) @pytest.fixture(autouse=True) def mock_chat_postMessage(self): with patch( "slack_sdk.web.WebClient.chat_postMessage", return_value=SlackResponse( client=None, http_verb="POST", api_url="https://slack.com/api/chat.postMessage", req_args={}, data={"ok": True}, headers={}, status_code=200, ), ) as self.mock_post: yield def get_success_response(self, data: Mapping[str, Any] | None = None) -> HttpResponseBase: """This isn't in APITestCase so this isn't really an override.""" if data is not None: response = self.client.post( self.url, urlencode(data), content_type="application/x-www-form-urlencoded" ) else: response = self.client.get(self.url, content_type="application/x-www-form-urlencoded") assert response.status_code == status.HTTP_200_OK return response def get_error_response( self, data: Mapping[str, Any] | None = None, status_code: int = status.HTTP_404_NOT_FOUND, ) -> HttpResponseBase: if data: response = self.client.post( self.url, urlencode(data), content_type="application/x-www-form-urlencoded" ) else: response = self.client.get(self.url, content_type="application/x-www-form-urlencoded") assert response.status_code == status_code self.assertTemplateUsed(response, "sentry/integrations/generic-error.html") return response def link_team(self, team: Optional["Team"] = None) -> None: return link_team( team=team or self.team, integration=self.integration, channel_name=self.channel_name, channel_id=self.channel_id, ) def get_linked_teams( self, team_ids: Sequence[int] | None = None, organization: Organization | None = None ) -> QuerySet: team_ids = team_ids or [self.team.id] organization = organization or self.organization return ExternalActor.objects.filter( team_id__in=team_ids, organization=organization, integration_id=self.integration.id, provider=ExternalProviders.SLACK.value, external_name=self.channel_name, external_id=self.channel_id, ) def _create_user_valid_through_team_admin(self): user = self.create_user(email="foo@example.com") self.create_member( team_roles=[(self.team, "admin")], user=user, role="member", organization=self.organization, ) self.login_as(user)
SlackIntegrationLinkTeamTestBase