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
redis__redis-py
tests/test_monitor.py
{ "start": 156, "end": 2496 }
class ____: def test_wait_command_not_found(self, r): "Make sure the wait_for_command func works when command is not found" with r.monitor() as m: response = wait_for_command(r, m, "nothing") assert response is None def test_response_values(self, r): db = r.connection_pool.connection_kwargs.get("db", 0) with r.monitor() as m: r.ping() response = wait_for_command(r, m, "PING") assert isinstance(response["time"], float) assert response["db"] == db assert response["client_type"] in ("tcp", "unix") assert isinstance(response["client_address"], str) assert isinstance(response["client_port"], str) assert response["command"] == "PING" def test_command_with_quoted_key(self, r): with r.monitor() as m: r.get('foo"bar') response = wait_for_command(r, m, 'GET foo"bar') assert response["command"] == 'GET foo"bar' def test_command_with_binary_data(self, r): with r.monitor() as m: byte_string = b"foo\x92" r.get(byte_string) response = wait_for_command(r, m, "GET foo\\x92") assert response["command"] == "GET foo\\x92" def test_command_with_escaped_data(self, r): with r.monitor() as m: byte_string = b"foo\\x92" r.get(byte_string) response = wait_for_command(r, m, "GET foo\\\\x92") assert response["command"] == "GET foo\\\\x92" @skip_if_redis_enterprise() def test_lua_script(self, r): with r.monitor() as m: script = 'return redis.call("GET", "foo")' assert r.eval(script, 0) is None response = wait_for_command(r, m, "GET foo") assert response["command"] == "GET foo" assert response["client_type"] == "lua" assert response["client_address"] == "lua" assert response["client_port"] == "" @skip_ifnot_redis_enterprise() def test_lua_script_in_enterprise(self, r): with r.monitor() as m: script = 'return redis.call("GET", "foo")' assert r.eval(script, 0) is None response = wait_for_command(r, m, "GET foo") assert response is None
TestMonitor
python
Netflix__metaflow
metaflow/user_configs/config_options.py
{ "start": 4052, "end": 18602 }
class ____: # ConfigInput is an internal class responsible for processing all the --config and # --config-value options. # It gathers information from the --local-config-file (to figure out # where options are stored) and is also responsible for processing any `--config` or # `--config-value` options. Note that the process_configs function will be called # *twice* (once for the configs and another for the config-values). This makes # this function a little bit more tricky. We need to wait for both calls before # being able to process anything. # It will then store this information in the flow spec for use later in processing. # It is stored in the flow spec to avoid being global to support the Runner. loaded_configs = None # type: Optional[Dict[str, Dict[Any, Any]]] config_file = None # type: Optional[str] def __init__( self, req_configs: List[str], defaults: Dict[str, Tuple[Union[str, Dict[Any, Any]], bool]], parsers: Dict[str, Union[str, Callable[[str], Dict[Any, Any]]]], ): self._req_configs = set(req_configs) self._defaults = defaults self._parsers = parsers self._path_values = None self._value_values = None @staticmethod def make_key_name(name: str) -> str: # Special mark to indicate that the configuration value is not content or a file # name but a value that should be read in the config file (effectively where # the value has already been materialized). return "kv." + name @classmethod def set_config_file(cls, config_file: str): cls.config_file = config_file @classmethod def get_config(cls, config_name: str) -> Optional[Dict[Any, Any]]: if cls.loaded_configs is None: all_configs = _load_config_values(cls.config_file) if all_configs is None: raise MetaflowException( "Could not load expected configuration values " "from the CONFIG_PARAMETERS file. This is a Metaflow bug. " "Please contact support." ) cls.loaded_configs = all_configs return cls.loaded_configs[config_name] def process_configs( self, flow_name: str, param_name: str, param_value: Dict[str, Optional[str]], quiet: bool, datastore: str, click_obj: Optional[Any] = None, ): from ..cli import echo_always, echo_dev_null # Prevent circular import from ..flowspec import FlowStateItems # Prevent circular import flow_cls = getattr(current_flow, "flow_cls", None) if flow_cls is None: # This is an error raise MetaflowInternalError( "Config values should be processed for a FlowSpec" ) # This function is called by click when processing all the --config and # --config-value options. # The value passed in is a list of tuples (name, value). # Click will provide: # - all the defaults if nothing is provided on the command line # - provide *just* the passed in value if anything is provided on the command # line. # # We need to get all config and config-value options and click will call this # function twice. We will first get all the values on the command line and # *then* merge with the defaults to form a full set of values. # We therefore get a full set of values where: # - the name will correspond to the configuration name # - the value will be: # - the default (including None if there is no default). If the default is # not None, it will start with _CONVERTED_DEFAULT since Click will make # the value go through ConvertPath or ConvertDictOrStr # - the actual value passed through prefixed with _CONVERT_PREFIX debug.userconf_exec( "Processing configs for %s -- incoming values: %s" % (param_name, str(param_value)) ) do_return = self._value_values is None and self._path_values is None # We only keep around non default values. We could simplify by checking just one # value and if it is default it means all are but this doesn't seem much more effort # and is clearer if param_name == "config_value": self._value_values = { k: v for k, v in param_value.items() if v is not None and not v.startswith(_CONVERTED_DEFAULT) } else: self._path_values = { k: v for k, v in param_value.items() if v is not None and not v.startswith(_CONVERTED_DEFAULT) } if do_return: # One of values["value"] or values["path"] is None -- we are in the first # go around debug.userconf_exec("Incomplete config options; waiting for more") return None # The second go around, we process all the values and merge them. # If we are processing options that start with kv., we know we are in a subprocess # and ignore other stuff. In particular, environment variables used to pass # down configurations (like METAFLOW_FLOW_CONFIG) could still be present and # would cause an issue -- we can ignore those as the kv. values should trump # everything else. # NOTE: These are all *non default* keys all_keys = set(self._value_values).union(self._path_values) if all_keys and click_obj: click_obj.has_cl_config_options = True # Make sure we have at least some non default keys (we need some if we have # all kv) has_all_kv = all_keys and all( self._value_values.get(k, "").startswith(_CONVERT_PREFIX + "kv.") for k in all_keys ) to_return = {} if not has_all_kv: # Check that the user didn't provide *both* a path and a value. Again, these # are only user-provided (not defaults) common_keys = set(self._value_values or []).intersection( [k for k, v in self._path_values.items()] or [] ) if common_keys: exc = click.UsageError( "Cannot provide both a value and a file for the same configuration. " "Found such values for '%s'" % "', '".join(common_keys) ) if click_obj: click_obj.delayed_config_exception = exc return None raise exc all_values = dict(self._path_values) all_values.update(self._value_values) debug.userconf_exec("All config values: %s" % str(all_values)) merged_configs = {} # Now look at everything (including defaults) for name, (val, is_path) in self._defaults.items(): n = name if n in all_values: # We have the value provided by the user -- use that. merged_configs[n] = all_values[n] else: # No value provided by the user -- use the default if isinstance(val, DeployTimeField): # This supports a default value that is a deploy-time field (similar # to Parameter).) # We will form our own context and pass it down -- note that you cannot # use configs in the default value of configs as this introduces a bit # of circularity. Note also that quiet and datastore are *eager* # options so are available here. param_ctx = ParameterContext( flow_name=flow_name, user_name=get_username(), parameter_name=n, logger=(echo_dev_null if quiet else echo_always), ds_type=datastore, configs=None, ) val = val.fun(param_ctx) if is_path: # This is a file path merged_configs[n] = ConvertPath.convert_value(val, True) else: # This is a value merged_configs[n] = ConvertDictOrStr.convert_value(val, True) else: debug.userconf_exec("Fast path due to pre-processed values") merged_configs = self._value_values if click_obj: click_obj.has_config_options = True debug.userconf_exec("Configs merged with defaults: %s" % str(merged_configs)) missing_configs = set() no_file = [] no_default_file = [] msgs = [] for name, val in merged_configs.items(): if val is None: missing_configs.add(name) to_return[name] = None flow_cls._flow_state.self_data[FlowStateItems.CONFIGS][name] = ( None, True, ) continue if val.startswith(_CONVERTED_NO_FILE): no_file.append(name) continue if val.startswith(_CONVERTED_DEFAULT_NO_FILE): no_default_file.append(name) continue parser, is_plain = self._parsers[name] val = val[len(_CONVERT_PREFIX) :] # Remove the _CONVERT_PREFIX if val.startswith(_DEFAULT_PREFIX): # Remove the _DEFAULT_PREFIX if needed val = val[len(_DEFAULT_PREFIX) :] if val.startswith("kv."): # This means to load it from a file try: read_value, read_is_plain = self.get_config(val[3:]) except KeyError as e: exc = click.UsageError( "Could not find configuration '%s' in INFO file" % val ) if click_obj: click_obj.delayed_config_exception = exc return None raise exc from e if read_is_plain != is_plain: raise click.UsageError( "Configuration '%s' mismatched `plain` attribute -- " "this is a bug, please report it." % val[3:] ) flow_cls._flow_state.self_data[FlowStateItems.CONFIGS][name] = ( read_value, True if read_value is None else is_plain, ) to_return[name] = ( read_value if read_value is None or is_plain else ConfigValue(read_value) ) else: if parser: read_value = self._call_parser(parser, val, is_plain) else: if is_plain: read_value = val else: try: read_value = json.loads(val) except json.JSONDecodeError as e: msgs.append( "configuration value for '%s' is not valid JSON: %s" % (name, e) ) continue # TODO: Support YAML flow_cls._flow_state.self_data[FlowStateItems.CONFIGS][name] = ( read_value, True if read_value is None else is_plain, ) to_return[name] = ( read_value if read_value is None or is_plain else ConfigValue(read_value) ) reqs = missing_configs.intersection(self._req_configs) for missing in reqs: msgs.append("missing configuration for '%s'" % missing) for missing in no_file: msgs.append( "configuration file '%s' could not be read for '%s'" % (merged_configs[missing][len(_CONVERTED_NO_FILE) :], missing) ) for missing in no_default_file: msgs.append( "default configuration file '%s' could not be read for '%s'" % (merged_configs[missing][len(_CONVERTED_DEFAULT_NO_FILE) :], missing) ) if msgs: exc = click.UsageError( "Bad values passed for configuration options: %s" % ", ".join(msgs) ) if click_obj: click_obj.delayed_config_exception = exc return None raise exc debug.userconf_exec("Finalized configs: %s" % str(to_return)) return to_return def process_configs_click(self, ctx, param, value): return self.process_configs( ctx.obj.flow.name, param.name, dict(value), ctx.params["quiet"], ctx.params["datastore"], click_obj=ctx.obj, ) def __str__(self): return repr(self) def __repr__(self): return "ConfigInput" @staticmethod def _call_parser(parser, val, is_plain): if isinstance(parser, str): if len(parser) and parser[0] == ".": parser = "metaflow" + parser path, func = parser.rsplit(".", 1) try: func_module = importlib.import_module(path) except ImportError as e: raise ValueError("Cannot locate parser %s" % parser) from e parser = getattr(func_module, func, None) if parser is None or not callable(parser): raise ValueError( "Parser %s is either not part of %s or not a callable" % (func, path) ) return_value = parser(val) if not is_plain and not isinstance(return_value, Mapping): raise ValueError( "Parser %s returned a value that is not a mapping (got type %s): %s" % (str(parser), type(return_value), return_value) ) return return_value
ConfigInput
python
jazzband__django-oauth-toolkit
tests/test_client_credential.py
{ "start": 3838, "end": 4064 }
class ____(OAuthLibMixin, View): server_class = BackendApplicationServer validator_class = OAuth2Validator oauthlib_backend_class = OAuthLibCore def get_scopes(self): return ["read", "write"]
ExampleView
python
tensorflow__tensorflow
tensorflow/core/function/capture/free_vars_detect_test.py
{ "start": 14154, "end": 18630 }
class ____(parameterized.TestCase): def _remove_explanation(self, logging_txt): free_vars = logging_txt.split("\n") self.assertGreater(len(free_vars), 2) return "\n".join(free_vars[2:]) def test_none_input(self): txt = free_vars_detect.generate_free_var_logging(None) self.assertIsNone(txt) def test_non_function_input(self): x = 1 class Foo(): def bar(self): return x foo = Foo() txt = free_vars_detect.generate_free_var_logging(foo) self.assertIsNone(txt) def test_func_wo_source_code(self): code = "def f_exec():\n return 1" # Use `exec` to generate a function without source code exec(code, globals()) # pylint: disable=exec-used txt = free_vars_detect.generate_free_var_logging(f_exec) # pylint: disable=undefined-variable self.assertIsNone(txt) def test_no_free_var(self): def f(x): return x + 1 txt = free_vars_detect.generate_free_var_logging(f) self.assertIsNone(txt) def test_single_func(self): x = 1 y = 2 def f(a): return a + x + y txt = free_vars_detect.generate_free_var_logging(f) txt = self._remove_explanation(txt) self.assertEqual(txt, "Inside function f(): x, y") def test_nested_func(self): x = 1 y = 2 def g(): return y def f(): return g() + x txt = free_vars_detect.generate_free_var_logging(f) txt = self._remove_explanation(txt) lines = txt.split("\n") self.assertLen(lines, 2) self.assertEqual(lines[0], "Inside function f(): g, x") self.assertEqual(lines[1], "Inside function g(): y") def test_method_w_method_call(self): x = 0 class Foo(): def f(self): return self.g def g(self): return [x] foo = Foo() txt = free_vars_detect.generate_free_var_logging(foo.f) txt = self._remove_explanation(txt) lines = txt.split("\n") self.assertLen(lines, 2) self.assertEqual(lines[0], "Inside function Foo.f(): self.g") self.assertEqual(lines[1], "Inside function Foo.g(): x") def test_partial_func(self): x = 1 y = 2 def f(a): return a + x + y partial_f = functools.partial(f, a=0) txt = free_vars_detect.generate_free_var_logging(partial_f) txt = self._remove_explanation(txt) self.assertEqual(txt, "Inside function f(): x, y") def test_partial_method(self): x = 0 class Foo(): def f(self): return self.g def g(self): return [x] partial_f = functools.partialmethod(f) foo = Foo() txt = free_vars_detect.generate_free_var_logging(foo.partial_f) txt = self._remove_explanation(txt) lines = txt.split("\n") self.assertLen(lines, 2) self.assertEqual(lines[0], "Inside function Foo.f(): self.g") self.assertEqual(lines[1], "Inside function Foo.g(): x") def test_partial_wrapped_partial_func(self): def decorator_foo(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return functools.update_wrapper(wrapper, func) x = 1 y = 2 def f(a, b): return a + b + x + y f = functools.partial(f, a=0) f = decorator_foo(f) f = functools.partial(f, b=0) txt = free_vars_detect.generate_free_var_logging(f) txt = self._remove_explanation(txt) self.assertEqual(txt, "Inside function f(): x, y") def test_freevar_threshold(self): a = b = c = d = e = 1 def f(): return a + b + c + d + e txt = free_vars_detect.generate_free_var_logging(f, var_threshold=3) txt = self._remove_explanation(txt) self.assertEqual(txt, "Inside function f(): a, b, c...") def test_func_threshold(self): x = 1 def g(): return x def h(): return x def f(): return g() + h() txt = free_vars_detect.generate_free_var_logging(f, fn_threshold=2) txt = self._remove_explanation(txt) lines = txt.split("\n") self.assertLen(lines, 3) self.assertEqual(lines[0], "Inside function f(): g, h") self.assertEqual(lines[1], "Inside function g(): x") self.assertEqual(lines[2], "...") def test_func_second_call_return_none(self): x = 1 def f(): return x logging_txt = free_vars_detect.generate_free_var_logging(f) self.assertIsNotNone(logging_txt) logging_txt = free_vars_detect.generate_free_var_logging(f) self.assertIsNone(logging_txt) if __name__ == "__main__": unittest.main()
GenerateLoggingTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 347295, "end": 347598 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("Gist", graphql_name="node")
GistEdge
python
sanic-org__sanic
sanic/exceptions.py
{ "start": 5130, "end": 6138 }
class ____(HTTPException): """400 Bad Request Args: message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None` then the HTTP status 'Bad Request' will be sent. Defaults to `None`. quiet (Optional[bool], optional): When `True`, the error traceback will be suppressed from the logs. Defaults to `None`. context (Optional[Dict[str, Any]], optional): Additional mapping of key/value data that will be sent to the client upon exception. Defaults to `None`. extra (Optional[Dict[str, Any]], optional): Additional mapping of key/value data that will NOT be sent to the client when in PRODUCTION mode. Defaults to `None`. headers (Optional[Dict[str, Any]], optional): Additional headers that should be sent with the HTTP response. Defaults to `None`. """ # noqa: E501 status_code = 400 quiet = True InvalidUsage = BadRequest BadURL = BadRequest
BadRequest
python
modin-project__modin
modin/config/envvars.py
{ "start": 39167, "end": 40156 }
class ____(EnvironmentVariable, type=bool): """ It does not wait for the end of reading information from the source. It basically means, that the reading function only launches tasks for the dataframe to be read/created, but not ensures that the construction is finalized by the time the reading function returns a dataframe. This option was brought to improve performance of reading/construction of Modin DataFrames, however it may also: 1. Increase the peak memory consumption. Since the garbage collection of the temporary objects created during the reading is now also lazy and will only be performed when the reading/construction is actually finished. 2. Can break situations when the source is manually deleted after the reading function returns a result, for example, when reading inside of a context-block that deletes the file on ``__exit__()``. """ varname = "MODIN_ASYNC_READ_MODE" default = False
AsyncReadMode
python
huggingface__transformers
src/transformers/models/modernbert/modeling_modernbert.py
{ "start": 19037, "end": 22530 }
class ____(nn.Module): """Performs multi-headed self attention on a batch of unpadded sequences. If Flash Attention 2 is installed, this module uses Flash Attention to improve throughput. If Flash Attention 2 is not installed, the implementation will use PyTorch's SDPA kernel, which requires padding and unpadding inputs, adding some overhead. See `forward` method for additional details. """ def __init__(self, config: ModernBertConfig, layer_id: Optional[int] = None): super().__init__() self.config = config self.layer_id = layer_id if config.hidden_size % config.num_attention_heads != 0: raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads ({config.num_attention_heads})" ) self.attention_dropout = config.attention_dropout self.deterministic_flash_attn = config.deterministic_flash_attn self.num_heads = config.num_attention_heads self.head_dim = config.hidden_size // config.num_attention_heads self.all_head_size = self.head_dim * self.num_heads self.Wqkv = nn.Linear(config.hidden_size, 3 * self.all_head_size, bias=config.attention_bias) layer_type = config.layer_types[layer_id] if layer_id % config.global_attn_every_n_layers != 0: self.local_attention = (config.local_attention // 2, config.local_attention // 2) max_position_embeddings = config.local_attention else: self.local_attention = (-1, -1) max_position_embeddings = config.max_position_embeddings if config._attn_implementation == "flash_attention_2": rope_parameters_dict = ( self.config.rope_parameters[layer_type] if layer_type is not None else self.config.rope_parameters ) rope_theta = rope_parameters_dict["rope_theta"] self.rotary_emb = ModernBertUnpaddedRotaryEmbedding( dim=self.head_dim, max_seqlen=max_position_embeddings, base=rope_theta ) else: self.rotary_emb = None self.Wo = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias) self.out_drop = nn.Dropout(config.attention_dropout) if config.attention_dropout > 0.0 else nn.Identity() def forward( self, hidden_states: torch.Tensor, position_embeddings: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, **kwargs, ) -> torch.Tensor: qkv = self.Wqkv(hidden_states) bs = hidden_states.shape[0] if self.config._attn_implementation == "flash_attention_2": qkv = qkv.view(-1, 3, self.num_heads, self.head_dim) else: qkv = qkv.view(bs, -1, 3, self.num_heads, self.head_dim) attn_outputs = MODERNBERT_ATTENTION_FUNCTION[self.config._attn_implementation]( self, qkv=qkv, rotary_emb=self.rotary_emb, local_attention=self.local_attention, bs=bs, dim=self.all_head_size, position_embeddings=position_embeddings, output_attentions=output_attentions, **kwargs, ) hidden_states = attn_outputs[0] hidden_states = self.out_drop(self.Wo(hidden_states)) return (hidden_states,) + attn_outputs[1:] # add attentions if outputted
ModernBertAttention
python
django__django
tests/composite_pk/tests.py
{ "start": 612, "end": 10341 }
class ____(TestCase): maxDiff = None @classmethod def setUpTestData(cls): cls.tenant = Tenant.objects.create() cls.user = User.objects.create( tenant=cls.tenant, id=1, email="user0001@example.com", ) cls.comment = Comment.objects.create(tenant=cls.tenant, id=1, user=cls.user) @staticmethod def get_primary_key_columns(table): with connection.cursor() as cursor: return connection.introspection.get_primary_key_columns(cursor, table) def test_pk_updated_if_field_updated(self): user = User.objects.get(pk=self.user.pk) self.assertEqual(user.pk, (self.tenant.id, self.user.id)) self.assertIs(user._is_pk_set(), True) user.tenant_id = 9831 self.assertEqual(user.pk, (9831, self.user.id)) self.assertIs(user._is_pk_set(), True) user.id = 4321 self.assertEqual(user.pk, (9831, 4321)) self.assertIs(user._is_pk_set(), True) user.pk = (9132, 3521) self.assertEqual(user.tenant_id, 9132) self.assertEqual(user.id, 3521) self.assertIs(user._is_pk_set(), True) user.id = None self.assertEqual(user.pk, (9132, None)) self.assertEqual(user.tenant_id, 9132) self.assertIsNone(user.id) self.assertIs(user._is_pk_set(), False) def test_hash(self): self.assertEqual(hash(User(pk=(1, 2))), hash((1, 2))) self.assertEqual(hash(User(tenant_id=2, id=3)), hash((2, 3))) msg = "Model instances without primary key value are unhashable" with self.assertRaisesMessage(TypeError, msg): hash(User()) with self.assertRaisesMessage(TypeError, msg): hash(User(tenant_id=1)) with self.assertRaisesMessage(TypeError, msg): hash(User(id=1)) def test_pk_must_be_list_or_tuple(self): user = User.objects.get(pk=self.user.pk) test_cases = [ "foo", 1000, 3.14, True, False, ] for pk in test_cases: with self.assertRaisesMessage( ValueError, "'pk' must be a list or a tuple." ): user.pk = pk def test_pk_must_have_2_elements(self): user = User.objects.get(pk=self.user.pk) test_cases = [ (), [], (1000,), [1000], (1, 2, 3), [1, 2, 3], ] for pk in test_cases: with self.assertRaisesMessage(ValueError, "'pk' must have 2 elements."): user.pk = pk def test_composite_pk_in_fields(self): user_fields = {f.name for f in User._meta.get_fields()} self.assertTrue({"pk", "tenant", "id"}.issubset(user_fields)) comment_fields = {f.name for f in Comment._meta.get_fields()} self.assertTrue({"pk", "tenant", "id"}.issubset(comment_fields)) def test_pk_field(self): pk = User._meta.get_field("pk") self.assertIsInstance(pk, CompositePrimaryKey) self.assertIs(User._meta.pk, pk) def test_error_on_user_pk_conflict(self): with self.assertRaises(IntegrityError): User.objects.create(tenant=self.tenant, id=self.user.id) def test_error_on_comment_pk_conflict(self): with self.assertRaises(IntegrityError): Comment.objects.create(tenant=self.tenant, id=self.comment.id, user_id=1) def test_get_primary_key_columns(self): self.assertEqual( self.get_primary_key_columns(User._meta.db_table), ["tenant_id", "id"], ) self.assertEqual( self.get_primary_key_columns(Comment._meta.db_table), ["tenant_id", "comment_id"], ) def test_in_bulk(self): """ Test the .in_bulk() method of composite_pk models. """ result = Comment.objects.in_bulk() self.assertEqual(result, {self.comment.pk: self.comment}) result = Comment.objects.in_bulk([self.comment.pk]) self.assertEqual(result, {self.comment.pk: self.comment}) def test_in_bulk_batching(self): Comment.objects.all().delete() batching_required = connection.features.max_query_params is not None expected_queries = 2 if batching_required else 1 with unittest.mock.patch.object( type(connection.features), "max_query_params", 10 ): num_requiring_batching = ( connection.ops.bulk_batch_size([Comment._meta.pk], []) + 1 ) comments = [ Comment(id=i, tenant=self.tenant, user=self.user) for i in range(1, num_requiring_batching + 1) ] Comment.objects.bulk_create(comments) id_list = list(Comment.objects.values_list("pk", flat=True)) with self.assertNumQueries(expected_queries): comment_dict = Comment.objects.in_bulk(id_list=id_list) self.assertQuerySetEqual(comment_dict, id_list) def test_in_bulk_values(self): result = Comment.objects.values().in_bulk([self.comment.pk]) self.assertEqual( result, { self.comment.pk: { "tenant_id": self.comment.tenant_id, "id": self.comment.id, "user_id": self.comment.user_id, "text": self.comment.text, "integer": self.comment.integer, } }, ) def test_in_bulk_values_field(self): result = Comment.objects.values("text").in_bulk([self.comment.pk]) self.assertEqual( result, {self.comment.pk: {"text": self.comment.text}}, ) def test_in_bulk_values_fields(self): result = Comment.objects.values("pk", "text").in_bulk([self.comment.pk]) self.assertEqual( result, {self.comment.pk: {"pk": self.comment.pk, "text": self.comment.text}}, ) def test_in_bulk_values_list(self): result = Comment.objects.values_list("text").in_bulk([self.comment.pk]) self.assertEqual(result, {self.comment.pk: (self.comment.text,)}) def test_in_bulk_values_list_multiple_fields(self): result = Comment.objects.values_list("pk", "text").in_bulk([self.comment.pk]) self.assertEqual( result, {self.comment.pk: (self.comment.pk, self.comment.text)} ) def test_in_bulk_values_list_fields_are_pk(self): result = Comment.objects.values_list("tenant", "id").in_bulk([self.comment.pk]) self.assertEqual( result, {self.comment.pk: (self.comment.tenant_id, self.comment.id)} ) def test_in_bulk_values_list_flat(self): result = Comment.objects.values_list("text", flat=True).in_bulk( [self.comment.pk] ) self.assertEqual(result, {self.comment.pk: self.comment.text}) def test_in_bulk_values_list_flat_pk(self): result = Comment.objects.values_list("pk", flat=True).in_bulk([self.comment.pk]) self.assertEqual(result, {self.comment.pk: self.comment.pk}) def test_in_bulk_values_list_flat_tenant(self): result = Comment.objects.values_list("tenant", flat=True).in_bulk( [self.comment.pk] ) self.assertEqual(result, {self.comment.pk: self.tenant.id}) def test_iterator(self): """ Test the .iterator() method of composite_pk models. """ result = list(Comment.objects.iterator()) self.assertEqual(result, [self.comment]) def test_query(self): users = User.objects.values_list("pk").order_by("pk") self.assertNotIn('AS "pk"', str(users.query)) def test_raw(self): users = User.objects.raw("SELECT * FROM composite_pk_user") self.assertEqual(len(users), 1) user = users[0] self.assertEqual(user.tenant_id, self.user.tenant_id) self.assertEqual(user.id, self.user.id) self.assertEqual(user.email, self.user.email) def test_raw_missing_PK_fields(self): query = "SELECT tenant_id, email FROM composite_pk_user" msg = "Raw query must include the primary key" with self.assertRaisesMessage(FieldDoesNotExist, msg): list(User.objects.raw(query)) def test_only(self): users = User.objects.only("pk") self.assertSequenceEqual(users, (self.user,)) user = users[0] with self.assertNumQueries(0): self.assertEqual(user.pk, (self.user.tenant_id, self.user.id)) self.assertEqual(user.tenant_id, self.user.tenant_id) self.assertEqual(user.id, self.user.id) with self.assertNumQueries(1): self.assertEqual(user.email, self.user.email) def test_select_related(self): Comment.objects.create(tenant=self.tenant, id=2) with self.assertNumQueries(1): comments = list(Comment.objects.select_related("user").order_by("pk")) self.assertEqual(len(comments), 2) self.assertEqual(comments[0].user, self.user) self.assertIsNone(comments[1].user) def test_model_forms(self): fields = ["tenant", "id", "user_id", "text", "integer"] self.assertEqual(list(CommentForm.base_fields), fields) form = modelform_factory(Comment, fields="__all__") self.assertEqual(list(form().fields), fields) with self.assertRaisesMessage( FieldError, "Unknown field(s) (pk) specified for Comment" ): self.assertIsNone(modelform_factory(Comment, fields=["pk"]))
CompositePKTests
python
rq__rq
rq/local.py
{ "start": 4738, "end": 6745 }
class ____: """Local objects cannot manage themselves. For that you need a local manager. You can pass a local manager multiple locals or add them later by appending them to `manager.locals`. Everytime the manager cleans up it, will clean up all the data left in the locals for this context. The `ident_func` parameter can be added to override the default ident function for the wrapped locals. .. versionchanged:: 0.6.1 Instead of a manager the :func:`release_local` function can be used as well. .. versionchanged:: 0.7 `ident_func` was added. """ def __init__(self, locals=None, ident_func=None): if locals is None: self.locals = [] elif isinstance(locals, Local): self.locals = [locals] else: self.locals = list(locals) if ident_func is not None: self.ident_func = ident_func for local in self.locals: object.__setattr__(local, '__ident_func__', ident_func) else: self.ident_func = get_ident def get_ident(self): """Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy's scoped sessions) to the Werkzeug locals. .. versionchanged:: 0.7 You can pass a different ident function to the local manager that will then be propagated to all the locals passed to the constructor. """ return self.ident_func() def cleanup(self): """Manually clean up the data in the locals for this context. Call this at the end of the request or use `make_middleware()`. """ for local in self.locals: release_local(local) def __repr__(self): return '<%s storages: %d>' % (self.__class__.__name__, len(self.locals))
LocalManager
python
huggingface__transformers
src/transformers/models/umt5/modeling_umt5.py
{ "start": 6106, "end": 16061 }
class ____(nn.Module): """ T5's attention using relative_attention_bias. """ def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None): super().__init__() self.is_decoder = config.is_decoder self.has_relative_attention_bias = has_relative_attention_bias self.relative_attention_num_buckets = config.relative_attention_num_buckets self.relative_attention_max_distance = config.relative_attention_max_distance self.d_model = config.d_model self.key_value_proj_dim = config.d_kv self.n_heads = config.num_heads self.dropout = config.dropout_rate self.inner_dim = self.n_heads * self.key_value_proj_dim self.layer_idx = layer_idx if layer_idx is None and self.is_decoder: logger.warning_once( f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and " "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) self.q = nn.Linear(self.d_model, self.inner_dim, bias=False) self.k = nn.Linear(self.d_model, self.inner_dim, bias=False) self.v = nn.Linear(self.d_model, self.inner_dim, bias=False) self.o = nn.Linear(self.inner_dim, self.d_model, bias=False) if self.has_relative_attention_bias: self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads) def _shape(self, projection: torch.Tensor) -> torch.Tensor: new_projection_shape = projection.size()[:-1] + (self.n_heads, self.key_value_proj_dim) # move heads to 2nd position (B, T, H * D) -> (B, T, H, D) -> (B, H, T, D) new_projection = projection.view(new_projection_shape).permute(0, 2, 1, 3) return new_projection def _relative_position_bucket(self, relative_position): """ Adapted from Mesh Tensorflow: https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593 Translate relative position to a bucket number for relative attention. The relative position is defined as memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for small absolute relative_position and larger buckets for larger absolute relative_positions. All relative positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket. This should allow for more graceful generalization to longer sequences than the model has been trained on Args: relative_position: an int32 Tensor bidirectional: a boolean - whether the attention is bidirectional num_buckets: an integer max_distance: an integer Returns: a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets) """ relative_buckets = 0 num_buckets = self.relative_attention_num_buckets max_distance = self.relative_attention_max_distance if not self.is_decoder: num_buckets //= 2 relative_buckets += (relative_position > 0).to(torch.long) * num_buckets relative_position = torch.abs(relative_position) else: relative_position = -torch.min(relative_position, torch.zeros_like(relative_position)) # now relative_position is in the range [0, inf) # half of the buckets are for exact increments in positions max_exact = num_buckets // 2 is_small = relative_position < max_exact # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance log_ratio = torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact) log_ratio = log_ratio * (num_buckets - max_exact) relative_position_if_large = max_exact + log_ratio.to(torch.long) relative_position_if_large = torch.min( relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1) ) relative_buckets += torch.where(is_small, relative_position, relative_position_if_large) return relative_buckets def compute_bias(self, query_length, key_length, device=None, cache_position=None): """Compute binned relative position bias""" if device is None: device = self.relative_attention_bias.weight.device if cache_position is None: context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None] else: context_position = cache_position[:, None] memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :] relative_position = memory_position - context_position # shape (query_length, key_length) relative_position_bucket = self._relative_position_bucket(relative_position) values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads) values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length) return values def forward( self, hidden_states: torch.Tensor, encoder_hidden_states: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.Tensor] = None, cache_position: Optional[torch.Tensor] = None, ): batch_size, seq_length = hidden_states.shape[:2] # if encoder_hidden_states are provided this layer is used as a cross-attention layer for the decoder is_cross_attention = encoder_hidden_states is not None query_states = self.q(hidden_states) query_states = query_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2) # Check is encoder-decoder model is being used. Otherwise we'll get `DynamicCache` is_updated = False if past_key_values is not None and isinstance(past_key_values, EncoderDecoderCache): is_updated = past_key_values.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_states from cache curr_past_key_values = past_key_values.cross_attention_cache else: curr_past_key_values = past_key_values.self_attention_cache else: curr_past_key_values = past_key_values current_states = encoder_hidden_states if is_cross_attention else hidden_states if is_cross_attention and past_key_values is not None and is_updated: # reuse k,v, cross_attentions key_states = curr_past_key_values.layers[self.layer_idx].keys value_states = curr_past_key_values.layers[self.layer_idx].values else: key_states = self.k(current_states) value_states = self.v(current_states) key_states = key_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2) value_states = value_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2) if past_key_values is not None: # save all key/value_states to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not is_cross_attention else None key_states, value_states = curr_past_key_values.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache): past_key_values.is_updated[self.layer_idx] = True # compute scores, equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9 scores = torch.matmul(query_states, key_states.transpose(3, 2)) # cache position is 0-indexed so we add 1 to get the real length of queries (aka with past) real_seq_length = seq_length + past_key_values.get_seq_length() if past_key_values is not None else seq_length key_length = key_states.shape[-2] if not self.has_relative_attention_bias: position_bias = torch.zeros( (1, self.n_heads, seq_length, key_length), device=scores.device, dtype=scores.dtype ) else: position_bias = self.compute_bias( real_seq_length, key_length, device=scores.device, cache_position=cache_position ) position_bias = position_bias[:, :, -seq_length:, :] if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] position_bias = position_bias + causal_mask position_bias_masked = position_bias scores += position_bias_masked # (batch_size, n_heads, seq_length, key_length) attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores) attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.view(batch_size, seq_length, -1) attn_output = self.o(attn_output) return attn_output, attn_weights
UMT5Attention
python
pytorch__pytorch
test/inductor/test_max_autotune.py
{ "start": 110956, "end": 118154 }
class ____(TestCase): # Use only one device/subprocess so we test the process restarts # and is usable after a crash. @config.patch({"autotune_multi_device": False}) def test_tuning_pool_crash(self): tuning_pool = TuningProcessPool() # First force the tuning process to crash. bmreq = _TestBenchmarkRequest(0, crash=True) choice = _TestTritonTemplateCaller(bmreq) timings = tuning_pool.benchmark([choice]) self.assertTrue(choice in timings) self.assertEqual(timings[choice], float("inf")) # Then send another request and make sure the sub-process # has restarted and is operational. bmreq = _TestBenchmarkRequest(3.14) choice = _TestTritonTemplateCaller(bmreq) timings = tuning_pool.benchmark([choice]) self.assertTrue(choice in timings) self.assertEqual(timings[choice], bmreq.result) tuning_pool.shutdown() @config.patch({"autotune_multi_device": False}) def test_tuning_pool_timeout(self): tuning_pool = TuningProcessPool() # First force the tuning process to timeout. bmreq = _TestBenchmarkRequest(0, sleep=120) choice = _TestTritonTemplateCaller(bmreq) with config.patch({"max_autotune_subproc_result_timeout_seconds": 1.0}): timings = tuning_pool.benchmark([choice]) self.assertTrue(choice in timings) self.assertEqual(timings[choice], float("inf")) # Then send another request and make sure the sub-process # has restarted and is operational. bmreq = _TestBenchmarkRequest(3.14) choice = _TestTritonTemplateCaller(bmreq) timings = tuning_pool.benchmark([choice]) self.assertTrue(choice in timings) self.assertEqual(timings[choice], bmreq.result) tuning_pool.shutdown() # XPU have to enable XPU_VISIBLE_DEVICES to control devices visibility. @skipIfXpu @config.patch({"autotune_multi_device": True}) def test_tuning_pool_multiple_devices(self): # Adapt the test to the available devices (and whether CUDA_VISIBLE_DEVICES # is already set in the environment); use a subset of the available devices # to ensure only the subset are visible to the sub-processes. if CUDA_VISIBLE_DEVICES in os.environ: visible_devices = os.environ[CUDA_VISIBLE_DEVICES].split(",") else: visible_devices = [str(d) for d in range(torch.cuda.device_count())] cuda_visible_devices = ",".join(visible_devices[-2:]) with unittest.mock.patch.dict( os.environ, {CUDA_VISIBLE_DEVICES: cuda_visible_devices} ): tuning_pool = TuningProcessPool() choice1 = _TestTritonTemplateCaller(_TestBenchmarkRequest(3.14)) choice2 = _TestTritonTemplateCaller(_TestBenchmarkRequest(2.718)) timings = tuning_pool.benchmark([choice1, choice2]) self.assertEqual(timings[choice1], choice1.bmreq.result) self.assertEqual(timings[choice2], choice2.bmreq.result) tuning_pool.shutdown() def test_add_feedback_saver(self): """Test that add_feedback_saver correctly adds feedback functions.""" from torch._inductor.select_algorithm import get_algorithm_selector_cache # Clear any existing feedback savers clear_feedback_savers() # Create a simple feedback saver function feedback_calls = [] def simple_feedback_saver(timings, name, input_nodes, choices, profiled_time): feedback_calls.append( { "name": name, "num_choices": len(choices), "num_timings": len(timings), "has_profiled_time": profiled_time is not None, } ) # Add the feedback saver add_feedback_saver(simple_feedback_saver) # Get the global cache and verify the function was added cache = get_algorithm_selector_cache() self.assertEqual(len(cache.feedback_saver_fns), 1) self.assertEqual(cache.feedback_saver_fns[0], simple_feedback_saver) # Test that we can add multiple feedback savers def another_feedback_saver(timings, name, input_nodes, choices, profiled_time): pass add_feedback_saver(another_feedback_saver) self.assertEqual(len(cache.feedback_saver_fns), 2) # Clean up clear_feedback_savers() def test_clear_feedback_savers(self): """Test that clear_feedback_savers removes all feedback functions.""" from torch._inductor.select_algorithm import get_algorithm_selector_cache # Add some feedback savers first def feedback_saver1(timings, name, input_nodes, choices, profiled_time): pass def feedback_saver2(timings, name, input_nodes, choices, profiled_time): pass add_feedback_saver(feedback_saver1) add_feedback_saver(feedback_saver2) # Verify they were added cache = get_algorithm_selector_cache() self.assertEqual(len(cache.feedback_saver_fns), 2) # Clear all feedback savers clear_feedback_savers() # Verify they were cleared self.assertEqual(len(cache.feedback_saver_fns), 0) def test_feedback_saver_integration(self): """Test that feedback savers are actually called during autotuning.""" # Clear any existing feedback savers clear_feedback_savers() feedback_calls = [] def test_feedback_saver(timings, name, input_nodes, choices, profiled_time): # Store information about the call for verification feedback_calls.append( { "name": name, "num_choices": len(choices), "num_timings": len(timings), "input_node_count": len(input_nodes), } ) # Add our test feedback saver add_feedback_saver(test_feedback_saver) # Create a simple matrix multiplication that will trigger autotuning def mm(a, b): return a @ b a = torch.randn(32, 32, device=GPU_TYPE) b = torch.randn(32, 32, device=GPU_TYPE) with config.patch( { "max_autotune": True, "max_autotune_gemm_backends": "TRITON", "triton.native_matmul": False, } ): torch.compile(mm)(a, b) # Verify that our feedback saver was called self.assertGreater( len(feedback_calls), 0, "Feedback saver should have been called" ) # Verify the structure of the feedback call call = feedback_calls[0] self.assertIn("name", call) self.assertIn("num_choices", call) self.assertIn("num_timings", call) self.assertIn("input_node_count", call) self.assertGreater(call["num_choices"], 0) self.assertEqual(call["input_node_count"], 2) # Two input matrices # Clean up clear_feedback_savers() @instantiate_parametrized_tests
TestTuningProcessPool
python
huggingface__transformers
src/transformers/models/moshi/modeling_moshi.py
{ "start": 13992, "end": 14680 }
class ____(nn.Module): def __init__(self, input_dim, output_dim, num_codebooks, use_flexible_linear=False): super().__init__() self.use_flexible_linear = use_flexible_linear if not use_flexible_linear: self.linear = nn.Linear(input_dim, output_dim, bias=False) else: self.linear = MoshiFlexibleLinear(input_dim, output_dim, num_layers=num_codebooks) def forward(self, x, layer_idx=None): if self.use_flexible_linear: return self.linear(x, layer_idx) else: return self.linear(x) # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Moshi
MoshiLinear
python
ray-project__ray
rllib/examples/algorithms/dqn/benchmark_dqn_atari_rllib_preprocessing.py
{ "start": 9677, "end": 13474 }
class ____(Stopper): def __init__(self, benchmark_envs): self.benchmark_envs = benchmark_envs def __call__(self, trial_id, result): # Stop training if the mean reward is reached. if ( result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= self.benchmark_envs[result["env"]][ f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" ] ): return True # Otherwise check, if the total number of timesteps is exceeded. elif ( result[f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}"] >= self.benchmark_envs[result["env"]][f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}"] ): return True # Otherwise continue training. else: return False # Note, this needs to implemented b/c the parent class is abstract. def stop_all(self): return False # See Table 1 in the Rainbow paper for the hyperparameters. config = ( DQNConfig() .environment( env=tune.grid_search(list(benchmark_envs.keys())), env_config={ # "sticky actions" but not according to Danijar's 100k configs. "repeat_action_probability": 0.0, # "full action space" but not according to Danijar's 100k configs. "full_action_space": False, # Already done by MaxAndSkip wrapper: "action repeat" == 4. "frameskip": 1, # NOTE, because we use the atari wrapper of RLlib, we also have # framestack: 4, # dim: 84, # NOTE, we do not use grayscale here, so this run will need # more memory on GPU and CPU (buffer). }, clip_rewards=True, ) .env_runners( # Every 4 agent steps a training update is performed. rollout_fragment_length=4, num_env_runners=1, ) .learners( # We have a train/sample ratio of 1:1 and a batch of 32. num_learners=1, num_gpus_per_learner=1, ) # TODO (simon): Adjust to new model_config_dict. .training( # Note, the paper uses also an Adam epsilon of 0.00015. lr=0.0000625, n_step=1, tau=1.0, # TODO (simon): Activate when new model_config_dict is available. # epsilon=0.01, train_batch_size=32, target_network_update_freq=8000, replay_buffer_config={ "type": "PrioritizedEpisodeReplayBuffer", "capacity": 1000000, "alpha": 0.5, # Note the paper used a linear schedule for beta. "beta": 0.4, }, # Note, these are frames. num_steps_sampled_before_learning_starts=20000, noisy=True, num_atoms=51, v_min=-10.0, v_max=10.0, double_q=True, dueling=True, model={ "cnn_filter_specifiers": [[32, 8, 4], [64, 4, 2], [64, 3, 1]], "fcnet_activation": "tanh", "post_fcnet_hiddens": [512], "post_fcnet_activation": "relu", "post_fcnet_weights_initializer": "orthogonal_", "post_fcnet_weights_initializer_config": {"gain": 0.01}, }, ) .reporting( metrics_num_episodes_for_smoothing=10, min_sample_timesteps_per_iteration=1000, ) .evaluation( evaluation_duration="auto", evaluation_interval=1, evaluation_num_env_runners=1, evaluation_parallel_to_training=True, evaluation_config={ "explore": False, }, ) ) tuner = tune.Tuner( "DQN", param_space=config, run_config=tune.RunConfig( stop=BenchmarkStopper(benchmark_envs=benchmark_envs), name="benchmark_dqn_atari_rllib_preprocessing", ), ) tuner.fit()
BenchmarkStopper
python
numba__numba
numba/core/typing/mathdecl.py
{ "start": 4310, "end": 4488 }
class ____(ConcreteTemplate): cases = [ signature(types.float64, types.float64, types.intc), signature(types.float32, types.float32, types.intc), ]
Math_ldexp
python
pypa__warehouse
warehouse/manage/views/organizations.py
{ "start": 4802, "end": 9349 }
class ____: def __init__(self, request): self.request = request self.user_service = request.find_service(IUserService, context=None) self.organization_service = request.find_service( IOrganizationService, context=None ) @property def default_response(self): all_user_organizations = user_organizations(self.request) # Get list of applications for Organizations organization_applications = self.request.user.organization_applications # Get list of invites as (organization, token) tuples. organization_invites = ( self.organization_service.get_organization_invites_by_user( self.request.user.id ) ) organization_invites = [ (organization_invite.organization, organization_invite.token) for organization_invite in organization_invites ] # Get list of organizations that are approved (True) or pending (None). organizations = self.organization_service.get_organizations_by_user( self.request.user.id ) return { "organization_invites": organization_invites, "organization_applications": organization_applications, "organizations": organizations, "organizations_managed": list( organization.name for organization in all_user_organizations["organizations_managed"] ), "organizations_owned": list( organization.name for organization in all_user_organizations["organizations_owned"] ), "organizations_billing": list( organization.name for organization in all_user_organizations["organizations_billing"] ), "create_organization_application_form": ( CreateOrganizationApplicationForm( organization_service=self.organization_service, user=self.request.user, ) if len( [ app for app in self.request.user.organization_applications if app.status not in ( OrganizationApplicationStatus.Approved, OrganizationApplicationStatus.Declined, ) ] ) < self.request.registry.settings[ "warehouse.organizations.max_undecided_organization_applications" ] else None ), } @view_config(request_method="GET") def manage_organizations(self): # Organizations must be enabled. if not self.request.organization_access: raise HTTPNotFound() return self.default_response @view_config( request_method="POST", request_param=CreateOrganizationApplicationForm.__params__, ) def create_organization_application(self): # Organizations must be enabled. if not self.request.organization_access: raise HTTPNotFound() form = CreateOrganizationApplicationForm( self.request.POST, organization_service=self.organization_service, user=self.request.user, max_apps=self.request.registry.settings[ "warehouse.organizations.max_undecided_organization_applications" ], ) if form.validate(): data = form.data organization = self.organization_service.add_organization_application( **data, submitted_by=self.request.user ) send_new_organization_requested_email( self.request, self.request.user, organization_name=organization.name ) self.request.session.flash( "Request for new organization submitted", queue="success" ) else: return {"create_organization_application_form": form} return HTTPSeeOther(self.request.path) @view_defaults( route_name="manage.organizations.application", context=OrganizationApplication, renderer="warehouse:templates/manage/organization/application.html", uses_session=True, require_csrf=True, require_methods=False, permission=Permissions.OrganizationApplicationsManage, has_translations=True, )
ManageOrganizationsViews
python
realpython__materials
python-guitar-synthesizer/source_code_final/src/digitar/instrument.py
{ "start": 228, "end": 470 }
class ____: pitch: Pitch def press_fret(self, fret_number: int | None = None) -> Pitch: if fret_number is None: return self.pitch return self.pitch.adjust(fret_number) @dataclass(frozen=True)
VibratingString
python
getsentry__sentry
src/sentry/utils/cursors.py
{ "start": 1836, "end": 2216 }
class ____(Cursor): @classmethod def from_string(cls, cursor_str: str) -> StringCursor: bits = cursor_str.rsplit(":", 2) if len(bits) != 3: raise ValueError try: value = bits[0] return StringCursor(value, int(bits[1]), int(bits[2])) except (TypeError, ValueError): raise ValueError
StringCursor
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_legacy_tests.py
{ "start": 53340, "end": 54423 }
class ____(TestCase): class Schema: plugins = c.Plugins(default=[]) hooks = c.Hooks('plugins') @tempdir() def test_hooks(self, src_dir): write_file( b'def on_page_markdown(markdown, **kwargs): return markdown.replace("f", "z")', os.path.join(src_dir, 'hooks', 'my_hook.py'), ) write_file( b'foo foo', os.path.join(src_dir, 'docs', 'index.md'), ) conf = self.get_config( self.Schema, {'hooks': ['hooks/my_hook.py']}, config_file_path=os.path.join(src_dir, 'mkdocs.yml'), ) self.assertIn('hooks/my_hook.py', conf['plugins']) hook = conf['plugins']['hooks/my_hook.py'] self.assertTrue(hasattr(hook, 'on_page_markdown')) self.assertEqual( {**conf['plugins'].events, 'page_markdown': [hook.on_page_markdown]}, conf['plugins'].events, ) self.assertEqual(hook.on_page_markdown('foo foo'), 'zoo zoo') self.assertFalse(hasattr(hook, 'on_nav'))
HooksTest
python
ray-project__ray
python/ray/train/v2/jax/config.py
{ "start": 3055, "end": 5116 }
class ____(Backend): def on_start(self, worker_group: WorkerGroup, backend_config: JaxConfig): if not backend_config.use_tpu and not backend_config.use_gpu: return master_addr, master_port = worker_group.execute_single(0, get_address_and_port) master_addr_with_port = f"{master_addr}:{master_port}" # Set up JAX distributed environment on all workers setup_futures = [] for i in range(len(worker_group)): setup_futures.append( worker_group.execute_single_async( i, _setup_jax_distributed_environment, master_addr_with_port=master_addr_with_port, num_workers=len(worker_group), index=i, use_tpu=backend_config.use_tpu, use_gpu=backend_config.use_gpu, resources_per_worker=worker_group.get_resources_per_worker(), ) ) ray.get(setup_futures) def on_shutdown(self, worker_group: WorkerGroup, backend_config: JaxConfig): """Cleanup JAX distributed resources when shutting down worker group.""" if not backend_config.use_tpu and not backend_config.use_gpu: return # Shutdown JAX distributed on all workers shutdown_futures = worker_group.execute_async(_shutdown_jax_distributed) timeout_s = ray_constants.env_integer( JAX_DISTRIBUTED_SHUTDOWN_TIMEOUT_S, DEFAULT_JAX_DISTRIBUTED_SHUTDOWN_TIMEOUT_S, ) try: ray.get(shutdown_futures, timeout=timeout_s) logger.debug("JAX distributed shutdown completed") except ray.exceptions.GetTimeoutError: logger.warning( f"JAX distributed shutdown timed out after {timeout_s} seconds. " "This may indicate workers are hung or unresponsive." ) except Exception as e: logger.warning(f"Error during JAX distributed shutdown: {e}")
_JaxBackend
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI041_1.py
{ "start": 1728, "end": 2137 }
class ____: def f1(self, arg: None | int | None | float = None) -> None: # PYI041 - no fix pass if TYPE_CHECKING: def f2(self, arg: None | int | None | float = None) -> None: ... # PYI041 - with fix else: def f2(self, arg=None) -> None: pass def f3(self, arg: None | float | None | int | None = None) -> None: # PYI041 - with fix pass
Issue18298
python
tensorflow__tensorflow
tensorflow/python/framework/constant_op.py
{ "start": 15906, "end": 16678 }
class ____: """Codec for Numpy.""" def can_encode(self, pyobj): return isinstance(pyobj, np.ndarray) def do_encode(self, numpy_value, encode_fn): """Returns an encoded `TensorProto` for `np.ndarray`.""" del encode_fn encoded_numpy = struct_pb2.StructuredValue() encoded_numpy.numpy_value.CopyFrom( tensor_util.make_tensor_proto(numpy_value) ) return encoded_numpy def can_decode(self, value): return value.HasField("numpy_value") def do_decode(self, value, decode_fn): """Returns the `np.ndarray` encoded by the proto `value`.""" del decode_fn tensor_proto = value.numpy_value numpy = tensor_util.MakeNdarray(tensor_proto) return numpy nested_structure_coder.register_codec(_NumpyCodec())
_NumpyCodec
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/neptune.py
{ "start": 4227, "end": 5868 }
class ____(AwsBaseWaiterTrigger): """ Triggers when a Neptune Cluster Instance is available. :param db_cluster_id: Cluster ID to wait on instances from :param waiter_delay: The amount of time in seconds to wait between attempts. :param waiter_max_attempts: The maximum number of attempts to be made. :param aws_conn_id: The Airflow connection used for AWS credentials. :param region_name: AWS region name (example: us-east-1) """ def __init__( self, *, db_cluster_id: str, waiter_delay: int = 30, waiter_max_attempts: int = 60, aws_conn_id: str | None = None, region_name: str | None = None, **kwargs, ) -> None: super().__init__( serialized_fields={"db_cluster_id": db_cluster_id}, waiter_name="db_instance_available", waiter_args={"Filters": [{"Name": "db-cluster-id", "Values": [db_cluster_id]}]}, failure_message="Failed to start Neptune instances", status_message="Status of Neptune instances are", status_queries=["DBInstances[].Status"], return_key="db_cluster_id", return_value=db_cluster_id, waiter_delay=waiter_delay, waiter_max_attempts=waiter_max_attempts, aws_conn_id=aws_conn_id, **kwargs, ) def hook(self) -> AwsGenericHook: return NeptuneHook( aws_conn_id=self.aws_conn_id, region_name=self.region_name, verify=self.verify, config=self.botocore_config, )
NeptuneClusterInstancesAvailableTrigger
python
ethereum__web3.py
web3/_utils/filters.py
{ "start": 3452, "end": 4683 }
class ____: callbacks: list[Callable[..., Any]] = None stopped = False poll_interval = None filter_id = None def __init__(self, filter_id: HexStr) -> None: self.filter_id = filter_id self.callbacks = [] super().__init__() def __str__(self) -> str: return f"Filter for {self.filter_id}" def format_entry(self, entry: LogReceipt) -> LogReceipt: """ Hook for subclasses to change the format of the value that is passed into the callback functions. """ return entry def is_valid_entry(self, entry: LogReceipt) -> bool: """ Hook for subclasses to implement additional filtering layers. """ return True def _filter_valid_entries( self, entries: Collection[LogReceipt] ) -> Iterator[LogReceipt]: return filter(self.is_valid_entry, entries) def _format_log_entries( self, log_entries: Iterator[LogReceipt] | None = None ) -> list[LogReceipt]: if log_entries is None: return [] formatted_log_entries = [ self.format_entry(log_entry) for log_entry in log_entries ] return formatted_log_entries
BaseFilter
python
imageio__imageio
imageio/plugins/ffmpeg.py
{ "start": 7407, "end": 26979 }
class ____(Format): """Read/Write ImageResources using FFMPEG. See :mod:`imageio.plugins.ffmpeg` """ def _can_read(self, request): # Read from video stream? # Note that we could write the _video flag here, but a user might # select this format explicitly (and this code is not run) if re.match(r"<video(\d+)>", request.filename): return True # Read from file that we know? if request.extension in self.extensions: return True def _can_write(self, request): if request.extension in self.extensions: return True # -- class Reader(Format.Reader): _frame_catcher = None _read_gen = None def _get_cam_inputname(self, index): if sys.platform.startswith("linux"): return "/dev/" + self.request._video[1:-1] elif sys.platform.startswith("win"): # Ask ffmpeg for list of dshow device names ffmpeg_api = imageio_ffmpeg cmd = [ ffmpeg_api.get_ffmpeg_exe(), "-list_devices", "true", "-f", CAM_FORMAT, "-i", "dummy", ] # Set `shell=True` in sp.run to prevent popup of a command # line window in frozen applications. Note: this would be a # security vulnerability if user-input goes into the cmd. # Note that the ffmpeg process returns with exit code 1 when # using `-list_devices` (or `-list_options`), even if the # command is successful, so we set `check=False` explicitly. completed_process = sp.run( cmd, stdout=sp.PIPE, stderr=sp.PIPE, encoding="utf-8", shell=True, check=False, ) # Return device name at index try: name = parse_device_names(completed_process.stderr)[index] except IndexError: raise IndexError("No ffdshow camera at index %i." % index) return "video=%s" % name elif sys.platform.startswith("darwin"): # Appears that newer ffmpeg builds don't support -list-devices # on OS X. But you can directly open the camera by index. name = str(index) return name else: # pragma: no cover return "??" def _open( self, loop=False, size=None, dtype=None, pixelformat=None, print_info=False, ffmpeg_params=None, input_params=None, output_params=None, fps=None, ): # Get generator functions self._ffmpeg_api = imageio_ffmpeg # Process input args self._arg_loop = bool(loop) if size is None: self._arg_size = None elif isinstance(size, tuple): self._arg_size = "%ix%i" % size elif isinstance(size, str) and "x" in size: self._arg_size = size else: raise ValueError('FFMPEG size must be tuple of "NxM"') if pixelformat is None: pass elif not isinstance(pixelformat, str): raise ValueError("FFMPEG pixelformat must be str") if dtype is None: self._dtype = np.dtype("uint8") else: self._dtype = np.dtype(dtype) allowed_dtypes = ["uint8", "uint16"] if self._dtype.name not in allowed_dtypes: raise ValueError( "dtype must be one of: {}".format(", ".join(allowed_dtypes)) ) self._arg_pixelformat = pixelformat self._arg_input_params = input_params or [] self._arg_output_params = output_params or [] self._arg_input_params += ffmpeg_params or [] # backward compat # Write "_video"_arg - indicating webcam support self.request._video = None regex_match = re.match(r"<video(\d+)>", self.request.filename) if regex_match: self.request._video = self.request.filename # Get local filename if self.request._video: index = int(regex_match.group(1)) self._filename = self._get_cam_inputname(index) else: self._filename = self.request.get_local_filename() # When passed to imageio-ffmpeg (<0.4.2) on command line, carets need to be escaped. if get_version() < (0, 4, 2): self._filename = self._filename.replace("^", "^^") # Determine pixel format and depth self._depth = 3 if self._dtype.name == "uint8": self._pix_fmt = "rgb24" self._bytes_per_channel = 1 else: self._pix_fmt = "rgb48le" self._bytes_per_channel = 2 # Initialize parameters self._pos = -1 self._meta = {"plugin": "ffmpeg"} self._lastread = None # Calculating this from fps and duration is not accurate, # and calculating it exactly with ffmpeg_api.count_frames_and_secs # takes too long to do for each video. But we need it for looping. self._nframes = float("inf") if self._arg_loop and not self.request._video: self._nframes = self.count_frames() self._meta["nframes"] = self._nframes # Specify input framerate? (only on macOS) # Ideally we'd get the supported framerate from the metadata, but we get the # metadata when we boot ffmpeg ... maybe we could refactor this so we can # get the metadata beforehand, but for now we'll just give it 2 tries on MacOS, # one with fps 30 and one with fps 15. need_input_fps = need_output_fps = False if self.request._video and platform.system().lower() == "darwin": if "-framerate" not in str(self._arg_input_params): need_input_fps = True if not self.request.kwargs.get("fps", None): need_output_fps = True if need_input_fps: self._arg_input_params.extend(["-framerate", str(float(30))]) if need_output_fps: self._arg_output_params.extend(["-r", str(float(30))]) # Start ffmpeg subprocess and get meta information try: self._initialize() except IndexError: # Specify input framerate again, this time different. if need_input_fps: self._arg_input_params[-1] = str(float(15)) self._initialize() else: raise # For cameras, create thread that keeps reading the images if self.request._video: self._frame_catcher = FrameCatcher(self._read_gen) # For reference - but disabled, because it is inaccurate # if self._meta["nframes"] == float("inf"): # if self._meta.get("fps", 0) > 0: # if self._meta.get("duration", 0) > 0: # n = round(self._meta["duration"] * self._meta["fps"]) # self._meta["nframes"] = int(n) def _close(self): # First close the frame catcher, because we cannot close the gen # if the frame catcher thread is using it if self._frame_catcher is not None: self._frame_catcher.stop_me() self._frame_catcher = None if self._read_gen is not None: self._read_gen.close() self._read_gen = None def count_frames(self): """Count the number of frames. Note that this can take a few seconds for large files. Also note that it counts the number of frames in the original video and does not take a given fps into account. """ # This would have been nice, but this does not work :( # oargs = [] # if self.request.kwargs.get("fps", None): # fps = float(self.request.kwargs["fps"]) # oargs += ["-r", "%.02f" % fps] cf = self._ffmpeg_api.count_frames_and_secs return cf(self._filename)[0] def _get_length(self): return self._nframes # only not inf if loop is True def _get_data(self, index): """Reads a frame at index. Note for coders: getting an arbitrary frame in the video with ffmpeg can be painfully slow if some decoding has to be done. This function tries to avoid fectching arbitrary frames whenever possible, by moving between adjacent frames.""" # Modulo index (for looping) if self._arg_loop and self._nframes < float("inf"): index %= self._nframes if index == self._pos: return self._lastread, dict(new=False) elif index < 0: raise IndexError("Frame index must be >= 0") elif index >= self._nframes: raise IndexError("Reached end of video") else: if (index < self._pos) or (index > self._pos + 100): self._initialize(index) else: self._skip_frames(index - self._pos - 1) result, is_new = self._read_frame() self._pos = index return result, dict(new=is_new) def _get_meta_data(self, index): return self._meta def _initialize(self, index=0): # Close the current generator, and thereby terminate its subprocess if self._read_gen is not None: self._read_gen.close() iargs = [] oargs = [] # Create input args iargs += self._arg_input_params if self.request._video: iargs += ["-f", CAM_FORMAT] if self._arg_pixelformat: iargs += ["-pix_fmt", self._arg_pixelformat] if self._arg_size: iargs += ["-s", self._arg_size] elif index > 0: # re-initialize / seek # Note: only works if we initialized earlier, and now have meta # Some info here: https://trac.ffmpeg.org/wiki/Seeking # There are two ways to seek, one before -i (input_params) and # after (output_params). The former is fast, because it uses # keyframes, the latter is slow but accurate. According to # the article above, the fast method should also be accurate # from ffmpeg version 2.1, however in version 4.1 our tests # start failing again. Not sure why, but we can solve this # by combining slow and fast. Seek the long stretch using # the fast method, and seek the last 10s the slow way. starttime = index / self._meta["fps"] seek_slow = min(10, starttime) seek_fast = starttime - seek_slow # We used to have this epsilon earlier, when we did not use # the slow seek. I don't think we need it anymore. # epsilon = -1 / self._meta["fps"] * 0.1 iargs += ["-ss", "%.06f" % (seek_fast)] oargs += ["-ss", "%.06f" % (seek_slow)] # Output args, for writing to pipe if self._arg_size: oargs += ["-s", self._arg_size] if self.request.kwargs.get("fps", None): fps = float(self.request.kwargs["fps"]) oargs += ["-r", "%.02f" % fps] oargs += self._arg_output_params # Get pixelformat and bytes per pixel pix_fmt = self._pix_fmt bpp = self._depth * self._bytes_per_channel # Create generator rf = self._ffmpeg_api.read_frames self._read_gen = rf( self._filename, pix_fmt, bpp, input_params=iargs, output_params=oargs ) # Read meta data. This start the generator (and ffmpeg subprocess) if self.request._video: # With cameras, catch error and turn into IndexError try: meta = self._read_gen.__next__() except IOError as err: err_text = str(err) if "darwin" in sys.platform: if "Unknown input format: 'avfoundation'" in err_text: err_text += ( "Try installing FFMPEG using " "home brew to get a version with " "support for cameras." ) raise IndexError( "No (working) camera at {}.\n\n{}".format( self.request._video, err_text ) ) else: self._meta.update(meta) elif index == 0: self._meta.update(self._read_gen.__next__()) else: self._read_gen.__next__() # we already have meta data def _skip_frames(self, n=1): """Reads and throws away n frames""" for i in range(n): self._read_gen.__next__() self._pos += n def _read_frame(self): # Read and convert to numpy array w, h = self._meta["size"] framesize = w * h * self._depth * self._bytes_per_channel # t0 = time.time() # Read frame if self._frame_catcher: # pragma: no cover - camera thing s, is_new = self._frame_catcher.get_frame() else: s = self._read_gen.__next__() is_new = True # Check if len(s) != framesize: raise RuntimeError( "Frame is %i bytes, but expected %i." % (len(s), framesize) ) result = np.frombuffer(s, dtype=self._dtype).copy() result = result.reshape((h, w, self._depth)) # t1 = time.time() # print('etime', t1-t0) # Store and return self._lastread = result return result, is_new # -- class Writer(Format.Writer): _write_gen = None def _open( self, fps=10, codec="libx264", bitrate=None, pixelformat="yuv420p", ffmpeg_params=None, input_params=None, output_params=None, ffmpeg_log_level="quiet", quality=5, macro_block_size=16, audio_path=None, audio_codec=None, ): self._ffmpeg_api = imageio_ffmpeg self._filename = self.request.get_local_filename() self._pix_fmt = None self._depth = None self._size = None def _close(self): if self._write_gen is not None: self._write_gen.close() self._write_gen = None def _append_data(self, im, meta): # Get props of image h, w = im.shape[:2] size = w, h depth = 1 if im.ndim == 2 else im.shape[2] # Ensure that image is in uint8 im = image_as_uint(im, bitdepth=8) # To be written efficiently, ie. without creating an immutable # buffer, by calling im.tobytes() the array must be contiguous. if not im.flags.c_contiguous: # checkign the flag is a micro optimization. # the image will be a numpy subclass. See discussion # https://github.com/numpy/numpy/issues/11804 im = np.ascontiguousarray(im) # Set size and initialize if not initialized yet if self._size is None: map = {1: "gray", 2: "gray8a", 3: "rgb24", 4: "rgba"} self._pix_fmt = map.get(depth, None) if self._pix_fmt is None: raise ValueError("Image must have 1, 2, 3 or 4 channels") self._size = size self._depth = depth self._initialize() # Check size of image if size != self._size: raise ValueError("All images in a movie should have same size") if depth != self._depth: raise ValueError( "All images in a movie should have same " "number of channels" ) assert self._write_gen is not None # Check status # Write. Yes, we can send the data in as a numpy array self._write_gen.send(im) def set_meta_data(self, meta): raise RuntimeError( "The ffmpeg format does not support setting " "meta data." ) def _initialize(self): # Close existing generator if self._write_gen is not None: self._write_gen.close() # Get parameters # Use None to let imageio-ffmpeg (or ffmpeg) select good results fps = self.request.kwargs.get("fps", 10) codec = self.request.kwargs.get("codec", None) bitrate = self.request.kwargs.get("bitrate", None) quality = self.request.kwargs.get("quality", None) input_params = self.request.kwargs.get("input_params") or [] output_params = self.request.kwargs.get("output_params") or [] output_params += self.request.kwargs.get("ffmpeg_params") or [] pixelformat = self.request.kwargs.get("pixelformat", None) macro_block_size = self.request.kwargs.get("macro_block_size", 16) ffmpeg_log_level = self.request.kwargs.get("ffmpeg_log_level", None) audio_path = self.request.kwargs.get("audio_path", None) audio_codec = self.request.kwargs.get("audio_codec", None) macro_block_size = macro_block_size or 1 # None -> 1 # Create generator self._write_gen = self._ffmpeg_api.write_frames( self._filename, self._size, pix_fmt_in=self._pix_fmt, pix_fmt_out=pixelformat, fps=fps, quality=quality, bitrate=bitrate, codec=codec, macro_block_size=macro_block_size, ffmpeg_log_level=ffmpeg_log_level, input_params=input_params, output_params=output_params, audio_path=audio_path, audio_codec=audio_codec, ) # Seed the generator (this is where the ffmpeg subprocess starts) self._write_gen.send(None)
FfmpegFormat
python
numpy__numpy
numpy/_core/tests/test_cpu_features.py
{ "start": 3923, "end": 11628 }
class ____: cwd = pathlib.Path(__file__).parent.resolve() env = os.environ.copy() _enable = os.environ.pop('NPY_ENABLE_CPU_FEATURES', None) _disable = os.environ.pop('NPY_DISABLE_CPU_FEATURES', None) SUBPROCESS_ARGS = {"cwd": cwd, "capture_output": True, "text": True, "check": True} unavailable_feats = [ feat for feat in __cpu_dispatch__ if not __cpu_features__[feat] ] UNAVAILABLE_FEAT = ( None if len(unavailable_feats) == 0 else unavailable_feats[0] ) BASELINE_FEAT = None if len(__cpu_baseline__) == 0 else __cpu_baseline__[0] SCRIPT = """ def main(): from numpy._core._multiarray_umath import ( __cpu_features__, __cpu_dispatch__ ) detected = [feat for feat in __cpu_dispatch__ if __cpu_features__[feat]] print(detected) if __name__ == "__main__": main() """ @pytest.fixture(autouse=True) def setup_class(self, tmp_path_factory): file = tmp_path_factory.mktemp("runtime_test_script") file /= "_runtime_detect.py" file.write_text(self.SCRIPT) self.file = file def _run(self): return subprocess.run( [sys.executable, self.file], env=self.env, **self.SUBPROCESS_ARGS, ) # Helper function mimicking pytest.raises for subprocess call def _expect_error( self, msg, err_type, no_error_msg="Failed to generate error" ): try: self._run() except subprocess.CalledProcessError as e: assertion_message = f"Expected: {msg}\nGot: {e.stderr}" assert re.search(msg, e.stderr), assertion_message assertion_message = ( f"Expected error of type: {err_type}; see full " f"error:\n{e.stderr}" ) assert re.search(err_type, e.stderr), assertion_message else: assert False, no_error_msg def setup_method(self): """Ensure that the environment is reset""" self.env = os.environ.copy() def test_runtime_feature_selection(self): """ Ensure that when selecting `NPY_ENABLE_CPU_FEATURES`, only the features exactly specified are dispatched. """ # Capture runtime-enabled features out = self._run() non_baseline_features = _text_to_list(out.stdout) if non_baseline_features is None: pytest.skip( "No dispatchable features outside of baseline detected." ) feature = non_baseline_features[0] # Capture runtime-enabled features when `NPY_ENABLE_CPU_FEATURES` is # specified self.env['NPY_ENABLE_CPU_FEATURES'] = feature out = self._run() enabled_features = _text_to_list(out.stdout) # Ensure that only one feature is enabled, and it is exactly the one # specified by `NPY_ENABLE_CPU_FEATURES` assert set(enabled_features) == {feature} if len(non_baseline_features) < 2: pytest.skip("Only one non-baseline feature detected.") # Capture runtime-enabled features when `NPY_ENABLE_CPU_FEATURES` is # specified self.env['NPY_ENABLE_CPU_FEATURES'] = ",".join(non_baseline_features) out = self._run() enabled_features = _text_to_list(out.stdout) # Ensure that both features are enabled, and they are exactly the ones # specified by `NPY_ENABLE_CPU_FEATURES` assert set(enabled_features) == set(non_baseline_features) @pytest.mark.parametrize("enabled, disabled", [ ("feature", "feature"), ("feature", "same"), ]) def test_both_enable_disable_set(self, enabled, disabled): """ Ensure that when both environment variables are set then an ImportError is thrown """ self.env['NPY_ENABLE_CPU_FEATURES'] = enabled self.env['NPY_DISABLE_CPU_FEATURES'] = disabled msg = "Both NPY_DISABLE_CPU_FEATURES and NPY_ENABLE_CPU_FEATURES" err_type = "ImportError" self._expect_error(msg, err_type) @pytest.mark.skipif( not __cpu_dispatch__, reason=( "NPY_*_CPU_FEATURES only parsed if " "`__cpu_dispatch__` is non-empty" ) ) @pytest.mark.parametrize("action", ["ENABLE", "DISABLE"]) def test_variable_too_long(self, action): """ Test that an error is thrown if the environment variables are too long to be processed. Current limit is 1024, but this may change later. """ MAX_VAR_LENGTH = 1024 # Actual length is MAX_VAR_LENGTH + 1 due to null-termination self.env[f'NPY_{action}_CPU_FEATURES'] = "t" * MAX_VAR_LENGTH msg = ( f"Length of environment variable 'NPY_{action}_CPU_FEATURES' is " f"{MAX_VAR_LENGTH + 1}, only {MAX_VAR_LENGTH} accepted" ) err_type = "RuntimeError" self._expect_error(msg, err_type) @pytest.mark.skipif( not __cpu_dispatch__, reason=( "NPY_*_CPU_FEATURES only parsed if " "`__cpu_dispatch__` is non-empty" ) ) def test_impossible_feature_disable(self): """ Test that a RuntimeError is thrown if an impossible feature-disabling request is made. This includes disabling a baseline feature. """ if self.BASELINE_FEAT is None: pytest.skip("There are no unavailable features to test with") bad_feature = self.BASELINE_FEAT self.env['NPY_DISABLE_CPU_FEATURES'] = bad_feature msg = ( f"You cannot disable CPU feature '{bad_feature}', since it is " "part of the baseline optimizations" ) err_type = "RuntimeError" self._expect_error(msg, err_type) def test_impossible_feature_enable(self): """ Test that a RuntimeError is thrown if an impossible feature-enabling request is made. This includes enabling a feature not supported by the machine, or disabling a baseline optimization. """ if self.UNAVAILABLE_FEAT is None: pytest.skip("There are no unavailable features to test with") bad_feature = self.UNAVAILABLE_FEAT self.env['NPY_ENABLE_CPU_FEATURES'] = bad_feature msg = ( f"You cannot enable CPU features \\({bad_feature}\\), since " "they are not supported by your machine." ) err_type = "RuntimeError" self._expect_error(msg, err_type) # Ensure that it fails even when providing garbage in addition feats = f"{bad_feature}, Foobar" self.env['NPY_ENABLE_CPU_FEATURES'] = feats msg = ( f"You cannot enable CPU features \\({bad_feature}\\), since they " "are not supported by your machine." ) self._expect_error(msg, err_type) if self.BASELINE_FEAT is not None: # Ensure that only the bad feature gets reported feats = f"{bad_feature}, {self.BASELINE_FEAT}" self.env['NPY_ENABLE_CPU_FEATURES'] = feats msg = ( f"You cannot enable CPU features \\({bad_feature}\\), since " "they are not supported by your machine." ) self._expect_error(msg, err_type) is_linux = sys.platform.startswith('linux') is_cygwin = sys.platform.startswith('cygwin') machine = platform.machine() is_x86 = re.match(r"^(amd64|x86|i386|i686)", machine, re.IGNORECASE) @pytest.mark.skipif( not (is_linux or is_cygwin) or not is_x86, reason="Only for Linux and x86" )
TestEnvPrivation
python
mlflow__mlflow
mlflow/gateway/app.py
{ "start": 7308, "end": 7359 }
class ____(BaseModel): status: str
HealthResponse
python
viewflow__viewflow
tests/fsm/test_fsm__basics.py
{ "start": 425, "end": 944 }
class ____(object): # noqa:D100 state = fsm.State(ReviewState, default=ReviewState.NEW) def __init__(self, text): self.text = text @state.transition(source=ReviewState.NEW, target=ReviewState.PUBLISHED) def publish(self): pass @state.transition(source=fsm.State.ANY, target=ReviewState.REMOVED) def remove(self): pass @state.transition(source=ReviewState.PUBLISHED, target=ReviewState.HIDDEN) def hide(self): pass # REST # Admin # Viewset
Publication
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0078_add_external_builds_privacy_level_field.py
{ "start": 185, "end": 1311 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0077_remote_repository_data_migration"), ] operations = [ migrations.AddField( model_name="project", name="external_builds_privacy_level", field=models.CharField( choices=[("public", "Public"), ("private", "Private")], default=readthedocs.projects.models.default_privacy_level, help_text="Should builds from pull requests be public?", max_length=20, null=True, verbose_name="Privacy level of Pull Requests", ), ), migrations.AlterField( model_name="project", name="external_builds_enabled", field=models.BooleanField( default=False, help_text='More information in <a href="https://docs.readthedocs.io/page/guides/autobuild-docs-for-pull-requests.html">our docs</a>', verbose_name="Build pull requests for this project", ), ), ]
Migration
python
jazzband__django-polymorphic
example/pexp/admin.py
{ "start": 843, "end": 990 }
class ____(PolymorphicParentModelAdmin): list_filter = (PolymorphicChildModelFilter,) child_models = (UUIDModelA, UUIDModelB)
UUIDModelAAdmin
python
vyperlang__vyper
vyper/abi_types.py
{ "start": 5133, "end": 5217 }
class ____(ABI_Bytes): def selector_name(self): return "string"
ABI_String
python
PrefectHQ__prefect
tests/test_logging.py
{ "start": 49617, "end": 53795 }
class ____: @pytest.fixture def handler(self): yield PrefectConsoleHandler() @pytest.fixture def logger(self, handler: PrefectConsoleHandler): logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(handler) yield logger logger.removeHandler(handler) def test_init_defaults(self): handler = PrefectConsoleHandler() console = handler.console assert isinstance(console, Console) assert isinstance(console.highlighter, PrefectConsoleHighlighter) assert console._theme_stack._entries == [{}] # inherit=False assert handler.level == logging.NOTSET def test_init_styled_console_disabled(self): with temporary_settings({PREFECT_LOGGING_COLORS: False}): handler = PrefectConsoleHandler() console = handler.console assert isinstance(console, Console) assert isinstance(console.highlighter, NullHighlighter) assert console._theme_stack._entries == [{}] assert handler.level == logging.NOTSET def test_init_override_kwargs(self): handler = PrefectConsoleHandler( highlighter=ReprHighlighter, styles={"number": "red"}, level=logging.DEBUG ) console = handler.console assert isinstance(console, Console) assert isinstance(console.highlighter, ReprHighlighter) assert console._theme_stack._entries == [ {"number": Style(color=Color("red", ColorType.STANDARD, number=1))} ] assert handler.level == logging.DEBUG def test_uses_stderr_by_default(self, capsys: pytest.CaptureFixture[str]): logger = get_logger(uuid.uuid4().hex) logger.handlers = [PrefectConsoleHandler()] logger.info("Test!") stdout, stderr = capsys.readouterr() assert stdout == "" assert "Test!" in stderr def test_respects_given_stream(self, capsys: pytest.CaptureFixture[str]): logger = get_logger(uuid.uuid4().hex) logger.handlers = [PrefectConsoleHandler(stream=sys.stdout)] logger.info("Test!") stdout, stderr = capsys.readouterr() assert stderr == "" assert "Test!" in stdout def test_includes_tracebacks_during_exceptions( self, capsys: pytest.CaptureFixture[str] ): logger = get_logger(uuid.uuid4().hex) logger.handlers = [PrefectConsoleHandler()] try: raise ValueError("oh my") except Exception: logger.exception("Helpful context!") _, stderr = capsys.readouterr() assert "Helpful context!" in stderr assert "Traceback" in stderr assert 'raise ValueError("oh my")' in stderr assert "ValueError: oh my" in stderr def test_does_not_word_wrap_or_crop_messages( self, capsys: pytest.CaptureFixture[str] ): logger = get_logger(uuid.uuid4().hex) handler = PrefectConsoleHandler() logger.handlers = [handler] # Pretend we have a narrow little console with temporary_console_width(handler.console, 10): logger.info("x" * 1000) _, stderr = capsys.readouterr() # There will be newlines in the middle if cropped assert "x" * 1000 in stderr def test_outputs_square_brackets_as_text(self, capsys: pytest.CaptureFixture[str]): logger = get_logger(uuid.uuid4().hex) handler = PrefectConsoleHandler() logger.handlers = [handler] msg = "DROP TABLE [dbo].[SomeTable];" logger.info(msg) _, stderr = capsys.readouterr() assert msg in stderr def test_outputs_square_brackets_as_style(self, capsys: pytest.CaptureFixture[str]): with temporary_settings({PREFECT_LOGGING_MARKUP: True}): logger = get_logger(uuid.uuid4().hex) handler = PrefectConsoleHandler() logger.handlers = [handler] msg = "this applies [red]style[/red]!;" logger.info(msg) _, stderr = capsys.readouterr() assert "this applies style" in stderr
TestPrefectConsoleHandler
python
sphinx-doc__sphinx
sphinx/util/tags.py
{ "start": 252, "end": 1257 }
class ____(jinja2.parser.Parser): """Only allow conditional expressions and binary operators.""" def parse_compare(self) -> jinja2.nodes.Expr: node: jinja2.nodes.Expr token = self.stream.current if token.type == 'name': if token.value in {'true', 'True'}: node = jinja2.nodes.Const(True, lineno=token.lineno) elif token.value in {'false', 'False'}: node = jinja2.nodes.Const(False, lineno=token.lineno) elif token.value in {'none', 'None'}: node = jinja2.nodes.Const(None, lineno=token.lineno) else: node = jinja2.nodes.Name(token.value, 'load', lineno=token.lineno) next(self.stream) elif token.type == 'lparen': next(self.stream) node = self.parse_expression() self.stream.expect('rparen') else: self.fail(f"unexpected token '{token}'", token.lineno) return node
BooleanParser
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/schedule_tests/test_business_logic.py
{ "start": 7411, "end": 13374 }
class ____: """Test the schedule formatting functions.""" def _create_sample_schedule_list(self): """Create sample DgApiScheduleList for testing.""" schedules = [ DgApiSchedule( id="schedule1-id", name="daily_job", status=DgApiScheduleStatus.RUNNING, cron_schedule="0 0 * * *", pipeline_name="daily_pipeline", description="Runs daily at midnight", execution_timezone="UTC", code_location_origin="main_location@main_repo", next_tick_timestamp=1705311000.0, # 2024-01-15T10:30:00Z ), DgApiSchedule( id="schedule2-id", name="hourly_job", status=DgApiScheduleStatus.STOPPED, cron_schedule="0 * * * *", pipeline_name="hourly_pipeline", description="Runs every hour", execution_timezone="America/New_York", code_location_origin="main_location@main_repo", next_tick_timestamp=None, ), DgApiSchedule( id="schedule3-id", name="minimal_schedule", status=DgApiScheduleStatus.RUNNING, cron_schedule="*/5 * * * *", pipeline_name="quick_job", description=None, execution_timezone=None, code_location_origin=None, next_tick_timestamp=None, ), ] return DgApiScheduleList(items=schedules, total=len(schedules)) def _create_empty_schedule_list(self): """Create empty DgApiScheduleList for testing.""" return DgApiScheduleList(items=[], total=0) def _create_single_schedule(self): """Create single DgApiSchedule for testing.""" return DgApiSchedule( id="single-schedule-id", name="critical_job", status=DgApiScheduleStatus.RUNNING, cron_schedule="0 0 * * *", pipeline_name="critical_pipeline", description="Critical production schedule", execution_timezone="UTC", code_location_origin="prod_location@prod_repo", next_tick_timestamp=1705311900.0, # 2024-01-15T10:45:00Z ) def test_format_schedules_text_output(self, snapshot): """Test formatting schedules as text.""" from dagster_shared.utils.timing import fixed_timezone schedule_list = self._create_sample_schedule_list() with fixed_timezone("UTC"): result = format_schedules(schedule_list, as_json=False) # Snapshot the entire text output snapshot.assert_match(result) def test_format_schedules_json_output(self, snapshot): """Test formatting schedules as JSON.""" schedule_list = self._create_sample_schedule_list() result = format_schedules(schedule_list, as_json=True) # For JSON, we want to snapshot the parsed structure to avoid formatting differences parsed = json.loads(result) snapshot.assert_match(parsed) def test_format_empty_schedules_text_output(self, snapshot): """Test formatting empty schedule list as text.""" schedule_list = self._create_empty_schedule_list() result = format_schedules(schedule_list, as_json=False) snapshot.assert_match(result) def test_format_empty_schedules_json_output(self, snapshot): """Test formatting empty schedule list as JSON.""" schedule_list = self._create_empty_schedule_list() result = format_schedules(schedule_list, as_json=True) parsed = json.loads(result) snapshot.assert_match(parsed) def test_format_single_schedule_text_output(self, snapshot): """Test formatting single schedule as text.""" from dagster_shared.utils.timing import fixed_timezone schedule = self._create_single_schedule() with fixed_timezone("UTC"): result = format_schedule(schedule, as_json=False) # Snapshot the text output snapshot.assert_match(result) def test_format_single_schedule_json_output(self, snapshot): """Test formatting single schedule as JSON.""" schedule = self._create_single_schedule() result = format_schedule(schedule, as_json=True) # For JSON, we want to snapshot the parsed structure to avoid formatting differences parsed = json.loads(result) snapshot.assert_match(parsed) def test_format_minimal_schedule_text_output(self, snapshot): """Test formatting minimal schedule as text.""" from dagster_shared.utils.timing import fixed_timezone schedule = DgApiSchedule( id="minimal-id", name="minimal_schedule", status=DgApiScheduleStatus.STOPPED, cron_schedule="*/15 * * * *", pipeline_name="minimal_pipeline", description=None, execution_timezone=None, code_location_origin=None, next_tick_timestamp=None, ) with fixed_timezone("UTC"): result = format_schedule(schedule, as_json=False) snapshot.assert_match(result) def test_format_minimal_schedule_json_output(self, snapshot): """Test formatting minimal schedule as JSON.""" schedule = DgApiSchedule( id="minimal-id", name="minimal_schedule", status=DgApiScheduleStatus.STOPPED, cron_schedule="*/15 * * * *", pipeline_name="minimal_pipeline", description=None, execution_timezone=None, code_location_origin=None, next_tick_timestamp=None, ) result = format_schedule(schedule, as_json=True) parsed = json.loads(result) snapshot.assert_match(parsed)
TestFormatSchedules
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py
{ "start": 3234, "end": 3521 }
class ____(BaseTestSuite): def test_reload_location_real(self, graphql_client): assert ( graphql_client.reload_repository_location(main_repo_location_name()).status == ReloadRepositoryLocationStatus.SUCCESS )
TestReloadRepositoryLocationWithClient
python
plotly__plotly.py
_plotly_utils/basevalidators.py
{ "start": 51020, "end": 53076 }
class ____(BaseValidator): """ "angle": { "description": "A number (in degree) between -180 and 180.", "requiredOpts": [], "otherOpts": [ "dflt", "arrayOk" ] }, """ def __init__(self, plotly_name, parent_name, array_ok=False, **kwargs): super(AngleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, **kwargs ) self.array_ok = array_ok def description(self): desc = """\ The '{plotly_name}' property is a angle (in degrees) that may be specified as a number between -180 and 180{array_ok}. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). """.format( plotly_name=self.plotly_name, array_ok=( ", or a list, numpy array or other iterable thereof" if self.array_ok else "" ), ) return desc def validate_coerce(self, v): if is_none_or_typed_array_spec(v): pass elif self.array_ok and is_homogeneous_array(v): try: v_array = copy_to_readonly_numpy_array(v, force_numeric=True) except (ValueError, TypeError, OverflowError): self.raise_invalid_val(v) v = v_array # Always numeric numpy array # Normalize v onto the interval [-180, 180) v = (v + 180) % 360 - 180 elif self.array_ok and is_simple_array(v): # Check numeric invalid_els = [e for e in v if not isinstance(e, numbers.Number)] if invalid_els: self.raise_invalid_elements(invalid_els[:10]) v = [(x + 180) % 360 - 180 for x in to_scalar_or_list(v)] elif not isinstance(v, numbers.Number): self.raise_invalid_val(v) else: # Normalize v onto the interval [-180, 180) v = (v + 180) % 360 - 180 return v
AngleValidator
python
matplotlib__matplotlib
lib/matplotlib/_api/deprecation.py
{ "start": 376, "end": 8223 }
class ____(DeprecationWarning): """A class for issuing deprecation warnings for Matplotlib users.""" def _generate_deprecation_warning( since, message='', name='', alternative='', pending=False, obj_type='', addendum='', *, removal=''): if pending: if removal: raise ValueError("A pending deprecation cannot have a scheduled removal") elif removal == '': macro, meso, *_ = since.split('.') removal = f'{macro}.{int(meso) + 2}' if not message: message = ( ("The %(name)s %(obj_type)s" if obj_type else "%(name)s") + (" will be deprecated in a future version" if pending else (" was deprecated in Matplotlib %(since)s" + (" and will be removed in %(removal)s" if removal else ""))) + "." + (" Use %(alternative)s instead." if alternative else "") + (" %(addendum)s" if addendum else "")) warning_cls = PendingDeprecationWarning if pending else MatplotlibDeprecationWarning return warning_cls(message % dict( func=name, name=name, obj_type=obj_type, since=since, removal=removal, alternative=alternative, addendum=addendum)) def warn_deprecated( since, *, message='', name='', alternative='', pending=False, obj_type='', addendum='', removal=''): """ Display a standardized deprecation. Parameters ---------- since : str The release at which this API became deprecated. message : str, optional Override the default deprecation message. The ``%(since)s``, ``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``, and ``%(removal)s`` format specifiers will be replaced by the values of the respective arguments passed to this function. name : str, optional The name of the deprecated object. alternative : str, optional An alternative API that the user may use in place of the deprecated API. The deprecation warning will tell the user about this alternative if provided. pending : bool, optional If True, uses a PendingDeprecationWarning instead of a DeprecationWarning. Cannot be used together with *removal*. obj_type : str, optional The object type being deprecated. addendum : str, optional Additional text appended directly to the final message. removal : str, optional The expected removal version. With the default (an empty string), a removal version is automatically computed from *since*. Set to other Falsy values to not schedule a removal date. Cannot be used together with *pending*. Examples -------- :: # To warn of the deprecation of "matplotlib.name_of_module" warn_deprecated('1.4.0', name='matplotlib.name_of_module', obj_type='module') """ warning = _generate_deprecation_warning( since, message, name, alternative, pending, obj_type, addendum, removal=removal) from . import warn_external warn_external(warning, category=MatplotlibDeprecationWarning) def deprecated(since, *, message='', name='', alternative='', pending=False, obj_type=None, addendum='', removal=''): """ Decorator to mark a function, a class, or a property as deprecated. When deprecating a classmethod, a staticmethod, or a property, the ``@deprecated`` decorator should go *under* ``@classmethod`` and ``@staticmethod`` (i.e., `deprecated` should directly decorate the underlying callable), but *over* ``@property``. When deprecating a class ``C`` intended to be used as a base class in a multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method (if ``C`` instead inherited its ``__init__`` from its own base class, then ``@deprecated`` would mess up ``__init__`` inheritance when installing its own (deprecation-emitting) ``C.__init__``). Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to 'class' if decorating a class, 'attribute' if decorating a property, and 'function' otherwise. Examples -------- :: @deprecated('1.4.0') def the_function_to_deprecate(): pass """ def deprecate(obj, message=message, name=name, alternative=alternative, pending=pending, obj_type=obj_type, addendum=addendum): from matplotlib._api import classproperty if isinstance(obj, type): if obj_type is None: obj_type = "class" func = obj.__init__ name = name or obj.__name__ old_doc = obj.__doc__ def finalize(wrapper, new_doc): try: obj.__doc__ = new_doc except AttributeError: # Can't set on some extension objects. pass obj.__init__ = functools.wraps(obj.__init__)(wrapper) return obj elif isinstance(obj, (property, classproperty)): if obj_type is None: obj_type = "attribute" func = None name = name or obj.fget.__name__ old_doc = obj.__doc__ class _deprecated_property(type(obj)): def __get__(self, instance, owner=None): if instance is not None or owner is not None \ and isinstance(self, classproperty): emit_warning() return super().__get__(instance, owner) def __set__(self, instance, value): if instance is not None: emit_warning() return super().__set__(instance, value) def __delete__(self, instance): if instance is not None: emit_warning() return super().__delete__(instance) def __set_name__(self, owner, set_name): nonlocal name if name == "<lambda>": name = set_name def finalize(_, new_doc): return _deprecated_property( fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc) else: if obj_type is None: obj_type = "function" func = obj name = name or obj.__name__ old_doc = func.__doc__ def finalize(wrapper, new_doc): wrapper = functools.wraps(func)(wrapper) wrapper.__doc__ = new_doc return wrapper def emit_warning(): warn_deprecated( since, message=message, name=name, alternative=alternative, pending=pending, obj_type=obj_type, addendum=addendum, removal=removal) def wrapper(*args, **kwargs): emit_warning() return func(*args, **kwargs) old_doc = inspect.cleandoc(old_doc or '').strip('\n') notes_header = '\nNotes\n-----' second_arg = ' '.join([t.strip() for t in (message, f"Use {alternative} instead." if alternative else "", addendum) if t]) new_doc = (f"[*Deprecated*] {old_doc}\n" f"{notes_header if notes_header not in old_doc else ''}\n" f".. deprecated:: {since}\n" f" {second_arg}") if not old_doc: # This is to prevent a spurious 'unexpected unindent' warning from # docutils when the original docstring was blank. new_doc += r'\ ' return finalize(wrapper, new_doc) return deprecate
MatplotlibDeprecationWarning
python
matplotlib__matplotlib
lib/matplotlib/legend_handler.py
{ "start": 9916, "end": 11263 }
class ____(HandlerNpoints): """ Handler for `.Line2D` instances. See Also -------- HandlerLine2DCompound : An earlier handler implementation, which used one artist for the line and another for the marker(s). """ def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): # docstring inherited xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent, width, height, fontsize) markevery = None if self.get_numpoints(legend) == 1: # Special case: one wants a single marker in the center # and a line that extends on both sides. One will use a # 3 points line, but only mark the #1 (i.e. middle) point. xdata = np.linspace(xdata[0], xdata[-1], 3) markevery = [1] ydata = np.full_like(xdata, (height - ydescent) / 2) legline = Line2D(xdata, ydata, markevery=markevery) self.update_prop(legline, orig_handle, legend) if legend.markerscale != 1: newsz = legline.get_markersize() * legend.markerscale legline.set_markersize(newsz) legline.set_transform(trans) return [legline]
HandlerLine2D
python
Textualize__textual
src/textual/drivers/windows_driver.py
{ "start": 319, "end": 4486 }
class ____(Driver): """Powers display and input for Windows.""" def __init__( self, app: App, *, debug: bool = False, mouse: bool = True, size: tuple[int, int] | None = None, ) -> None: """Initialize Windows driver. Args: app: The App instance. debug: Enable debug mode. mouse: Enable mouse support. size: Initial size of the terminal or `None` to detect. """ super().__init__(app, debug=debug, mouse=mouse, size=size) self._file = sys.__stdout__ self.exit_event = Event() self._event_thread: Thread | None = None self._restore_console: Callable[[], None] | None = None self._writer_thread: WriterThread | None = None @property def can_suspend(self) -> bool: """Can this driver be suspended?""" return True def write(self, data: str) -> None: """Write data to the output device. Args: data: Raw data. """ assert self._writer_thread is not None, "Driver must be in application mode" self._writer_thread.write(data) def _enable_mouse_support(self) -> None: """Enable reporting of mouse events.""" if not self._mouse: return write = self.write write("\x1b[?1000h") # SET_VT200_MOUSE write("\x1b[?1003h") # SET_ANY_EVENT_MOUSE write("\x1b[?1015h") # SET_VT200_HIGHLIGHT_MOUSE write("\x1b[?1006h") # SET_SGR_EXT_MODE_MOUSE self.flush() def _disable_mouse_support(self) -> None: """Disable reporting of mouse events.""" if not self._mouse: return write = self.write write("\x1b[?1000l") write("\x1b[?1003l") write("\x1b[?1015l") write("\x1b[?1006l") self.flush() def _enable_bracketed_paste(self) -> None: """Enable bracketed paste mode.""" self.write("\x1b[?2004h") def _disable_bracketed_paste(self) -> None: """Disable bracketed paste mode.""" self.write("\x1b[?2004l") def start_application_mode(self) -> None: """Start application mode.""" loop = asyncio.get_running_loop() self._restore_console = win32.enable_application_mode() self._writer_thread = WriterThread(self._file) self._writer_thread.start() self.write("\x1b[?1049h") # Enable alt screen self._enable_mouse_support() self.write("\x1b[?25l") # Hide cursor self.write("\033[?1004h") # Enable FocusIn/FocusOut. self.write("\x1b[>1u") # https://sw.kovidgoyal.net/kitty/keyboard-protocol/ self.flush() self._enable_bracketed_paste() self._event_thread = win32.EventMonitor( loop, self._app, self.exit_event, self.process_message ) self._event_thread.start() def disable_input(self) -> None: """Disable further input.""" try: if not self.exit_event.is_set(): self._disable_mouse_support() self.exit_event.set() if self._event_thread is not None: self._event_thread.join() self._event_thread = None self.exit_event.clear() except Exception as error: # TODO: log this pass def stop_application_mode(self) -> None: """Stop application mode, restore state.""" self._disable_bracketed_paste() self.disable_input() # Disable the Kitty keyboard protocol. This must be done before leaving # the alt screen. https://sw.kovidgoyal.net/kitty/keyboard-protocol/ self.write("\x1b[<u") # Disable alt screen, show cursor self.write("\x1b[?1049l" + "\x1b[?25h") self.write("\033[?1004l") # Disable FocusIn/FocusOut. self.flush() def close(self) -> None: """Perform cleanup.""" if self._writer_thread is not None: self._writer_thread.stop() if self._restore_console: self._restore_console()
WindowsDriver
python
kamyu104__LeetCode-Solutions
Python/count-subarrays-with-majority-element-i.py
{ "start": 54, "end": 573 }
class ____(object): def countMajoritySubarrays(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ cnt = [0]*((2*len(nums)+1)+1) prefix = [0]*((2*len(nums)+1)+1) prefix[0] = cnt[0] = 1 result = curr = 0 for x in nums: curr += +1 if x == target else -1 cnt[curr] += 1 prefix[curr] = prefix[curr-1]+cnt[curr] result += prefix[curr-1] return result
Solution
python
Netflix__metaflow
metaflow/runner/deployer_impl.py
{ "start": 689, "end": 7299 }
class ____(object): """ Base class for deployer implementations. Each implementation should define a TYPE class variable that matches the name of the CLI group. Parameters ---------- flow_file : str Path to the flow file to deploy, relative to current directory. show_output : bool, default True Show the 'stdout' and 'stderr' to the console by default. profile : Optional[str], default None Metaflow profile to use for the deployment. If not specified, the default profile is used. env : Optional[Dict], default None Additional environment variables to set for the deployment. cwd : Optional[str], default None The directory to run the subprocess in; if not specified, the current directory is used. file_read_timeout : int, default 3600 The timeout until which we try to read the deployer attribute file (in seconds). **kwargs : Any Additional arguments that you would pass to `python myflow.py` before the deployment command. """ TYPE: ClassVar[Optional[str]] = None def __init__( self, flow_file: str, show_output: bool = True, profile: Optional[str] = None, env: Optional[Dict] = None, cwd: Optional[str] = None, file_read_timeout: int = 3600, **kwargs ): if self.TYPE is None: raise ValueError( "DeployerImpl doesn't have a 'TYPE' to target. Please use a sub-class " "of DeployerImpl." ) from metaflow.parameters import flow_context # Reload the CLI with an "empty" flow -- this will remove any configuration # and parameter options. They are re-added in from_cli (called below). with flow_context(None): [ importlib.reload(sys.modules[module]) for module in self.to_reload if module in sys.modules ] from metaflow.cli import start from metaflow.runner.click_api import MetaflowAPI # Convert flow_file to absolute path if it's relative if not os.path.isabs(flow_file): self.flow_file = os.path.abspath(flow_file) else: self.flow_file = flow_file self.show_output = show_output self.profile = profile self.env = env self.cwd = cwd or os.getcwd() self.file_read_timeout = file_read_timeout self.env_vars = os.environ.copy() self.env_vars.update(self.env or {}) if self.profile: self.env_vars["METAFLOW_PROFILE"] = profile self.spm = SubprocessManager() self.top_level_kwargs = kwargs self.api = MetaflowAPI.from_cli(self.flow_file, start) @property def to_reload(self) -> List[str]: """ List of modules to reload when the deployer is initialized. This is used to ensure that the CLI is in a clean state before deploying the flow. """ return [ "metaflow.cli", "metaflow.cli_components.run_cmds", "metaflow.cli_components.init_cmd", ] @property def deployer_kwargs(self) -> Dict[str, Any]: raise NotImplementedError @staticmethod def deployed_flow_type() -> Type["metaflow.runner.deployer.DeployedFlow"]: raise NotImplementedError def __enter__(self) -> "DeployerImpl": return self def create(self, **kwargs) -> "metaflow.runner.deployer.DeployedFlow": """ Create a sub-class of a `DeployedFlow` depending on the deployer implementation. Parameters ---------- **kwargs : Any Additional arguments to pass to `create` corresponding to the command line arguments of `create` Returns ------- DeployedFlow DeployedFlow object representing the deployed flow. Raises ------ Exception If there is an error during deployment. """ # Sub-classes should implement this by simply calling _create and pass the # proper class as the DeployedFlow to return. raise NotImplementedError def _create( self, create_class: Type["metaflow.runner.deployer.DeployedFlow"], **kwargs ) -> "metaflow.runner.deployer.DeployedFlow": with temporary_fifo() as (attribute_file_path, attribute_file_fd): # every subclass needs to have `self.deployer_kwargs` # TODO: Get rid of CLICK_API_PROCESS_CONFIG in the near future if CLICK_API_PROCESS_CONFIG: # We need to run this in the cwd because configs depend on files # that may be located in paths relative to the directory the user # wants to run in with with_dir(self.cwd): command = get_lower_level_group( self.api, self.top_level_kwargs, self.TYPE, self.deployer_kwargs ).create(deployer_attribute_file=attribute_file_path, **kwargs) else: command = get_lower_level_group( self.api, self.top_level_kwargs, self.TYPE, self.deployer_kwargs ).create(deployer_attribute_file=attribute_file_path, **kwargs) pid = self.spm.run_command( [sys.executable, *command], env=self.env_vars, cwd=self.cwd, show_output=self.show_output, ) command_obj = self.spm.get(pid) content = handle_timeout( attribute_file_fd, command_obj, self.file_read_timeout ) content = json.loads(content) self.name = content.get("name") self.flow_name = content.get("flow_name") self.metadata = content.get("metadata") # Additional info is used to pass additional deployer specific information. # It is used in non-OSS deployers (extensions). self.additional_info = content.get("additional_info", {}) command_obj.sync_wait() if command_obj.process.returncode == 0: return create_class(deployer=self) raise RuntimeError("Error deploying %s to %s" % (self.flow_file, self.TYPE)) def __exit__(self, exc_type, exc_value, traceback): """ Cleanup resources on exit. """ self.cleanup() def cleanup(self): """ Cleanup resources. """ self.spm.cleanup()
DeployerImpl
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 163116, "end": 163240 }
class ____(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase): pass @requireAttrs(socket.socket, "recvmsg")
SendmsgUDPTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dlp.py
{ "start": 91207, "end": 95030 }
class ____(GoogleCloudBaseOperator): """ Lists stored infoTypes. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDLPListStoredInfoTypesOperator` :param organization_id: (Optional) The organization ID. Required to set this field if parent resource is an organization. :param project_id: (Optional) Google Cloud project ID where the DLP Instance exists. Only set this field if the parent resource is a project instead of an organization. :param page_size: (Optional) The maximum number of resources contained in the underlying API response. :param order_by: (Optional) Optional comma separated list of fields to order by, followed by asc or desc postfix. :param retry: (Optional) A retry object used to retry requests. If None is specified, requests will not be retried. :param timeout: (Optional) The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :param metadata: (Optional) Additional metadata that is provided to the method. :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "organization_id", "project_id", "gcp_conn_id", "impersonation_chain", ) operator_extra_links = (CloudDLPInfoTypesListLink(),) def __init__( self, *, organization_id: str | None = None, project_id: str = PROVIDE_PROJECT_ID, page_size: int | None = None, order_by: str | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.organization_id = organization_id self.project_id = project_id self.page_size = page_size self.order_by = order_by self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = CloudDLPHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) infos = hook.list_stored_info_types( organization_id=self.organization_id, project_id=self.project_id, page_size=self.page_size, order_by=self.order_by, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) project_id = self.project_id or hook.project_id if project_id: CloudDLPInfoTypesListLink.persist( context=context, project_id=project_id, ) return [StoredInfoType.to_dict(i) for i in infos]
CloudDLPListStoredInfoTypesOperator
python
huggingface__transformers
src/transformers/models/falcon/modeling_falcon.py
{ "start": 9756, "end": 21641 }
class ____(nn.Module): def __init__(self, config: FalconConfig, layer_idx=None): super().__init__() self.config = config self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.hidden_size // self.num_heads self.split_size = self.hidden_size self.hidden_dropout = config.hidden_dropout self.max_position_embeddings = config.max_position_embeddings self.is_causal = True self.layer_idx = layer_idx if layer_idx is None: logger.warning_once( f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will " "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) if self.head_dim * self.num_heads != self.hidden_size: raise ValueError( f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:" f" {self.num_heads})." ) # Layer-wise attention scaling self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim) self.beta = self.inv_norm_factor if config.new_decoder_architecture: qkv_out_dim = (config.num_kv_heads * 2 + config.num_attention_heads) * self.head_dim elif config.multi_query: qkv_out_dim = self.hidden_size + 2 * self.head_dim else: qkv_out_dim = 3 * self.hidden_size self.query_key_value = FalconLinear(self.hidden_size, qkv_out_dim, bias=config.bias) self.new_decoder_architecture = config.new_decoder_architecture self.multi_query = config.multi_query self.dense = FalconLinear(self.hidden_size, self.hidden_size, bias=config.bias) self.attention_dropout = nn.Dropout(config.attention_dropout) self.num_kv_heads = config.num_kv_heads if (self.new_decoder_architecture or not self.multi_query) else 1 def _split_heads(self, fused_qkv: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Split the last dimension into (num_heads, head_dim), results share same memory storage as `fused_qkv` Args: fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim] Returns: query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim] value: [batch_size, seq_length, num_heads, head_dim] """ if self.new_decoder_architecture: batch, seq_len, _ = fused_qkv.shape qkv = fused_qkv.view(batch, seq_len, -1, self.num_heads // self.num_kv_heads + 2, self.head_dim) query = qkv[:, :, :, :-2] key = qkv[:, :, :, [-2]] value = qkv[:, :, :, [-1]] key = torch.broadcast_to(key, query.shape) value = torch.broadcast_to(value, query.shape) query, key, value = [x.flatten(2, 3) for x in (query, key, value)] return query, key, value elif not self.multi_query: batch_size, seq_length, three_times_hidden_size = fused_qkv.shape fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim) return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :] else: batch_size, seq_length, three_times_hidden_size = fused_qkv.shape fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads + 2, self.head_dim) return fused_qkv[..., :-2, :], fused_qkv[..., [-2], :], fused_qkv[..., [-1], :] # Copied from transformers.models.bloom.modeling_bloom.BloomAttention._merge_heads def _merge_heads(self, x: torch.Tensor) -> torch.Tensor: """ Merge heads together over the last dimension Args: x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim] Returns: torch.tensor: [batch_size, seq_length, num_heads * head_dim] """ # What we want to achieve is: # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim batch_size_and_num_heads, seq_length, _ = x.shape batch_size = batch_size_and_num_heads // self.num_heads # First view to decompose the batch size # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim x = x.view(batch_size, self.num_heads, seq_length, self.head_dim) # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim x = x.permute(0, 2, 1, 3) # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim) def forward( self, hidden_states: torch.Tensor, alibi: Optional[torch.Tensor], attention_mask: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, layer_past: Optional[Cache] = None, use_cache: bool = False, output_attentions: bool = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, ): fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size] num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads # 3 x [batch_size, seq_length, num_heads, head_dim] (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv) batch_size, query_length, _, _ = query_layer.shape query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim) key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim) value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim) if alibi is None: cos, sin = position_embeddings query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin) if layer_past is not None: cache_kwargs = {"cache_position": cache_position} if alibi is None: cache_kwargs.update({"sin": sin, "cos": cos}) key_layer, value_layer = layer_past.update(key_layer, value_layer, self.layer_idx, cache_kwargs) kv_length = key_layer.shape[-2] if ( self.config._attn_implementation == "sdpa" and query_layer.device.type == "cuda" and attention_mask is not None ): # For torch<=2.1.2, SDPA with memory-efficient backend is bugged with non-contiguous inputs with custom attn_mask, # Reference: https://github.com/pytorch/pytorch/issues/112577. query_layer = query_layer.contiguous() key_layer = key_layer.contiguous() value_layer = value_layer.contiguous() if attention_mask is not None: attention_mask = attention_mask[:, :, :, : key_layer.shape[-2]] if alibi is None: if self.config._attn_implementation == "sdpa" and not output_attentions: # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True` # The query_length > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not # create a causal mask in case query_length == 1. is_causal = self.is_causal and attention_mask is None and query_length > 1 attn_output = torch.nn.functional.scaled_dot_product_attention( query_layer, key_layer, value_layer, attn_mask=attention_mask, dropout_p=0.0, is_causal=is_causal, ) attention_scores = None else: attention_scores = query_layer @ key_layer.transpose(-1, -2) attention_scores /= math.sqrt(self.head_dim) attention_scores = F.softmax(attention_scores + attention_mask, dim=-1, dtype=hidden_states.dtype) # It is unclear why dropout is not applied here (while it is with alibi). attn_output = attention_scores @ value_layer attn_output = attn_output.view(batch_size, self.num_heads, query_length, self.head_dim) attn_output = attn_output.permute(0, 2, 1, 3) attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim) attn_output = self.dense(attn_output) return attn_output, attention_scores else: if self.config._attn_implementation == "sdpa" and not output_attentions: # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True` is_causal = self.is_causal and attention_mask is None and query_length > 1 attn_output = torch.nn.functional.scaled_dot_product_attention( query_layer, key_layer, value_layer, attn_mask=attention_mask, dropout_p=self.attention_dropout.p if self.training else 0.0, is_causal=is_causal, ) attention_probs = None attn_output = attn_output.transpose(1, 2) attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim) attn_output = self.dense(attn_output) else: matmul_result = query_layer @ key_layer.transpose(-1, -2) # change view to [batch_size, num_heads, q_length, kv_length] attention_scores = matmul_result.view(batch_size, self.num_heads, query_length, kv_length) # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length] input_dtype = attention_scores.dtype # `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38` if input_dtype == torch.float16 or input_dtype == torch.bfloat16: attention_scores = attention_scores.to(torch.float32) attention_logits = attention_scores + alibi.view(batch_size, self.num_heads, 1, -1) attention_logits *= self.inv_norm_factor attention_probs = F.softmax(attention_logits + attention_mask, dim=-1, dtype=hidden_states.dtype) # [batch_size, num_heads, q_length, kv_length] attention_probs = self.attention_dropout(attention_probs) # change view [batch_size, num_heads, q_length, kv_length] attention_probs_reshaped = attention_probs.view(batch_size, self.num_heads, query_length, kv_length) # matmul: [batch_size * num_heads, q_length, head_dim] attn_output = (attention_probs_reshaped @ value_layer).flatten(0, 1) # change view [batch_size, q_length, num_heads * head_dim] attn_output = self._merge_heads(attn_output) attn_output = self.dense(attn_output) return attn_output, attention_probs
FalconAttention
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/idna/core.py
{ "start": 599, "end": 12663 }
class ____(IDNAError): """ Exception when the codepoint is not valid in the context it is used """ pass def _combining_class(cp: int) -> int: v = unicodedata.combining(chr(cp)) if v == 0: if not unicodedata.name(chr(cp)): raise ValueError('Unknown character in unicodedata') return v def _is_script(cp: str, script: str) -> bool: return intranges_contain(ord(cp), idnadata.scripts[script]) def _punycode(s: str) -> bytes: return s.encode('punycode') def _unot(s: int) -> str: return 'U+{:04X}'.format(s) def valid_label_length(label: Union[bytes, str]) -> bool: if len(label) > 63: return False return True def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool: if len(label) > (254 if trailing_dot else 253): return False return True def check_bidi(label: str, check_ltr: bool = False) -> bool: # Bidi rules should only be applied if string contains RTL characters bidi_label = False for (idx, cp) in enumerate(label, 1): direction = unicodedata.bidirectional(cp) if direction == '': # String likely comes from a newer version of Unicode raise IDNABidiError('Unknown directionality in label {} at position {}'.format(repr(label), idx)) if direction in ['R', 'AL', 'AN']: bidi_label = True if not bidi_label and not check_ltr: return True # Bidi rule 1 direction = unicodedata.bidirectional(label[0]) if direction in ['R', 'AL']: rtl = True elif direction == 'L': rtl = False else: raise IDNABidiError('First codepoint in label {} must be directionality L, R or AL'.format(repr(label))) valid_ending = False number_type = None # type: Optional[str] for (idx, cp) in enumerate(label, 1): direction = unicodedata.bidirectional(cp) if rtl: # Bidi rule 2 if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: raise IDNABidiError('Invalid direction for codepoint at position {} in a right-to-left label'.format(idx)) # Bidi rule 3 if direction in ['R', 'AL', 'EN', 'AN']: valid_ending = True elif direction != 'NSM': valid_ending = False # Bidi rule 4 if direction in ['AN', 'EN']: if not number_type: number_type = direction else: if number_type != direction: raise IDNABidiError('Can not mix numeral types in a right-to-left label') else: # Bidi rule 5 if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: raise IDNABidiError('Invalid direction for codepoint at position {} in a left-to-right label'.format(idx)) # Bidi rule 6 if direction in ['L', 'EN']: valid_ending = True elif direction != 'NSM': valid_ending = False if not valid_ending: raise IDNABidiError('Label ends with illegal codepoint directionality') return True def check_initial_combiner(label: str) -> bool: if unicodedata.category(label[0])[0] == 'M': raise IDNAError('Label begins with an illegal combining character') return True def check_hyphen_ok(label: str) -> bool: if label[2:4] == '--': raise IDNAError('Label has disallowed hyphens in 3rd and 4th position') if label[0] == '-' or label[-1] == '-': raise IDNAError('Label must not start or end with a hyphen') return True def check_nfc(label: str) -> None: if unicodedata.normalize('NFC', label) != label: raise IDNAError('Label must be in Normalization Form C') def valid_contextj(label: str, pos: int) -> bool: cp_value = ord(label[pos]) if cp_value == 0x200c: if pos > 0: if _combining_class(ord(label[pos - 1])) == _virama_combining_class: return True ok = False for i in range(pos-1, -1, -1): joining_type = idnadata.joining_types.get(ord(label[i])) if joining_type == ord('T'): continue elif joining_type in [ord('L'), ord('D')]: ok = True break else: break if not ok: return False ok = False for i in range(pos+1, len(label)): joining_type = idnadata.joining_types.get(ord(label[i])) if joining_type == ord('T'): continue elif joining_type in [ord('R'), ord('D')]: ok = True break else: break return ok if cp_value == 0x200d: if pos > 0: if _combining_class(ord(label[pos - 1])) == _virama_combining_class: return True return False else: return False def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: cp_value = ord(label[pos]) if cp_value == 0x00b7: if 0 < pos < len(label)-1: if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c: return True return False elif cp_value == 0x0375: if pos < len(label)-1 and len(label) > 1: return _is_script(label[pos + 1], 'Greek') return False elif cp_value == 0x05f3 or cp_value == 0x05f4: if pos > 0: return _is_script(label[pos - 1], 'Hebrew') return False elif cp_value == 0x30fb: for cp in label: if cp == '\u30fb': continue if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'): return True return False elif 0x660 <= cp_value <= 0x669: for cp in label: if 0x6f0 <= ord(cp) <= 0x06f9: return False return True elif 0x6f0 <= cp_value <= 0x6f9: for cp in label: if 0x660 <= ord(cp) <= 0x0669: return False return True return False def check_label(label: Union[str, bytes, bytearray]) -> None: if isinstance(label, (bytes, bytearray)): label = label.decode('utf-8') if len(label) == 0: raise IDNAError('Empty Label') check_nfc(label) check_hyphen_ok(label) check_initial_combiner(label) for (pos, cp) in enumerate(label): cp_value = ord(cp) if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']): continue elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']): if not valid_contextj(label, pos): raise InvalidCodepointContext('Joiner {} not allowed at position {} in {}'.format( _unot(cp_value), pos+1, repr(label))) elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']): if not valid_contexto(label, pos): raise InvalidCodepointContext('Codepoint {} not allowed at position {} in {}'.format(_unot(cp_value), pos+1, repr(label))) else: raise InvalidCodepoint('Codepoint {} at position {} of {} not allowed'.format(_unot(cp_value), pos+1, repr(label))) check_bidi(label) def alabel(label: str) -> bytes: try: label_bytes = label.encode('ascii') ulabel(label_bytes) if not valid_label_length(label_bytes): raise IDNAError('Label too long') return label_bytes except UnicodeEncodeError: pass check_label(label) label_bytes = _alabel_prefix + _punycode(label) if not valid_label_length(label_bytes): raise IDNAError('Label too long') return label_bytes def ulabel(label: Union[str, bytes, bytearray]) -> str: if not isinstance(label, (bytes, bytearray)): try: label_bytes = label.encode('ascii') except UnicodeEncodeError: check_label(label) return label else: label_bytes = label label_bytes = label_bytes.lower() if label_bytes.startswith(_alabel_prefix): label_bytes = label_bytes[len(_alabel_prefix):] if not label_bytes: raise IDNAError('Malformed A-label, no Punycode eligible content found') if label_bytes.decode('ascii')[-1] == '-': raise IDNAError('A-label must not end with a hyphen') else: check_label(label_bytes) return label_bytes.decode('ascii') try: label = label_bytes.decode('punycode') except UnicodeError: raise IDNAError('Invalid A-label') check_label(label) return label def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: """Re-map the characters in the string according to UTS46 processing.""" from .uts46data import uts46data output = '' for pos, char in enumerate(domain): code_point = ord(char) try: uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, 'Z')) - 1] status = uts46row[1] replacement = None # type: Optional[str] if len(uts46row) == 3: replacement = uts46row[2] if (status == 'V' or (status == 'D' and not transitional) or (status == '3' and not std3_rules and replacement is None)): output += char elif replacement is not None and (status == 'M' or (status == '3' and not std3_rules) or (status == 'D' and transitional)): output += replacement elif status != 'I': raise IndexError() except IndexError: raise InvalidCodepoint( 'Codepoint {} not allowed at position {} in {}'.format( _unot(code_point), pos + 1, repr(domain))) return unicodedata.normalize('NFC', output) def encode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False, transitional: bool = False) -> bytes: if not isinstance(s, str): try: s = str(s, 'ascii') except UnicodeDecodeError: raise IDNAError('should pass a unicode string to the function rather than a byte string.') if uts46: s = uts46_remap(s, std3_rules, transitional) trailing_dot = False result = [] if strict: labels = s.split('.') else: labels = _unicode_dots_re.split(s) if not labels or labels == ['']: raise IDNAError('Empty domain') if labels[-1] == '': del labels[-1] trailing_dot = True for label in labels: s = alabel(label) if s: result.append(s) else: raise IDNAError('Empty label') if trailing_dot: result.append(b'') s = b'.'.join(result) if not valid_string_length(s, trailing_dot): raise IDNAError('Domain too long') return s def decode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False) -> str: try: if not isinstance(s, str): s = str(s, 'ascii') except UnicodeDecodeError: raise IDNAError('Invalid ASCII in A-label') if uts46: s = uts46_remap(s, std3_rules, False) trailing_dot = False result = [] if not strict: labels = _unicode_dots_re.split(s) else: labels = s.split('.') if not labels or labels == ['']: raise IDNAError('Empty domain') if not labels[-1]: del labels[-1] trailing_dot = True for label in labels: s = ulabel(label) if s: result.append(s) else: raise IDNAError('Empty label') if trailing_dot: result.append('') return '.'.join(result)
InvalidCodepointContext
python
kamyu104__LeetCode-Solutions
Python/univalued-binary-tree.py
{ "start": 191, "end": 621 }
class ____(object): def isUnivalTree(self, root): """ :type root: TreeNode :rtype: bool """ s = [root] while s: node = s.pop() if not node: continue if node.val != root.val: return False s.append(node.left) s.append(node.right) return True # Time: O(n) # Space: O(h)
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/instrumentation/events/embedding.py
{ "start": 547, "end": 908 }
class ____(BaseEvent): """ EmbeddingEndEvent. Args: chunks (List[str]): List of chunks. embeddings (List[List[float]]): List of embeddings. """ chunks: List[str] embeddings: List[List[float]] @classmethod def class_name(cls) -> str: """Class name.""" return "EmbeddingEndEvent"
EmbeddingEndEvent
python
django-import-export__django-import-export
tests/core/tests/admin_integration/mixins.py
{ "start": 238, "end": 5403 }
class ____: author_export_url = "/admin/core/author/export/" category_change_url = "/admin/core/category/" category_export_url = "/admin/core/category/export/" uuid_category_change_url = "/admin/core/uuidcategory/" uuid_category_export_url = "/admin/core/uuidcategory/export/" book_import_url = "/admin/core/book/import/" book_export_url = "/admin/core/book/export/" ebook_import_url = "/admin/core/ebook/import/" ebook_export_url = "/admin/core/ebook/export/" core_book_url = "/admin/core/book/" process_ebook_import_url = "/admin/core/ebook/process_import/" book_process_import_url = "/admin/core/book/process_import/" ebook_process_import_url = "/admin/core/ebook/process_import/" legacybook_import_url = "/admin/core/legacybook/import/" legacybook_process_import_url = "/admin/core/legacybook/process_import/" core_author_url = "/admin/core/author/" child_import_url = "/admin/core/child/import/" change_list_url = "admin/import_export/change_list.html" child_process_import_url = "/admin/core/child/process_import/" admin_import_template_url = "admin/import_export/import.html" change_list_template_url = "admin/import_export/change_list_import_export.html" import_export_import_template_url = "admin/import_export/import.html" def setUp(self): super().setUp() self.user = User.objects.create_user("admin", "admin@example.com", "password") self.user.is_staff = True self.user.is_superuser = True self.user.save() self.client.login(username="admin", password="password") def _do_import_post( self, url, filename, input_format=0, encoding=None, resource=None, follow=False, data=None, ): filename = os.path.join( os.path.dirname(__file__), os.path.pardir, os.path.pardir, "exports", filename, ) with open(filename, "rb") as f: if data is None: data = {} data.update( { f"{FORM_FIELD_PREFIX}format": str(input_format), "import_file": f, } ) if encoding: BookAdmin.from_encoding = encoding if resource: data.update({f"{FORM_FIELD_PREFIX}resource": resource}) response = self.client.post(url, data, follow=follow) return response def _assert_string_in_response( self, url, filename, input_format, encoding=None, str_in_response=None, follow=False, status_code=200, ): response = self._do_import_post( url, filename, input_format, encoding=encoding, follow=follow ) self.assertEqual(response.status_code, status_code) self.assertIn("result", response.context) self.assertFalse(response.context["result"].has_errors()) if str_in_response is not None: self.assertContains(response, str_in_response) def _get_input_format_index(self, format): for i, f in enumerate(DEFAULT_FORMATS): if f().get_title() == format: xlsx_index = i break else: raise Exception( "Unable to find %s format. DEFAULT_FORMATS: %r" % (format, DEFAULT_FORMATS) ) return xlsx_index def _check_export_file_response( self, response, target_file_contents, file_prefix="Book" ): date_str = datetime.now().strftime("%Y-%m-%d") self.assertEqual(response.status_code, 200) self.assertTrue(response.has_header("Content-Disposition")) self.assertEqual(response["Content-Type"], "text/csv") self.assertEqual( response["Content-Disposition"], f'attachment; filename="{file_prefix}-{date_str}.csv"', ) self.assertEqual(target_file_contents.encode(), response.content) def _get_url_response( self, url, expected_status_code=200, str_in_response=None, html=False ): response = self.client.get(url) assert response.status_code == expected_status_code if str_in_response is not None: assert str_in_response in response.content.decode() if html: assert ( "text/html" in response.headers["Content-Type"] ), "Response is not HTML" return response def _post_url_response(self, url, data, expected_status_code=200, follow=False): response = self.client.post(url, data, follow=follow) assert response.status_code == expected_status_code return response def _prepend_form_prefix(self, data): """ Add the form prefix to form data in tests. """ prefix = "django-import-export-" keys_to_update = list(data.keys()) for key in keys_to_update: if key in ["format", "resource", "export_items"]: data[prefix + key] = data.pop(key)
AdminTestMixin
python
apache__airflow
airflow-core/tests/unit/core/test_core.py
{ "start": 1233, "end": 3662 }
class ____: @staticmethod def clean_db(): clear_db_dags() clear_db_runs() def teardown_method(self): self.clean_db() def test_dryrun(self, dag_maker): class TemplateFieldOperator(BaseOperator): template_fields = ["bash_command"] def __init__(self, bash_command, **kwargs): self.bash_command = bash_command super().__init__(**kwargs) with dag_maker(): op = TemplateFieldOperator(task_id="test_dryrun", bash_command="echo success") dag_maker.create_dagrun() op.dry_run() def test_dryrun_with_invalid_template_field(self, dag_maker): class InvalidTemplateFieldOperator(BaseOperator): template_fields = ["missing_field"] with dag_maker(): op = InvalidTemplateFieldOperator(task_id="test_dryrun_invalid_template_field") dag_maker.create_dagrun() error_message = ( "'missing_field' is configured as a template field but InvalidTemplateFieldOperator does not " "have this attribute." ) with pytest.raises(AttributeError, match=error_message): op.dry_run() def test_dag_params_and_task_params(self, dag_maker): # This test case guards how params of DAG and Operator work together. # - If any key exists in either DAG's or Operator's params, # it is guaranteed to be available eventually. # - If any key exists in both DAG's params and Operator's params, # the latter has precedence. with dag_maker( schedule=timedelta(weeks=1), params={"key_1": "value_1", "key_2": "value_2_old"}, serialized=True, ): task1 = EmptyOperator( task_id="task1", params={"key_2": "value_2_new", "key_3": "value_3"}, ) task2 = EmptyOperator(task_id="task2") dr = dag_maker.create_dagrun( run_type=DagRunType.SCHEDULED, ) ti1 = dag_maker.run_ti(task1.task_id, dr) ti2 = dag_maker.run_ti(task2.task_id, dr) context1 = ti1.get_template_context() context2 = ti2.get_template_context() assert context1["params"] == {"key_1": "value_1", "key_2": "value_2_new", "key_3": "value_3"} assert context2["params"] == {"key_1": "value_1", "key_2": "value_2_old"}
TestCore
python
ray-project__ray
python/ray/tune/utils/resource_updater.py
{ "start": 367, "end": 7514 }
class ____( namedtuple( "_Resources", [ "cpu", "gpu", "memory", "object_store_memory", "extra_cpu", "extra_gpu", "extra_memory", "extra_object_store_memory", "custom_resources", "extra_custom_resources", "has_placement_group", ], ) ): """Ray resources required to schedule a trial. Parameters: cpu: Number of CPUs to allocate to the trial. gpu: Number of GPUs to allocate to the trial. memory: Memory to reserve for the trial. object_store_memory: Object store memory to reserve. extra_cpu: Extra CPUs to reserve in case the trial needs to launch additional Ray actors that use CPUs. extra_gpu: Extra GPUs to reserve in case the trial needs to launch additional Ray actors that use GPUs. extra_memory: Memory to reserve for the trial launching additional Ray actors that use memory. extra_object_store_memory: Object store memory to reserve for the trial launching additional Ray actors that use object store memory. custom_resources: Mapping of resource to quantity to allocate to the trial. extra_custom_resources: Extra custom resources to reserve in case the trial needs to launch additional Ray actors that use any of these custom resources. has_placement_group: Bool indicating if the trial also has an associated placement group. """ __slots__ = () def __new__( cls, cpu: float, gpu: float, memory: float = 0, object_store_memory: float = 0.0, extra_cpu: float = 0.0, extra_gpu: float = 0.0, extra_memory: float = 0.0, extra_object_store_memory: float = 0.0, custom_resources: Optional[dict] = None, extra_custom_resources: Optional[dict] = None, has_placement_group: bool = False, ): custom_resources = custom_resources or {} extra_custom_resources = extra_custom_resources or {} leftovers = set(custom_resources) ^ set(extra_custom_resources) for value in leftovers: custom_resources.setdefault(value, 0) extra_custom_resources.setdefault(value, 0) cpu = round(cpu, 2) gpu = round(gpu, 2) memory = round(memory, 2) object_store_memory = round(object_store_memory, 2) extra_cpu = round(extra_cpu, 2) extra_gpu = round(extra_gpu, 2) extra_memory = round(extra_memory, 2) extra_object_store_memory = round(extra_object_store_memory, 2) custom_resources = { resource: round(value, 2) for resource, value in custom_resources.items() } extra_custom_resources = { resource: round(value, 2) for resource, value in extra_custom_resources.items() } all_values = [ cpu, gpu, memory, object_store_memory, extra_cpu, extra_gpu, extra_memory, extra_object_store_memory, ] all_values += list(custom_resources.values()) all_values += list(extra_custom_resources.values()) assert len(custom_resources) == len(extra_custom_resources) for entry in all_values: assert isinstance(entry, Number), ("Improper resource value.", entry) return super(_Resources, cls).__new__( cls, cpu, gpu, memory, object_store_memory, extra_cpu, extra_gpu, extra_memory, extra_object_store_memory, custom_resources, extra_custom_resources, has_placement_group, ) def summary_string(self): summary = "{} CPUs, {} GPUs".format( self.cpu + self.extra_cpu, self.gpu + self.extra_gpu ) if self.memory or self.extra_memory: summary += ", {} GiB heap".format( round((self.memory + self.extra_memory) / (1024**3), 2) ) if self.object_store_memory or self.extra_object_store_memory: summary += ", {} GiB objects".format( round( (self.object_store_memory + self.extra_object_store_memory) / (1024**3), 2, ) ) custom_summary = ", ".join( [ "{} {}".format(self.get_res_total(res), res) for res in self.custom_resources if not res.startswith(NODE_ID_PREFIX) ] ) if custom_summary: summary += " ({})".format(custom_summary) return summary def cpu_total(self): return self.cpu + self.extra_cpu def gpu_total(self): return self.gpu + self.extra_gpu def memory_total(self): return self.memory + self.extra_memory def object_store_memory_total(self): return self.object_store_memory + self.extra_object_store_memory def get_res_total(self, key): return self.custom_resources.get(key, 0) + self.extra_custom_resources.get( key, 0 ) def get(self, key): return self.custom_resources.get(key, 0) def is_nonnegative(self): all_values = [self.cpu, self.gpu, self.extra_cpu, self.extra_gpu] all_values += list(self.custom_resources.values()) all_values += list(self.extra_custom_resources.values()) return all(v >= 0 for v in all_values) @classmethod def subtract(cls, original, to_remove): cpu = original.cpu - to_remove.cpu gpu = original.gpu - to_remove.gpu memory = original.memory - to_remove.memory object_store_memory = ( original.object_store_memory - to_remove.object_store_memory ) extra_cpu = original.extra_cpu - to_remove.extra_cpu extra_gpu = original.extra_gpu - to_remove.extra_gpu extra_memory = original.extra_memory - to_remove.extra_memory extra_object_store_memory = ( original.extra_object_store_memory - to_remove.extra_object_store_memory ) all_resources = set(original.custom_resources).union( set(to_remove.custom_resources) ) new_custom_res = { k: original.custom_resources.get(k, 0) - to_remove.custom_resources.get(k, 0) for k in all_resources } extra_custom_res = { k: original.extra_custom_resources.get(k, 0) - to_remove.extra_custom_resources.get(k, 0) for k in all_resources } return _Resources( cpu, gpu, memory, object_store_memory, extra_cpu, extra_gpu, extra_memory, extra_object_store_memory, new_custom_res, extra_custom_res, )
_Resources
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/dense_to_sparse_batch_test.py
{ "start": 1240, "end": 4527 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testBasic(self): components = np.random.randint(12, size=(100,)).astype(np.int32) dataset = dataset_ops.Dataset.from_tensor_slices( components).map(lambda x: array_ops.fill([x], x)).apply( batching.dense_to_sparse_batch(4, [12])) get_next = self.getNext(dataset) for start in range(0, len(components), 4): results = self.evaluate(get_next()) self.assertAllEqual([[i, j] for i, c in enumerate(components[start:start + 4]) for j in range(c)], results.indices) self.assertAllEqual( [c for c in components[start:start + 4] for _ in range(c)], results.values) self.assertAllEqual([min(4, len(components) - start), 12], results.dense_shape) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(test_base.default_test_combinations()) def testWithUnknownShape(self): components = np.random.randint(5, size=(40,)).astype(np.int32) dataset = dataset_ops.Dataset.from_tensor_slices( components).map(lambda x: array_ops.fill([x, x], x)).apply( batching.dense_to_sparse_batch(4, [5, None])) get_next = self.getNext(dataset) for start in range(0, len(components), 4): results = self.evaluate(get_next()) self.assertAllEqual([[i, j, z] for i, c in enumerate(components[start:start + 4]) for j in range(c) for z in range(c)], results.indices) self.assertAllEqual([ c for c in components[start:start + 4] for _ in range(c) for _ in range(c) ], results.values) self.assertAllEqual([ min(4, len(components) - start), 5, np.max(components[start:start + 4]) ], results.dense_shape) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) @combinations.generate(test_base.default_test_combinations()) def testWithInvalidShape(self): input_tensor = array_ops.constant([[1]]) with self.assertRaisesRegex(ValueError, "Dimension -2 must be >= 0"): dataset_ops.Dataset.from_tensors(input_tensor).apply( batching.dense_to_sparse_batch(4, [-2])) @combinations.generate(test_base.default_test_combinations()) def testShapeErrors(self): def dataset_fn(input_tensor): return dataset_ops.Dataset.from_tensors(input_tensor).apply( batching.dense_to_sparse_batch(4, [12])) # Initialize with an input tensor of incompatible rank. get_next = self.getNext(dataset_fn([[1]])) with self.assertRaisesRegex(errors.InvalidArgumentError, "incompatible with the row shape"): self.evaluate(get_next()) # Initialize with an input tensor that is larger than `row_shape`. get_next = self.getNext(dataset_fn(np.int32(range(13)))) with self.assertRaisesRegex(errors.DataLossError, "larger than the row shape"): self.evaluate(get_next())
DenseToSparseBatchTest
python
neetcode-gh__leetcode
python/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.py
{ "start": 0, "end": 336 }
class ____: def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: res = 0 curSum = sum(arr[:k-1]) for L in range(len(arr) - k + 1): curSum += arr[L + k - 1] if (curSum / k) >= threshold: res += 1 curSum -= arr[L] return res
Solution
python
django__django
django/db/models/fields/json.py
{ "start": 7015, "end": 10623 }
class ____(PostgresOperatorLookup): logical_operator = None def compile_json_path_final_key(self, connection, key_transform): # Compile the final key without interpreting ints as array elements. return ".%s" % json.dumps(key_transform) def _as_sql_parts(self, compiler, connection): # Process JSON path from the left-hand side. if isinstance(self.lhs, KeyTransform): lhs_sql, lhs_params, lhs_key_transforms = self.lhs.preprocess_lhs( compiler, connection ) lhs_json_path = connection.ops.compile_json_path(lhs_key_transforms) else: lhs_sql, lhs_params = self.process_lhs(compiler, connection) lhs_json_path = "$" # Process JSON path from the right-hand side. rhs = self.rhs if not isinstance(rhs, (list, tuple)): rhs = [rhs] for key in rhs: if isinstance(key, KeyTransform): *_, rhs_key_transforms = key.preprocess_lhs(compiler, connection) else: rhs_key_transforms = [key] *rhs_key_transforms, final_key = rhs_key_transforms rhs_json_path = connection.ops.compile_json_path( rhs_key_transforms, include_root=False ) rhs_json_path += self.compile_json_path_final_key(connection, final_key) yield lhs_sql, lhs_params, lhs_json_path + rhs_json_path def _combine_sql_parts(self, parts): # Add condition for each key. if self.logical_operator: return "(%s)" % self.logical_operator.join(parts) return "".join(parts) def as_sql(self, compiler, connection, template=None): sql_parts = [] params = [] for lhs_sql, lhs_params, rhs_json_path in self._as_sql_parts( compiler, connection ): sql_parts.append(template % (lhs_sql, "%s")) params.extend([*lhs_params, rhs_json_path]) return self._combine_sql_parts(sql_parts), tuple(params) def as_mysql(self, compiler, connection): return self.as_sql( compiler, connection, template="JSON_CONTAINS_PATH(%s, 'one', %s)" ) def as_oracle(self, compiler, connection): # Use a custom delimiter to prevent the JSON path from escaping the SQL # literal. See comment in KeyTransform. template = "JSON_EXISTS(%s, q'\uffff%s\uffff')" sql_parts = [] params = [] for lhs_sql, lhs_params, rhs_json_path in self._as_sql_parts( compiler, connection ): # Add right-hand-side directly into SQL because it cannot be passed # as bind variables to JSON_EXISTS. It might result in invalid # queries but it is assumed that it cannot be evaded because the # path is JSON serialized. sql_parts.append(template % (lhs_sql, rhs_json_path)) params.extend(lhs_params) return self._combine_sql_parts(sql_parts), tuple(params) def as_postgresql(self, compiler, connection): if isinstance(self.rhs, KeyTransform): *_, rhs_key_transforms = self.rhs.preprocess_lhs(compiler, connection) for key in rhs_key_transforms[:-1]: self.lhs = KeyTransform(key, self.lhs) self.rhs = rhs_key_transforms[-1] return super().as_postgresql(compiler, connection) def as_sqlite(self, compiler, connection): return self.as_sql( compiler, connection, template="JSON_TYPE(%s, %s) IS NOT NULL" )
HasKeyLookup
python
mlflow__mlflow
mlflow/types/llm.py
{ "start": 9950, "end": 11019 }
class ____(ParamType): """ A single parameter within a function definition. Args: type (str): The type of the parameter. Possible values are "string", "number", "integer", "object", "array", "boolean", or "null", conforming to the JSON Schema specification. description (str): A description of the parameter. **Optional**, defaults to ``None`` enum (List[str]): Used to constrain the possible values for the parameter. **Optional**, defaults to ``None`` items (:py:class:`ParamProperty`): If the param is of ``array`` type, this field can be used to specify the type of its items. **Optional**, defaults to ``None`` """ description: str | None = None enum: list[str] | None = None items: ParamType | None = None def __post_init__(self): self._validate_field("description", str, False) self._validate_list("enum", str, False) self._convert_dataclass("items", ParamType, False) super().__post_init__() @dataclass
ParamProperty
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 21589, "end": 23628 }
class ____(mp.Process): # Why no *args? # py2 doesn't support def fn(x, *args, key=val, **kwargs) # Setting disable_stderr=True may generate a lot of unrelated error outputs # but could be helpful for debugging. def __init__(self, disable_stderr=True, **kwargs): super().__init__(**kwargs) self._pconn, self._cconn = mp.Pipe() self._exception = None self.disable_stderr = disable_stderr def run(self): set_faulthander_if_available() if self.disable_stderr: # Disable polluting stderr with errors that are supposed to happen. with open(os.devnull, "w") as devnull: os.dup2(devnull.fileno(), sys.stderr.fileno()) try: super().run() self._cconn.send(None) except Exception: self._cconn.send(ExceptionWrapper(sys.exc_info())) raise def print_traces_of_all_threads(self): assert self.is_alive(), ( "can only use print_traces_of_all_threads if the process is alive" ) assert not self.disable_stderr, ( "do not disable stderr if you use print_traces_of_all_threads" ) # On platforms without `SIGUSR1`, `set_faulthander_if_available` sets # `faulthandler.enable()`, and `print_traces_of_all_threads` may kill # the process. So let's poll the exception first _ = self.exception print_traces_of_all_threads(self.pid) @property def exception(self): if self._pconn.poll(): self._exception = self._pconn.recv() if self._exception is None: return None else: return self._exception.exc_type(self._exception.exc_msg) # ESRCH means that os.kill can't finds alive proc def send_signal(self, signum, ignore_ESRCH=False): try: os.kill(self.pid, signum) except OSError as e: if not ignore_ESRCH or e.errno != errno.ESRCH: raise
ErrorTrackingProcess
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/interfaces.py
{ "start": 7223, "end": 7768 }
class ____(TypedDict, total=False): compiled_cache: Optional[CompiledCacheType] logging_token: str isolation_level: IsolationLevel no_parameters: bool stream_results: bool max_row_buffer: int yield_per: int insertmanyvalues_page_size: int schema_translate_map: Optional[SchemaTranslateMapType] preserve_rowcount: bool driver_column_names: bool _ExecuteOptions = immutabledict[str, Any] CoreExecuteOptionsParameter = Union[ _CoreKnownExecutionOptions, Mapping[str, Any] ]
_CoreKnownExecutionOptions
python
eriklindernoren__ML-From-Scratch
mlfromscratch/supervised_learning/xgboost.py
{ "start": 468, "end": 1023 }
class ____(): def __init__(self): sigmoid = Sigmoid() self.log_func = sigmoid self.log_grad = sigmoid.gradient def loss(self, y, y_pred): y_pred = np.clip(y_pred, 1e-15, 1 - 1e-15) p = self.log_func(y_pred) return y * np.log(p) + (1 - y) * np.log(1 - p) # gradient w.r.t y_pred def gradient(self, y, y_pred): p = self.log_func(y_pred) return -(y - p) # w.r.t y_pred def hess(self, y, y_pred): p = self.log_func(y_pred) return p * (1 - p)
LogisticLoss
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 28732, "end": 29027 }
class ____(StateMachineEvent): __slots__ = ("data",) data: dict[Key, object] def to_loggable(self, *, handled: float) -> StateMachineEvent: out = copy(self) out.handled = handled out.data = dict.fromkeys(self.data) return out @dataclass
UpdateDataEvent
python
getsentry__sentry
tests/sentry/sentry_apps/test_sentry_app_component_preparer.py
{ "start": 354, "end": 3356 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.sentry_app = self.create_sentry_app( schema={"elements": [self.create_issue_link_schema()]} ) self.install = self.create_sentry_app_installation(slug=self.sentry_app.slug) self.component = self.sentry_app.components.first() with assume_test_silo_mode(SiloMode.REGION): self.project = Organization.objects.get( id=self.install.organization_id ).project_set.get() self.preparer = SentryAppComponentPreparer( component=self.component, install=self.install, project_slug=self.project.slug ) @responses.activate def test_prepares_components_requiring_requests(self) -> None: # the webhook uris that we'll contact to get field options uris = ["sentry/foo", "sentry/beep", "sentry/bar"] self.component.schema = { "link": { "required_fields": [ {"type": "select", "name": "foo", "label": "Foo", "uri": "/sentry/foo"} ], "optional_fields": [ {"type": "select", "name": "beep", "label": "Beep", "uri": "/sentry/beep"} ], }, "create": { "required_fields": [ {"type": "select", "name": "bar", "label": "Bar", "uri": "/sentry/bar"} ], "optional_fields": [ { "type": "select", "name": "baz", "label": "Baz", "uri": "/sentry/baz", "skip_load_on_open": True, } ], }, } responses.add( method=responses.GET, url=f"https://example.com/{uris[0]}?installationId={self.install.uuid}&projectSlug={self.project.slug}", json=[{"label": "Skibidi", "value": "Toilet", "default": True}], status=200, content_type="application/json", ) responses.add( method=responses.GET, url=f"https://example.com/{uris[1]}?installationId={self.install.uuid}&projectSlug={self.project.slug}", json=[{"label": "Dentge", "value": "skateparkge"}], status=200, content_type="application/json", ) responses.add( method=responses.GET, url=f"https://example.com/{uris[2]}?installationId={self.install.uuid}&projectSlug={self.project.slug}", json=[{"label": "uhhhhh idk", "value": "great_idea"}], status=200, content_type="application/json", ) self.preparer.run() # check that we did not make a request for skip_on_load components assert not any("/sentry/baz" in request.url for request, response in responses.calls) @control_silo_test
TestPreparerIssueLink
python
openai__openai-python
src/openai/_module_client.py
{ "start": 2258, "end": 2389 }
class ____(LazyProxy["Batches"]): @override def __load__(self) -> Batches: return _load_client().batches
BatchesProxy
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py
{ "start": 18647, "end": 21416 }
class ____(graphene.ObjectType): description = graphene.NonNull(graphene.String) type = graphene.NonNull(GraphenePartitionDefinitionType) dimensionTypes = non_null_list(GrapheneDimensionDefinitionType) name = graphene.Field(graphene.String) fmt = graphene.Field(graphene.String) class Meta: name = "PartitionDefinition" def resolve_dimensionTypes(self, _graphene_info): partition_def_data = self._partition_def_data return ( [ GrapheneDimensionDefinitionType( name=dim.name, description=str(dim.partitions.get_partitions_definition()), type=GraphenePartitionDefinitionType.from_partition_def_data(dim.partitions), isPrimaryDimension=dim.name == cast( "MultiPartitionsDefinition", partition_def_data.get_partitions_definition() ).primary_dimension.name, dynamicPartitionsDefinitionName=( dim.partitions.name if isinstance( dim.partitions, DynamicPartitionsSnap, ) else None ), ) for dim in partition_def_data.partition_dimensions ] if isinstance(partition_def_data, MultiPartitionsSnap) else [ GrapheneDimensionDefinitionType( name="default", description="", type=GraphenePartitionDefinitionType.from_partition_def_data( partition_def_data ), isPrimaryDimension=True, dynamicPartitionsDefinitionName=( partition_def_data.name if isinstance(partition_def_data, DynamicPartitionsSnap) else None ), ) ] ) def __init__(self, partition_def_data: PartitionsSnap): self._partition_def_data = partition_def_data super().__init__( description=str(partition_def_data.get_partitions_definition()), type=GraphenePartitionDefinitionType.from_partition_def_data(partition_def_data), name=( partition_def_data.name if isinstance(partition_def_data, DynamicPartitionsSnap) else None ), fmt=( partition_def_data.fmt if isinstance(partition_def_data, TimeWindowPartitionsSnap) else None ), )
GraphenePartitionDefinition
python
scrapy__scrapy
scrapy/extensions/memusage.py
{ "start": 757, "end": 6124 }
class ____: def __init__(self, crawler: Crawler): if not crawler.settings.getbool("MEMUSAGE_ENABLED"): raise NotConfigured try: # stdlib's resource module is only available on unix platforms. self.resource = import_module("resource") except ImportError: raise NotConfigured self.crawler: Crawler = crawler self.warned: bool = False self.notify_mails: list[str] = crawler.settings.getlist("MEMUSAGE_NOTIFY_MAIL") self.limit: int = crawler.settings.getint("MEMUSAGE_LIMIT_MB") * 1024 * 1024 self.warning: int = crawler.settings.getint("MEMUSAGE_WARNING_MB") * 1024 * 1024 self.check_interval: float = crawler.settings.getfloat( "MEMUSAGE_CHECK_INTERVAL_SECONDS" ) self.mail: MailSender = MailSender.from_crawler(crawler) crawler.signals.connect(self.engine_started, signal=signals.engine_started) crawler.signals.connect(self.engine_stopped, signal=signals.engine_stopped) @classmethod def from_crawler(cls, crawler: Crawler) -> Self: return cls(crawler) def get_virtual_size(self) -> int: size: int = self.resource.getrusage(self.resource.RUSAGE_SELF).ru_maxrss if sys.platform != "darwin": # on macOS ru_maxrss is in bytes, on Linux it is in KB size *= 1024 return size def engine_started(self) -> None: assert self.crawler.stats self.crawler.stats.set_value("memusage/startup", self.get_virtual_size()) self.tasks: list[AsyncioLoopingCall | LoopingCall] = [] tsk = create_looping_call(self.update) self.tasks.append(tsk) tsk.start(self.check_interval, now=True) if self.limit: tsk = create_looping_call(self._check_limit) self.tasks.append(tsk) tsk.start(self.check_interval, now=True) if self.warning: tsk = create_looping_call(self._check_warning) self.tasks.append(tsk) tsk.start(self.check_interval, now=True) def engine_stopped(self) -> None: for tsk in self.tasks: if tsk.running: tsk.stop() def update(self) -> None: assert self.crawler.stats self.crawler.stats.max_value("memusage/max", self.get_virtual_size()) def _check_limit(self) -> None: assert self.crawler.engine assert self.crawler.stats peak_mem_usage = self.get_virtual_size() if peak_mem_usage > self.limit: self.crawler.stats.set_value("memusage/limit_reached", 1) mem = self.limit / 1024 / 1024 logger.error( "Memory usage exceeded %(memusage)dMiB. Shutting down Scrapy...", {"memusage": mem}, extra={"crawler": self.crawler}, ) if self.notify_mails: subj = ( f"{self.crawler.settings['BOT_NAME']} terminated: " f"memory usage exceeded {mem}MiB at {socket.gethostname()}" ) self._send_report(self.notify_mails, subj) self.crawler.stats.set_value("memusage/limit_notified", 1) if self.crawler.engine.spider is not None: _schedule_coro( self.crawler.engine.close_spider_async(reason="memusage_exceeded") ) else: _schedule_coro(self.crawler.stop_async()) else: logger.info( "Peak memory usage is %(virtualsize)dMiB", {"virtualsize": peak_mem_usage / 1024 / 1024}, ) def _check_warning(self) -> None: if self.warned: # warn only once return assert self.crawler.stats if self.get_virtual_size() > self.warning: self.crawler.stats.set_value("memusage/warning_reached", 1) mem = self.warning / 1024 / 1024 logger.warning( "Memory usage reached %(memusage)dMiB", {"memusage": mem}, extra={"crawler": self.crawler}, ) if self.notify_mails: subj = ( f"{self.crawler.settings['BOT_NAME']} warning: " f"memory usage reached {mem}MiB at {socket.gethostname()}" ) self._send_report(self.notify_mails, subj) self.crawler.stats.set_value("memusage/warning_notified", 1) self.warned = True def _send_report(self, rcpts: list[str], subject: str) -> None: """send notification mail with some additional useful info""" assert self.crawler.engine assert self.crawler.stats stats = self.crawler.stats s = f"Memory usage at engine startup : {stats.get_value('memusage/startup') / 1024 / 1024}M\r\n" s += f"Maximum memory usage : {stats.get_value('memusage/max') / 1024 / 1024}M\r\n" s += f"Current memory usage : {self.get_virtual_size() / 1024 / 1024}M\r\n" s += ( "ENGINE STATUS ------------------------------------------------------- \r\n" ) s += "\r\n" s += pformat(get_engine_status(self.crawler.engine)) s += "\r\n" self.mail.send(rcpts, subject, s)
MemoryUsage
python
PyCQA__pylint
tests/functional/m/missing/missing_docstring_new_style.py
{ "start": 311, "end": 843 }
class ____: # [missing-class-docstring] pass def public_documented(): """It has a docstring.""" def _private_undocumented(): # Doesn't need a docstring pass def _private_documented(): """It has a docstring.""" def public_undocumented(): # [missing-function-docstring] pass # pylint: disable=missing-function-docstring def undocumented_function(): pass # pylint: enable=missing-function-docstring def undocumented_other_function(): # [missing-function-docstring] pass
OtherClassUndocumented
python
dagster-io__dagster
python_modules/libraries/dagster-deltalake/dagster_deltalake/handler.py
{ "start": 1109, "end": 6719 }
class ____(DbTypeHandler[T], Generic[T]): @abstractmethod def from_arrow(self, obj: pa.RecordBatchReader, target_type: type) -> T: pass @abstractmethod def to_arrow(self, obj: T) -> tuple[pa.RecordBatchReader, dict[str, Any]]: pass def handle_output( self, context: OutputContext, table_slice: TableSlice, obj: T, connection: TableConnection, ): """Stores pyarrow types in Delta table.""" metadata = context.definition_metadata or {} resource_config = context.resource_config or {} reader, delta_params = self.to_arrow(obj=obj) save_mode = metadata.get("mode") main_save_mode = resource_config.get("mode") main_custom_metadata = resource_config.get("custom_metadata") overwrite_schema = resource_config.get("overwrite_schema") writerprops = resource_config.get("writer_properties") if save_mode is not None: context.log.debug( "IO manager mode overridden with the asset metadata mode, %s -> %s", main_save_mode, save_mode, ) main_save_mode = save_mode # Handle default mode and partitioned table logic if main_save_mode is None: main_save_mode = "overwrite" # default mode # For partitioned tables, determine the appropriate mode and predicate predicate = None if _has_partitions(table_slice): try: existing_table = DeltaTable( connection.table_uri, storage_options=connection.storage_options ) if main_save_mode == "overwrite": predicate = _build_partition_predicate( table_slice.partition_dimensions, existing_table.schema() ) if predicate: context.log.debug( f"Table exists and is partitioned, using predicate to overwrite specific partition: {predicate}" ) else: # Fallback to append if we can't build predicate main_save_mode = "append" context.log.debug( "Table exists and is partitioned, using append mode to preserve other partitions" ) except Exception: # Table doesn't exist, keep the original mode pass context.log.debug("Writing with mode: %s", main_save_mode) partition_columns = None if _has_partitions(table_slice): # TODO make robust and move to function partition_columns = [ dim.partition_expr for dim in table_slice.partition_dimensions or [] ] # legacy parameter overwrite_schema = metadata.get("overwrite_schema") or overwrite_schema # Prepare commit properties custom_metadata = metadata.get("custom_metadata") or main_custom_metadata commit_props = None if custom_metadata and isinstance(custom_metadata, dict): commit_props = CommitProperties(custom_metadata=custom_metadata) # Prepare write parameters write_params = { "table_or_uri": connection.table_uri, "data": reader, "storage_options": connection.storage_options, "mode": main_save_mode, "partition_by": partition_columns, "schema_mode": "overwrite" if overwrite_schema else None, "commit_properties": commit_props, "writer_properties": WriterProperties(**writerprops) # type: ignore if writerprops is not None else writerprops, **delta_params, } # Add predicate if specified for partition-specific overwrite if predicate is not None: write_params["predicate"] = predicate write_deltalake(**write_params) # TODO make stats computation configurable on type handler dt = DeltaTable(connection.table_uri, storage_options=connection.storage_options) try: _table, stats = _get_partition_stats(dt=dt, table_slice=table_slice) except Exception as e: context.log.warn(f"error while computing table stats: {e}") stats = {} context.add_output_metadata( { "table_columns": MetadataValue.table_schema( TableSchema( columns=[ TableColumn(name=name, type=str(dtype)) for name, dtype in zip(reader.schema.names, reader.schema.types) ] ) ), "table_uri": connection.table_uri, **stats, } ) def load_input( self, context: InputContext, table_slice: TableSlice, connection: TableConnection, ) -> T: """Loads the input as a pyarrow Table or RecordBatchReader.""" dataset = _table_reader(table_slice, connection) if context.dagster_type.typing_type == ds.Dataset: if table_slice.columns is not None: raise ValueError("Cannot select columns when loading as Dataset.") return dataset scanner = dataset.scanner(columns=table_slice.columns) return self.from_arrow(scanner.to_reader(), context.dagster_type.typing_type)
DeltalakeBaseArrowTypeHandler
python
pytorch__pytorch
torch/_export/db/examples/dynamic_shape_view.py
{ "start": 41, "end": 444 }
class ____(torch.nn.Module): """ Dynamic shapes should be propagated to view arguments instead of being baked into the exported graph. """ def forward(self, x): new_x_shape = x.size()[:-1] + (2, 5) x = x.view(*new_x_shape) return x.permute(0, 2, 1) example_args = (torch.randn(10, 10),) tags = {"torch.dynamic-shape"} model = DynamicShapeView()
DynamicShapeView
python
ray-project__ray
python/ray/autoscaler/_private/updater.py
{ "start": 1024, "end": 24691 }
class ____: """A process for syncing files and running init commands on a node. Arguments: node_id: the Node ID provider_config: Provider section of autoscaler yaml provider: NodeProvider Class auth_config: Auth section of autoscaler yaml cluster_name: the name of the cluster. file_mounts: Map of remote to local paths initialization_commands: Commands run before container launch setup_commands: Commands run before ray starts ray_start_commands: Commands to start ray runtime_hash: Used to check for config changes file_mounts_contents_hash: Used to check for changes to file mounts is_head_node: Whether to use head start/setup commands rsync_options: Extra options related to the rsync command. process_runner: the module to use to run the commands in the CommandRunner. E.g., subprocess. use_internal_ip: Wwhether the node_id belongs to an internal ip or external ip. docker_config: Docker section of autoscaler yaml restart_only: Whether to skip setup commands & just restart ray for_recovery: True if updater is for a recovering node. Only used for metric tracking. """ def __init__( self, node_id, provider_config, provider, auth_config, cluster_name, file_mounts, initialization_commands, setup_commands, ray_start_commands, runtime_hash, file_mounts_contents_hash, is_head_node, node_resources=None, node_labels=None, cluster_synced_files=None, rsync_options=None, process_runner=subprocess, use_internal_ip=False, docker_config=None, restart_only=False, for_recovery=False, ): self.log_prefix = "NodeUpdater: {}: ".format(node_id) # Three cases: # 1) use_internal_ip arg is True -> use_internal_ip is True # 2) worker node -> use value of provider_config["use_internal_ips"] # 3) head node -> use value of provider_config["use_internal_ips"] unless # overriden by provider_config["use_external_head_ip"] use_internal_ip = use_internal_ip or ( provider_config.get("use_internal_ips", False) and not ( is_head_node and provider_config.get("use_external_head_ip", False) ) ) self.cmd_runner = provider.get_command_runner( self.log_prefix, node_id, auth_config, cluster_name, process_runner, use_internal_ip, docker_config, ) self.daemon = True self.node_id = node_id self.provider_type = provider_config.get("type") self.provider = provider # Some node providers don't specify empty structures as # defaults. Better to be defensive. file_mounts = file_mounts or {} self.file_mounts = { remote: os.path.expanduser(local) for remote, local in file_mounts.items() } self.initialization_commands = initialization_commands self.setup_commands = setup_commands self.ray_start_commands = ray_start_commands self.node_resources = node_resources self.node_labels = node_labels self.runtime_hash = runtime_hash self.file_mounts_contents_hash = file_mounts_contents_hash # TODO (Alex): This makes the assumption that $HOME on the head and # worker nodes is the same. Also note that `cluster_synced_files` is # set on the head -> worker updaters only (so `expanduser` is only run # on the head node). cluster_synced_files = cluster_synced_files or [] self.cluster_synced_files = [ os.path.expanduser(path) for path in cluster_synced_files ] self.rsync_options = rsync_options or {} self.auth_config = auth_config self.is_head_node = is_head_node self.docker_config = docker_config self.restart_only = restart_only self.update_time = None self.for_recovery = for_recovery def run(self): update_start_time = time.time() if ( cmd_output_util.does_allow_interactive() and cmd_output_util.is_output_redirected() ): # this is most probably a bug since the user has no control # over these settings msg = ( "Output was redirected for an interactive command. " "Either do not pass `--redirect-command-output` " "or also pass in `--use-normal-shells`." ) cli_logger.abort(msg) try: with LogTimer( self.log_prefix + "Applied config {}".format(self.runtime_hash) ): self.do_update() except Exception as e: self.provider.set_node_tags( self.node_id, {TAG_RAY_NODE_STATUS: STATUS_UPDATE_FAILED} ) cli_logger.error("New status: {}", cf.bold(STATUS_UPDATE_FAILED)) cli_logger.error("!!!") if hasattr(e, "cmd"): stderr_output = getattr(e, "stderr", "No stderr available") cli_logger.error( "Setup command `{}` failed with exit code {}. stderr: {}", cf.bold(e.cmd), e.returncode, stderr_output, ) else: cli_logger.verbose_error("Exception details: {}", str(vars(e))) full_traceback = traceback.format_exc() cli_logger.error("Full traceback: {}", full_traceback) # todo: handle this better somehow? cli_logger.error("Error message: {}", str(e)) cli_logger.error("!!!") cli_logger.newline() if isinstance(e, click.ClickException): # todo: why do we ignore this here return raise tags_to_set = { TAG_RAY_NODE_STATUS: STATUS_UP_TO_DATE, TAG_RAY_RUNTIME_CONFIG: self.runtime_hash, } if self.file_mounts_contents_hash is not None: tags_to_set[TAG_RAY_FILE_MOUNTS_CONTENTS] = self.file_mounts_contents_hash self.provider.set_node_tags(self.node_id, tags_to_set) cli_logger.labeled_value("New status", STATUS_UP_TO_DATE) self.update_time = time.time() - update_start_time self.exitcode = 0 def sync_file_mounts(self, sync_cmd, step_numbers=(0, 2)): # step_numbers is (# of previous steps, total steps) previous_steps, total_steps = step_numbers nolog_paths = [] if cli_logger.verbosity == 0: nolog_paths = ["~/ray_bootstrap_key.pem", "~/ray_bootstrap_config.yaml"] def do_sync(remote_path, local_path, allow_non_existing_paths=False): if allow_non_existing_paths and not os.path.exists(local_path): cli_logger.print("sync: {} does not exist. Skipping.", local_path) # Ignore missing source files. In the future we should support # the --delete-missing-args command to delete files that have # been removed return assert os.path.exists(local_path), local_path if os.path.isdir(local_path): if not local_path.endswith("/"): local_path += "/" if not remote_path.endswith("/"): remote_path += "/" with LogTimer( self.log_prefix + "Synced {} to {}".format(local_path, remote_path) ): is_docker = ( self.docker_config and self.docker_config["container_name"] != "" ) if not is_docker: # The DockerCommandRunner handles this internally. self.cmd_runner.run( "mkdir -p {}".format(os.path.dirname(remote_path)), run_env="host", ) sync_cmd(local_path, remote_path, docker_mount_if_possible=True) if remote_path not in nolog_paths: # todo: timed here? cli_logger.print( "{} from {}", cf.bold(remote_path), cf.bold(local_path) ) # Rsync file mounts with cli_logger.group( "Processing file mounts", _numbered=("[]", previous_steps + 1, total_steps) ): for remote_path, local_path in self.file_mounts.items(): do_sync(remote_path, local_path) previous_steps += 1 if self.cluster_synced_files: with cli_logger.group( "Processing worker file mounts", _numbered=("[]", previous_steps + 1, total_steps), ): cli_logger.print("synced files: {}", str(self.cluster_synced_files)) for path in self.cluster_synced_files: do_sync(path, path, allow_non_existing_paths=True) previous_steps += 1 else: cli_logger.print( "No worker file mounts to sync", _numbered=("[]", previous_steps + 1, total_steps), ) def wait_ready(self, deadline): with cli_logger.group( "Waiting for SSH to become available", _numbered=("[]", 1, NUM_SETUP_STEPS) ): with LogTimer(self.log_prefix + "Got remote shell"): cli_logger.print("Running `{}` as a test.", cf.bold("uptime")) first_conn_refused_time = None while True: if time.time() > deadline: raise Exception("wait_ready timeout exceeded.") if self.provider.is_terminated(self.node_id): raise Exception( "wait_ready aborting because node " "detected as terminated." ) try: # Run outside of the container self.cmd_runner.run("uptime", timeout=10, run_env="host") cli_logger.success("Success.") return True except ProcessRunnerError as e: first_conn_refused_time = cmd_output_util.handle_ssh_fails( e, first_conn_refused_time, retry_interval=READY_CHECK_INTERVAL, ) time.sleep(READY_CHECK_INTERVAL) except Exception as e: # TODO(maximsmol): we should not be ignoring # exceptions if they get filtered properly # (new style log + non-interactive shells) # # however threading this configuration state # is a pain and I'm leaving it for later retry_str = "(" + str(e) + ")" if hasattr(e, "cmd"): if isinstance(e.cmd, str): cmd_ = e.cmd elif isinstance(e.cmd, list): cmd_ = " ".join(e.cmd) else: logger.debug( f"e.cmd type ({type(e.cmd)}) not list or str." ) cmd_ = str(e.cmd) retry_str = "(Exit Status {}): {}".format( e.returncode, cmd_ ) cli_logger.print( "SSH still not available {}, retrying in {} seconds.", cf.dimmed(retry_str), cf.bold(str(READY_CHECK_INTERVAL)), ) time.sleep(READY_CHECK_INTERVAL) def do_update(self): self.provider.set_node_tags( self.node_id, {TAG_RAY_NODE_STATUS: STATUS_WAITING_FOR_SSH} ) cli_logger.labeled_value("New status", STATUS_WAITING_FOR_SSH) deadline = time.time() + AUTOSCALER_NODE_START_WAIT_S self.wait_ready(deadline) global_event_system.execute_callback(CreateClusterEvent.ssh_control_acquired) node_tags = self.provider.node_tags(self.node_id) logger.debug("Node tags: {}".format(str(node_tags))) if self.provider_type == "aws" and self.provider.provider_config: from ray.autoscaler._private.aws.cloudwatch.cloudwatch_helper import ( CloudwatchHelper, ) CloudwatchHelper( self.provider.provider_config, self.node_id, self.provider.cluster_name ).update_from_config(self.is_head_node) if node_tags.get(TAG_RAY_RUNTIME_CONFIG) == self.runtime_hash: # When resuming from a stopped instance the runtime_hash may be the # same, but the container will not be started. init_required = self.cmd_runner.run_init( as_head=self.is_head_node, file_mounts=self.file_mounts, sync_run_yet=False, ) if init_required: node_tags[TAG_RAY_RUNTIME_CONFIG] += "-invalidate" # This ensures that `setup_commands` are not removed self.restart_only = False if self.restart_only: self.setup_commands = [] # runtime_hash will only change whenever the user restarts # or updates their cluster with `get_or_create_head_node` if node_tags.get(TAG_RAY_RUNTIME_CONFIG) == self.runtime_hash and ( not self.file_mounts_contents_hash or node_tags.get(TAG_RAY_FILE_MOUNTS_CONTENTS) == self.file_mounts_contents_hash ): # todo: we lie in the confirmation message since # full setup might be cancelled here cli_logger.print( "Configuration already up to date, " "skipping file mounts, initalization and setup commands.", _numbered=("[]", "2-6", NUM_SETUP_STEPS), ) else: cli_logger.print( "Updating cluster configuration.", _tags=dict(hash=self.runtime_hash) ) self.provider.set_node_tags( self.node_id, {TAG_RAY_NODE_STATUS: STATUS_SYNCING_FILES} ) cli_logger.labeled_value("New status", STATUS_SYNCING_FILES) self.sync_file_mounts(self.rsync_up, step_numbers=(1, NUM_SETUP_STEPS)) # Only run setup commands if runtime_hash has changed because # we don't want to run setup_commands every time the head node # file_mounts folders have changed. if node_tags.get(TAG_RAY_RUNTIME_CONFIG) != self.runtime_hash: # Run init commands self.provider.set_node_tags( self.node_id, {TAG_RAY_NODE_STATUS: STATUS_SETTING_UP} ) cli_logger.labeled_value("New status", STATUS_SETTING_UP) if self.initialization_commands: with cli_logger.group( "Running initialization commands", _numbered=("[]", 4, NUM_SETUP_STEPS), ): global_event_system.execute_callback( CreateClusterEvent.run_initialization_cmd ) with LogTimer( self.log_prefix + "Initialization commands", show_status=True, ): for cmd in self.initialization_commands: global_event_system.execute_callback( CreateClusterEvent.run_initialization_cmd, {"command": cmd}, ) try: # Overriding the existing SSHOptions class # with a new SSHOptions class that uses # this ssh_private_key as its only __init__ # argument. # Run outside docker. self.cmd_runner.run( cmd, ssh_options_override_ssh_key=self.auth_config.get( # noqa: E501 "ssh_private_key" ), run_env="host", ) except ProcessRunnerError as e: if e.msg_type == "ssh_command_failed": cli_logger.error("Failed.") cli_logger.error("See above for stderr.") raise click.ClickException( "Initialization command failed." ) from None else: cli_logger.print( "No initialization commands to run.", _numbered=("[]", 4, NUM_SETUP_STEPS), ) with cli_logger.group( "Initializing command runner", # todo: fix command numbering _numbered=("[]", 5, NUM_SETUP_STEPS), ): self.cmd_runner.run_init( as_head=self.is_head_node, file_mounts=self.file_mounts, sync_run_yet=True, ) if self.setup_commands: with cli_logger.group( "Running setup commands", # todo: fix command numbering _numbered=("[]", 6, NUM_SETUP_STEPS), ): global_event_system.execute_callback( CreateClusterEvent.run_setup_cmd ) with LogTimer( self.log_prefix + "Setup commands", show_status=True ): total = len(self.setup_commands) for i, cmd in enumerate(self.setup_commands): global_event_system.execute_callback( CreateClusterEvent.run_setup_cmd, {"command": cmd} ) if cli_logger.verbosity == 0 and len(cmd) > 30: cmd_to_print = cf.bold(cmd[:30]) + "..." else: cmd_to_print = cf.bold(cmd) cli_logger.print( "{}", cmd_to_print, _numbered=("()", i, total) ) try: # Runs in the container if docker is in use self.cmd_runner.run(cmd, run_env="auto") except ProcessRunnerError as e: if e.msg_type == "ssh_command_failed": cli_logger.error("Failed.") cli_logger.error("See above for stderr.") raise click.ClickException("Setup command failed.") else: cli_logger.print( "No setup commands to run.", _numbered=("[]", 6, NUM_SETUP_STEPS), ) with cli_logger.group( "Starting the Ray runtime", _numbered=("[]", 7, NUM_SETUP_STEPS) ): global_event_system.execute_callback(CreateClusterEvent.start_ray_runtime) with LogTimer(self.log_prefix + "Ray start commands", show_status=True): for cmd in self.ray_start_commands: env_vars = {} if self.is_head_node: if usage_lib.usage_stats_enabled(): env_vars[usage_constants.USAGE_STATS_ENABLED_ENV_VAR] = 1 else: # Disable usage stats collection in the cluster. env_vars[usage_constants.USAGE_STATS_ENABLED_ENV_VAR] = 0 # Add a resource override env variable if needed. # Local NodeProvider doesn't need resource and label override. if self.provider_type != "local": if self.node_resources: env_vars[ RESOURCES_ENVIRONMENT_VARIABLE ] = self.node_resources if self.node_labels: env_vars[LABELS_ENVIRONMENT_VARIABLE] = self.node_labels try: old_redirected = cmd_output_util.is_output_redirected() cmd_output_util.set_output_redirected(False) # Runs in the container if docker is in use self.cmd_runner.run( cmd, environment_variables=env_vars, run_env="auto" ) cmd_output_util.set_output_redirected(old_redirected) except ProcessRunnerError as e: if e.msg_type == "ssh_command_failed": cli_logger.error("Failed.") cli_logger.error("See above for stderr.") raise click.ClickException("Start command failed.") global_event_system.execute_callback( CreateClusterEvent.start_ray_runtime_completed ) def rsync_up(self, source, target, docker_mount_if_possible=False): options = {} options["docker_mount_if_possible"] = docker_mount_if_possible options["rsync_exclude"] = self.rsync_options.get("rsync_exclude") options["rsync_filter"] = self.rsync_options.get("rsync_filter") self.cmd_runner.run_rsync_up(source, target, options=options) cli_logger.verbose( "`rsync`ed {} (local) to {} (remote)", cf.bold(source), cf.bold(target) ) def rsync_down(self, source, target, docker_mount_if_possible=False): options = {} options["docker_mount_if_possible"] = docker_mount_if_possible options["rsync_exclude"] = self.rsync_options.get("rsync_exclude") options["rsync_filter"] = self.rsync_options.get("rsync_filter") self.cmd_runner.run_rsync_down(source, target, options=options) cli_logger.verbose( "`rsync`ed {} (remote) to {} (local)", cf.bold(source), cf.bold(target) )
NodeUpdater
python
django__django
django/db/migrations/operations/models.py
{ "start": 28994, "end": 30504 }
class ____(ModelOptionOperation): """ Set new model options that don't directly affect the database schema (like verbose_name, permissions, ordering). Python code in migrations may still need them. """ # Model options we want to compare and preserve in an AlterModelOptions op ALTER_OPTION_KEYS = [ "base_manager_name", "default_manager_name", "default_related_name", "get_latest_by", "managed", "ordering", "permissions", "default_permissions", "select_on_save", "verbose_name", "verbose_name_plural", ] def __init__(self, name, options): self.options = options super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "options": self.options, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, self.options, self.ALTER_OPTION_KEYS, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change Meta options on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_options" % self.name_lower
AlterModelOptions
python
kamyu104__LeetCode-Solutions
Python/distance-to-a-cycle-in-undirected-graph.py
{ "start": 63, "end": 1519 }
class ____(object): def distanceToCycle(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[int] """ def cycle(parent, v, u): result = [parent[v], v] while u != parent[v]: result.append(u) u = parent[u] return result def iter_dfs(adj): stk = [0] parent = [-2]*len(adj) parent[0] = -1 while stk: u = stk.pop() for v in reversed(adj[u]): if parent[v] != -2: if v == parent[u]: continue return cycle(parent, v, u) parent[v] = u stk.append(v) def bfs(adj, q): result = [-1]*n for x in q: result[x] = 0 d = 1 while q: new_q = [] for u in q: for v in adj[u]: if result[v] != -1: continue result[v] = d new_q.append(v) q = new_q d += 1 return result adj = [[] for _ in xrange(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) return bfs(adj, iter_dfs(adj))
Solution
python
django-guardian__django-guardian
guardian/migrations/0002_generic_permissions_index.py
{ "start": 92, "end": 615 }
class ____(migrations.Migration): dependencies = [ ("guardian", "0001_initial"), ] operations = [ migrations.AddIndex( model_name="groupobjectpermission", index=models.Index(fields=["content_type", "object_pk"], name="guardian_gr_content_ae6aec_idx"), ), migrations.AddIndex( model_name="userobjectpermission", index=models.Index(fields=["content_type", "object_pk"], name="guardian_us_content_179ed2_idx"), ), ]
Migration
python
ray-project__ray
python/ray/data/_internal/plan.py
{ "start": 1320, "end": 25618 }
class ____: """A lazy execution plan for a Dataset. This lazy execution plan builds up a chain of ``List[RefBundle]`` --> ``List[RefBundle]`` operators. Prior to execution, we apply a set of logical plan optimizations, such as operator fusion, in order to reduce Ray task overhead and data copies. Internally, the execution plan holds a snapshot of a computed list of blocks and their associated metadata under ``self._snapshot_bundle``, where this snapshot is the cached output of executing the operator chain.""" def __init__( self, stats: DatasetStats, data_context: DataContext, ): """Create a plan with no transformation operators. Args: stats: Stats for the base blocks. data_context: :class:`~ray.data.context.DataContext` object to use for execution. """ self._in_stats = stats # A computed snapshot of some prefix of operators and their corresponding # output blocks and stats. self._snapshot_operator: Optional[LogicalOperator] = None self._snapshot_stats = None self._snapshot_bundle = None # Snapshot of only metadata corresponding to the final operator's # output bundles, used as the source of truth for the Dataset's schema # and count. This is calculated and cached when the plan is executed as an # iterator (`execute_to_iterator()`), and avoids caching # all of the output blocks in memory like in `self.snapshot_bundle`. # TODO(scottjlee): To keep the caching logic consistent, update `execute()` # to also store the metadata in `_snapshot_metadata` instead of # `_snapshot_bundle`. For example, we could store the blocks in # `self._snapshot_blocks` and the metadata in `self._snapshot_metadata`. self._snapshot_metadata_schema: Optional["BlockMetadataWithSchema"] = None # Cached schema. self._schema = None # Set when a Dataset is constructed with this plan self._dataset_uuid = None # Index of the current execution. self._run_index = -1 self._dataset_name = None self._has_started_execution = False self._context = data_context def get_dataset_id(self) -> str: """Unique ID of the dataset, including the dataset name, UUID, and current execution index. """ return ( f"{self._dataset_name or 'dataset'}_{self._dataset_uuid}_{self._run_index}" ) def create_executor(self) -> "StreamingExecutor": """Create an executor for this plan.""" from ray.data._internal.execution.streaming_executor import StreamingExecutor self._run_index += 1 executor = StreamingExecutor(self._context, self.get_dataset_id()) return executor def __repr__(self) -> str: return ( f"ExecutionPlan(" f"dataset_uuid={self._dataset_uuid}, " f"snapshot_operator={self._snapshot_operator}" f")" ) def explain(self) -> str: """Return a string representation of the logical and physical plan.""" convert_fns = [lambda x: x] + get_plan_conversion_fns() titles: List[str] = [ "Logical Plan", "Logical Plan (Optimized)", "Physical Plan", "Physical Plan (Optimized)", ] # 1. Set initial plan plan = self._logical_plan sections = [] for title, convert_fn in zip(titles, convert_fns): # 2. Convert plan to new plan plan = convert_fn(plan) # 3. Generate plan str from new plan. plan_str, _ = self.generate_plan_string(plan.dag, show_op_repr=True) banner = f"\n-------- {title} --------\n" section = f"{banner}{plan_str}" sections.append(section) return "".join(sections) @staticmethod def generate_plan_string( op: Operator, curr_str: str = "", depth: int = 0, including_source: bool = True, show_op_repr: bool = False, ): """Traverse (DFS) the Plan DAG and return a string representation of the operators.""" if not including_source and isinstance(op, SourceOperator): return curr_str, depth curr_max_depth = depth # For logical plan, only show the operator name like "Aggregate". # But for physical plan, show the operator class name as well like "AllToAllOperator[Aggregate]". op_str = repr(op) if show_op_repr else op.name if depth == 0: curr_str += f"{op_str}\n" else: trailing_space = " " * ((depth - 1) * 3) curr_str += f"{trailing_space}+- {op_str}\n" for input in op.input_dependencies: curr_str, input_max_depth = ExecutionPlan.generate_plan_string( input, curr_str, depth + 1, including_source, show_op_repr ) curr_max_depth = max(curr_max_depth, input_max_depth) return curr_str, curr_max_depth def get_plan_as_string(self, dataset_cls: Type["Dataset"]) -> str: """Create a cosmetic string representation of this execution plan. Returns: The string representation of this execution plan. """ # NOTE: this is used for Dataset.__repr__ to give a user-facing string # representation. Ideally ExecutionPlan.__repr__ should be replaced with this # method as well. from ray.data.dataset import MaterializedDataset # Do not force execution for schema, as this method is expected to be very # cheap. plan_str = "" plan_max_depth = 0 if not self.has_computed_output(): # using dataset as source here, so don't generate source operator in generate_plan_string plan_str, plan_max_depth = self.generate_plan_string( self._logical_plan.dag, including_source=False ) if self._snapshot_bundle is not None: # This plan has executed some but not all operators. schema = self._snapshot_bundle.schema count = self._snapshot_bundle.num_rows() elif self._snapshot_metadata_schema is not None: schema = self._snapshot_metadata_schema.schema count = self._snapshot_metadata_schema.metadata.num_rows else: # This plan hasn't executed any operators. has_n_ary_operator = False dag = self._logical_plan.dag while not isinstance(dag, SourceOperator): if len(dag.input_dependencies) > 1: has_n_ary_operator = True break dag = dag.input_dependencies[0] # TODO(@bveeramani): Handle schemas for n-ary operators like `Union`. if has_n_ary_operator: schema = None count = None else: assert isinstance(dag, SourceOperator), dag plan = ExecutionPlan( DatasetStats(metadata={}, parent=None), self._context, ) plan.link_logical_plan(LogicalPlan(dag, plan._context)) schema = plan.schema() count = plan.meta_count() else: # Get schema of output blocks. schema = self.schema(fetch_if_missing=False) count = self._snapshot_bundle.num_rows() if schema is None: schema_str = "Unknown schema" elif isinstance(schema, type): schema_str = str(schema) else: schema_str = [] for n, t in zip(schema.names, schema.types): if hasattr(t, "__name__"): t = t.__name__ schema_str.append(f"{n}: {t}") schema_str = ", ".join(schema_str) schema_str = "{" + schema_str + "}" if count is None: count = "?" num_blocks = None if dataset_cls == MaterializedDataset: num_blocks = self.initial_num_blocks() assert num_blocks is not None name_str = ( "name={}, ".format(self._dataset_name) if self._dataset_name is not None else "" ) num_blocks_str = f"num_blocks={num_blocks}, " if num_blocks else "" dataset_str = "{}({}{}num_rows={}, schema={})".format( dataset_cls.__name__, name_str, num_blocks_str, count, schema_str, ) # If the resulting string representation fits in one line, use it directly. SCHEMA_LINE_CHAR_LIMIT = 80 MIN_FIELD_LENGTH = 10 INDENT_STR = " " * 3 trailing_space = INDENT_STR * plan_max_depth if len(dataset_str) > SCHEMA_LINE_CHAR_LIMIT: # If the resulting string representation exceeds the line char limit, # first try breaking up each `Dataset` parameter into its own line # and check if each line fits within the line limit. We check the # `schema` param's length, since this is likely the longest string. schema_str_on_new_line = f"{trailing_space}{INDENT_STR}schema={schema_str}" if len(schema_str_on_new_line) > SCHEMA_LINE_CHAR_LIMIT: # If the schema cannot fit on a single line, break up each field # into its own line. schema_str = [] for n, t in zip(schema.names, schema.types): if hasattr(t, "__name__"): t = t.__name__ col_str = f"{trailing_space}{INDENT_STR * 2}{n}: {t}" # If the field line exceeds the char limit, abbreviate # the field name to fit while maintaining the full type if len(col_str) > SCHEMA_LINE_CHAR_LIMIT: shortened_suffix = f"...: {str(t)}" # Show at least 10 characters of the field name, even if # we have already hit the line limit with the type. chars_left_for_col_name = max( SCHEMA_LINE_CHAR_LIMIT - len(shortened_suffix), MIN_FIELD_LENGTH, ) col_str = ( f"{col_str[:chars_left_for_col_name]}{shortened_suffix}" ) schema_str.append(col_str) schema_str = ",\n".join(schema_str) schema_str = ( "{\n" + schema_str + f"\n{trailing_space}{INDENT_STR}" + "}" ) name_str = ( f"\n{trailing_space}{INDENT_STR}name={self._dataset_name}," if self._dataset_name is not None else "" ) num_blocks_str = ( f"\n{trailing_space}{INDENT_STR}num_blocks={num_blocks}," if num_blocks else "" ) dataset_str = ( f"{dataset_cls.__name__}(" f"{name_str}" f"{num_blocks_str}" f"\n{trailing_space}{INDENT_STR}num_rows={count}," f"\n{trailing_space}{INDENT_STR}schema={schema_str}" f"\n{trailing_space})" ) if plan_max_depth == 0: plan_str += dataset_str else: plan_str += f"{INDENT_STR * (plan_max_depth - 1)}+- {dataset_str}" return plan_str def link_logical_plan(self, logical_plan: "LogicalPlan"): """Link the logical plan into this execution plan. This is used for triggering execution for optimizer code path in this legacy execution plan. """ self._logical_plan = logical_plan self._logical_plan._context = self._context def copy(self) -> "ExecutionPlan": """Create a shallow copy of this execution plan. This copy can be executed without mutating the original, but clearing the copy will also clear the original. Returns: A shallow copy of this execution plan. """ plan_copy = ExecutionPlan( self._in_stats, data_context=self._context, ) if self._snapshot_bundle is not None: # Copy over the existing snapshot. plan_copy._snapshot_bundle = self._snapshot_bundle plan_copy._snapshot_operator = self._snapshot_operator plan_copy._snapshot_stats = self._snapshot_stats plan_copy._dataset_name = self._dataset_name return plan_copy def deep_copy(self) -> "ExecutionPlan": """Create a deep copy of this execution plan. This copy can be executed AND cleared without mutating the original. Returns: A deep copy of this execution plan. """ plan_copy = ExecutionPlan( copy.copy(self._in_stats), data_context=self._context.copy(), ) if self._snapshot_bundle: # Copy over the existing snapshot. plan_copy._snapshot_bundle = copy.copy(self._snapshot_bundle) plan_copy._snapshot_operator = copy.copy(self._snapshot_operator) plan_copy._snapshot_stats = copy.copy(self._snapshot_stats) plan_copy._dataset_name = self._dataset_name return plan_copy def initial_num_blocks(self) -> Optional[int]: """Get the estimated number of blocks from the logical plan after applying execution plan optimizations, but prior to fully executing the dataset.""" return self._logical_plan.dag.estimated_num_outputs() def schema( self, fetch_if_missing: bool = False ) -> Union[type, "pyarrow.lib.Schema"]: """Get the schema after applying all execution plan optimizations, but prior to fully executing the dataset (unless `fetch_if_missing` is set to True). Args: fetch_if_missing: Whether to execute the plan to fetch the schema. Returns: The schema of the output dataset. """ if self._schema is not None: return self._schema schema = None if self.has_computed_output(): schema = self._snapshot_bundle.schema else: schema = self._logical_plan.dag.infer_schema() if schema is None and fetch_if_missing: # For consistency with the previous implementation, we fetch the schema if # the plan is read-only even if `fetch_if_missing` is False. iter_ref_bundles, _, executor = self.execute_to_iterator() # Make sure executor is fully shutdown upon exiting with executor: schema = _take_first_non_empty_schema( bundle.schema for bundle in iter_ref_bundles ) self.cache_schema(schema) return self._schema def cache_schema(self, schema: Union[type, "pyarrow.lib.Schema"]): self._schema = schema def input_files(self) -> Optional[List[str]]: """Get the input files of the dataset, if available.""" return self._logical_plan.dag.infer_metadata().input_files def meta_count(self) -> Optional[int]: """Get the number of rows after applying all plan optimizations, if possible. This method will never trigger any computation. Returns: The number of records of the result Dataset, or None. """ dag = self._logical_plan.dag if self.has_computed_output(): num_rows = sum(m.num_rows for m in self._snapshot_bundle.metadata) elif dag.infer_metadata().num_rows is not None: num_rows = dag.infer_metadata().num_rows else: num_rows = None return num_rows @omit_traceback_stdout def execute_to_iterator( self, ) -> Tuple[Iterator[RefBundle], DatasetStats, Optional["StreamingExecutor"]]: """Execute this plan, returning an iterator. This will use streaming execution to generate outputs. NOTE: Executor will be shutdown upon either of the 2 following conditions: - Iterator is fully exhausted (ie until StopIteration is raised) - Executor instances is garbage-collected Returns: Tuple of iterator over output RefBundles, DatasetStats, and the executor. """ self._has_started_execution = True if self.has_computed_output(): bundle = self.execute() return iter([bundle]), self._snapshot_stats, None from ray.data._internal.execution.legacy_compat import ( execute_to_legacy_bundle_iterator, ) executor = self.create_executor() bundle_iter = execute_to_legacy_bundle_iterator(executor, self) # Since the generator doesn't run any code until we try to fetch the first # value, force execution of one bundle before we call get_stats(). gen = iter(bundle_iter) try: bundle_iter = itertools.chain([next(gen)], gen) except StopIteration: pass self._snapshot_stats = executor.get_stats() return bundle_iter, self._snapshot_stats, executor @omit_traceback_stdout def execute( self, preserve_order: bool = False, ) -> RefBundle: """Executes this plan (eagerly). Args: preserve_order: Whether to preserve order in execution. Returns: The blocks of the output dataset. """ self._has_started_execution = True # Always used the saved context for execution. context = self._context if not ray.available_resources().get("CPU"): if log_once("cpu_warning"): logger.warning( "Warning: The Ray cluster currently does not have " "any available CPUs. The Dataset job will hang unless more CPUs " "are freed up. A common reason is that cluster resources are " "used by Actors or Tune trials; see the following link " "for more details: " "https://docs.ray.io/en/latest/data/data-internals.html#ray-data-and-tune" # noqa: E501 ) if not self.has_computed_output(): from ray.data._internal.execution.legacy_compat import ( _get_initial_stats_from_plan, execute_to_legacy_block_list, ) if ( isinstance(self._logical_plan.dag, SourceOperator) and self._logical_plan.dag.output_data() is not None ): # If the data is already materialized (e.g., `from_pandas`), we can # skip execution and directly return the output data. This avoids # recording unnecessary metrics for an empty plan execution. stats = _get_initial_stats_from_plan(self) # TODO(@bveeramani): Make `ExecutionPlan.execute()` return # `List[RefBundle]` instead of `RefBundle`. Among other reasons, it'd # allow us to remove the unwrapping logic below. output_bundles = self._logical_plan.dag.output_data() owns_blocks = all(bundle.owns_blocks for bundle in output_bundles) schema = _take_first_non_empty_schema( bundle.schema for bundle in output_bundles ) bundle = RefBundle( [ (block, metadata) for bundle in output_bundles for block, metadata in bundle.blocks ], owns_blocks=owns_blocks, schema=schema, ) else: # Make sure executor is properly shutdown with self.create_executor() as executor: blocks = execute_to_legacy_block_list( executor, self, dataset_uuid=self._dataset_uuid, preserve_order=preserve_order, ) bundle = RefBundle( tuple(blocks.iter_blocks_with_metadata()), owns_blocks=blocks._owned_by_consumer, schema=blocks.get_schema(), ) stats = executor.get_stats() stats_summary_string = stats.to_summary().to_string( include_parent=False ) if context.enable_auto_log_stats: logger.info(stats_summary_string) # Retrieve memory-related stats from ray. try: reply = get_memory_info_reply( get_state_from_address(ray.get_runtime_context().gcs_address) ) if reply.store_stats.spill_time_total_s > 0: stats.global_bytes_spilled = int( reply.store_stats.spilled_bytes_total ) if reply.store_stats.restore_time_total_s > 0: stats.global_bytes_restored = int( reply.store_stats.restored_bytes_total ) except Exception as e: logger.debug( "Skipping recording memory spilled and restored statistics due to " f"exception: {e}" ) stats.dataset_bytes_spilled = 0 def collect_stats(cur_stats): stats.dataset_bytes_spilled += cur_stats.extra_metrics.get( "obj_store_mem_spilled", 0 ) for parent in cur_stats.parents: collect_stats(parent) collect_stats(stats) # Set the snapshot to the output of the final operator. self._snapshot_bundle = bundle self._snapshot_operator = self._logical_plan.dag self._snapshot_stats = stats self._snapshot_stats.dataset_uuid = self._dataset_uuid return self._snapshot_bundle @property def has_started_execution(self) -> bool: """Return ``True`` if this plan has been partially or fully executed.""" return self._has_started_execution def clear_snapshot(self) -> None: """Clear the snapshot kept in the plan to the beginning state.""" self._snapshot_bundle = None self._snapshot_operator = None self._snapshot_stats = None def stats(self) -> DatasetStats: """Return stats for this plan. If the plan isn't executed, an empty stats object will be returned. """ if not self._snapshot_stats: return DatasetStats(metadata={}, parent=None) return self._snapshot_stats def has_lazy_input(self) -> bool: """Return whether this plan has lazy input blocks.""" return all(isinstance(op, Read) for op in self._logical_plan.sources()) def has_computed_output(self) -> bool: """Whether this plan has a computed snapshot for the final operator, i.e. for the output of this plan. """ return ( self._snapshot_bundle is not None and self._snapshot_operator == self._logical_plan.dag ) def require_preserve_order(self) -> bool: """Whether this plan requires to preserve order.""" from ray.data._internal.logical.operators.all_to_all_operator import Sort from ray.data._internal.logical.operators.n_ary_operator import Zip for op in self._logical_plan.dag.post_order_iter(): if isinstance(op, (Zip, Sort)): return True return False
ExecutionPlan
python
readthedocs__readthedocs.org
readthedocs/proxito/views/mixins.py
{ "start": 1304, "end": 10479 }
class ____: """Class implementing all the logic to serve a document.""" # We force all storage calls to use internal versions # unless explicitly set to external. version_type = INTERNAL def _serve_docs(self, request, project, version, filename, check_if_exists=False): """ Serve a documentation file. :param check_if_exists: If `True` we check if the file exists before trying to serve it. This will raisen an exception if the file doesn't exists. Useful to make sure were are serving a file that exists in storage, checking if the file exists will make one additional request to the storage. """ base_storage_path = project.get_storage_path( type_=MEDIA_TYPE_HTML, version_slug=version.slug, include_file=False, # Force to always read from the internal or extrernal storage, # according to the current request. version_type=self.version_type, ) # Handle our backend storage not supporting directory indexes, # so we need to append index.html when appropriate. if not filename or filename.endswith("/"): filename += "index.html" # If the filename starts with `/`, the join will fail, # so we strip it before joining it. try: storage_path = build_media_storage.join(base_storage_path, filename.lstrip("/")) except ValueError: # We expect this exception from the django storages safe_join # function, when the filename resolves to a higher relative path. # The request is malicious or malformed in this case. raise BadRequest("Invalid URL") if check_if_exists and not build_media_storage.exists(storage_path): raise StorageFileNotFound self._track_pageview( project=project, path=filename, request=request, download=False, ) return self._serve_file( request=request, storage_path=storage_path, storage_backend=build_media_storage, ) def _serve_dowload(self, request, project, version, type_): """ Serve downloadable content for the given version. The HTTP header ``Content-Disposition`` is added with the proper filename (e.g. "pip-pypa-io-en-latest.pdf" or "pip-pypi-io-en-v2.0.pdf" or "docs-celeryproject-org-kombu-en-stable.pdf"). """ storage_path = project.get_storage_path( type_=type_, version_slug=version.slug, # Force to always read from the internal or extrernal storage, # according to the current request. version_type=self.version_type, include_file=True, ) self._track_pageview( project=project, path=storage_path, request=request, download=True, ) response = self._serve_file( request=request, storage_path=storage_path, storage_backend=build_media_storage, ) # Set the filename of the download. filename_ext = storage_path.rsplit(".", 1)[-1] domain = unicode_slugify(project.subdomain().replace(".", "-")) if project.is_subproject: filename = f"{domain}-{project.alias}-{project.language}-{version.slug}.{filename_ext}" else: filename = f"{domain}-{project.language}-{version.slug}.{filename_ext}" response["Content-Disposition"] = f"filename={filename}" return response def _serve_file(self, request, storage_path, storage_backend): """ Serve a file from storage. Serve from the filesystem if using ``PYTHON_MEDIA``. We definitely shouldn't do this in production, but I don't want to force a check for ``DEBUG``. :param storage_path: Path to file to serve. :param storage_backend: Storage backend class from where to serve the file. """ storage_url = self._get_storage_url( request=request, storage_path=storage_path, storage_backend=storage_backend, ) if settings.PYTHON_MEDIA: return self._serve_file_from_python(request, storage_url, storage_backend) return self._serve_file_from_nginx( storage_url, root_path=storage_backend.internal_redirect_root_path, ) def _get_storage_url(self, request, storage_path, storage_backend): """ Get the full storage URL from a storage path. The URL will be without scheme and domain, this is to perform an NGINX internal redirect. Authorization query arguments will stay in place (useful for private buckets). """ # We are catching a broader exception, # since depending on the storage backend, # an invalid path may raise a different exception. try: # NOTE: calling ``.url`` will remove any double slashes. # e.g: '/foo//bar///' -> '/foo/bar/'. storage_url = storage_backend.url(storage_path, http_method=request.method) except Exception as e: log.info("Invalid storage path.", path=storage_path, exc_info=e) raise InvalidPathError parsed_url = urlparse(storage_url)._replace(scheme="", netloc="") return parsed_url.geturl() def _track_pageview(self, project, path, request, download): """Create an audit log of the page view if audit is enabled.""" # Remove any query args (like the token access from AWS). path_only = urlparse(path).path track_file = path_only.endswith((".html", ".pdf", ".epub", ".zip")) if track_file and self._is_audit_enabled(project): action = AuditLog.DOWNLOAD if download else AuditLog.PAGEVIEW AuditLog.objects.new( action=action, user=request.user, request=request, project=project, ) def _is_audit_enabled(self, project): """ Check if the project has the audit feature enabled to track individual page views. This feature is different from page views analytics, as it records every page view individually with more metadata like the user, IP, etc. """ return bool(get_feature(project, feature_type=TYPE_AUDIT_PAGEVIEWS)) def _serve_static_file(self, request, filename): return self._serve_file( request=request, storage_path=filename, storage_backend=staticfiles_storage, ) def _serve_file_from_nginx(self, path, root_path): """ Serve a file from nginx. Returns a response with ``X-Accel-Redirect``, which will cause nginx to serve it directly as an internal redirect. :param path: The path of the file to serve. :param root_path: The root path of the internal redirect. """ internal_path = f"/{root_path}/" + path.lstrip("/") log.debug( "Nginx serve.", original_path=path, internal_path=internal_path, ) content_type, encoding = mimetypes.guess_type(internal_path) content_type = content_type or "application/octet-stream" response = HttpResponse( f"Serving internal path: {internal_path}", content_type=content_type ) if encoding: response["Content-Encoding"] = encoding # NGINX does not support non-ASCII characters in the header, so we # convert the IRI path to URI so it's compatible with what NGINX expects # as the header value. # https://github.com/benoitc/gunicorn/issues/1448 # https://docs.djangoproject.com/en/1.11/ref/unicode/#uri-and-iri-handling x_accel_redirect = iri_to_uri(internal_path) response["X-Accel-Redirect"] = x_accel_redirect # Needed to strip any GET args, etc. response.proxito_path = urlparse(internal_path).path return response def _serve_file_from_python(self, request, path, storage): """ Serve a file from Python. .. warning:: Don't use this in production! """ log.debug("Django serve.", path=path) root_path = storage.path("") return serve(request, path, root_path) def _serve_401(self, request, project): res = render(request, "errors/proxito/401.html") res.status_code = 401 log.debug("Unauthorized access to documentation.", project_slug=project.slug) return res def allowed_user(self, request, version): return True def _spam_response(self, request, project): if "readthedocsext.spamfighting" in settings.INSTALLED_APPS: from readthedocsext.spamfighting.utils import is_serve_docs_denied # noqa if is_serve_docs_denied(project): return render(request, template_name="errors/proxito/spam.html", status=410)
ServeDocsMixin
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/rich/theme.py
{ "start": 155, "end": 2576 }
class ____: """A container for style information, used by :class:`~rich.console.Console`. Args: styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for a theme with no styles. inherit (bool, optional): Inherit default styles. Defaults to True. """ styles: Dict[str, Style] def __init__( self, styles: Optional[Mapping[str, StyleType]] = None, inherit: bool = True ): self.styles = DEFAULT_STYLES.copy() if inherit else {} if styles is not None: self.styles.update( { name: style if isinstance(style, Style) else Style.parse(style) for name, style in styles.items() } ) @property def config(self) -> str: """Get contents of a config file for this theme.""" config = "[styles]\n" + "\n".join( f"{name} = {style}" for name, style in sorted(self.styles.items()) ) return config @classmethod def from_file( cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True ) -> "Theme": """Load a theme from a text mode file. Args: config_file (IO[str]): An open conf file. source (str, optional): The filename of the open file. Defaults to None. inherit (bool, optional): Inherit default styles. Defaults to True. Returns: Theme: A New theme instance. """ config = configparser.ConfigParser() config.read_file(config_file, source=source) styles = {name: Style.parse(value) for name, value in config.items("styles")} theme = Theme(styles, inherit=inherit) return theme @classmethod def read( cls, path: str, inherit: bool = True, encoding: Optional[str] = None ) -> "Theme": """Read a theme from a path. Args: path (str): Path to a config file readable by Python configparser module. inherit (bool, optional): Inherit default styles. Defaults to True. encoding (str, optional): Encoding of the config file. Defaults to None. Returns: Theme: A new theme instance. """ with open(path, "rt", encoding=encoding) as config_file: return cls.from_file(config_file, source=path, inherit=inherit)
Theme
python
great-expectations__great_expectations
great_expectations/core/config_provider.py
{ "start": 4687, "end": 6441 }
class ____(_AbstractConfigurationProvider): """ Responsible for the management of user-defined configuration variables. These can be found in the user's /uncommitted/config_variables.yml file. """ def __init__( self, config_variables_file_path: str, root_directory: Optional[str] = None ) -> None: self._config_variables_file_path = config_variables_file_path self._root_directory = root_directory super().__init__() @override def get_values(self) -> Dict[str, str]: env_vars = dict(os.environ) # noqa: TID251 # os.environ allowed in config files try: # If the user specifies the config variable path with an environment variable, we want to substitute it # noqa: E501 # FIXME CoP defined_path: str = self._substitutor.substitute_config_variable( # type: ignore[assignment] # FIXME CoP self._config_variables_file_path, env_vars ) if not os.path.isabs(defined_path): # noqa: PTH117 # FIXME CoP root_directory: str = self._root_directory or os.curdir else: root_directory = "" var_path = os.path.join(root_directory, defined_path) # noqa: PTH118 # FIXME CoP with open(var_path) as config_variables_file: contents = config_variables_file.read() variables = dict(yaml.load(contents)) or {} return cast( "Dict[str, str]", self._substitutor.substitute_all_config_variables(variables, env_vars), ) except OSError as e: if e.errno != errno.ENOENT: raise return {}
_ConfigurationVariablesConfigurationProvider
python
squidfunk__mkdocs-material
material/plugins/search/config.py
{ "start": 1777, "end": 1887 }
class ____(Config): boost = Type((int, float), default = 1.0) # Search plugin configuration
SearchFieldConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/enum11.py
{ "start": 788, "end": 1161 }
class ____(Enum): def __init__(self, value: int, other: str): self._value_ = value # This should generate an error because of a type mismatch. RED = 1 # This should generate an error because of a type mismatch. GREEN = "green" BLUE = (1, "blue") # This should generate an error because of a type mismatch. GRAY = (1, "blue", 1)
Enum4
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 16012, "end": 17245 }
class ____(sgqlc.types.Enum): """The possible values for the enterprise allow private repository forking policy value. Enumeration Choices: * `ENTERPRISE_ORGANIZATIONS`: Members can fork a repository to an organization within this enterprise. * `ENTERPRISE_ORGANIZATIONS_USER_ACCOUNTS`: Members can fork a repository to their enterprise-managed user account or an organization inside this enterprise. * `EVERYWHERE`: Members can fork a repository to their user account or an organization, either inside or outside of this enterprise. * `SAME_ORGANIZATION`: Members can fork a repository only within the same organization (intra-org). * `SAME_ORGANIZATION_USER_ACCOUNTS`: Members can fork a repository to their user account or within the same organization. * `USER_ACCOUNTS`: Members can fork a repository to their user account. """ __schema__ = github_schema __choices__ = ( "ENTERPRISE_ORGANIZATIONS", "ENTERPRISE_ORGANIZATIONS_USER_ACCOUNTS", "EVERYWHERE", "SAME_ORGANIZATION", "SAME_ORGANIZATION_USER_ACCOUNTS", "USER_ACCOUNTS", )
EnterpriseAllowPrivateRepositoryForkingPolicyValue
python
skorch-dev__skorch
skorch/callbacks/scoring.py
{ "start": 2562, "end": 5508 }
class ____(Callback): """Base class for scoring. Subclass and implement an ``on_*`` method before using. """ def __init__( self, scoring, lower_is_better=True, on_train=False, name=None, target_extractor=to_numpy, use_caching=True, ): self.scoring = scoring self.lower_is_better = lower_is_better self.on_train = on_train self.name = name self.target_extractor = target_extractor self.use_caching = use_caching # pylint: disable=protected-access def _get_name(self): """Find name of scoring function.""" if self.name is not None: return self.name if self.scoring_ is None: return 'score' if isinstance(self.scoring_, str): return self.scoring_ if isinstance(self.scoring_, partial): return self.scoring_.func.__name__ if isinstance(self.scoring_, _BaseScorer): if hasattr(self.scoring_._score_func, '__name__'): # sklearn < 0.22 return self.scoring_._score_func.__name__ # sklearn >= 0.22 return self.scoring_._score_func._score_func.__name__ if isinstance(self.scoring_, dict): raise ValueError("Dict not supported as scorer for multi-metric scoring." " Register multiple scoring callbacks instead.") return self.scoring_.__name__ def initialize(self): self.best_score_ = np.inf if self.lower_is_better else -np.inf self.scoring_ = convert_sklearn_metric_function(self.scoring) self.name_ = self._get_name() return self # pylint: disable=attribute-defined-outside-init,arguments-differ def on_train_begin(self, net, X, y, **kwargs): self.X_indexing_ = check_indexing(X) self.y_indexing_ = check_indexing(y) # Looks for the right most index where `*_best` is True # That index is used to get the best score in `net.history` with suppress(ValueError, IndexError, KeyError): best_name_history = net.history[:, '{}_best'.format(self.name_)] idx_best_reverse = best_name_history[::-1].index(True) idx_best = len(best_name_history) - idx_best_reverse - 1 self.best_score_ = net.history[idx_best, self.name_] def _scoring(self, net, X_test, y_test): """Resolve scoring and apply it to data. Use cached prediction instead of running inference again, if available.""" scorer = check_scoring(net, self.scoring_) return scorer(net, X_test, y_test) def _is_best_score(self, current_score): if self.lower_is_better is None: return None if self.lower_is_better: return current_score < self.best_score_ return current_score > self.best_score_
ScoringBase
python
jazzband__django-pipeline
tests/tests/test_compiler.py
{ "start": 2385, "end": 2687 }
class ____(CompilerBase): output_extension = "js" def match_file(self, path): return path.endswith(".coffee") def compile_file(self, infile, outfile, outdated=False, force=False): return @pipeline_settings(COMPILERS=["tests.tests.test_compiler.DummyCompiler"])
DummyCompiler
python
kamyu104__LeetCode-Solutions
Python/form-smallest-number-from-two-digit-arrays.py
{ "start": 50, "end": 430 }
class ____(object): def minNumber(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ common = set(nums1)&set(nums2) if common: return min(common) mn1, mn2 = min(nums1), min(nums2) if mn1 > mn2: mn1, mn2 = mn2, mn1 return 10*mn1+mn2
Solution
python
google__pytype
pytype/pytd/pytd_utils.py
{ "start": 8664, "end": 9959 }
class ____: """Utility class for building union types.""" def __init__(self): self.union = pytd.NothingType() self.tags = set() def add_type(self, other): """Add a new pytd type to the types represented by this TypeBuilder.""" if isinstance(other, pytd.Annotated): self.tags.update(other.annotations) other = other.base_type self.union = JoinTypes([self.union, other]) def wrap(self, base): """Wrap the type in a generic type.""" self.union = pytd.GenericType( base_type=pytd.NamedType(base), parameters=(self.union,) ) def build(self): """Get a union of all the types added so far.""" if self.tags: return pytd.Annotated(self.union, tuple(sorted(self.tags))) else: return self.union def __bool__(self): return not isinstance(self.union, pytd.NothingType) # For running under Python 2 __nonzero__ = __bool__ def NamedOrClassType(name, cls): """Create Classtype / NamedType.""" if cls is None: return pytd.NamedType(name) else: return pytd.ClassType(name, cls) def NamedTypeWithModule(name, module=None): """Create NamedType, dotted if we have a module.""" if module is None: return pytd.NamedType(name) else: return pytd.NamedType(module + "." + name)
TypeBuilder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 576583, "end": 577349 }
class ____(sgqlc.types.relay.Connection): """The connection type for DiscussionCategory.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("DiscussionCategoryEdge"), graphql_name="edges") """A list of edges.""" nodes = sgqlc.types.Field(sgqlc.types.list_of("DiscussionCategory"), graphql_name="nodes") """A list of nodes.""" page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo") """Information to aid in pagination.""" total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount") """Identifies the total count of items in the connection."""
DiscussionCategoryConnection
python
huggingface__transformers
src/transformers/models/nllb_moe/modeling_nllb_moe.py
{ "start": 16147, "end": 17631 }
class ____(nn.ModuleDict): def __init__(self, config: NllbMoeConfig, ffn_dim: int): super().__init__() self.num_experts = config.num_experts for idx in range(self.num_experts): self[f"expert_{idx}"] = NllbMoeDenseActDense(config, ffn_dim) self.moe_token_dropout = config.moe_token_dropout self.token_dropout = nn.Dropout(self.moe_token_dropout) def forward(self, hidden_states: torch.Tensor, router_mask: torch.Tensor, router_probs: torch.Tensor): final_hidden_states = torch.zeros_like(hidden_states) expert_mask = torch.nn.functional.one_hot(router_mask, num_classes=self.num_experts).permute(2, 1, 0) expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero() for expert_idx in expert_hit: idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0)) current_state = hidden_states[None, top_x].reshape(-1, hidden_states.shape[-1]) current_hidden_states = self[f"expert_{expert_idx[0]}"](current_state) * router_probs[top_x, idx, None] if self.moe_token_dropout > 0: if self.training: current_hidden_states = self.token_dropout(current_hidden_states) else: current_hidden_states *= 1 - self.moe_token_dropout final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype)) return final_hidden_states
NllbMoeExperts
python
pypa__warehouse
tests/unit/test_filters.py
{ "start": 1228, "end": 9287 }
class ____: def test_camoify(self): html = "<img src=http://example.com/image.jpg>" request = pretend.stub( registry=pretend.stub( settings={ "camo.url": "https://camo.example.net/", "camo.key": "fake key", } ) ) camo_url = partial(filters._camo_url, request) request.camo_url = camo_url ctx = {"request": request} result = filters.camoify(ctx, html) assert result == ( '<img src="https://camo.example.net/' "b410d235a3d2fc44b50ccab827e531dece213062/" '687474703a2f2f6578616d706c652e636f6d2f696d6167652e6a7067">' ) def test_camoify_no_src(self, monkeypatch): html = "<img>" request = pretend.stub( registry=pretend.stub( settings={ "camo.url": "https://camo.example.net/", "camo.key": "fake key", } ) ) camo_url = partial(filters._camo_url, request) request.camo_url = camo_url ctx = {"request": request} gen_camo_url = pretend.call_recorder( lambda curl, ckey, url: "https://camo.example.net/image.jpg" ) monkeypatch.setattr(filters, "_camo_url", gen_camo_url) result = filters.camoify(ctx, html) assert result == "<img>" assert gen_camo_url.calls == [] @pytest.mark.parametrize( ("inp", "expected"), [ (1, "1"), (999, "999"), (1234, "1.23k"), (4304264, "4.3M"), (7878123132, "7.88G"), (9999999999999, "10T"), ], ) def test_shorten_number(inp, expected): assert filters.shorten_number(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [({"foo": "bar", "left": "right"}, '{"foo":"bar","left":"right"}')], ) def test_tojson(inp, expected): assert filters.tojson(inp) == expected def test_urlparse(): inp = "https://google.com/foo/bar?a=b" expected = parse_url(inp) assert filters.urlparse(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [ ( "'python', finance, \"data\", code , test automation", ["python", "finance", "data", "code", "test automation"], ), ( "'python'; finance; \"data\"; code ; test automation", ["python", "finance", "data", "code", "test automation"], ), ("a \"b\" c d 'e'", ["a", "b", "c", "d", "e"]), (" ' ' \" \"", []), ], ) def test_format_tags(inp, expected): assert filters.format_tags(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [ ( ["Foo :: Bar :: Baz", "Foo :: Bar :: Qux", "Vleep"], [("Foo", ["Bar :: Baz", "Bar :: Qux"])], ), ( ["Foo :: Bar :: Baz", "Vleep :: Foo", "Foo :: Bar :: Qux"], [("Foo", ["Bar :: Baz", "Bar :: Qux"]), ("Vleep", ["Foo"])], ), ( [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.8", ], [ ( "Programming Language", ["Python :: 3.8", "Python :: 3.10", "Python :: 3.11"], ) ], ), ], ) def test_format_classifiers(inp, expected): assert list(filters.format_classifiers(inp).items()) == expected @pytest.mark.parametrize( ("inp", "expected"), [("Foo", "Foo"), ("Foo :: Foo", "Foo_._Foo")] ) def test_classifier_id(inp, expected): assert filters.classifier_id(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [ (["abcdef", "ghijkl"], False), (["https://github.com/example/test", "https://pypi.io/"], True), (["abcdef", "https://github.com/example/test"], True), ], ) def test_contains_valid_uris(inp, expected): assert filters.contains_valid_uris(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [ ("bdist_dmg", "OSX Disk Image"), ("bdist_dumb", "Dumb Binary"), ("bdist_egg", "Egg"), ("bdist_msi", "Windows MSI Installer"), ("bdist_rpm", "RPM"), ("bdist_wheel", "Wheel"), ("bdist_wininst", "Windows Installer"), ("sdist", "Source"), ("invalid", "invalid"), ], ) def test_format_package_type(inp, expected): assert filters.format_package_type(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [ ("1.0", packaging.version.Version("1.0")), ("dog", packaging_legacy.version.LegacyVersion("dog")), ], ) def test_parse_version(inp, expected): assert filters.parse_version(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [ ( datetime.datetime(2018, 12, 26, 13, 36, 5, 789013), "2018-12-26 13:36:05.789013 UTC", ) ], ) def test_localize_datetime(inp, expected): datetime_format = "%Y-%m-%d %H:%M:%S.%f %Z" assert filters.localize_datetime(inp).strftime(datetime_format) == expected @pytest.mark.parametrize( ("inp", "expected"), [ ( datetime.datetime(2018, 12, 26, 13, 36, 5, 789013).isoformat(), datetime.datetime(2018, 12, 26, 13, 36, 5, 789013), ) ], ) def test_parse_isoformat(inp, expected): assert filters.parse_isoformat(inp) == expected @pytest.mark.parametrize( ("inp", "expected"), [ ( 1667404296, datetime.datetime(2022, 11, 2, 15, 51, 36), ) ], ) def test_ctime(inp, expected): assert filters.ctime(inp) == expected @pytest.mark.parametrize( ("delta", "expected"), [ (datetime.timedelta(days=31), False), (datetime.timedelta(days=30), False), (datetime.timedelta(days=29), True), (datetime.timedelta(), True), (datetime.timedelta(days=-1), True), ], ) def test_is_recent(delta, expected): timestamp = datetime.datetime.now() - delta assert filters.is_recent(timestamp) == expected def test_is_recent_none(): assert filters.is_recent(None) is False @pytest.mark.parametrize( ("meta_email", "expected_name", "expected_email"), [ ("not-an-email-address", "", ""), ("foo@bar.com", "", "foo@bar.com"), ('"Foo Bar" <foo@bar.com>', "Foo Bar", "foo@bar.com"), ], ) def test_format_email(meta_email, expected_name, expected_email): name, email = filters.format_email(meta_email) assert name == expected_name assert email == expected_email @pytest.mark.parametrize( ("inp", "expected"), [ ("foo", "foo"), # no change (" foo  bar ", " foo bar "), # U+001B : <control> ESCAPE [ESC] ("foo \x1b bar", "foo bar"), # U+001B : <control> ESCAPE [ESC] ("foo \x00 bar", "foo bar"), # U+0000 : <control> NULL ("foo 🐍 bar", "foo 🐍 bar"), # U+1F40D : SNAKE [snake] (emoji) [Python] (None, None), # no change ], ) def test_remove_invalid_xml_unicode(inp, expected): """ Test that invalid XML unicode characters are removed. """ assert filters.remove_invalid_xml_unicode(inp) == expected def test_canonical_url(): request = pretend.stub( matched_route=pretend.stub(name="foo"), route_url=pretend.call_recorder(lambda a: "bar"), ) assert filters._canonical_url(request) == "bar" assert request.route_url.calls == [pretend.call("foo")] def test_canonical_url_no_matched_route(): request = pretend.stub(matched_route=None) assert filters._canonical_url(request) is None def test_canonical_url_missing_kwargs(): request = pretend.stub( matched_route=pretend.stub(name="foo"), route_url=pretend.raiser(KeyError), ) assert filters._canonical_url(request) is None
TestCamoify
python
huggingface__transformers
tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
{ "start": 1193, "end": 2245 }
class ____(unittest.TestCase): def test_to_dict(self): """ Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object """ quantization_config = FbgemmFp8Config() config_to_dict = quantization_config.to_dict() for key in config_to_dict: self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) def test_from_dict(self): """ Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict """ dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "fbgemm_fp8"} quantization_config = FbgemmFp8Config.from_dict(dict) self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) self.assertEqual(dict["quant_method"], quantization_config.quant_method) @slow @require_torch_gpu @require_fbgemm_gpu @require_accelerate @require_read_token
FbgemmFp8ConfigTest
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_datafusion.py
{ "start": 2377, "end": 3357 }
class ____: @mock.patch(RESOURCE_PATH_TO_DICT_STR) @mock.patch(HOOK_STR) def test_execute_check_hook_call_should_execute_successfully(self, mock_hook, mock_resource_to_dict): update_maks = "instance.name" mock_resource_to_dict.return_value = {"projects": PROJECT_ID} op = CloudDataFusionUpdateInstanceOperator( task_id="test_tasks", instance_name=INSTANCE_NAME, instance=INSTANCE, update_mask=update_maks, location=LOCATION, project_id=PROJECT_ID, ) op.execute(context=mock.MagicMock()) mock_hook.return_value.patch_instance.assert_called_once_with( instance_name=INSTANCE_NAME, instance=INSTANCE, update_mask=update_maks, location=LOCATION, project_id=PROJECT_ID, ) assert mock_hook.return_value.wait_for_operation.call_count == 1
TestCloudDataFusionUpdateInstanceOperator
python
great-expectations__great_expectations
great_expectations/expectations/metrics/table_metric_provider.py
{ "start": 200, "end": 1257 }
class ____(MetricProvider): """Base class for all Table Metrics, which define metrics to be calculated across a complete table. An example of this is `table.column.unique`, which verifies that a table contains unique, non-duplicate columns. Args: metric_name (str): A name identifying the metric. Metric Name must be globally unique in a great_expectations installation. domain_keys (tuple): A tuple of the keys used to determine the domain of the metric. value_keys (tuple): A tuple of the keys used to determine the value of the metric. In some cases, subclasses of MetricProvider, such as TableMetricProvider, will already have correct values that may simply be inherited by Metric classes. ---Documentation--- - https://docs.greatexpectations.io/docs/guides/expectations/custom_expectations_lp """ # noqa: E501 # FIXME CoP domain_keys: Tuple[str, ...] = ( "batch_id", "table", "row_condition", "condition_parser", )
TableMetricProvider
python
scipy__scipy
scipy/stats/tests/test_multivariate.py
{ "start": 86104, "end": 94159 }
class ____: def test_scale_dimensions(self): # Test that we can call the Wishart with various scale dimensions # Test case: dim=1, scale=1 true_scale = np.array(1, ndmin=2) scales = [ 1, # scalar [1], # iterable np.array(1), # 0-dim np.r_[1], # 1-dim np.array(1, ndmin=2) # 2-dim ] for scale in scales: w = wishart(1, scale) assert_equal(w.scale, true_scale) assert_equal(w.scale.shape, true_scale.shape) # Test case: dim=2, scale=[[1,0] # [0,2] true_scale = np.array([[1,0], [0,2]]) scales = [ [1,2], # iterable np.r_[1,2], # 1-dim np.array([[1,0], # 2-dim [0,2]]) ] for scale in scales: w = wishart(2, scale) assert_equal(w.scale, true_scale) assert_equal(w.scale.shape, true_scale.shape) # We cannot call with a df < dim - 1 assert_raises(ValueError, wishart, 1, np.eye(2)) # But we can call with dim - 1 < df < dim wishart(1.1, np.eye(2)) # no error # see gh-5562 # We cannot call with a 3-dimension array scale = np.array(1, ndmin=3) assert_raises(ValueError, wishart, 1, scale) def test_quantile_dimensions(self): # Test that we can call the Wishart rvs with various quantile dimensions # If dim == 1, consider x.shape = [1,1,1] X = [ 1, # scalar [1], # iterable np.array(1), # 0-dim np.r_[1], # 1-dim np.array(1, ndmin=2), # 2-dim np.array([1], ndmin=3) # 3-dim ] w = wishart(1,1) density = w.pdf(np.array(1, ndmin=3)) for x in X: assert_equal(w.pdf(x), density) # If dim == 1, consider x.shape = [1,1,*] X = [ [1,2,3], # iterable np.r_[1,2,3], # 1-dim np.array([1,2,3], ndmin=3) # 3-dim ] w = wishart(1,1) density = w.pdf(np.array([1,2,3], ndmin=3)) for x in X: assert_equal(w.pdf(x), density) # If dim == 2, consider x.shape = [2,2,1] # where x[:,:,*] = np.eye(1)*2 X = [ 2, # scalar [2,2], # iterable np.array(2), # 0-dim np.r_[2,2], # 1-dim np.array([[2,0], [0,2]]), # 2-dim np.array([[2,0], [0,2]])[:,:,np.newaxis] # 3-dim ] w = wishart(2,np.eye(2)) density = w.pdf(np.array([[2,0], [0,2]])[:,:,np.newaxis]) for x in X: assert_equal(w.pdf(x), density) def test_frozen(self): # Test that the frozen and non-frozen Wishart gives the same answers # Construct an arbitrary positive definite scale matrix dim = 4 scale = np.diag(np.arange(dim)+1) scale[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2) scale = np.dot(scale.T, scale) # Construct a collection of positive definite matrices to test the PDF X = [] for i in range(5): x = np.diag(np.arange(dim)+(i+1)**2) x[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2) x = np.dot(x.T, x) X.append(x) X = np.array(X).T # Construct a 1D and 2D set of parameters parameters = [ (10, 1, np.linspace(0.1, 10, 5)), # 1D case (10, scale, X) ] for (df, scale, x) in parameters: w = wishart(df, scale) assert_equal(w.var(), wishart.var(df, scale)) assert_equal(w.mean(), wishart.mean(df, scale)) assert_equal(w.mode(), wishart.mode(df, scale)) assert_equal(w.entropy(), wishart.entropy(df, scale)) assert_equal(w.pdf(x), wishart.pdf(x, df, scale)) def test_wishart_2D_rvs(self): dim = 3 df = 10 # Construct a simple non-diagonal positive definite matrix scale = np.eye(dim) scale[0,1] = 0.5 scale[1,0] = 0.5 # Construct frozen Wishart random variables w = wishart(df, scale) # Get the generated random variables from a known seed rng = np.random.RandomState(248042) w_rvs = wishart.rvs(df, scale, random_state=rng) rng = np.random.RandomState(248042) frozen_w_rvs = w.rvs(random_state=rng) # Manually calculate what it should be, based on the Bartlett (1933) # decomposition of a Wishart into D A A' D', where D is the Cholesky # factorization of the scale matrix and A is the lower triangular matrix # with the square root of chi^2 variates on the diagonal and N(0,1) # variates in the lower triangle. rng = np.random.RandomState(248042) covariances = rng.normal(size=3) variances = np.r_[ rng.chisquare(df), rng.chisquare(df-1), rng.chisquare(df-2), ]**0.5 # Construct the lower-triangular A matrix A = np.diag(variances) A[np.tril_indices(dim, k=-1)] = covariances # Wishart random variate D = np.linalg.cholesky(scale) DA = D.dot(A) manual_w_rvs = np.dot(DA, DA.T) # Test for equality assert_allclose(w_rvs, manual_w_rvs) assert_allclose(frozen_w_rvs, manual_w_rvs) def test_1D_is_chisquared(self): # The 1-dimensional Wishart with an identity scale matrix is just a # chi-squared distribution. # Test variance, mean, entropy, pdf # Kolgomorov-Smirnov test for rvs rng = np.random.default_rng(482974) sn = 500 dim = 1 scale = np.eye(dim) df_range = np.arange(1, 10, 2, dtype=float) X = np.linspace(0.1,10,num=10) for df in df_range: w = wishart(df, scale) c = chi2(df) # Statistics assert_allclose(w.var(), c.var()) assert_allclose(w.mean(), c.mean()) assert_allclose(w.entropy(), c.entropy()) # PDF assert_allclose(w.pdf(X), c.pdf(X)) # rvs rvs = w.rvs(size=sn, random_state=rng) args = (df,) alpha = 0.01 check_distribution_rvs('chi2', args, alpha, rvs) def test_is_scaled_chisquared(self): # The 2-dimensional Wishart with an arbitrary scale matrix can be # transformed to a scaled chi-squared distribution. # For :math:`S \sim W_p(V,n)` and :math:`\lambda \in \mathbb{R}^p` we have # :math:`\lambda' S \lambda \sim \lambda' V \lambda \times \chi^2(n)` rng = np.random.default_rng(482974) sn = 500 df = 10 dim = 4 # Construct an arbitrary positive definite matrix scale = np.diag(np.arange(4)+1) scale[np.tril_indices(4, k=-1)] = np.arange(6) scale = np.dot(scale.T, scale) # Use :math:`\lambda = [1, \dots, 1]'` lamda = np.ones((dim,1)) sigma_lamda = lamda.T.dot(scale).dot(lamda).squeeze() w = wishart(df, sigma_lamda) c = chi2(df, scale=sigma_lamda) # Statistics assert_allclose(w.var(), c.var()) assert_allclose(w.mean(), c.mean()) assert_allclose(w.entropy(), c.entropy()) # PDF X = np.linspace(0.1,10,num=10) assert_allclose(w.pdf(X), c.pdf(X)) # rvs rvs = w.rvs(size=sn, random_state=rng) args = (df,0,sigma_lamda) alpha = 0.01 check_distribution_rvs('chi2', args, alpha, rvs)
TestWishart
python
wandb__wandb
wandb/automations/_filters/operators.py
{ "start": 5001, "end": 5184 }
class ____(BaseOp): val: Scalar = Field(alias="$gt") @override def __invert__(self) -> Lte: """Implements `~Gt(a) -> Lte(a)`.""" return Lte(val=self.val)
Gt
python
walkccc__LeetCode
solutions/2128. Remove All Ones With Row and Column Flips/2128.py
{ "start": 0, "end": 173 }
class ____: def removeOnes(self, grid: list[list[int]]) -> bool: revRow = [a ^ 1 for a in grid[0]] return all(row == grid[0] or row == revRow for row in grid)
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1188454, "end": 1206212 }
class ____( MarkPropDefstringnullTypeForShape, ShapeDef ): r""" FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull 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. 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, :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. condition : dict, :class:`ConditionalValueDefstringnullExprRef`, :class:`ConditionalParameterValueDefstringnullExprRef`, :class:`ConditionalPredicateValueDefstringnullExprRef`, Sequence[dict, :class:`ConditionalValueDefstringnullExprRef`, :class:`ConditionalParameterValueDefstringnullExprRef`, :class:`ConditionalPredicateValueDefstringnullExprRef`] One or more value definition(s) with `a parameter or a test predicate <https://vega.github.io/vega-lite/docs/condition.html>`__. **Note:** A field definition's ``condition`` property can only contain `conditional value definitions <https://vega.github.io/vega-lite/docs/condition.html#value>`__ since Vega-Lite only allows at most one encoded field per encoding channel. 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``. legend : dict, :class:`Legend`, None An object defining properties of the legend. If ``null``, the legend for the encoding channel will be removed. **Default value:** If undefined, default `legend properties <https://vega.github.io/vega-lite/docs/legend.html>`__ are applied. **See also:** `legend <https://vega.github.io/vega-lite/docs/legend.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. 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:`TypeForShape`, Literal['nominal', 'ordinal', 'geojson'] 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/FieldOrDatumDefWithCondition<MarkPropFieldDef<TypeForShape>,(string|null)>" } def __init__( self, shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined, aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined, bandPosition: Optional[float] = Undefined, bin: Optional[bool | SchemaBase | Map | None] = Undefined, condition: Optional[SchemaBase | Sequence[SchemaBase | Map] | Map] = Undefined, field: Optional[str | SchemaBase | Map] = Undefined, legend: 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, timeUnit: Optional[ SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T ] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, type: Optional[SchemaBase | TypeForShape_T] = Undefined, **kwds, ): super().__init__( shorthand=shorthand, aggregate=aggregate, bandPosition=bandPosition, bin=bin, condition=condition, field=field, legend=legend, scale=scale, sort=sort, timeUnit=timeUnit, title=title, type=type, **kwds, )
FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull
python
takluyver__flit
flit_core/flit_core/common.py
{ "start": 3735, "end": 10640 }
class ____(Exception): def __init__(self, msg, directory): self.msg = msg self.directory = directory def __str__(self): return f'{self.msg} ({self.directory})' @contextmanager def _module_load_ctx(): """Preserve some global state that modules might change at import time. - Handlers on the root logger. """ logging_handlers = logging.root.handlers[:] try: yield finally: logging.root.handlers = logging_handlers def get_docstring_and_version_via_ast(target): """ Return a tuple like (docstring, version) for the given module, extracted by parsing its AST. """ version = None for target_path in target.version_files: # read as bytes to enable custom encodings with target_path.open('rb') as f: node = ast.parse(f.read()) for child in node.body: if is_version_str_assignment(child): version = child.value.value break return ast.get_docstring(node), version def is_version_str_assignment(node): """Check if *node* is a simple string assignment to __version__""" if not isinstance(node, (ast.Assign, ast.AnnAssign)): return False if not isinstance(node.value, ast.Constant): return False targets = (node.target,) if isinstance(node, ast.AnnAssign) else node.targets for target in targets: if isinstance(target, ast.Name) and target.id == "__version__": return True return False # To ensure we're actually loading the specified file, give it a unique name to # avoid any cached import. In normal use we'll only load one module per process, # so it should only matter for the tests, but we'll do it anyway. _import_i = 0 def get_docstring_and_version_via_import(target): """ Return a tuple like (docstring, version) for the given module, extracted by importing the module and pulling __doc__ & __version__ from it. """ global _import_i _import_i += 1 log.debug("Loading module %s", target.file) from importlib.util import spec_from_file_location, module_from_spec mod_name = f'flit_core.dummy.import{_import_i}' spec = spec_from_file_location(mod_name, target.file) with _module_load_ctx(): m = module_from_spec(spec) # Add the module to sys.modules to allow relative imports to work. # importlib has more code around this to handle the case where two # threads are trying to load the same module at the same time, but Flit # should always be running a single thread, so we won't duplicate that. sys.modules[mod_name] = m try: spec.loader.exec_module(m) finally: sys.modules.pop(mod_name, None) docstring = m.__dict__.get('__doc__', None) version = m.__dict__.get('__version__', None) return docstring, version def get_info_from_module(target, for_fields=('version', 'description')): """Load the module/package, get its docstring and __version__ """ if not for_fields: return {} # What core metadata calls Summary, PEP 621 calls description want_summary = 'description' in for_fields want_version = 'version' in for_fields log.debug("Loading module %s", target.file) # Attempt to extract our docstring & version by parsing our target's # AST, falling back to an import if that fails. This allows us to # build without necessarily requiring that our built package's # requirements are installed. docstring, version = get_docstring_and_version_via_ast(target) if (want_summary and not docstring) or (want_version and not version): docstring, version = get_docstring_and_version_via_import(target) res = {} if want_summary: if (not docstring) or not docstring.strip(): raise NoDocstringError( 'Flit cannot package module without docstring, or empty docstring. ' f'Please add a docstring to your module ({target.file}).' ) res['summary'] = docstring.lstrip().splitlines()[0] if want_version: res['version'] = check_version(version) return res def check_version(version): """ Check whether a given version string match PEP 440, and do normalisation. Raise InvalidVersion/NoVersionError with relevant information if version is invalid. Log a warning if the version is not canonical with respect to PEP 440. Returns the version in canonical PEP 440 format. """ if not version: raise NoVersionError('Cannot package module without a version string. ' 'Please define a `__version__ = "x.y.z"` in your module.') if not isinstance(version, str): raise InvalidVersion(f'__version__ must be a string, not {type(version)}.') # Import here to avoid circular import version = normalise_version(version) return version script_template = """\ #!{interpreter} # -*- coding: utf-8 -*- import re import sys from {module} import {import_name} if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0]) sys.exit({func}()) """ def parse_entry_point(ep): """Check and parse a 'package.module:func' style entry point specification. Returns (modulename, funcname) """ if ':' not in ep: raise ValueError(f"Invalid entry point (no ':'): {ep!r}") mod, func = ep.split(':') for piece in func.split('.'): if not piece.isidentifier(): raise ValueError(f"Invalid entry point: {piece!r} is not an identifier") for piece in mod.split('.'): if not piece.isidentifier(): raise ValueError(f"Invalid entry point: {piece!r} is not a module path") return mod, func def write_entry_points(d, fp): """Write entry_points.txt from a two-level dict Sorts on keys to ensure results are reproducible. """ for group_name in sorted(d): fp.write(f'[{group_name}]\n') group = d[group_name] for name in sorted(group): val = group[name] fp.write(f'{name}={val}\n') fp.write('\n') def hash_file(path, algorithm='sha256'): with open(path, 'rb') as f: h = hashlib.new(algorithm, f.read()) return h.hexdigest() def normalize_file_permissions(st_mode): """Normalize the permission bits in the st_mode field from stat to 644/755 Popular VCSs only track whether a file is executable or not. The exact permissions can vary on systems with different umasks. Normalising to 644 (non executable) or 755 (executable) makes builds more reproducible. """ # Set 644 permissions, leaving higher bits of st_mode unchanged new_mode = (st_mode | 0o644) & ~0o133 if st_mode & 0o100: new_mode |= 0o111 # Executable: 644 -> 755 return new_mode
VCSError
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 323310, "end": 333080 }
class ____(FieldChannelMixin, core.SecondaryFieldDef): r""" Latitude2 schema wrapper. A field definition of a secondary channel that shares a scale with another primary channel. For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``. 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. 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 : 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``. 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. """ _class_is_valid_at_instantiation = False _encoding_name = "latitude2" @overload def aggregate(self, _: NonArgAggregateOp_T, /) -> Latitude2: ... @overload def aggregate( self, *, argmax: Optional[str | SchemaBase] = Undefined ) -> Latitude2: ... @overload def aggregate( self, *, argmin: Optional[str | SchemaBase] = Undefined ) -> Latitude2: ... @overload def bandPosition(self, _: float, /) -> Latitude2: ... @overload def bin(self, _: None, /) -> Latitude2: ... @overload def field(self, _: str | RepeatRef, /) -> Latitude2: ... @overload def field( self, *, repeat: Optional[Literal["row", "column", "repeat", "layer"]] = Undefined, ) -> Latitude2: ... @overload def timeUnit( self, _: TimeUnitParams | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T, /, ) -> Latitude2: ... @overload def timeUnit( self, *, binned: Optional[bool] = Undefined, maxbins: Optional[float] = Undefined, step: Optional[float] = Undefined, unit: Optional[SchemaBase | MultiTimeUnit_T | SingleTimeUnit_T] = Undefined, utc: Optional[bool] = Undefined, ) -> Latitude2: ... @overload def title(self, _: str | Sequence[str] | None, /) -> Latitude2: ... def __init__( self, shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined, aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined, bandPosition: Optional[float] = Undefined, bin: Optional[None] = Undefined, field: Optional[str | SchemaBase | Map] = Undefined, timeUnit: Optional[ SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T ] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, **kwds, ): super().__init__( shorthand=shorthand, aggregate=aggregate, bandPosition=bandPosition, bin=bin, field=field, timeUnit=timeUnit, title=title, **kwds, ) @with_property_setters
Latitude2
python
plotly__plotly.py
plotly/matplotlylib/mplexporter/renderers/vincent_renderer.py
{ "start": 77, "end": 1864 }
class ____(Renderer): def open_figure(self, fig, props): self.chart = None self.figwidth = int(props["figwidth"] * props["dpi"]) self.figheight = int(props["figheight"] * props["dpi"]) def draw_line(self, data, coordinates, style, label, mplobj=None): import vincent # only import if VincentRenderer is used if coordinates != "data": warnings.warn("Only data coordinates supported. Skipping this") linedata = {"x": data[:, 0], "y": data[:, 1]} line = vincent.Line( linedata, iter_idx="x", width=self.figwidth, height=self.figheight ) # TODO: respect the other style settings line.scales["color"].range = [style["color"]] if self.chart is None: self.chart = line else: warnings.warn("Multiple plot elements not yet supported") def draw_markers(self, data, coordinates, style, label, mplobj=None): import vincent # only import if VincentRenderer is used if coordinates != "data": warnings.warn("Only data coordinates supported. Skipping this") markerdata = {"x": data[:, 0], "y": data[:, 1]} markers = vincent.Scatter( markerdata, iter_idx="x", width=self.figwidth, height=self.figheight ) # TODO: respect the other style settings markers.scales["color"].range = [style["facecolor"]] if self.chart is None: self.chart = markers else: warnings.warn("Multiple plot elements not yet supported") def fig_to_vincent(fig): """Convert a matplotlib figure to a vincent object""" renderer = VincentRenderer() exporter = Exporter(renderer) exporter.run(fig) return renderer.chart
VincentRenderer
python
numpy__numpy
numpy/_core/tests/test_ufunc.py
{ "start": 116310, "end": 131541 }
class ____: def test_conv1d_full_without_out(self): x = np.arange(5.0) y = np.arange(13.0) w = umt.conv1d_full(x, y) assert_equal(w, np.convolve(x, y, mode='full')) def test_conv1d_full_with_out(self): x = np.arange(5.0) y = np.arange(13.0) out = np.zeros(len(x) + len(y) - 1) umt.conv1d_full(x, y, out=out) assert_equal(out, np.convolve(x, y, mode='full')) def test_conv1d_full_basic_broadcast(self): # x.shape is (3, 6) x = np.array([[1, 3, 0, -10, 2, 2], [0, -1, 2, 2, 10, 4], [8, 9, 10, 2, 23, 3]]) # y.shape is (2, 1, 7) y = np.array([[[3, 4, 5, 20, 30, 40, 29]], [[5, 6, 7, 10, 11, 12, -5]]]) # result should have shape (2, 3, 12) result = umt.conv1d_full(x, y) assert result.shape == (2, 3, 12) for i in range(2): for j in range(3): assert_equal(result[i, j], np.convolve(x[j], y[i, 0])) def test_bad_out_shape(self): x = np.ones((1, 2)) y = np.ones((2, 3)) out = np.zeros((2, 3)) # Not the correct shape. with pytest.raises(ValueError, match=r'does not equal m \+ n - 1'): umt.conv1d_full(x, y, out=out) def test_bad_input_both_inputs_length_zero(self): with pytest.raises(ValueError, match='both inputs have core dimension 0'): umt.conv1d_full([], []) @pytest.mark.parametrize('ufunc', [getattr(np, x) for x in dir(np) if isinstance(getattr(np, x), np.ufunc)]) def test_ufunc_types(ufunc): ''' Check all ufuncs that the correct type is returned. Avoid object and boolean types since many operations are not defined for for them. Choose the shape so even dot and matmul will succeed ''' for typ in ufunc.types: # types is a list of strings like ii->i if 'O' in typ or '?' in typ: continue inp, out = typ.split('->') args = [np.ones((3, 3), t) for t in inp] with warnings.catch_warnings(record=True): warnings.filterwarnings("always") res = ufunc(*args) if isinstance(res, tuple): outs = tuple(out) assert len(res) == len(outs) for r, t in zip(res, outs): assert r.dtype == np.dtype(t) else: assert res.dtype == np.dtype(out) @pytest.mark.parametrize('ufunc', [getattr(np, x) for x in dir(np) if isinstance(getattr(np, x), np.ufunc)]) def test_ufunc_noncontiguous(ufunc): ''' Check that contiguous and non-contiguous calls to ufuncs have the same results for values in range(9) ''' for typ in ufunc.types: # types is a list of strings like ii->i if any(set('O?mM') & set(typ)): # bool, object, datetime are too irregular for this simple test continue inp, out = typ.split('->') args_c = [np.empty((6, 6), t) for t in inp] # non contiguous (2, 3 step on the two dimensions) args_n = [np.empty((12, 18), t)[::2, ::3] for t in inp] # alignment != itemsize is possible. So create an array with such # an odd step manually. args_o = [] for t in inp: orig_dt = np.dtype(t) off_dt = f"S{orig_dt.alignment}" # offset by alignment dtype = np.dtype([("_", off_dt), ("t", orig_dt)], align=False) args_o.append(np.empty((6, 6), dtype=dtype)["t"]) for a in args_c + args_n + args_o: a.flat = range(1, 37) with warnings.catch_warnings(record=True): warnings.filterwarnings("always") res_c = ufunc(*args_c) res_n = ufunc(*args_n) res_o = ufunc(*args_o) if len(out) == 1: res_c = (res_c,) res_n = (res_n,) res_o = (res_o,) for c_ar, n_ar, o_ar in zip(res_c, res_n, res_o): dt = c_ar.dtype if np.issubdtype(dt, np.floating): # for floating point results allow a small fuss in comparisons # since different algorithms (libm vs. intrinsics) can be used # for different input strides res_eps = np.finfo(dt).eps tol = 3 * res_eps assert_allclose(res_c, res_n, atol=tol, rtol=tol) assert_allclose(res_c, res_o, atol=tol, rtol=tol) else: assert_equal(c_ar, n_ar) assert_equal(c_ar, o_ar) @pytest.mark.parametrize('ufunc', [np.sign, np.equal]) def test_ufunc_warn_with_nan(ufunc): # issue gh-15127 # test that calling certain ufuncs with a non-standard `nan` value does not # emit a warning # `b` holds a 64 bit signaling nan: the most significant bit of the # significand is zero. b = np.array([0x7ff0000000000001], 'i8').view('f8') assert np.isnan(b) if ufunc.nin == 1: ufunc(b) elif ufunc.nin == 2: ufunc(b, b.copy()) else: raise ValueError('ufunc with more than 2 inputs') @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") def test_ufunc_out_casterrors(): # Tests that casting errors are correctly reported and buffers are # cleared. # The following array can be added to itself as an object array, but # the result cannot be cast to an integer output: value = 123 # relies on python cache (leak-check will still find it) arr = np.array([value] * int(ncu.BUFSIZE * 1.5) + ["string"] + [value] * int(1.5 * ncu.BUFSIZE), dtype=object) out = np.ones(len(arr), dtype=np.intp) count = sys.getrefcount(value) with pytest.raises(ValueError): # Output casting failure: np.add(arr, arr, out=out, casting="unsafe") assert count == sys.getrefcount(value) # output is unchanged after the error, this shows that the iteration # was aborted (this is not necessarily defined behaviour) assert out[-1] == 1 with pytest.raises(ValueError): # Input casting failure: np.add(arr, arr, out=out, dtype=np.intp, casting="unsafe") assert count == sys.getrefcount(value) # output is unchanged after the error, this shows that the iteration # was aborted (this is not necessarily defined behaviour) assert out[-1] == 1 @pytest.mark.parametrize("bad_offset", [0, int(ncu.BUFSIZE * 1.5)]) def test_ufunc_input_casterrors(bad_offset): value = 123 arr = np.array([value] * bad_offset + ["string"] + [value] * int(1.5 * ncu.BUFSIZE), dtype=object) with pytest.raises(ValueError): # Force cast inputs, but the buffered cast of `arr` to intp fails: np.add(arr, arr, dtype=np.intp, casting="unsafe") @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm") @pytest.mark.parametrize("bad_offset", [0, int(ncu.BUFSIZE * 1.5)]) def test_ufunc_input_floatingpoint_error(bad_offset): value = 123 arr = np.array([value] * bad_offset + [np.nan] + [value] * int(1.5 * ncu.BUFSIZE)) with np.errstate(invalid="raise"), pytest.raises(FloatingPointError): # Force cast inputs, but the buffered cast of `arr` to intp fails: np.add(arr, arr, dtype=np.intp, casting="unsafe") @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO") @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc") @pytest.mark.parametrize( "methodname", ["__call__", "accumulate", "at", "outer", "reduce", "reduceat", "resolve_dtypes"], ) def test_ufunc_method_signatures(methodname: str): method = getattr(np.ufunc, methodname) try: _ = inspect.signature(method) except ValueError as e: pytest.fail(e.args[0]) def test_trivial_loop_invalid_cast(): # This tests the fast-path "invalid cast", see gh-19904. with pytest.raises(TypeError, match="cast ufunc 'add' input 0"): # the void dtype definitely cannot cast to double: np.add(np.array(1, "i,i"), 3, signature="dd->d") @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") @pytest.mark.parametrize("offset", [0, ncu.BUFSIZE // 2, int(1.5 * ncu.BUFSIZE)]) def test_reduce_casterrors(offset): # Test reporting of casting errors in reductions, we test various # offsets to where the casting error will occur, since these may occur # at different places during the reduction procedure. For example # the first item may be special. value = 123 # relies on python cache (leak-check will still find it) arr = np.array([value] * offset + ["string"] + [value] * int(1.5 * ncu.BUFSIZE), dtype=object) out = np.array(-1, dtype=np.intp) count = sys.getrefcount(value) with pytest.raises(ValueError, match="invalid literal"): # This is an unsafe cast, but we currently always allow that. # Note that the double loop is picked, but the cast fails. # `initial=None` disables the use of an identity here to test failures # while copying the first values path (not used when identity exists). np.add.reduce(arr, dtype=np.intp, out=out, initial=None) assert count == sys.getrefcount(value) # If an error occurred during casting, the operation is done at most until # the error occurs (the result of which would be `value * offset`) and -1 # if the error happened immediately. # This does not define behaviour, the output is invalid and thus undefined assert out[()] < value * offset @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") def test_reduction_no_reference_leak(): # Test that the generic reduction does not leak references. # gh-29358 arr = np.array([1, 2, 3], dtype=np.int32) count = sys.getrefcount(arr) np.add.reduce(arr, dtype=np.int32, initial=0) assert count == sys.getrefcount(arr) np.add.accumulate(arr, dtype=np.int32) assert count == sys.getrefcount(arr) np.add.reduceat(arr, [0, 1], dtype=np.int32) assert count == sys.getrefcount(arr) # with `out=` the reference count is not changed out = np.empty((), dtype=np.int32) out_count = sys.getrefcount(out) np.add.reduce(arr, dtype=np.int32, out=out, initial=0) assert count == sys.getrefcount(arr) assert out_count == sys.getrefcount(out) out = np.empty(arr.shape, dtype=np.int32) out_count = sys.getrefcount(out) np.add.accumulate(arr, dtype=np.int32, out=out) assert count == sys.getrefcount(arr) assert out_count == sys.getrefcount(out) out = np.empty((2,), dtype=np.int32) out_count = sys.getrefcount(out) np.add.reduceat(arr, [0, 1], dtype=np.int32, out=out) assert count == sys.getrefcount(arr) assert out_count == sys.getrefcount(out) def test_object_reduce_cleanup_on_failure(): # Test cleanup, including of the initial value (manually provided or not) with pytest.raises(TypeError): np.add.reduce([1, 2, None], initial=4) with pytest.raises(TypeError): np.add.reduce([1, 2, None]) @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm") @pytest.mark.parametrize("method", [np.add.accumulate, np.add.reduce, pytest.param(lambda x: np.add.reduceat(x, [0]), id="reduceat"), pytest.param(lambda x: np.log.at(x, [2]), id="at")]) def test_ufunc_methods_floaterrors(method): # adding inf and -inf (or log(-inf) creates an invalid float and warns arr = np.array([np.inf, 0, -np.inf]) with np.errstate(all="warn"): with pytest.warns(RuntimeWarning, match="invalid value"): method(arr) arr = np.array([np.inf, 0, -np.inf]) with np.errstate(all="raise"): with pytest.raises(FloatingPointError): method(arr) def _check_neg_zero(value): if value != 0.0: return False if not np.signbit(value.real): return False if value.dtype.kind == "c": return np.signbit(value.imag) return True @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"]) def test_addition_negative_zero(dtype): dtype = np.dtype(dtype) if dtype.kind == "c": neg_zero = dtype.type(complex(-0.0, -0.0)) else: neg_zero = dtype.type(-0.0) arr = np.array(neg_zero) arr2 = np.array(neg_zero) assert _check_neg_zero(arr + arr2) # In-place ops may end up on a different path (reduce path) see gh-21211 arr += arr2 assert _check_neg_zero(arr) @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"]) @pytest.mark.parametrize("use_initial", [True, False]) def test_addition_reduce_negative_zero(dtype, use_initial): dtype = np.dtype(dtype) if dtype.kind == "c": neg_zero = dtype.type(complex(-0.0, -0.0)) else: neg_zero = dtype.type(-0.0) kwargs = {} if use_initial: kwargs["initial"] = neg_zero else: pytest.xfail("-0. propagation in sum currently requires initial") # Test various length, in case SIMD paths or chunking play a role. # 150 extends beyond the pairwise blocksize; probably not important. for i in range(150): arr = np.array([neg_zero] * i, dtype=dtype) res = np.sum(arr, **kwargs) if i > 0 or use_initial: assert _check_neg_zero(res) else: # `sum([])` should probably be 0.0 and not -0.0 like `sum([-0.0])` assert not np.signbit(res.real) assert not np.signbit(res.imag) @pytest.mark.parametrize(["dt1", "dt2"], [("S", "U"), ("U", "S"), ("S", "d"), ("S", "V"), ("U", "l")]) def test_addition_string_types(dt1, dt2): arr1 = np.array([1234234], dtype=dt1) arr2 = np.array([b"423"], dtype=dt2) with pytest.raises(np._core._exceptions.UFuncTypeError) as exc: np.add(arr1, arr2) @pytest.mark.parametrize("order1,order2", [(">", ">"), ("<", "<"), (">", "<"), ("<", ">")]) def test_addition_unicode_inverse_byte_order(order1, order2): element = 'abcd' arr1 = np.array([element], dtype=f"{order1}U4") arr2 = np.array([element], dtype=f"{order2}U4") result = arr1 + arr2 assert result == 2 * element @pytest.mark.parametrize("dtype", [np.int8, np.int16, np.int32, np.int64]) def test_find_non_long_args(dtype): element = 'abcd' start = dtype(0) end = dtype(len(element)) arr = np.array([element]) result = np._core.umath.find(arr, "a", start, end) assert result.dtype == np.dtype("intp") assert result == 0 def test_find_access_past_buffer(): # This checks that no read past the string buffer occurs in # string_fastsearch.h. The buffer class makes sure this is checked. # To see it in action, you can remove the checks in the buffer and # this test will produce an 'Invalid read' if run under valgrind. arr = np.array([b'abcd', b'ebcd']) result = np._core.umath.find(arr, b'cde', 0, np.iinfo(np.int64).max) assert np.all(result == -1)
TestGUFuncProcessCoreDims
python
ray-project__ray
python/ray/llm/tests/serve/mocks/mock_vllm_engine.py
{ "start": 763, "end": 15327 }
class ____(LLMEngine): """Mock vLLM Engine that generates fake text responses. - In case of LoRA it generates a prefix with the model name in the text part of the response. """ def __init__(self, llm_config: LLMConfig): """Create a mock vLLM Engine. Args: llm_config: The llm configuration for this engine """ self.llm_config = llm_config self.started = False self._current_lora_model: Dict[str, DiskMultiplexConfig] = {} async def start(self): """Start the mock engine.""" self.started = True async def resolve_lora(self, lora_model: DiskMultiplexConfig): """Resolve/load a LoRA model.""" self._current_lora_model[lora_model.model_id] = lora_model async def check_health(self) -> None: """Check the health of the mock engine.""" if not self.started: raise RuntimeError("Engine not started") async def reset_prefix_cache(self) -> None: """Reset the prefix cache of the mock engine.""" if not self.started: raise RuntimeError("Engine not started") async def start_profile(self) -> None: """Start profiling of the mock engine.""" if not self.started: raise RuntimeError("Engine not started") async def stop_profile(self) -> None: """Stop profiling of the mock engine.""" if not self.started: raise RuntimeError("Engine not started") async def chat( self, request: ChatCompletionRequest ) -> AsyncGenerator[Union[str, ChatCompletionResponse, ErrorResponse], None]: """Mock chat completion.""" if not self.started: raise RuntimeError("Engine not started") # Extract prompt text from messages prompt_text = "" if request.messages: for message in request.messages: if hasattr(message, "content") and message.content: prompt_text += str(message.content) + " " max_tokens = getattr(request, "max_tokens", None) or randint(1, 10) # Generate streaming response async for response in self._generate_chat_response( request=request, prompt_text=prompt_text.strip(), max_tokens=max_tokens ): yield response async def completions( self, request: CompletionRequest ) -> AsyncGenerator[Union[str, CompletionResponse, ErrorResponse], None]: """Mock text completion.""" if not self.started: raise RuntimeError("Engine not started") prompt_text = str(request.prompt) if request.prompt else "" max_tokens = getattr(request, "max_tokens", None) or randint(5, 20) # Generate streaming response async for response in self._generate_completion_response( request=request, prompt_text=prompt_text, max_tokens=max_tokens ): yield response async def embeddings( self, request: EmbeddingRequest ) -> AsyncGenerator[Union[str, EmbeddingResponse, ErrorResponse], None]: """Mock embeddings generation.""" if not self.started: raise RuntimeError("Engine not started") # Generate a mock embedding response embedding_data = [] inputs = request.input if isinstance(request.input, list) else [request.input] for i, text in enumerate(inputs): # Generate random embedding vector dimensions = getattr(request, "dimensions", None) or 1536 embedding = [random.uniform(-1, 1) for _ in range(dimensions)] embedding_data.append( {"object": "embedding", "embedding": embedding, "index": i} ) response = EmbeddingResponse( object="list", data=embedding_data, model=getattr(request, "model", "mock-model"), usage={ "prompt_tokens": len(str(request.input).split()), "total_tokens": len(str(request.input).split()), }, ) yield response async def transcriptions( self, request: TranscriptionRequest ) -> AsyncGenerator[Union[str, TranscriptionResponse, ErrorResponse], None]: """Mock transcription generation.""" if not self.started: raise RuntimeError("Engine not started") # Extract audio file info language = getattr(request, "language", "en") temperature = getattr(request, "temperature", 0.0) # Generate transcription response async for response in self._generate_transcription_response( request=request, language=language, temperature=temperature ): yield response async def score( self, request: ScoreRequest ) -> AsyncGenerator[Union[str, ScoreResponse, ErrorResponse], None]: """Mock score generation for text pairs.""" if not self.started: raise RuntimeError("Engine not started") # Extract text_1 and text_2 from the request text_1 = getattr(request, "text_1", "") text_2 = getattr(request, "text_2", "") # Convert to lists if they aren't already text_1_list = text_1 if isinstance(text_1, list) else [text_1] text_2_list = text_2 if isinstance(text_2, list) else [text_2] # Generate mock scores for each pair score_data = [] for i, (t1, t2) in enumerate(zip(text_1_list, text_2_list)): # Generate a random score (can be any float value) score = random.uniform(-10.0, 10.0) score_data.append({"object": "score", "score": score, "index": i}) # Create the response response = ScoreResponse( object="list", data=score_data, model=getattr(request, "model", "mock-model"), usage={ "prompt_tokens": len(str(text_1).split()) + len(str(text_2).split()), "total_tokens": len(str(text_1).split()) + len(str(text_2).split()), }, ) yield response async def _generate_chat_response( self, request: ChatCompletionRequest, prompt_text: str, max_tokens: int ) -> AsyncGenerator[Union[str, ChatCompletionResponse], None]: """Generate mock chat completion response.""" request_id = request.request_id or f"chatcmpl-{random.randint(1000, 9999)}" lora_prefix = ( "" if request.model not in self._current_lora_model else f"[lora_model] {request.model}: " ) if request.stream: # Streaming response - return SSE formatted strings created_time = int(asyncio.get_event_loop().time()) model_name = getattr(request, "model", "mock-model") for i in range(max_tokens): if i == 0: token = f"{lora_prefix}test_{i} " else: token = f"test_{i} " if i == max_tokens - 1: # no space for the last token token = f"test_{i}" # Create streaming chunk choice = { "index": 0, "delta": { "content": token, "role": "assistant" if i == 0 else None, }, "finish_reason": "stop" if i == max_tokens - 1 else None, } chunk_data = { "id": request_id, "object": "chat.completion.chunk", "created": created_time, "model": model_name, "choices": [choice], } # Format as SSE yield f"data: {json.dumps(chunk_data)}\n\n" await asyncio.sleep(0.01) # Simulate processing time # Send final [DONE] message yield "data: [DONE]\n\n" else: # Non-streaming response - return response object generated_text = " ".join([f"test_{i}" for i in range(max_tokens)]) generated_text = f"{lora_prefix}{generated_text}" choice = { "index": 0, "message": {"role": "assistant", "content": generated_text}, "finish_reason": "stop", } response = ChatCompletionResponse( id=request_id, object="chat.completion", created=int(asyncio.get_event_loop().time()), model=getattr(request, "model", "mock-model"), choices=[choice], usage={ "prompt_tokens": len(prompt_text.split()), "completion_tokens": max_tokens, "total_tokens": len(prompt_text.split()) + max_tokens, }, ) yield response async def _generate_completion_response( self, request: CompletionRequest, prompt_text: str, max_tokens: int ) -> AsyncGenerator[Union[str, CompletionResponse], None]: """Generate mock completion response.""" request_id = request.request_id or f"cmpl-{random.randint(1000, 9999)}" lora_prefix = ( "" if request.model not in self._current_lora_model else f"[lora_model] {request.model}: " ) if request.stream: # Streaming response - return SSE formatted strings created_time = int(asyncio.get_event_loop().time()) model_name = getattr(request, "model", "mock-model") for i in range(max_tokens): if i == 0: token = f"{lora_prefix}test_{i} " else: token = f"test_{i} " if i == max_tokens - 1: # no space for the last token token = f"test_{i}" choice = { "index": 0, "text": token, "finish_reason": "stop" if i == max_tokens - 1 else None, } chunk_data = { "id": request_id, "object": "text_completion", "created": created_time, "model": model_name, "choices": [choice], } # Format as SSE yield f"data: {json.dumps(chunk_data)}\n\n" await asyncio.sleep(0.01) # Send final [DONE] message yield "data: [DONE]\n\n" else: # Non-streaming response - return response object generated_text = " ".join([f"test_{i}" for i in range(max_tokens)]) generated_text = f"{lora_prefix}{generated_text}" choice = {"index": 0, "text": generated_text, "finish_reason": "stop"} response = CompletionResponse( id=request_id, object="text_completion", created=int(asyncio.get_event_loop().time()), model=getattr(request, "model", "mock-model"), choices=[choice], usage={ "prompt_tokens": len(prompt_text.split()), "completion_tokens": max_tokens, "total_tokens": len(prompt_text.split()) + max_tokens, }, ) yield response async def _generate_transcription_response( self, request: TranscriptionRequest, language: str, temperature: float, ) -> AsyncGenerator[Union[str, TranscriptionResponse], None]: """Generate mock transcription response.""" request_id = request.request_id or f"transcribe-{random.randint(1000, 9999)}" lora_prefix = ( "" if request.model not in self._current_lora_model else f"[lora_model] {request.model}: " ) # Generate mock transcription text with LoRA prefix mock_transcription_text = ( f"Mock transcription in {language} language with temperature {temperature}" ) if lora_prefix: mock_transcription_text = f"{lora_prefix}{mock_transcription_text}" if request.stream: # Streaming response - return SSE formatted strings created_time = int(asyncio.get_event_loop().time()) model_name = getattr(request, "model", "mock-model") # Split transcription into words for streaming words = mock_transcription_text.split() for i, word in enumerate(words): # Create streaming chunk choice = { "delta": { "content": word + (" " if i < len(words) - 1 else ""), }, } chunk_data = { "delta": None, "type": None, "logprobs": None, "id": request_id, "object": "transcription.chunk", "created": created_time, "model": model_name, "choices": [choice], } # Format as SSE yield f"data: {json.dumps(chunk_data)}\n\n" await asyncio.sleep(0.01) # Simulate processing time # Send final chunk with finish_reason final_choice = { "delta": { "content": "", "finish_reason": "stop", "stop_reason": None, }, } final_chunk_data = { "delta": None, "type": None, "logprobs": None, "id": request_id, "object": "transcription.chunk", "created": created_time, "model": model_name, "choices": [final_choice], } yield f"data: {json.dumps(final_chunk_data)}\n\n" # Send final [DONE] message yield "data: [DONE]\n\n" else: # Non-streaming response - return response object response = TranscriptionResponse( text=mock_transcription_text, logprobs=None, usage={ "seconds": 5.0, "type": "duration", }, ) yield response
MockVLLMEngine
python
getsentry__sentry
tests/sentry/utils/test_snuba.py
{ "start": 9812, "end": 15309 }
class ____(TestCase): def test_events_dataset_with_project_id(self) -> None: query_params = SnubaQueryParams( dataset=Dataset.Events, filter_keys={"project_id": [self.project.id]} ) kwargs, _, _ = _prepare_query_params(query_params) assert kwargs["project"] == [self.project.id] def test_with_deleted_project(self) -> None: query_params = SnubaQueryParams( dataset=Dataset.Events, filter_keys={"project_id": [self.project.id]} ) self.project.delete() with pytest.raises(UnqualifiedQueryError): get_query_params_to_update_for_projects(query_params) @mock.patch("sentry.models.Project.objects.get_from_cache", side_effect=Project.DoesNotExist) def test_with_some_deleted_projects(self, mock_project: mock.MagicMock) -> None: other_project = self.create_project(organization=self.organization, slug="a" * 32) query_params = SnubaQueryParams( dataset=Dataset.Events, filter_keys={"project_id": [self.project.id, other_project.id]} ) other_project.delete() organization_id, _ = get_query_params_to_update_for_projects(query_params) assert organization_id == self.organization.id def test_outcomes_dataset_with_org_id(self) -> None: query_params = SnubaQueryParams( dataset=Dataset.Outcomes, filter_keys={"org_id": [self.organization.id]} ) kwargs, _, _ = _prepare_query_params(query_params) assert kwargs["organization"] == self.organization.id def test_outcomes_dataset_with_key_id(self) -> None: key = self.create_project_key(project=self.project) query_params = SnubaQueryParams(dataset=Dataset.Outcomes, filter_keys={"key_id": [key.id]}) kwargs, _, _ = _prepare_query_params(query_params) assert kwargs["organization"] == self.organization.id def test_outcomes_dataset_with_no_org_id_given(self) -> None: query_params = SnubaQueryParams(dataset=Dataset.Outcomes) with pytest.raises(UnqualifiedQueryError): _prepare_query_params(query_params) def test_invalid_dataset_provided(self) -> None: query_params = SnubaQueryParams(dataset="invalid_dataset") with pytest.raises(UnqualifiedQueryError): _prepare_query_params(query_params) def test_original_query_params_does_not_get_mutated(self) -> None: snuba_params = SnubaQueryParams( dataset=Dataset.Sessions, start=datetime.now() - timedelta(hours=1), end=datetime.now(), groupby=[], conditions=[[["environment", "IN", {"development", "abc"}]]], filter_keys={"release": [self.create_release(version="1.0.0").id]}, aggregations=[], rollup=86400, is_grouprelease=False, **{"selected_columns": ["sessions"]}, ) conditions = [[["environment", "IN", {"development", "abc"}]]] kwargs = {"selected_columns": ["sessions"]} _prepare_query_params(snuba_params) assert conditions == snuba_params.conditions assert kwargs == snuba_params.kwargs def test_preprocess_group_redirects(self) -> None: g1 = self.create_group(id=1) g2 = self.create_group(id=2) g3 = self.create_group(id=3) g4 = self.create_group(id=4) GroupRedirect.objects.create( organization_id=g1.project.organization_id, group_id=g1.id, previous_group_id=g2.id, ) GroupRedirect.objects.create( organization_id=g1.project.organization_id, group_id=g1.id, previous_group_id=g3.id, ) params = SnubaQueryParams(dataset=Dataset.Events, filter_keys={"group_id": {g1.id}}) assert params.conditions[0] == ["group_id", "IN", {g1.id, g2.id, g3.id}] params = SnubaQueryParams(dataset=Dataset.Events, conditions=[["group_id", "=", g1.id]]) assert params.conditions[0] == ["group_id", "IN", {g1.id, g2.id, g3.id}] params = SnubaQueryParams( dataset=Dataset.Events, filter_keys={"group_id": {g4.id}}, conditions=[["group_id", "IN", [g1.id, g4.id]]], ) assert params.conditions[0] == ["group_id", "IN", {g4.id}] params = SnubaQueryParams( dataset=Dataset.Events, conditions=[["group_id", "IN", [g1.id, g4.id]], ["group_id", "IN", [g1.id]]], ) assert params.conditions[0] == ["group_id", "IN", {g1.id, g2.id, g3.id}] params = SnubaQueryParams( dataset=Dataset.Events, conditions=[["group_id", "IN", [g1.id, g4.id]], ["group_id", "NOT IN", [g1.id]]], ) assert params.conditions[0] == ["group_id", "IN", {g4.id}] params = SnubaQueryParams( dataset=Dataset.Events, conditions=[["foo", "=", "bar"]], ) assert params.conditions[0] == ["foo", "=", "bar"] assert len(params.conditions) == 1 # Should not mutate inputs filter_keys = {"group_id": {g4.id}} conditions = [["group_id", "IN", [g1.id, g4.id]]] SnubaQueryParams( dataset=Dataset.Events, filter_keys=filter_keys, conditions=conditions, ) assert filter_keys == {"group_id": {g4.id}} assert conditions == [["group_id", "IN", [g1.id, g4.id]]]
PrepareQueryParamsTest
python
doocs__leetcode
solution/2400-2499/2489.Number of Substrings With Fixed Ratio/Solution.py
{ "start": 0, "end": 326 }
class ____: def fixedRatio(self, s: str, num1: int, num2: int) -> int: n0 = n1 = 0 ans = 0 cnt = Counter({0: 1}) for c in s: n0 += c == '0' n1 += c == '1' x = n1 * num1 - n0 * num2 ans += cnt[x] cnt[x] += 1 return ans
Solution
python
huggingface__transformers
src/transformers/models/bloom/modeling_bloom.py
{ "start": 47260, "end": 50989 }
class ____(BloomPreTrainedModel): def __init__(self, config): super().__init__(config) self.transformer = BloomModel(config) self.qa_outputs = nn.Linear(config.hidden_size, 2) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, QuestionAnsweringModelOutput]: r""" input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.transformer( input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[2:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = [ "BloomForCausalLM", "BloomModel", "BloomPreTrainedModel", "BloomForSequenceClassification", "BloomForTokenClassification", "BloomForQuestionAnswering", ]
BloomForQuestionAnswering
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_runs_feed.py
{ "start": 4423, "end": 17559 }
class ____(ExecutingGraphQLContextTestMatrix): """Tests for the runs feed that can be done on a instance that has 10 runs and 10 backfills created in alternating order. Split these tests into a separate class so that we can make the runs and backfills once and re-use them across tests. """ @pytest.fixture(scope="class") def gql_context_with_runs_and_backfills(self, class_scoped_graphql_context): for _ in range(10): _create_run(class_scoped_graphql_context) time.sleep(CREATE_DELAY) _create_backfill(class_scoped_graphql_context) return class_scoped_graphql_context def test_get_runs_feed(self, gql_context_with_runs_and_backfills): result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 25, "cursor": None, "filter": None, "view": "ROOTS", }, ) _assert_results_match_count_match_expected(result, 20) prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 10, "cursor": None, "filter": None, "view": "ROOTS", }, ) assert not result.errors assert result.data # limit was used, count will differ from number of results returned assert len(result.data["runsFeedOrError"]["results"]) == 10 prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert result.data["runsFeedOrError"]["hasMore"] old_cursor = result.data["runsFeedOrError"]["cursor"] assert old_cursor is not None result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 10, "cursor": old_cursor, "filter": None, "view": "ROOTS", }, ) assert len(result.data["runsFeedOrError"]["results"]) == 10 for res in result.data["runsFeedOrError"]["results"]: if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert not result.data["runsFeedOrError"]["hasMore"] def test_get_runs_feed_inexact_limit(self, gql_context_with_runs_and_backfills): result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 15, "cursor": None, "filter": None, "view": "ROOTS", }, ) assert not result.errors assert result.data assert len(result.data["runsFeedOrError"]["results"]) == 15 prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert result.data["runsFeedOrError"]["hasMore"] assert result.data["runsFeedOrError"]["cursor"] is not None result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 10, "cursor": result.data["runsFeedOrError"]["cursor"], "filter": None, "view": "ROOTS", }, ) # limit was used, count will differ from number of results returned assert len(result.data["runsFeedOrError"]["results"]) == 5 for res in result.data["runsFeedOrError"]["results"]: if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert not result.data["runsFeedOrError"]["hasMore"] def test_get_runs_feed_cursor_respected(self, gql_context_with_runs_and_backfills): result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 10, "cursor": None, "filter": None, "view": "ROOTS", }, ) assert not result.errors assert result.data assert len(result.data["runsFeedOrError"]["results"]) == 10 prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert result.data["runsFeedOrError"]["hasMore"] assert result.data["runsFeedOrError"]["cursor"] is not None old_cursor = RunsFeedCursor.from_string(result.data["runsFeedOrError"]["cursor"]) run_cursor_run = gql_context_with_runs_and_backfills.instance.get_run_record_by_id( old_cursor.run_cursor ) backfill_cursor_backfill = gql_context_with_runs_and_backfills.instance.get_backfill( old_cursor.backfill_cursor ) result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 10, "cursor": old_cursor.to_string(), "filter": None, "view": "ROOTS", }, ) assert len(result.data["runsFeedOrError"]["results"]) == 10 for res in result.data["runsFeedOrError"]["results"]: if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert res["id"] != old_cursor.run_cursor assert res["id"] != old_cursor.backfill_cursor assert res["creationTime"] <= run_cursor_run.create_timestamp.timestamp() assert res["creationTime"] <= backfill_cursor_backfill.backfill_timestamp assert not result.data["runsFeedOrError"]["hasMore"] def test_get_runs_feed_with_view_runs(self, gql_context_with_runs_and_backfills): result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 25, "cursor": None, "filter": None, "view": "RUNS", }, ) _assert_results_match_count_match_expected(result, 10) prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "Run" if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 10, "cursor": None, "filter": None, "view": "RUNS", }, ) assert not result.errors assert result.data assert len(result.data["runsFeedOrError"]["results"]) == 10 prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "Run" if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert not result.data["runsFeedOrError"]["hasMore"] result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 5, "cursor": None, "filter": None, "view": "RUNS", }, ) assert not result.errors assert result.data assert len(result.data["runsFeedOrError"]["results"]) == 5 prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "Run" if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert result.data["runsFeedOrError"]["hasMore"] old_cursor = result.data["runsFeedOrError"]["cursor"] assert old_cursor is not None result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 5, "cursor": old_cursor, "filter": None, "view": "RUNS", }, ) assert len(result.data["runsFeedOrError"]["results"]) == 5 for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "Run" if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert not result.data["runsFeedOrError"]["hasMore"] def test_get_runs_feed_with_view_backfills(self, gql_context_with_runs_and_backfills): result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 25, "cursor": None, "filter": None, "view": "BACKFILLS", }, ) _assert_results_match_count_match_expected(result, 10) prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "PartitionBackfill" if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 10, "cursor": None, "filter": None, "view": "BACKFILLS", }, ) assert not result.errors assert result.data assert len(result.data["runsFeedOrError"]["results"]) == 10 prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "PartitionBackfill" if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert not result.data["runsFeedOrError"]["hasMore"] result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 5, "cursor": None, "filter": None, "view": "BACKFILLS", }, ) assert not result.errors assert result.data assert len(result.data["runsFeedOrError"]["results"]) == 5 prev_run_time = None for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "PartitionBackfill" if prev_run_time: assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert result.data["runsFeedOrError"]["hasMore"] old_cursor = result.data["runsFeedOrError"]["cursor"] assert old_cursor is not None result = execute_dagster_graphql( gql_context_with_runs_and_backfills.create_request_context(), GET_RUNS_FEED_QUERY, variables={ "limit": 5, "cursor": old_cursor, "filter": None, "view": "BACKFILLS", }, ) assert len(result.data["runsFeedOrError"]["results"]) == 5 for res in result.data["runsFeedOrError"]["results"]: assert res["__typename"] == "PartitionBackfill" assert res["creationTime"] <= prev_run_time prev_run_time = res["creationTime"] assert not result.data["runsFeedOrError"]["hasMore"]
TestRunsFeedWithSharedSetup
python
keras-team__keras
keras/src/testing/test_utils_test.py
{ "start": 142, "end": 5860 }
class ____(test_case.TestCase): def setUp(self): self.train_samples = 100 self.test_samples = 50 self.input_shape = (28, 28) self.num_classes = 10 def test_labels_within_range(self): """Check if labels are within valid range.""" (_, y_train), (_, y_test) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, ) self.assertTrue(np.all(y_train < self.num_classes)) self.assertTrue(np.all(y_train >= 0)) self.assertTrue(np.all(y_test < self.num_classes)) self.assertTrue(np.all(y_test >= 0)) def test_edge_cases_for_zero_samples(self): """Test when train or test samples are zero.""" (x_train, _), (x_test, _) = test_utils.get_test_data( 0, self.test_samples, self.input_shape, self.num_classes ) self.assertEqual(len(x_train), 0) (x_train, _), (x_test, _) = test_utils.get_test_data( self.train_samples, 0, self.input_shape, self.num_classes ) self.assertEqual(len(x_test), 0) def test_get_test_data_returns_correct_number_of_samples(self): """Check if returned samples count is correct.""" (x_train, y_train), (x_test, y_test) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, ) self.assertEqual(len(x_train), self.train_samples) self.assertEqual(len(y_train), self.train_samples) self.assertEqual(len(x_test), self.test_samples) self.assertEqual(len(y_test), self.test_samples) def test_get_test_data_returns_correct_shape_of_data(self): """Check if returned data shape is correct.""" (x_train, y_train), (x_test, y_test) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, ) self.assertEqual( x_train.shape, (self.train_samples,) + self.input_shape ) self.assertEqual(y_train.shape, (self.train_samples,)) self.assertEqual(x_test.shape, (self.test_samples,) + self.input_shape) self.assertEqual(y_test.shape, (self.test_samples,)) def test_get_test_data_returns_different_data_for_different_seeds(self): """Test variability with different seeds.""" (x_train_1, y_train_1), (x_test_1, y_test_1) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, random_seed=1, ) (x_train_2, y_train_2), (x_test_2, y_test_2) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, random_seed=2, ) self.assertFalse(np.array_equal(x_train_1, x_train_2)) self.assertFalse(np.array_equal(y_train_1, y_train_2)) self.assertFalse(np.array_equal(x_test_1, x_test_2)) self.assertFalse(np.array_equal(y_test_1, y_test_2)) def test_get_test_data_returns_consistent_data_for_same_seed(self): """Test consistency with the same seed.""" (x_train_1, y_train_1), (x_test_1, y_test_1) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, random_seed=1, ) (x_train_2, y_train_2), (x_test_2, y_test_2) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, random_seed=1, ) self.assertTrue(np.array_equal(x_train_1, x_train_2)) self.assertTrue(np.array_equal(y_train_1, y_train_2)) self.assertTrue(np.array_equal(x_test_1, x_test_2)) self.assertTrue(np.array_equal(y_test_1, y_test_2)) def test_input_shape_variations(self): """Check function for different input shapes.""" input_shape_3d = (28, 28, 3) (x_train_3d, _), (_, _) = test_utils.get_test_data( self.train_samples, self.test_samples, input_shape_3d, self.num_classes, ) self.assertEqual( x_train_3d.shape, (self.train_samples,) + input_shape_3d ) def test_all_classes_represented(self): """Ensure all classes are represented in the data.""" (_, y_train), (_, y_test) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, ) self.assertEqual(len(np.unique(y_train)), self.num_classes) self.assertEqual(len(np.unique(y_test)), self.num_classes) def test_data_type(self): """Validate the type of the generated data.""" (x_train, _), (x_test, _) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, ) self.assertEqual(x_train.dtype, np.float32) self.assertEqual(x_test.dtype, np.float32) def test_label_type(self): """Validate label type of the generated labels.""" (_, y_train), (_, y_test) = test_utils.get_test_data( self.train_samples, self.test_samples, self.input_shape, self.num_classes, ) self.assertEqual(y_train.dtype, np.int64) self.assertEqual(y_test.dtype, np.int64)
GetTestDataTest