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
doocs__leetcode
solution/0400-0499/0439.Ternary Expression Parser/Solution.py
{ "start": 0, "end": 601 }
class ____: def parseTernary(self, expression: str) -> str: stk = [] cond = False for c in expression[::-1]: if c == ':': continue if c == '?': cond = True else: if cond: if c == 'T': x = stk.pop() stk.pop() stk.append(x) else: stk.pop() cond = False else: stk.append(c) return stk[0]
Solution
python
mlflow__mlflow
mlflow/utils/search_utils.py
{ "start": 47882, "end": 55901 }
class ____(SearchUtils): NUMERIC_ATTRIBUTES = {"creation_timestamp", "last_updated_timestamp"} VALID_SEARCH_ATTRIBUTE_KEYS = {"name"} VALID_ORDER_BY_KEYS_REGISTERED_MODELS = {"name", "creation_timestamp", "last_updated_timestamp"} @classmethod def _does_registered_model_match_clauses(cls, model, sed): key_type = sed.get("type") key = sed.get("key") value = sed.get("value") comparator = sed.get("comparator").upper() # what comparators do we support here? if cls.is_string_attribute(key_type, key, comparator): lhs = getattr(model, key) elif cls.is_numeric_attribute(key_type, key, comparator): lhs = getattr(model, key) value = int(value) elif cls.is_tag(key_type, comparator): # NB: We should use the private attribute `_tags` instead of the `tags` property # to consider all tags including reserved ones. lhs = model._tags.get(key, None) else: raise MlflowException( f"Invalid search expression type '{key_type}'", error_code=INVALID_PARAMETER_VALUE ) # NB: Handling the special `mlflow.prompt.is_prompt` tag. This tag is used for # distinguishing between prompt models and normal models. For example, we want to # search for models only by the following filter string: # # tags.`mlflow.prompt.is_prompt` != 'true' # tags.`mlflow.prompt.is_prompt` = 'false' # # However, models do not have this tag, so lhs is None in this case. Instead of returning # False like normal tag filter, we need to return True here. if key == IS_PROMPT_TAG_KEY and lhs is None: return (comparator == "=" and value == "false") or ( comparator == "!=" and value == "true" ) if lhs is None: return False return SearchUtils.get_comparison_func(comparator)(lhs, value) @classmethod def filter(cls, registered_models, filter_string): """Filters a set of registered models based on a search filter string.""" if not filter_string: return registered_models parsed = cls.parse_search_filter(filter_string) def registered_model_matches(model): return all(cls._does_registered_model_match_clauses(model, s) for s in parsed) return [ registered_model for registered_model in registered_models if registered_model_matches(registered_model) ] @classmethod def parse_order_by_for_search_registered_models(cls, order_by): token_value, is_ascending = cls._parse_order_by_string(order_by) identifier = SearchExperimentsUtils._get_identifier( token_value.strip(), cls.VALID_ORDER_BY_KEYS_REGISTERED_MODELS ) return identifier["type"], identifier["key"], is_ascending @classmethod def _get_sort_key(cls, order_by_list): order_by = [] parsed_order_by = map(cls.parse_order_by_for_search_registered_models, order_by_list or []) for type_, key, ascending in parsed_order_by: if type_ == "attribute": order_by.append((key, ascending)) else: raise MlflowException.invalid_parameter_value(f"Invalid order_by entity: {type_}") # Add a tie-breaker if not any(key == "name" for key, _ in order_by): order_by.append(("name", True)) return lambda model: tuple(_apply_reversor(model, k, asc) for (k, asc) in order_by) @classmethod def sort(cls, models, order_by_list): return sorted(models, key=cls._get_sort_key(order_by_list)) @classmethod def _process_statement(cls, statement): tokens = _join_in_comparison_tokens(statement.tokens) invalids = list(filter(cls._invalid_statement_token_search_model_registry, tokens)) if len(invalids) > 0: invalid_clauses = ", ".join(map(str, invalids)) raise MlflowException.invalid_parameter_value( f"Invalid clause(s) in filter string: {invalid_clauses}" ) return [cls._get_comparison(t) for t in tokens if isinstance(t, Comparison)] @classmethod def _get_model_search_identifier(cls, identifier, valid_attributes): tokens = identifier.split(".", maxsplit=1) if len(tokens) == 1: key = tokens[0] identifier = cls._ATTRIBUTE_IDENTIFIER else: entity_type, key = tokens valid_entity_types = ("attribute", "tag", "tags") if entity_type not in valid_entity_types: raise MlflowException.invalid_parameter_value( f"Invalid entity type '{entity_type}'. " f"Valid entity types are {valid_entity_types}" ) identifier = ( cls._TAG_IDENTIFIER if entity_type in ("tag", "tags") else cls._ATTRIBUTE_IDENTIFIER ) if identifier == cls._ATTRIBUTE_IDENTIFIER and key not in valid_attributes: raise MlflowException.invalid_parameter_value( f"Invalid attribute key '{key}' specified. Valid keys are '{valid_attributes}'" ) key = cls._trim_backticks(cls._strip_quotes(key)) return {"type": identifier, "key": key} @classmethod def _get_comparison(cls, comparison): stripped_comparison = [token for token in comparison.tokens if not token.is_whitespace] cls._validate_comparison(stripped_comparison) left, comparator, right = stripped_comparison comp = cls._get_model_search_identifier(left.value, cls.VALID_SEARCH_ATTRIBUTE_KEYS) comp["comparator"] = comparator.value.upper() comp["value"] = cls._get_value(comp.get("type"), comp.get("key"), right) return comp @classmethod def _get_value(cls, identifier_type, key, token): if identifier_type == cls._TAG_IDENTIFIER: if token.ttype in cls.STRING_VALUE_TYPES or isinstance(token, Identifier): return cls._strip_quotes(token.value, expect_quoted_value=True) raise MlflowException( "Expected a quoted string value for " f"{identifier_type} (e.g. 'my-value'). Got value " f"{token.value}", error_code=INVALID_PARAMETER_VALUE, ) elif identifier_type == cls._ATTRIBUTE_IDENTIFIER: if token.ttype in cls.STRING_VALUE_TYPES or isinstance(token, Identifier): return cls._strip_quotes(token.value, expect_quoted_value=True) elif isinstance(token, Parenthesis): if key != "run_id": raise MlflowException( "Only the 'run_id' attribute supports comparison with a list of quoted " "string values.", error_code=INVALID_PARAMETER_VALUE, ) return cls._parse_run_ids(token) else: raise MlflowException( "Expected a quoted string value or a list of quoted string values for " f"attributes. Got value {token.value}", error_code=INVALID_PARAMETER_VALUE, ) else: # Expected to be either "param" or "metric". raise MlflowException( "Invalid identifier type. Expected one of " f"{[cls._ATTRIBUTE_IDENTIFIER, cls._TAG_IDENTIFIER]}.", error_code=INVALID_PARAMETER_VALUE, ) @classmethod def _invalid_statement_token_search_model_registry(cls, token): if ( isinstance(token, Comparison) or token.is_whitespace or token.match(ttype=TokenType.Keyword, values=["AND"]) ): return False return True
SearchModelUtils
python
getsentry__sentry
src/sentry/preprod/analytics.py
{ "start": 1527, "end": 1751 }
class ____(analytics.Event): organization_id: int project_id: int user_id: int | None = None artifact_id: str @analytics.eventclass("preprod_artifact.api.admin_batch_delete")
PreprodArtifactApiAdminGetInfoEvent
python
pydantic__pydantic
tests/test_create_model.py
{ "start": 12200, "end": 12241 }
class ____(BaseModel): pass @dataclass
X
python
getsentry__sentry
src/sentry/backup/sanitize.py
{ "start": 1686, "end": 4219 }
class ____: """ A pairing a of a `NormalizedModelName` with a field in that model, specifying the target for a sanitization operation. """ from sentry.backup.dependencies import NormalizedModelName model: NormalizedModelName field: str def validate_json_model(self, json: Any) -> None: """ Validates the JSON model is shaped the way we expect a serialized Django model to be, and that we have the right kind of model for this `SanitizableField`. Raises errors if there is a validation failure. """ model_name = json.get("model", None) if model_name is None: raise InvalidJSONError( "JSON is not properly formatted, must be a serialized Django model" ) if model_name != str(self.model): raise UnexpectedModelError(f"Expected model `{model_name}`, got `{str(self.model)}`") return None def _get_field_value(json: Any, field: SanitizableField) -> Any | None: return json.get("fields", {}).get(field.field, None) def _set_field_value(json: Any, field: SanitizableField, value: Any) -> Any: json.get("fields", {})[field.field] = value return value def default_string_sanitizer(old: str) -> str: """ Default string randomizer. Looks at the characters present in the source string to create a new, random string from a roughly similar set of characters. """ has_upper_case_hex = False has_upper_case_non_hex = False has_lower_case_hex = False has_lower_case_non_hex = False has_digit = False other_ascii = set() for char in old: if char in UPPER_CASE_HEX: has_upper_case_hex = True elif char in UPPER_CASE_NON_HEX: has_upper_case_non_hex = True elif char in LOWER_CASE_HEX: has_lower_case_hex = True elif char in LOWER_CASE_NON_HEX: has_lower_case_non_hex = True elif char.isdigit(): has_digit = True elif char.isascii(): other_ascii.add(char) chars = "".join(other_ascii) if has_upper_case_hex: chars += "".join(UPPER_CASE_HEX) if has_upper_case_non_hex: chars += "".join(UPPER_CASE_NON_HEX) if has_lower_case_hex: chars += "".join(LOWER_CASE_HEX) if has_lower_case_non_hex: chars += "".join(LOWER_CASE_NON_HEX) if has_digit: chars += "0123456789" return "".join([choice(list(chars)) for _ in range(len(old))])
SanitizableField
python
walkccc__LeetCode
solutions/3128. Right Triangles/3128.py
{ "start": 0, "end": 441 }
class ____: def numberOfRightTriangles(self, grid: list[list[int]]) -> int: rows = [0] * len(grid) cols = [0] * len(grid[0]) for i, row in enumerate(grid): for j, num in enumerate(row): if num == 1: rows[i] += 1 cols[j] += 1 return sum((rows[i] - 1) * (cols[j] - 1) for i, row in enumerate(grid) for j, num in enumerate(row) if num == 1)
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B027.py
{ "start": 1703, "end": 2129 }
class ____(ABC): @overload def empty_1(self, foo: str): ... @typing.overload def empty_1(self, foo: int): ... @t.overload def empty_1(self, foo: list): ... @anything.overload def empty_1(self, foo: float): ... @abstractmethod def empty_1(self, foo: Union[str, int, list, float]): ... from dataclasses import dataclass @dataclass
AbstractClass
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 29120, "end": 29517 }
class ____(sgqlc.types.Enum): """The possible values for the IP allow list configuration for installed GitHub Apps setting. Enumeration Choices: * `DISABLED`: The setting is disabled for the owner. * `ENABLED`: The setting is enabled for the owner. """ __schema__ = github_schema __choices__ = ("DISABLED", "ENABLED")
IpAllowListForInstalledAppsEnabledSettingValue
python
wandb__wandb
tests/system_tests/test_functional/keras/keras_eval_tables_builder.py
{ "start": 711, "end": 2045 }
class ____(WandbEvalCallback): def __init__( self, validation_data, data_table_columns, pred_table_columns, num_samples=100 ): super().__init__(data_table_columns, pred_table_columns) self.x = validation_data[0] self.y = validation_data[1] def add_ground_truth(self, logs=None): for idx, (image, label) in enumerate(zip(self.x, self.y)): self.data_table.add_data(idx, wandb.Image(image), label) def add_model_predictions(self, epoch, logs=None): preds = self.model.predict(self.x, verbose=0) preds = tf.argmax(preds, axis=-1) data_table_ref = self.data_table_ref table_idxs = data_table_ref.get_index() for idx in table_idxs: pred = preds[idx] self.pred_table.add_data( epoch, data_table_ref.data[idx][0], data_table_ref.data[idx][1], data_table_ref.data[idx][2], pred, ) model.fit( x, y, epochs=2, validation_data=(x, y), callbacks=[ WandbClfEvalCallback( validation_data=(x, y), data_table_columns=["idx", "image", "label"], pred_table_columns=["epoch", "idx", "image", "label", "pred"], ) ], ) run.finish()
WandbClfEvalCallback
python
wandb__wandb
wandb/sdk/launch/errors.py
{ "start": 33, "end": 121 }
class ____(Error): """Raised when a known error occurs in wandb launch."""
LaunchError
python
rapidsai__cudf
python/cudf/cudf/core/character_normalizer.py
{ "start": 204, "end": 1320 }
class ____: """ A normalizer object used to normalize input text. Parameters ---------- do_lower : bool If True, the normalizer should also lower-case while normalizing. special_tokens : cudf.Series Series of special tokens. These are expected to be all upper case and include the bracket ``[]`` characters. """ def __init__( self, do_lower: bool, special_tokens: Series | None = None, ) -> None: if special_tokens is None: special_tokens = Series([], dtype="object") self.normalizer = plc.nvtext.normalize.CharacterNormalizer( do_lower, special_tokens._column.plc_column ) def normalize(self, text: Series) -> Series: """ Parameters ---------- text : cudf.Series The strings to be normalized. Returns ------- cudf.Series Normalized strings """ result = text._column.normalize_characters(self.normalizer) return Series._from_column(result)
CharacterNormalizer
python
pytest-dev__pytest
src/_pytest/legacypath.py
{ "start": 10366, "end": 16588 }
class ____: @staticmethod @fixture(scope="session") def tmpdir_factory(request: FixtureRequest) -> TempdirFactory: """Return a :class:`pytest.TempdirFactory` instance for the test session.""" # Set dynamically by pytest_configure(). return request.config._tmpdirhandler # type: ignore @staticmethod @fixture def tmpdir(tmp_path: Path) -> LEGACY_PATH: """Return a temporary directory (as `legacy_path`_ object) which is unique to each test function invocation. The temporary directory is created as a subdirectory of the base temporary directory, with configurable retention, as discussed in :ref:`temporary directory location and retention`. .. note:: These days, it is preferred to use ``tmp_path``. :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`. .. _legacy_path: https://py.readthedocs.io/en/latest/path.html """ return legacy_path(tmp_path) def Cache_makedir(self: Cache, name: str) -> LEGACY_PATH: """Return a directory path object with the given name. Same as :func:`mkdir`, but returns a legacy py path instance. """ return legacy_path(self.mkdir(name)) def FixtureRequest_fspath(self: FixtureRequest) -> LEGACY_PATH: """(deprecated) The file system path of the test module which collected this test.""" return legacy_path(self.path) def TerminalReporter_startdir(self: TerminalReporter) -> LEGACY_PATH: """The directory from which pytest was invoked. Prefer to use ``startpath`` which is a :class:`pathlib.Path`. :type: LEGACY_PATH """ return legacy_path(self.startpath) def Config_invocation_dir(self: Config) -> LEGACY_PATH: """The directory from which pytest was invoked. Prefer to use :attr:`invocation_params.dir <InvocationParams.dir>`, which is a :class:`pathlib.Path`. :type: LEGACY_PATH """ return legacy_path(str(self.invocation_params.dir)) def Config_rootdir(self: Config) -> LEGACY_PATH: """The path to the :ref:`rootdir <rootdir>`. Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`. :type: LEGACY_PATH """ return legacy_path(str(self.rootpath)) def Config_inifile(self: Config) -> LEGACY_PATH | None: """The path to the :ref:`configfile <configfiles>`. Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`. :type: Optional[LEGACY_PATH] """ return legacy_path(str(self.inipath)) if self.inipath else None def Session_startdir(self: Session) -> LEGACY_PATH: """The path from which pytest was invoked. Prefer to use ``startpath`` which is a :class:`pathlib.Path`. :type: LEGACY_PATH """ return legacy_path(self.startpath) def Config__getini_unknown_type(self, name: str, type: str, value: str | list[str]): if type == "pathlist": # TODO: This assert is probably not valid in all cases. assert self.inipath is not None dp = self.inipath.parent input_values = shlex.split(value) if isinstance(value, str) else value return [legacy_path(str(dp / x)) for x in input_values] else: raise ValueError(f"unknown configuration type: {type}", value) def Node_fspath(self: Node) -> LEGACY_PATH: """(deprecated) returns a legacy_path copy of self.path""" return legacy_path(self.path) def Node_fspath_set(self: Node, value: LEGACY_PATH) -> None: self.path = Path(value) @hookimpl(tryfirst=True) def pytest_load_initial_conftests(early_config: Config) -> None: """Monkeypatch legacy path attributes in several classes, as early as possible.""" mp = MonkeyPatch() early_config.add_cleanup(mp.undo) # Add Cache.makedir(). mp.setattr(Cache, "makedir", Cache_makedir, raising=False) # Add FixtureRequest.fspath property. mp.setattr(FixtureRequest, "fspath", property(FixtureRequest_fspath), raising=False) # Add TerminalReporter.startdir property. mp.setattr( TerminalReporter, "startdir", property(TerminalReporter_startdir), raising=False ) # Add Config.{invocation_dir,rootdir,inifile} properties. mp.setattr(Config, "invocation_dir", property(Config_invocation_dir), raising=False) mp.setattr(Config, "rootdir", property(Config_rootdir), raising=False) mp.setattr(Config, "inifile", property(Config_inifile), raising=False) # Add Session.startdir property. mp.setattr(Session, "startdir", property(Session_startdir), raising=False) # Add pathlist configuration type. mp.setattr(Config, "_getini_unknown_type", Config__getini_unknown_type) # Add Node.fspath property. mp.setattr(Node, "fspath", property(Node_fspath, Node_fspath_set), raising=False) @hookimpl def pytest_configure(config: Config) -> None: """Installs the LegacyTmpdirPlugin if the ``tmpdir`` plugin is also installed.""" if config.pluginmanager.has_plugin("tmpdir"): mp = MonkeyPatch() config.add_cleanup(mp.undo) # Create TmpdirFactory and attach it to the config object. # # This is to comply with existing plugins which expect the handler to be # available at pytest_configure time, but ideally should be moved entirely # to the tmpdir_factory session fixture. try: tmp_path_factory = config._tmp_path_factory # type: ignore[attr-defined] except AttributeError: # tmpdir plugin is blocked. pass else: _tmpdirhandler = TempdirFactory(tmp_path_factory, _ispytest=True) mp.setattr(config, "_tmpdirhandler", _tmpdirhandler, raising=False) config.pluginmanager.register(LegacyTmpdirPlugin, "legacypath-tmpdir") @hookimpl def pytest_plugin_registered(plugin: object, manager: PytestPluginManager) -> None: # pytester is not loaded by default and is commonly loaded from a conftest, # so checking for it in `pytest_configure` is not enough. is_pytester = plugin is manager.get_plugin("pytester") if is_pytester and not manager.is_registered(LegacyTestdirPlugin): manager.register(LegacyTestdirPlugin, "legacypath-pytester")
LegacyTmpdirPlugin
python
kubernetes-client__python
kubernetes/client/models/v1beta1_capacity_request_policy.py
{ "start": 383, "end": 6796 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'default': 'str', 'valid_range': 'V1beta1CapacityRequestPolicyRange', 'valid_values': 'list[str]' } attribute_map = { 'default': 'default', 'valid_range': 'validRange', 'valid_values': 'validValues' } def __init__(self, default=None, valid_range=None, valid_values=None, local_vars_configuration=None): # noqa: E501 """V1beta1CapacityRequestPolicy - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._default = None self._valid_range = None self._valid_values = None self.discriminator = None if default is not None: self.default = default if valid_range is not None: self.valid_range = valid_range if valid_values is not None: self.valid_values = valid_values @property def default(self): """Gets the default of this V1beta1CapacityRequestPolicy. # noqa: E501 Default specifies how much of this capacity is consumed by a request that does not contain an entry for it in DeviceRequest's Capacity. # noqa: E501 :return: The default of this V1beta1CapacityRequestPolicy. # noqa: E501 :rtype: str """ return self._default @default.setter def default(self, default): """Sets the default of this V1beta1CapacityRequestPolicy. Default specifies how much of this capacity is consumed by a request that does not contain an entry for it in DeviceRequest's Capacity. # noqa: E501 :param default: The default of this V1beta1CapacityRequestPolicy. # noqa: E501 :type: str """ self._default = default @property def valid_range(self): """Gets the valid_range of this V1beta1CapacityRequestPolicy. # noqa: E501 :return: The valid_range of this V1beta1CapacityRequestPolicy. # noqa: E501 :rtype: V1beta1CapacityRequestPolicyRange """ return self._valid_range @valid_range.setter def valid_range(self, valid_range): """Sets the valid_range of this V1beta1CapacityRequestPolicy. :param valid_range: The valid_range of this V1beta1CapacityRequestPolicy. # noqa: E501 :type: V1beta1CapacityRequestPolicyRange """ self._valid_range = valid_range @property def valid_values(self): """Gets the valid_values of this V1beta1CapacityRequestPolicy. # noqa: E501 ValidValues defines a set of acceptable quantity values in consuming requests. Must not contain more than 10 entries. Must be sorted in ascending order. If this field is set, Default must be defined and it must be included in ValidValues list. If the requested amount does not match any valid value but smaller than some valid values, the scheduler calculates the smallest valid value that is greater than or equal to the request. That is: min(ceil(requestedValue) ∈ validValues), where requestedValue ≤ max(validValues). If the requested amount exceeds all valid values, the request violates the policy, and this device cannot be allocated. # noqa: E501 :return: The valid_values of this V1beta1CapacityRequestPolicy. # noqa: E501 :rtype: list[str] """ return self._valid_values @valid_values.setter def valid_values(self, valid_values): """Sets the valid_values of this V1beta1CapacityRequestPolicy. ValidValues defines a set of acceptable quantity values in consuming requests. Must not contain more than 10 entries. Must be sorted in ascending order. If this field is set, Default must be defined and it must be included in ValidValues list. If the requested amount does not match any valid value but smaller than some valid values, the scheduler calculates the smallest valid value that is greater than or equal to the request. That is: min(ceil(requestedValue) ∈ validValues), where requestedValue ≤ max(validValues). If the requested amount exceeds all valid values, the request violates the policy, and this device cannot be allocated. # noqa: E501 :param valid_values: The valid_values of this V1beta1CapacityRequestPolicy. # noqa: E501 :type: list[str] """ self._valid_values = valid_values def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta1CapacityRequestPolicy): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta1CapacityRequestPolicy): return True return self.to_dict() != other.to_dict()
V1beta1CapacityRequestPolicy
python
PyCQA__pylint
tests/functional/p/postponed/postponed_evaluation_pep585.py
{ "start": 1450, "end": 1510 }
class ____: my_var: list[int] @dataclass()
CustomDataClass2
python
cython__cython
tests/run/ext_auto_richcmp.py
{ "start": 4925, "end": 5943 }
class ____(X): """ >>> a = ClassLe(1) >>> b = ClassLe(2) >>> c = ClassLe(1) >>> a <= b True >>> b >= a True >>> b <= a False >>> a >= b False >>> a <= c True >>> c >= a True >>> c <= a True >>> a >= c True >>> b <= c False >>> c >= b False >>> c <= b True >>> b >= c True >>> 2 >= a True >>> a <= 2 True >>> 1 >= a True >>> a <= 1 True >>> a <= 0 False >>> 'x' >= a # doctest: +ELLIPSIS Traceback (most recent call last): TypeError... >>> a <= 'x' # doctest: +ELLIPSIS Traceback (most recent call last): TypeError... """ def __le__(self, other): assert 1 <= self.x <= 2 assert isinstance(self, ClassLe), type(self) if isinstance(other, X): return self.x <= x_of(other) elif isinstance(other, int): return self.x <= other return NotImplemented @cython.cclass
ClassLe
python
milvus-io__pymilvus
tests/test_orm_iterator.py
{ "start": 9129, "end": 10528 }
class ____: """Test flag setting functionality for iterators""" def test_check_set_flag_various_types(self): """Test setting flags with various value types""" obj = Mock() # Boolean values kwargs = {"bool_flag": True} check_set_flag(obj, "test_bool", kwargs, "bool_flag") assert obj.test_bool is True # String values (should be truthy/falsy) kwargs = {"string_flag": "enabled"} check_set_flag(obj, "test_string", kwargs, "string_flag") assert obj.test_string == "enabled" # None values kwargs = {"none_flag": None} check_set_flag(obj, "test_none", kwargs, "none_flag") assert obj.test_none is None # Numeric values kwargs = {"num_flag": 42} check_set_flag(obj, "test_num", kwargs, "num_flag") assert obj.test_num == 42 # Missing key (should default to False) kwargs = {} check_set_flag(obj, "test_missing", kwargs, "missing_key") assert obj.test_missing is False def test_check_set_flag_overwrites(self): """Test that check_set_flag overwrites existing attributes""" obj = Mock() obj.existing_flag = "old_value" kwargs = {"new_value": "updated"} check_set_flag(obj, "existing_flag", kwargs, "new_value") assert obj.existing_flag == "updated"
TestIteratorFlags
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/glacier.py
{ "start": 1249, "end": 1370 }
class ____(Enum): """Glacier jobs description.""" IN_PROGRESS = "InProgress" SUCCEEDED = "Succeeded"
JobStatus
python
gevent__gevent
src/gevent/libuv/watcher.py
{ "start": 21975, "end": 23847 }
class ____(_base.AsyncMixin, watcher): _watcher_callback_name = '_gevent_async_callback0' # libuv async watchers are different than all other watchers: # They don't have a separate start/stop method (presumably # because of race conditions). Simply initing them places them # into the active queue. # # In the past, we sent a NULL C callback to the watcher, trusting # that no one would call send() without actually starting us (or after # closing us); doing so would crash. But we don't want to delay # initing the struct because it will crash in uv_close() when we get GC'd, # and send() will also crash. Plus that complicates our lifecycle (managing # the memory). # # Now, we always init the correct C callback, and use a dummy # Python callback that gets replaced when we are started and # stopped. This prevents mistakes from being crashes. _callback = lambda: None def _watcher_ffi_init(self, args): # NOTE: uv_async_init is NOT idempotent. Calling it more than # once adds the uv_async_t to the internal queue multiple times, # and uv_close only cleans up one of them, meaning that we tend to # crash. Thus we have to be very careful not to allow that. return self._watcher_init(self.loop.ptr, self._watcher, self._watcher_callback) def _watcher_ffi_start(self): pass def _watcher_ffi_stop(self): pass def send(self): assert self._callback is not async_._callback, "Sending to a closed watcher" if libuv.uv_is_closing(self._watcher): # pylint:disable-next=broad-exception-raised raise Exception("Closing handle") libuv.uv_async_send(self._watcher) @property def pending(self): return None locals()['async'] = async_
async_
python
viewflow__viewflow
tests/workflow/test_nodes__splitfirst.py
{ "start": 774, "end": 1289 }
class ____(flow.Flow): # noqa: D101 start = flow.StartHandle().Next(this.split) split = flow.SplitFirst().Next(this.case_1).Next(this.case_2) case_1 = flow.Handle(this.handle).Next(this.end) case_2 = flow.Handle(this.handle).Next(this.end) # continue_1 = flow.Handle(this.handle).Next(this.end) # continue_2 = flow.Handle(this.handle).Next(this.end) end = flow.End() def handle(self, activation): pass urlpatterns = [path("", FlowViewset(TestWorkflow).urls)]
TestWorkflow
python
huggingface__transformers
src/transformers/models/conditional_detr/modeling_conditional_detr.py
{ "start": 35878, "end": 43745 }
class ____(GradientCheckpointingLayer): def __init__(self, config: ConditionalDetrConfig): super().__init__() self.embed_dim = config.d_model d_model = config.d_model # Decoder Self-Attention projections self.sa_qcontent_proj = nn.Linear(d_model, d_model) self.sa_qpos_proj = nn.Linear(d_model, d_model) self.sa_kcontent_proj = nn.Linear(d_model, d_model) self.sa_kpos_proj = nn.Linear(d_model, d_model) self.sa_v_proj = nn.Linear(d_model, d_model) self.self_attn = ConditionalDetrAttention( embed_dim=self.embed_dim, out_dim=self.embed_dim, num_heads=config.decoder_attention_heads, dropout=config.attention_dropout, ) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) # Decoder Cross-Attention projections self.ca_qcontent_proj = nn.Linear(d_model, d_model) self.ca_qpos_proj = nn.Linear(d_model, d_model) self.ca_kcontent_proj = nn.Linear(d_model, d_model) self.ca_kpos_proj = nn.Linear(d_model, d_model) self.ca_v_proj = nn.Linear(d_model, d_model) self.ca_qpos_sine_proj = nn.Linear(d_model, d_model) self.encoder_attn = ConditionalDetrAttention( self.embed_dim * 2, self.embed_dim, config.decoder_attention_heads, dropout=config.attention_dropout ) self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim) self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim) self.nhead = config.decoder_attention_heads def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, object_queries: Optional[torch.Tensor] = None, query_position_embeddings: Optional[torch.Tensor] = None, query_sine_embed: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, is_first: Optional[bool] = False, ): """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative values. object_queries (`torch.FloatTensor`, *optional*): object_queries that are added to the queries and keys in the cross-attention layer. query_position_embeddings (`torch.FloatTensor`, *optional*): object_queries that are added to the queries and keys in the self-attention layer. encoder_hidden_states (`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative values. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states # ========== Begin of Self-Attention ============= # Apply projections here # shape: num_queries x batch_size x 256 q_content = self.sa_qcontent_proj( hidden_states ) # target is the input of the first decoder layer. zero by default. q_pos = self.sa_qpos_proj(query_position_embeddings) k_content = self.sa_kcontent_proj(hidden_states) k_pos = self.sa_kpos_proj(query_position_embeddings) v = self.sa_v_proj(hidden_states) _, num_queries, n_model = q_content.shape q = q_content + q_pos k = k_content + k_pos hidden_states, self_attn_weights = self.self_attn( hidden_states=q, attention_mask=attention_mask, key_states=k, value_states=v, output_attentions=output_attentions, ) # ============ End of Self-Attention ============= hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) # ========== Begin of Cross-Attention ============= # Apply projections here # shape: num_queries x batch_size x 256 q_content = self.ca_qcontent_proj(hidden_states) k_content = self.ca_kcontent_proj(encoder_hidden_states) v = self.ca_v_proj(encoder_hidden_states) batch_size, num_queries, n_model = q_content.shape _, source_len, _ = k_content.shape k_pos = self.ca_kpos_proj(object_queries) # For the first decoder layer, we concatenate the positional embedding predicted from # the object query (the positional embedding) into the original query (key) in DETR. if is_first: q_pos = self.ca_qpos_proj(query_position_embeddings) q = q_content + q_pos k = k_content + k_pos else: q = q_content k = k_content q = q.view(batch_size, num_queries, self.nhead, n_model // self.nhead) query_sine_embed = self.ca_qpos_sine_proj(query_sine_embed) query_sine_embed = query_sine_embed.view(batch_size, num_queries, self.nhead, n_model // self.nhead) q = torch.cat([q, query_sine_embed], dim=3).view(batch_size, num_queries, n_model * 2) k = k.view(batch_size, source_len, self.nhead, n_model // self.nhead) k_pos = k_pos.view(batch_size, source_len, self.nhead, n_model // self.nhead) k = torch.cat([k, k_pos], dim=3).view(batch_size, source_len, n_model * 2) # Cross-Attention Block cross_attn_weights = None if encoder_hidden_states is not None: residual = hidden_states hidden_states, cross_attn_weights = self.encoder_attn( hidden_states=q, attention_mask=encoder_attention_mask, key_states=k, value_states=v, output_attentions=output_attentions, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.encoder_attn_layer_norm(hidden_states) # ============ End of Cross-Attention ============= # Fully Connected residual = hidden_states hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.final_layer_norm(hidden_states) outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights, cross_attn_weights) return outputs # Copied from transformers.models.detr.modeling_detr.DetrMLPPredictionHead with DetrMLPPredictionHead->MLP
ConditionalDetrDecoderLayer
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_histogram.py
{ "start": 43920, "end": 44198 }
class ____( OrganizationEventsMetricsEnhancedPerformanceHistogramEndpointTest ): def setUp(self) -> None: super().setUp() self.features["organizations:use-metrics-layer"] = True
OrganizationEventsMetricsEnhancedPerformanceHistogramEndpointTestWithMetricLayer
python
scipy__scipy
scipy/special/tests/test_spfun_stats.py
{ "start": 236, "end": 2029 }
class ____: def test1(self): # A test of the identity # Gamma_1(a) = Gamma(a) np.random.seed(1234) a = np.abs(np.random.randn()) assert_array_equal(multigammaln(a, 1), gammaln(a)) def test2(self): # A test of the identity # Gamma_2(a) = sqrt(pi) * Gamma(a) * Gamma(a - 0.5) a = np.array([2.5, 10.0]) result = multigammaln(a, 2) expected = np.log(np.sqrt(np.pi)) + gammaln(a) + gammaln(a - 0.5) assert_allclose(result, expected, atol=1.5e-7, rtol=0) def test_bararg(self): assert_raises(ValueError, multigammaln, 0.5, 1.2) def _check_multigammaln_array_result(a, d): # Test that the shape of the array returned by multigammaln # matches the input shape, and that all the values match # the value computed when multigammaln is called with a scalar. result = multigammaln(a, d) assert_array_equal(a.shape, result.shape) a1 = a.ravel() result1 = result.ravel() for i in range(a.size): assert_array_almost_equal_nulp(result1[i], multigammaln(a1[i], d)) def test_multigammaln_array_arg(): # Check that the array returned by multigammaln has the correct # shape and contains the correct values. The cases have arrays # with several different shapes. # The cases include a regression test for ticket #1849 # (a = np.array([2.0]), an array with a single element). np.random.seed(1234) cases = [ # a, d (np.abs(np.random.randn(3, 2)) + 5, 5), (np.abs(np.random.randn(1, 2)) + 5, 5), (np.arange(10.0, 18.0).reshape(2, 2, 2), 3), (np.array([2.0]), 3), (np.float64(2.0), 3), ] for a, d in cases: _check_multigammaln_array_result(a, d)
TestMultiGammaLn
python
kamyu104__LeetCode-Solutions
Python/smallest-rotation-with-highest-score.py
{ "start": 29, "end": 376 }
class ____(object): def bestRotation(self, A): """ :type A: List[int] :rtype: int """ N = len(A) change = [1] * N for i in xrange(N): change[(i-A[i]+1)%N] -= 1 for i in xrange(1, N): change[i] += change[i-1] return change.index(max(change))
Solution
python
walkccc__LeetCode
solutions/2614. Prime In Diagonal/2614.py
{ "start": 0, "end": 529 }
class ____: def diagonalPrime(self, nums: list[list[int]]) -> int: def isPrime(n: int) -> bool: if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True primes1 = [row[i] for i, row in enumerate(nums) if isPrime(row[i])] primes2 = [row[-1 - i] for i, row in enumerate(nums) if isPrime(row[-1 - i])] return max(max(primes1) if primes1 else 0, max(primes2) if primes2 else 0)
Solution
python
streamlit__streamlit
lib/tests/exception_capturing_thread.py
{ "start": 3196, "end": 4371 }
class ____(threading.Thread): """Thread subclass that captures unhandled exceptions.""" def __init__( self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None ): super().__init__( group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon, ) self._unhandled_exception: BaseException | None = None @property def unhandled_exception(self) -> BaseException | None: """The unhandled exception raised by the thread's target, if it raised one.""" return self._unhandled_exception def assert_no_unhandled_exception(self) -> None: """If the thread target raised an unhandled exception, re-raise it. Otherwise no-op. """ if self._unhandled_exception is not None: raise RuntimeError( f"Unhandled exception in thread '{self.name}'" ) from self._unhandled_exception def run(self) -> None: try: super().run() except Exception as e: self._unhandled_exception = e
ExceptionCapturingThread
python
kamyu104__LeetCode-Solutions
Python/minimum-obstacle-removal-to-reach-corner.py
{ "start": 1187, "end": 2074 }
class ____(object): def minimumObstacles(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] b, t = (0, 0), (len(grid)-1, len(grid[0])-1) dq = collections.deque([(b, 0)]) lookup = set() while dq: b, d = dq.popleft() if b in lookup: continue lookup.add(b) if b == t: return d for dr, dc in directions: nb = (b[0]+dr, b[1]+dc) if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and nb not in lookup): continue if not grid[nb[0]][nb[1]]: dq.appendleft((nb, d)) else: dq.append((nb, d+1)) return -1 # never reach here
Solution2
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/dep_with_variants/package.py
{ "start": 216, "end": 570 }
class ____(Package): """Package that has a variant which adds a dependency forced to use non default values. """ homepage = "https://dev.null" version("1.0") variant("foo", default=False, description="nope") variant("bar", default=False, description="nope") variant("baz", default=False, description="nope")
DepWithVariants
python
doocs__leetcode
solution/1500-1599/1518.Water Bottles/Solution.py
{ "start": 0, "end": 237 }
class ____: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: ans = numBottles while numBottles >= numExchange: numBottles -= numExchange - 1 ans += 1 return ans
Solution
python
cherrypy__cherrypy
cherrypy/_cprequest.py
{ "start": 29878, "end": 30873 }
class ____(object): """The body of the HTTP response (the response entity).""" unicode_err = ( 'Page handlers MUST return bytes. Use tools.encode ' 'if you wish to return unicode.' ) def __get__(self, obj, objclass=None): """Return a response body through the descriptor protocol.""" if obj is None: # When calling on the class instead of an instance... return self else: return obj._body def __set__(self, obj, value): """Set a response body through the descriptor protocol. Convert the given value to an iterable object. """ if isinstance(value, str): raise ValueError(self.unicode_err) elif isinstance(value, list): # every item in a list must be bytes... if any(isinstance(item, str) for item in value): raise ValueError(self.unicode_err) obj._body = encoding.prepare_iter(value)
ResponseBody
python
lazyprogrammer__machine_learning_examples
nlp_class2/glove.py
{ "start": 966, "end": 12018 }
class ____: def __init__(self, D, V, context_sz): self.D = D self.V = V self.context_sz = context_sz def fit(self, sentences, cc_matrix=None, learning_rate=1e-4, reg=0.1, xmax=100, alpha=0.75, epochs=10, gd=False): # build co-occurrence matrix # paper calls it X, so we will call it X, instead of calling # the training data X # TODO: would it be better to use a sparse matrix? t0 = datetime.now() V = self.V D = self.D if not os.path.exists(cc_matrix): X = np.zeros((V, V)) N = len(sentences) print("number of sentences to process:", N) it = 0 for sentence in sentences: it += 1 if it % 10000 == 0: print("processed", it, "/", N) n = len(sentence) for i in range(n): # i is not the word index!!! # j is not the word index!!! # i just points to which element of the sequence (sentence) we're looking at wi = sentence[i] start = max(0, i - self.context_sz) end = min(n, i + self.context_sz) # we can either choose only one side as context, or both # here we are doing both # make sure "start" and "end" tokens are part of some context # otherwise their f(X) will be 0 (denominator in bias update) if i - self.context_sz < 0: points = 1.0 / (i + 1) X[wi,0] += points X[0,wi] += points if i + self.context_sz > n: points = 1.0 / (n - i) X[wi,1] += points X[1,wi] += points # left side for j in range(start, i): wj = sentence[j] points = 1.0 / (i - j) # this is +ve X[wi,wj] += points X[wj,wi] += points # right side for j in range(i + 1, end): wj = sentence[j] points = 1.0 / (j - i) # this is +ve X[wi,wj] += points X[wj,wi] += points # save the cc matrix because it takes forever to create np.save(cc_matrix, X) else: X = np.load(cc_matrix) print("max in X:", X.max()) # weighting fX = np.zeros((V, V)) fX[X < xmax] = (X[X < xmax] / float(xmax)) ** alpha fX[X >= xmax] = 1 print("max in f(X):", fX.max()) # target logX = np.log(X + 1) print("max in log(X):", logX.max()) print("time to build co-occurrence matrix:", (datetime.now() - t0)) # initialize weights W = np.random.randn(V, D) / np.sqrt(V + D) b = np.zeros(V) U = np.random.randn(V, D) / np.sqrt(V + D) c = np.zeros(V) mu = logX.mean() costs = [] sentence_indexes = range(len(sentences)) for epoch in range(epochs): delta = W.dot(U.T) + b.reshape(V, 1) + c.reshape(1, V) + mu - logX cost = ( fX * delta * delta ).sum() costs.append(cost) print("epoch:", epoch, "cost:", cost) if gd: # gradient descent method # update W # oldW = W.copy() for i in range(V): # for j in range(V): # W[i] -= learning_rate*fX[i,j]*(W[i].dot(U[j]) + b[i] + c[j] + mu - logX[i,j])*U[j] W[i] -= learning_rate*(fX[i,:]*delta[i,:]).dot(U) W -= learning_rate*reg*W # print "updated W" # update b for i in range(V): # for j in range(V): # b[i] -= learning_rate*fX[i,j]*(W[i].dot(U[j]) + b[i] + c[j] + mu - logX[i,j]) b[i] -= learning_rate*fX[i,:].dot(delta[i,:]) # b -= learning_rate*reg*b # print "updated b" # update U for j in range(V): # for i in range(V): # U[j] -= learning_rate*fX[i,j]*(W[i].dot(U[j]) + b[i] + c[j] + mu - logX[i,j])*W[i] U[j] -= learning_rate*(fX[:,j]*delta[:,j]).dot(W) U -= learning_rate*reg*U # print "updated U" # update c for j in range(V): # for i in range(V): # c[j] -= learning_rate*fX[i,j]*(W[i].dot(U[j]) + b[i] + c[j] + mu - logX[i,j]) c[j] -= learning_rate*fX[:,j].dot(delta[:,j]) # c -= learning_rate*reg*c # print "updated c" else: # ALS method # update W # fast way # t0 = datetime.now() for i in range(V): # matrix = reg*np.eye(D) + np.sum((fX[i,j]*np.outer(U[j], U[j]) for j in range(V)), axis=0) matrix = reg*np.eye(D) + (fX[i,:]*U.T).dot(U) # assert(np.abs(matrix - matrix2).sum() < 1e-5) vector = (fX[i,:]*(logX[i,:] - b[i] - c - mu)).dot(U) W[i] = np.linalg.solve(matrix, vector) # print "fast way took:", (datetime.now() - t0) # slow way # t0 = datetime.now() # for i in range(V): # matrix2 = reg*np.eye(D) # vector2 = 0 # for j in range(V): # matrix2 += fX[i,j]*np.outer(U[j], U[j]) # vector2 += fX[i,j]*(logX[i,j] - b[i] - c[j])*U[j] # print "slow way took:", (datetime.now() - t0) # assert(np.abs(matrix - matrix2).sum() < 1e-5) # assert(np.abs(vector - vector2).sum() < 1e-5) # W[i] = np.linalg.solve(matrix, vector) # print "updated W" # update b for i in range(V): denominator = fX[i,:].sum() + reg # assert(denominator > 0) numerator = fX[i,:].dot(logX[i,:] - W[i].dot(U.T) - c - mu) # for j in range(V): # numerator += fX[i,j]*(logX[i,j] - W[i].dot(U[j]) - c[j]) b[i] = numerator / denominator # print "updated b" # update U for j in range(V): # matrix = reg*np.eye(D) + np.sum((fX[i,j]*np.outer(W[i], W[i]) for i in range(V)), axis=0) matrix = reg*np.eye(D) + (fX[:,j]*W.T).dot(W) # assert(np.abs(matrix - matrix2).sum() < 1e-8) vector = (fX[:,j]*(logX[:,j] - b - c[j] - mu)).dot(W) # matrix = reg*np.eye(D) # vector = 0 # for i in range(V): # matrix += fX[i,j]*np.outer(W[i], W[i]) # vector += fX[i,j]*(logX[i,j] - b[i] - c[j])*W[i] U[j] = np.linalg.solve(matrix, vector) # print "updated U" # update c for j in range(V): denominator = fX[:,j].sum() + reg numerator = fX[:,j].dot(logX[:,j] - W.dot(U[j]) - b - mu) # for i in range(V): # numerator += fX[i,j]*(logX[i,j] - W[i].dot(U[j]) - b[i]) c[j] = numerator / denominator # print "updated c" self.W = W self.U = U plt.plot(costs) plt.show() def save(self, fn): # function word_analogies expects a (V,D) matrx and a (D,V) matrix arrays = [self.W, self.U.T] np.savez(fn, *arrays) def main(we_file, w2i_file, use_brown=True, n_files=100): if use_brown: cc_matrix = "cc_matrix_brown.npy" else: cc_matrix = "cc_matrix_%s.npy" % n_files # hacky way of checking if we need to re-load the raw data or not # remember, only the co-occurrence matrix is needed for training if os.path.exists(cc_matrix): with open(w2i_file) as f: word2idx = json.load(f) sentences = [] # dummy - we won't actually use it else: if use_brown: keep_words = set([ 'king', 'man', 'woman', 'france', 'paris', 'london', 'rome', 'italy', 'britain', 'england', 'french', 'english', 'japan', 'japanese', 'chinese', 'italian', 'australia', 'australian', 'december', 'november', 'june', 'january', 'february', 'march', 'april', 'may', 'july', 'august', 'september', 'october', ]) sentences, word2idx = get_sentences_with_word2idx_limit_vocab(n_vocab=5000, keep_words=keep_words) else: sentences, word2idx = get_wikipedia_data(n_files=n_files, n_vocab=2000) with open(w2i_file, 'w') as f: json.dump(word2idx, f) V = len(word2idx) model = Glove(100, V, 10) # alternating least squares method model.fit(sentences, cc_matrix=cc_matrix, epochs=20) # gradient descent method # model.fit( # sentences, # cc_matrix=cc_matrix, # learning_rate=5e-4, # reg=0.1, # epochs=500, # gd=True, # ) model.save(we_file) if __name__ == '__main__': we = 'glove_model_50.npz' w2i = 'glove_word2idx_50.json' # we = 'glove_model_brown.npz' # w2i = 'glove_word2idx_brown.json' main(we, w2i, use_brown=False) # load back embeddings npz = np.load(we) W1 = npz['arr_0'] W2 = npz['arr_1'] with open(w2i) as f: word2idx = json.load(f) idx2word = {i:w for w,i in word2idx.items()} for concat in (True, False): print("** concat:", concat) if concat: We = np.hstack([W1, W2.T]) else: We = (W1 + W2.T) / 2 find_analogies('king', 'man', 'woman', We, word2idx, idx2word) find_analogies('france', 'paris', 'london', We, word2idx, idx2word) find_analogies('france', 'paris', 'rome', We, word2idx, idx2word) find_analogies('paris', 'france', 'italy', We, word2idx, idx2word) find_analogies('france', 'french', 'english', We, word2idx, idx2word) find_analogies('japan', 'japanese', 'chinese', We, word2idx, idx2word) find_analogies('japan', 'japanese', 'italian', We, word2idx, idx2word) find_analogies('japan', 'japanese', 'australian', We, word2idx, idx2word) find_analogies('december', 'november', 'june', We, word2idx, idx2word)
Glove
python
gwtw__py-sorting
test/odd_even_sort_test.py
{ "start": 408, "end": 746 }
class ____(unittest.TestCase, BaseCustomComparisonSortTest, BasePositiveIntegerSortTest, BaseNegativeIntegerSortTest, BaseStringSortTest): def setUp(self): self.sort = odd_even_sort.sort if __name__ == '__main__': unittest.main()
OddEvenSortTest
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1211899, "end": 1212086 }
class ____(VegaLiteSchema): """Sort schema wrapper.""" _schema = {"$ref": "#/definitions/Sort"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
Sort
python
apache__airflow
airflow-core/tests/unit/models/test_deadline.py
{ "start": 4172, "end": 7525 }
class ____: @staticmethod def setup_method(): _clean_db() @staticmethod def teardown_method(): _clean_db() @pytest.mark.parametrize( "conditions", [ pytest.param({}, id="empty_conditions"), pytest.param({Deadline.dagrun_id: -1}, id="no_matches"), pytest.param({Deadline.dagrun_id: "valid_placeholder"}, id="single_condition"), pytest.param( { Deadline.dagrun_id: "valid_placeholder", Deadline.deadline_time: datetime.now() + timedelta(days=365), }, id="multiple_conditions", ), pytest.param( {Deadline.dagrun_id: "valid_placeholder", Deadline.callback: None}, id="mixed_conditions", ), ], ) @mock.patch("sqlalchemy.orm.Session") def test_prune_deadlines(self, mock_session, conditions, dagrun): """Test deadline resolution with various conditions.""" if Deadline.dagrun_id in conditions: if conditions[Deadline.dagrun_id] == "valid_placeholder": conditions[Deadline.dagrun_id] = dagrun.id expected_result = 1 if conditions else 0 # Set up the query chain to return a list of (Deadline, DagRun) pairs mock_dagrun = mock.Mock(spec=DagRun, end_date=datetime.now()) mock_deadline = mock.Mock(spec=Deadline, deadline_time=mock_dagrun.end_date + timedelta(days=365)) mock_query = mock_session.execute.return_value mock_query.all.return_value = [(mock_deadline, mock_dagrun)] if conditions else [] result = Deadline.prune_deadlines(conditions=conditions, session=mock_session) assert result == expected_result if conditions: mock_session.execute.return_value.all.assert_called_once() mock_session.delete.assert_called_once_with(mock_deadline) else: mock_session.query.assert_not_called() def test_repr(self, deadline_orm, dagrun): assert ( repr(deadline_orm) == f"[DagRun Deadline] Dag: {DAG_ID} Run: {dagrun.id} needed by " f"{DEFAULT_DATE} or run: {deadline_orm.callback}" ) @pytest.mark.db_test def test_handle_miss(self, dagrun, session): deadline_orm = Deadline( deadline_time=DEFAULT_DATE, callback=AsyncCallback(TEST_CALLBACK_PATH, TEST_CALLBACK_KWARGS), dagrun_id=dagrun.id, dag_id=dagrun.dag_id, ) session.add(deadline_orm) session.flush() assert not deadline_orm.missed with mock.patch.object(deadline_orm.callback, "queue") as mock_queue: deadline_orm.handle_miss(session) session.flush() mock_queue.assert_called_once() assert deadline_orm.missed callback_kwargs = deadline_orm.callback.data["kwargs"] context = callback_kwargs.pop("context") assert callback_kwargs == TEST_CALLBACK_KWARGS assert context["deadline"]["id"] == deadline_orm.id assert context["deadline"]["deadline_time"].timestamp() == deadline_orm.deadline_time.timestamp() assert context["dag_run"] == DAGRunResponse.model_validate(dagrun).model_dump(mode="json") @pytest.mark.db_test
TestDeadline
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1328686, "end": 1366037 }
class ____(AnyMarkConfig): """ TickConfig schema wrapper. Parameters ---------- align : dict, :class:`Align`, :class:`ExprRef`, Literal['left', 'center', 'right'] The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). One of ``"left"``, ``"right"``, ``"center"``. **Note:** Expression reference is *not* supported for range marks. angle : dict, float, :class:`ExprRef` The rotation angle of the text, in degrees. aria : bool, dict, :class:`ExprRef` A boolean flag indicating if `ARIA attributes <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ should be included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on the output SVG element, removing the mark item from the ARIA accessibility tree. ariaRole : str, dict, :class:`ExprRef` Sets the type of user interface element of the mark item for `ARIA accessibility <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ (SVG output only). If specified, this property determines the "role" attribute. Warning: this property is experimental and may be changed in the future. ariaRoleDescription : str, dict, :class:`ExprRef` A human-readable, author-localized description for the role of the mark item for `ARIA accessibility <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ (SVG output only). If specified, this property determines the "aria-roledescription" attribute. Warning: this property is experimental and may be changed in the future. aspect : bool, dict, :class:`ExprRef` Whether to keep aspect ratio of image marks. bandSize : float The width of the ticks. **Default value:** 3/4 of step (width step for horizontal ticks and height step for vertical ticks). baseline : dict, :class:`ExprRef`, :class:`Baseline`, :class:`TextBaseline`, Literal['alphabetic', 'line-bottom', 'line-top', 'top', 'middle', 'bottom'] For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an expression reference that provides one of the valid values. The ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. For range marks, the vertical alignment of the marks. One of ``"top"``, ``"middle"``, ``"bottom"``. **Note:** Expression reference is *not* supported for range marks. binSpacing : float Offset between bars for binned field. The ideal value for this is either 0 (preferred by statisticians) or 1 (Vega-Lite default, D3 example style). **Default value:** ``1`` blend : dict, :class:`Blend`, :class:`ExprRef`, Literal[None, 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'] The color blend mode for drawing an item on its current background. Any valid `CSS mix-blend-mode <https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode>`__ value can be used. **Default value:** ``"source-over"`` color : str, dict, :class:`Color`, :class:`ExprRef`, :class:`Gradient`, :class:`HexColor`, :class:`ColorName`, :class:`LinearGradient`, :class:`RadialGradient`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple'] Default color. **Default value:** ``"#4682b4"`` **Note:** * This property cannot be used in a `style config <https://vega.github.io/vega-lite/docs/mark.html#style-config>`__. * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and will override ``color``. continuousBandSize : float The default size of the bars on continuous scales. **Default value:** ``5`` cornerRadius : dict, float, :class:`ExprRef` The radius in pixels of rounded rectangles or arcs' corners. **Default value:** ``0`` cornerRadiusBottomLeft : dict, float, :class:`ExprRef` The radius in pixels of rounded rectangles' bottom left corner. **Default value:** ``0`` cornerRadiusBottomRight : dict, float, :class:`ExprRef` The radius in pixels of rounded rectangles' bottom right corner. **Default value:** ``0`` cornerRadiusTopLeft : dict, float, :class:`ExprRef` The radius in pixels of rounded rectangles' top right corner. **Default value:** ``0`` cornerRadiusTopRight : dict, float, :class:`ExprRef` The radius in pixels of rounded rectangles' top left corner. **Default value:** ``0`` cursor : dict, :class:`Cursor`, :class:`ExprRef`, Literal['auto', 'default', 'none', 'context-menu', 'help', 'pointer', 'progress', 'wait', 'cell', 'crosshair', 'text', 'vertical-text', 'alias', 'copy', 'move', 'no-drop', 'not-allowed', 'e-resize', 'n-resize', 'ne-resize', 'nw-resize', 's-resize', 'se-resize', 'sw-resize', 'w-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'col-resize', 'row-resize', 'all-scroll', 'zoom-in', 'zoom-out', 'grab', 'grabbing'] The mouse cursor used over the mark. Any valid `CSS cursor type <https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values>`__ can be used. description : str, dict, :class:`ExprRef` A text description of the mark item for `ARIA accessibility <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ (SVG output only). If specified, this property determines the `"aria-label" attribute <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute>`__. dir : dict, :class:`ExprRef`, :class:`TextDirection`, Literal['ltr', 'rtl'] The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` (right-to-left). This property determines on which side is truncated in response to the limit parameter. **Default value:** ``"ltr"`` discreteBandSize : dict, float, :class:`RelativeBandSize` The default size of the bars with discrete dimensions. If unspecified, the default size is ``step-2``, which provides 2 pixel offset between bars. dx : dict, float, :class:`ExprRef` The horizontal offset, in pixels, between the text label and its anchor point. The offset is applied after rotation by the *angle* property. dy : dict, float, :class:`ExprRef` The vertical offset, in pixels, between the text label and its anchor point. The offset is applied after rotation by the *angle* property. ellipsis : str, dict, :class:`ExprRef` The ellipsis string for text truncated in response to the limit parameter. **Default value:** ``"…"`` endAngle : dict, float, :class:`ExprRef` The end angle in radians for arc marks. A value of ``0`` indicates up (north), increasing values proceed clockwise. fill : str, dict, :class:`Color`, :class:`ExprRef`, :class:`Gradient`, :class:`HexColor`, :class:`ColorName`, :class:`LinearGradient`, :class:`RadialGradient`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple'], None Default fill color. This property has higher precedence than ``config.color``. Set to ``null`` to remove fill. **Default value:** (None) fillOpacity : dict, float, :class:`ExprRef` The fill opacity (value between [0,1]). **Default value:** ``1`` filled : bool Whether the mark's color should be used as fill color instead of stroke color. **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well as ``geoshape`` marks for `graticule <https://vega.github.io/vega-lite/docs/data.html#graticule>`__ data sources; otherwise, ``true``. **Note:** This property cannot be used in a `style config <https://vega.github.io/vega-lite/docs/mark.html#style-config>`__. font : str, dict, :class:`ExprRef` The typeface to set the text in (e.g., ``"Helvetica Neue"``). fontSize : dict, float, :class:`ExprRef` The font size, in pixels. **Default value:** ``11`` fontStyle : str, dict, :class:`ExprRef`, :class:`FontStyle` The font style (e.g., ``"italic"``). fontWeight : dict, :class:`ExprRef`, :class:`FontWeight`, Literal['normal', 'bold', 'lighter', 'bolder', 100, 200, 300, 400, 500, 600, 700, 800, 900] The font weight. This can be either a string (e.g ``"bold"``, ``"normal"``) or a number (``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and ``"bold"`` = ``700``). height : dict, float, :class:`ExprRef` Height of the marks. href : str, dict, :class:`URI`, :class:`ExprRef` A URL to load upon mouse click. If defined, the mark acts as a hyperlink. innerRadius : dict, float, :class:`ExprRef` The inner radius in pixels of arc marks. ``innerRadius`` is an alias for ``radius2``. **Default value:** ``0`` interpolate : dict, :class:`ExprRef`, :class:`Interpolate`, Literal['basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', 'cardinal-closed', 'catmull-rom', 'linear', 'linear-closed', 'monotone', 'natural', 'step', 'step-before', 'step-after'] The line interpolation method to use for line and area marks. One of the following: * ``"linear"``: piecewise linear segments, as in a polyline. * ``"linear-closed"``: close the linear segments to form a polygon. * ``"step"``: alternate between horizontal and vertical segments, as in a step function. * ``"step-before"``: alternate between vertical and horizontal segments, as in a step function. * ``"step-after"``: alternate between horizontal and vertical segments, as in a step function. * ``"basis"``: a B-spline, with control point duplication on the ends. * ``"basis-open"``: an open B-spline; may not intersect the start or end. * ``"basis-closed"``: a closed B-spline, as in a loop. * ``"cardinal"``: a Cardinal spline, with control point duplication on the ends. * ``"cardinal-open"``: an open Cardinal spline; may not intersect the start or end, but will intersect other control points. * ``"cardinal-closed"``: a closed Cardinal spline, as in a loop. * ``"bundle"``: equivalent to basis, except the tension parameter is used to straighten the spline. * ``"monotone"``: cubic interpolation that preserves monotonicity in y. invalid : :class:`MarkInvalidDataMode`, Literal['filter', 'break-paths-filter-domains', 'break-paths-show-domains', 'break-paths-show-path-domains', 'show'], None Invalid data mode, which defines how the marks and corresponding scales should represent invalid values (``null`` and ``NaN`` in continuous scales *without* defined output for invalid values). * ``"filter"`` — *Exclude* all invalid values from the visualization's *marks* and *scales*. For path marks (for line, area, trail), this option will create paths that connect valid points, as if the data rows with invalid values do not exist. * ``"break-paths-filter-domains"`` — Break path marks (for line, area, trail) at invalid values. For non-path marks, this is equivalent to ``"filter"``. All *scale* domains will *exclude* these filtered data points. * ``"break-paths-show-domains"`` — Break paths (for line, area, trail) at invalid values. Hide invalid values for non-path marks. All *scale* domains will *include* these filtered data points (for both path and non-path marks). * ``"show"`` or ``null`` — Show all data points in the marks and scale domains. Each scale will use the output for invalid values defined in ``config.scale.invalid`` or, if unspecified, by default invalid values will produce the same visual values as zero (if the scale includes zero) or the minimum value (if the scale does not include zero). * ``"break-paths-show-path-domains"`` (default) — This is equivalent to ``"break-paths-show-domains"`` for path-based marks (line/area/trail) and ``"filter"`` for non-path marks. **Note**: If any channel's scale has an output for invalid values defined in ``config.scale.invalid``, all values for the scales will be considered "valid" since they can produce a reasonable output for the scales. Thus, fields for such channels will not be filtered and will not cause path breaks. limit : dict, float, :class:`ExprRef` The maximum length of the text mark in pixels. The text value will be automatically truncated if the rendered size exceeds the limit. **Default value:** ``0`` -- indicating no limit lineBreak : str, dict, :class:`ExprRef` A delimiter, such as a newline character, upon which to break text strings into multiple lines. This property is ignored if the text is array-valued. lineHeight : dict, float, :class:`ExprRef` The line height in pixels (the spacing between subsequent lines of text) for multi-line text marks. minBandSize : dict, float, :class:`ExprRef` The minimum band size for bar and rectangle marks. **Default value:** ``0.25`` opacity : dict, float, :class:`ExprRef` The overall opacity (value between [0,1]). **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. order : bool, None For line and trail marks, this ``order`` property can be set to ``null`` or ``false`` to make the lines use the original order in the data sources. orient : :class:`Orientation`, Literal['horizontal', 'vertical'] The orientation of a non-stacked bar, tick, area, and line charts. The value is either horizontal (default) or vertical. * For bar, rule and tick, this determines whether the size of the bar and tick should be applied to x or y dimension. * For area, this property determines the orient property of the Vega output. * For line and trail marks, this property determines the sort order of the points in the line if ``config.sortLineBy`` is not specified. For stacked charts, this is always determined by the orientation of the stack; therefore explicitly specified value will be ignored. outerRadius : dict, float, :class:`ExprRef` The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. **Default value:** ``0`` padAngle : dict, float, :class:`ExprRef` The angular padding applied to sides of the arc, in radians. radius : dict, float, :class:`ExprRef` For arc mark, the primary (outer) radius in pixels. For text marks, polar coordinate radial offset, in pixels, of the text from the origin determined by the ``x`` and ``y`` properties. **Default value:** ``min(plot_width, plot_height)/2`` radius2 : dict, float, :class:`ExprRef` The secondary (inner) radius in pixels of arc marks. **Default value:** ``0`` shape : str, dict, :class:`ExprRef`, :class:`SymbolShape` Shape of the point marks. Supported values include: * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or ``"triangle-left"``. * the line symbol ``"stroke"`` * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` * a custom `SVG path string <https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths>`__ (For correct sizing, custom shape paths should be defined within a square bounding box with coordinates ranging from -1 to 1 along both the x and y dimensions.) **Default value:** ``"circle"`` size : dict, float, :class:`ExprRef` Default size for marks. * For ``point``/``circle``/``square``, this represents the pixel area of the marks. Note that this value sets the area of the symbol; the side lengths will increase with the square root of this value. * For ``bar``, this represents the band size of the bar, in pixels. * For ``text``, this represents the font size, in pixels. **Default value:** * ``30`` for point, circle, square marks; width/height's ``step`` * ``2`` for bar marks with discrete dimensions; * ``5`` for bar marks with continuous dimensions; * ``11`` for text marks. smooth : bool, dict, :class:`ExprRef` A boolean flag (default true) indicating if the image should be smoothed when resized. If false, individual pixels should be scaled directly rather than interpolated with smoothing. For SVG rendering, this option may not work in some browsers due to lack of standardization. startAngle : dict, float, :class:`ExprRef` The start angle in radians for arc marks. A value of ``0`` indicates up (north), increasing values proceed clockwise. stroke : str, dict, :class:`Color`, :class:`ExprRef`, :class:`Gradient`, :class:`HexColor`, :class:`ColorName`, :class:`LinearGradient`, :class:`RadialGradient`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple'], None Default stroke color. This property has higher precedence than ``config.color``. Set to ``null`` to remove stroke. **Default value:** (None) strokeCap : dict, :class:`ExprRef`, :class:`StrokeCap`, Literal['butt', 'round', 'square'] The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or ``"square"``. **Default value:** ``"butt"`` strokeDash : dict, Sequence[float], :class:`ExprRef` An array of alternating stroke, space lengths for creating dashed or dotted lines. strokeDashOffset : dict, float, :class:`ExprRef` The offset (in pixels) into which to begin drawing with the stroke dash array. strokeJoin : dict, :class:`ExprRef`, :class:`StrokeJoin`, Literal['miter', 'round', 'bevel'] The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. **Default value:** ``"miter"`` strokeMiterLimit : dict, float, :class:`ExprRef` The miter limit at which to bevel a line join. strokeOffset : dict, float, :class:`ExprRef` The offset in pixels at which to draw the group stroke and fill. If unspecified, the default behavior is to dynamically offset stroked groups such that 1 pixel stroke widths align with the pixel grid. strokeOpacity : dict, float, :class:`ExprRef` The stroke opacity (value between [0,1]). **Default value:** ``1`` strokeWidth : dict, float, :class:`ExprRef` The stroke width, in pixels. tension : dict, float, :class:`ExprRef` Depending on the interpolation type, sets the tension parameter (for line and area marks). text : str, dict, :class:`Text`, Sequence[str], :class:`ExprRef` Placeholder text if the ``text`` channel is not specified theta : dict, float, :class:`ExprRef` * For arc marks, the arc length in radians if theta2 is not specified, otherwise the start arc angle. (A value of 0 indicates up or “north”, increasing values proceed clockwise.) * For text marks, polar coordinate angle in radians. theta2 : dict, float, :class:`ExprRef` The end angle of arc marks in radians. A value of 0 indicates up or “north”, increasing values proceed clockwise. thickness : float Thickness of the tick mark. **Default value:** ``1`` time : dict, float, :class:`ExprRef` timeUnitBandPosition : float Default relative band position for a time unit. If set to ``0``, the marks will be positioned at the beginning of the time unit band step. If set to ``0.5``, the marks will be positioned in the middle of the time unit band step. timeUnitBandSize : float Default relative band size for a time unit. If set to ``1``, the bandwidth of the marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the marks will be half of the time unit band step. tooltip : str, bool, dict, float, :class:`ExprRef`, :class:`TooltipContent`, None The tooltip text string to show upon mouse hover or an object defining which fields should the tooltip be derived from. * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from ``encoding`` will be used. * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the highlighted data point will be used. * If set to ``null`` or ``false``, then no tooltip will be used. See the `tooltip <https://vega.github.io/vega-lite/docs/tooltip.html>`__ documentation for a detailed discussion about tooltip in Vega-Lite. **Default value:** ``null`` url : str, dict, :class:`URI`, :class:`ExprRef` The URL of the image file for image marks. width : dict, float, :class:`ExprRef` Width of the marks. x : dict, float, :class:`ExprRef`, Literal['width'] X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without specified ``x2`` or ``width``. The ``value`` of this channel can be a number or a string ``"width"`` for the width of the plot. x2 : dict, float, :class:`ExprRef`, Literal['width'] X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. The ``value`` of this channel can be a number or a string ``"width"`` for the width of the plot. y : dict, float, :class:`ExprRef`, Literal['height'] Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without specified ``y2`` or ``height``. The ``value`` of this channel can be a number or a string ``"height"`` for the height of the plot. y2 : dict, float, :class:`ExprRef`, Literal['height'] Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. The ``value`` of this channel can be a number or a string ``"height"`` for the height of the plot. """ _schema = {"$ref": "#/definitions/TickConfig"} def __init__( self, align: Optional[Parameter | SchemaBase | Map | Align_T] = Undefined, angle: Optional[float | Parameter | SchemaBase | Map] = Undefined, aria: Optional[bool | Parameter | SchemaBase | Map] = Undefined, ariaRole: Optional[str | Parameter | SchemaBase | Map] = Undefined, ariaRoleDescription: Optional[str | Parameter | SchemaBase | Map] = Undefined, aspect: Optional[bool | Parameter | SchemaBase | Map] = Undefined, bandSize: Optional[float] = Undefined, baseline: Optional[Parameter | SchemaBase | Map | TextBaseline_T] = Undefined, binSpacing: Optional[float] = Undefined, blend: Optional[Parameter | SchemaBase | Map | Blend_T] = Undefined, color: Optional[str | Parameter | SchemaBase | Map | ColorName_T] = Undefined, continuousBandSize: Optional[float] = Undefined, cornerRadius: Optional[float | Parameter | SchemaBase | Map] = Undefined, cornerRadiusBottomLeft: Optional[ float | Parameter | SchemaBase | Map ] = Undefined, cornerRadiusBottomRight: Optional[ float | Parameter | SchemaBase | Map ] = Undefined, cornerRadiusTopLeft: Optional[float | Parameter | SchemaBase | Map] = Undefined, cornerRadiusTopRight: Optional[ float | Parameter | SchemaBase | Map ] = Undefined, cursor: Optional[Parameter | SchemaBase | Map | Cursor_T] = Undefined, description: Optional[str | Parameter | SchemaBase | Map] = Undefined, dir: Optional[Parameter | SchemaBase | Map | TextDirection_T] = Undefined, discreteBandSize: Optional[float | SchemaBase | Map] = Undefined, dx: Optional[float | Parameter | SchemaBase | Map] = Undefined, dy: Optional[float | Parameter | SchemaBase | Map] = Undefined, ellipsis: Optional[str | Parameter | SchemaBase | Map] = Undefined, endAngle: Optional[float | Parameter | SchemaBase | Map] = Undefined, fill: Optional[ str | Parameter | SchemaBase | Map | ColorName_T | None ] = Undefined, fillOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined, filled: Optional[bool] = Undefined, font: Optional[str | Parameter | SchemaBase | Map] = Undefined, fontSize: Optional[float | Parameter | SchemaBase | Map] = Undefined, fontStyle: Optional[str | Parameter | SchemaBase | Map] = Undefined, fontWeight: Optional[Parameter | SchemaBase | Map | FontWeight_T] = Undefined, height: Optional[float | Parameter | SchemaBase | Map] = Undefined, href: Optional[str | Parameter | SchemaBase | Map] = Undefined, innerRadius: Optional[float | Parameter | SchemaBase | Map] = Undefined, interpolate: Optional[Parameter | SchemaBase | Map | Interpolate_T] = Undefined, invalid: Optional[SchemaBase | MarkInvalidDataMode_T | None] = Undefined, limit: Optional[float | Parameter | SchemaBase | Map] = Undefined, lineBreak: Optional[str | Parameter | SchemaBase | Map] = Undefined, lineHeight: Optional[float | Parameter | SchemaBase | Map] = Undefined, minBandSize: Optional[float | Parameter | SchemaBase | Map] = Undefined, opacity: Optional[float | Parameter | SchemaBase | Map] = Undefined, order: Optional[bool | None] = Undefined, orient: Optional[SchemaBase | Orientation_T] = Undefined, outerRadius: Optional[float | Parameter | SchemaBase | Map] = Undefined, padAngle: Optional[float | Parameter | SchemaBase | Map] = Undefined, radius: Optional[float | Parameter | SchemaBase | Map] = Undefined, radius2: Optional[float | Parameter | SchemaBase | Map] = Undefined, shape: Optional[str | Parameter | SchemaBase | Map] = Undefined, size: Optional[float | Parameter | SchemaBase | Map] = Undefined, smooth: Optional[bool | Parameter | SchemaBase | Map] = Undefined, startAngle: Optional[float | Parameter | SchemaBase | Map] = Undefined, stroke: Optional[ str | Parameter | SchemaBase | Map | ColorName_T | None ] = Undefined, strokeCap: Optional[Parameter | SchemaBase | Map | StrokeCap_T] = Undefined, strokeDash: Optional[ Parameter | SchemaBase | Sequence[float] | Map ] = Undefined, strokeDashOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined, strokeJoin: Optional[Parameter | SchemaBase | Map | StrokeJoin_T] = Undefined, strokeMiterLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined, strokeOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined, strokeOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined, strokeWidth: Optional[float | Parameter | SchemaBase | Map] = Undefined, tension: Optional[float | Parameter | SchemaBase | Map] = Undefined, text: Optional[str | Parameter | SchemaBase | Sequence[str] | Map] = Undefined, theta: Optional[float | Parameter | SchemaBase | Map] = Undefined, theta2: Optional[float | Parameter | SchemaBase | Map] = Undefined, thickness: Optional[float] = Undefined, time: Optional[float | Parameter | SchemaBase | Map] = Undefined, timeUnitBandPosition: Optional[float] = Undefined, timeUnitBandSize: Optional[float] = Undefined, tooltip: Optional[ str | bool | float | Parameter | SchemaBase | Map | None ] = Undefined, url: Optional[str | Parameter | SchemaBase | Map] = Undefined, width: Optional[float | Parameter | SchemaBase | Map] = Undefined, x: Optional[ float | Parameter | SchemaBase | Literal["width"] | Map ] = Undefined, x2: Optional[ float | Parameter | SchemaBase | Literal["width"] | Map ] = Undefined, y: Optional[ float | Parameter | SchemaBase | Literal["height"] | Map ] = Undefined, y2: Optional[ float | Parameter | SchemaBase | Literal["height"] | Map ] = Undefined, **kwds, ): super().__init__( align=align, angle=angle, aria=aria, ariaRole=ariaRole, ariaRoleDescription=ariaRoleDescription, aspect=aspect, bandSize=bandSize, baseline=baseline, binSpacing=binSpacing, blend=blend, color=color, continuousBandSize=continuousBandSize, cornerRadius=cornerRadius, cornerRadiusBottomLeft=cornerRadiusBottomLeft, cornerRadiusBottomRight=cornerRadiusBottomRight, cornerRadiusTopLeft=cornerRadiusTopLeft, cornerRadiusTopRight=cornerRadiusTopRight, cursor=cursor, description=description, dir=dir, discreteBandSize=discreteBandSize, dx=dx, dy=dy, ellipsis=ellipsis, endAngle=endAngle, fill=fill, fillOpacity=fillOpacity, filled=filled, font=font, fontSize=fontSize, fontStyle=fontStyle, fontWeight=fontWeight, height=height, href=href, innerRadius=innerRadius, interpolate=interpolate, invalid=invalid, limit=limit, lineBreak=lineBreak, lineHeight=lineHeight, minBandSize=minBandSize, opacity=opacity, order=order, orient=orient, outerRadius=outerRadius, padAngle=padAngle, radius=radius, radius2=radius2, shape=shape, size=size, smooth=smooth, startAngle=startAngle, stroke=stroke, strokeCap=strokeCap, strokeDash=strokeDash, strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, strokeMiterLimit=strokeMiterLimit, strokeOffset=strokeOffset, strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, tension=tension, text=text, theta=theta, theta2=theta2, thickness=thickness, time=time, timeUnitBandPosition=timeUnitBandPosition, timeUnitBandSize=timeUnitBandSize, tooltip=tooltip, url=url, width=width, x=x, x2=x2, y=y, y2=y2, **kwds, )
TickConfig
python
encode__django-rest-framework
tests/test_htmlrenderer.py
{ "start": 1391, "end": 5219 }
class ____(TestCase): def setUp(self): class MockResponse: template_name = None self.mock_response = MockResponse() self._monkey_patch_get_template() def _monkey_patch_get_template(self): """ Monkeypatch get_template """ self.get_template = django.template.loader.get_template def get_template(template_name, dirs=None): if template_name == 'example.html': return engines['django'].from_string("example: {{ object }}") raise TemplateDoesNotExist(template_name) def select_template(template_name_list, dirs=None, using=None): if template_name_list == ['example.html']: return engines['django'].from_string("example: {{ object }}") raise TemplateDoesNotExist(template_name_list[0]) django.template.loader.get_template = get_template django.template.loader.select_template = select_template def tearDown(self): """ Revert monkeypatching """ django.template.loader.get_template = self.get_template def test_simple_html_view(self): response = self.client.get('/') self.assertContains(response, "example: foobar") self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') def test_not_found_html_view(self): response = self.client.get('/not_found') self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(response.content, b"404 Not Found") self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') def test_permission_denied_html_view(self): response = self.client.get('/permission_denied') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.content, b"403 Forbidden") self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') def test_validation_error_html_view(self): response = self.client.get('/validation_error') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.content, b"400 Bad Request") self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') # 2 tests below are based on order of if statements in corresponding method # of TemplateHTMLRenderer def test_get_template_names_returns_own_template_name(self): renderer = TemplateHTMLRenderer() renderer.template_name = 'test_template' template_name = renderer.get_template_names(self.mock_response, view={}) assert template_name == ['test_template'] def test_get_template_names_returns_view_template_name(self): renderer = TemplateHTMLRenderer() class MockResponse: template_name = None class MockView: def get_template_names(self): return ['template from get_template_names method'] class MockView2: template_name = 'template from template_name attribute' template_name = renderer.get_template_names(self.mock_response, MockView()) assert template_name == ['template from get_template_names method'] template_name = renderer.get_template_names(self.mock_response, MockView2()) assert template_name == ['template from template_name attribute'] def test_get_template_names_raises_error_if_no_template_found(self): renderer = TemplateHTMLRenderer() with pytest.raises(ImproperlyConfigured): renderer.get_template_names(self.mock_response, view=object()) @override_settings(ROOT_URLCONF='tests.test_htmlrenderer')
TemplateHTMLRendererTests
python
sympy__sympy
sympy/functions/combinatorial/numbers.py
{ "start": 65823, "end": 68264 }
class ____(DefinedFunction): """ Mobius function maps natural number to {-1, 0, 1} It is defined as follows: 1) `1` if `n = 1`. 2) `0` if `n` has a squared prime factor. 3) `(-1)^k` if `n` is a square-free positive integer with `k` number of prime factors. It is an important multiplicative function in number theory and combinatorics. It has applications in mathematical series, algebraic number theory and also physics (Fermion operator has very concrete realization with Mobius Function model). Examples ======== >>> from sympy.functions.combinatorial.numbers import mobius >>> mobius(13*7) 1 >>> mobius(1) 1 >>> mobius(13*7*5) -1 >>> mobius(13**2) 0 Even in the case of a symbol, if it clearly contains a squared prime factor, it will be zero. >>> from sympy import Symbol >>> n = Symbol("n", integer=True, positive=True) >>> mobius(4*n) 0 >>> mobius(n**2) 0 References ========== .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function .. [2] Thomas Koshy "Elementary Number Theory with Applications" .. [3] https://oeis.org/A008683 """ is_integer = True is_prime = False @classmethod def eval(cls, n): if n.is_integer is False: raise TypeError("n should be an integer") if n.is_positive is False: raise ValueError("n should be a positive integer") if n.is_prime is True: return S.NegativeOne if n is S.One: return S.One result = None for m, e in (_.as_base_exp() for _ in Mul.make_args(n)): if m.is_integer is True and m.is_positive is True and \ e.is_integer is True and e.is_positive is True: lt = is_lt(S.One, e) # 1 < e if lt is True: result = S.Zero elif m.is_Integer is True: factors = factorint(m) if any(v > 1 for v in factors.values()): result = S.Zero elif lt is False: s = S.NegativeOne if len(factors) % 2 else S.One if result is None: result = s else: result *= s else: return return result
mobius
python
astropy__astropy
astropy/modeling/powerlaws.py
{ "start": 13003, "end": 15034 }
class ____(Fittable1DModel): """ One dimensional power law model with an exponential cutoff. Parameters ---------- amplitude : float Model amplitude x_0 : float Reference point alpha : float Power law index x_cutoff : float Cutoff point See Also -------- PowerLaw1D, BrokenPowerLaw1D, LogParabola1D Notes ----- Model formula (with :math:`A` for ``amplitude`` and :math:`\\alpha` for ``alpha``): .. math:: f(x) = A (x / x_0) ^ {-\\alpha} \\exp (-x / x_{cutoff}) """ amplitude = Parameter(default=1, description="Peak value of model") x_0 = Parameter(default=1, description="Reference point") alpha = Parameter(default=1, description="Power law index") x_cutoff = Parameter(default=1, description="Cutoff point") @staticmethod def evaluate(x, amplitude, x_0, alpha, x_cutoff): """One dimensional exponential cutoff power law model function.""" xx = x / x_0 return amplitude * xx ** (-alpha) * np.exp(-x / x_cutoff) @staticmethod def fit_deriv(x, amplitude, x_0, alpha, x_cutoff): """ One dimensional exponential cutoff power law derivative with respect to parameters. """ xx = x / x_0 xc = x / x_cutoff d_amplitude = xx ** (-alpha) * np.exp(-xc) d_x_0 = alpha * amplitude * d_amplitude / x_0 d_alpha = -amplitude * d_amplitude * np.log(xx) d_x_cutoff = amplitude * x * d_amplitude / x_cutoff**2 return [d_amplitude, d_x_0, d_alpha, d_x_cutoff] @property def input_units(self): if self.x_0.input_unit is None: return None return {self.inputs[0]: self.x_0.input_unit} def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): return { "x_0": inputs_unit[self.inputs[0]], "x_cutoff": inputs_unit[self.inputs[0]], "amplitude": outputs_unit[self.outputs[0]], }
ExponentialCutoffPowerLaw1D
python
davidhalter__jedi
test/completion/named_param.py
{ "start": 442, "end": 2031 }
class ____(object): def __init__(self, hello_other): pass def __call__(self, hello): pass def test(self, blub): pass #? 10 ['hello_other='] Test(hello=) #? 12 ['hello='] Test()(hello=) #? 11 [] Test()(self=) #? 16 [] Test().test(self=) #? 16 ['blub='] Test().test(blub=) # builtins #? 12 [] any(iterable=) def foo(xyz): pass #? 7 ['xyz='] @foo(xy) def x(): pass #? 7 ['xyz='] foo(xyz) # No completion should be possible if it's not a simple name #? 17 [] x = " "; foo(x.xyz) #? 17 [] x = " "; foo([xyz) #? 20 [] x = " "; foo(z[f,xyz) #? 18 [] x = " "; foo(z[xyz) #? 20 [] x = " "; foo(xyz[xyz) #? 20 [] x = " "; foo(xyz[(xyz) #? 8 ['xyz='] @foo(xyz) def x(): pass @str #? 8 ['xyz='] @foo(xyz) def x(): pass # ----------------- # Only keyword arguments are valid # ----------------- def x(bam, *, bar, baz): pass def y(bam, *bal, bar, baz, **bag): pass def z(bam, bar=2, *, bas=1): pass #? 7 ['bar=', 'baz='] x(1, ba) #? 14 ['baz='] x(1, bar=2, ba) #? 7 ['bar=', 'baz='] x(1, ba, baz=3) #? 14 ['baz='] x(1, bar=2, baz=3) #? 7 ['BaseException'] x(basee) #? 22 ['bar=', 'baz='] x(1, 2, 3, 4, 5, 6, bar=2) #? 14 ['baz='] y(1, bar=2, ba) #? 7 ['bar=', 'BaseException', 'baz='] y(1, ba, baz=3) #? 14 ['baz='] y(1, bar=2, baz=3) #? 7 ['BaseException'] y(basee) #? 22 ['bar=', 'BaseException', 'baz='] y(1, 2, 3, 4, 5, 6, bar=2) #? 11 ['bar=', 'bas='] z(bam=1, bar=2, bas=3) #? 8 ['BaseException', 'bas='] z(1, bas=2) #? 12 ['BaseException'] z(1, bas=bas) #? 19 ['dict'] z(1, bas=bas, **dic) #? 18 ['dict'] z(1, bas=bas, *dic)
Test
python
getsentry__sentry
src/sentry/core/endpoints/project_transfer.py
{ "start": 970, "end": 1085 }
class ____(ProjectPermission): scope_map = {"POST": ["org:admin"]} @region_silo_endpoint
RelaxedProjectPermission
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1577804, "end": 1580053 }
class ____(sgqlc.types.Type, Node, UniformResourceLocatable): """A workflow contains meta information about an Actions workflow file. """ __schema__ = github_schema __field_names__ = ("created_at", "database_id", "name", "runs", "state", "updated_at") created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt") """Identifies the date and time when the object was created.""" database_id = sgqlc.types.Field(Int, graphql_name="databaseId") """Identifies the primary key from the database.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The name of the workflow.""" runs = sgqlc.types.Field( sgqlc.types.non_null(WorkflowRunConnection), graphql_name="runs", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ( "order_by", sgqlc.types.Arg(WorkflowRunOrder, graphql_name="orderBy", default={"field": "CREATED_AT", "direction": "DESC"}), ), ) ), ) """The runs of the workflow. Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. * `order_by` (`WorkflowRunOrder`): Ordering options for the connection (default: `{field: CREATED_AT, direction: DESC}`) """ state = sgqlc.types.Field(sgqlc.types.non_null(WorkflowState), graphql_name="state") """The state of the workflow.""" updated_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="updatedAt") """Identifies the date and time when the object was last updated."""
Workflow
python
weaviate__weaviate-python-client
weaviate/collections/classes/grpc.py
{ "start": 6332, "end": 7361 }
class ____: """Define how the query's sort operation should be performed using the available static methods.""" def __init__(self) -> None: raise TypeError("Sort cannot be instantiated. Use the static methods to create a sorter.") @staticmethod def by_property(name: str, ascending: bool = True) -> Sorting: """Sort by an object property in the collection.""" return _Sorting().by_property(name=name, ascending=ascending) @staticmethod def by_id(ascending: bool = True) -> Sorting: """Sort by an object's ID in the collection.""" return _Sorting().by_id(ascending=ascending) @staticmethod def by_creation_time(ascending: bool = True) -> Sorting: """Sort by an object's creation time.""" return _Sorting().by_creation_time(ascending=ascending) @staticmethod def by_update_time(ascending: bool = True) -> Sorting: """Sort by an object's last update time.""" return _Sorting().by_update_time(ascending=ascending)
Sort
python
pypa__setuptools
setuptools/errors.py
{ "start": 1508, "end": 1988 }
class ____(BaseError, RuntimeError): # type: ignore[valid-type, misc] # distutils imports are `Any` on python 3.12+ """Error used for commands that have been removed in setuptools. Since ``setuptools`` is built on ``distutils``, simply removing a command from ``setuptools`` will make the behavior fall back to ``distutils``; this error is raised if a command exists in ``distutils`` but has been actively removed in ``setuptools``. """
RemovedCommandError
python
scipy__scipy
scipy/special/_mptestutils.py
{ "start": 4299, "end": 4661 }
class ____: def __init__(self, a=complex(-np.inf, -np.inf), b=complex(np.inf, np.inf)): self.real = Arg(a.real, b.real) self.imag = Arg(a.imag, b.imag) def values(self, n): m = int(np.floor(np.sqrt(n))) x = self.real.values(m) y = self.imag.values(m + 1) return (x[:,None] + 1j*y[None,:]).ravel()
ComplexArg
python
spyder-ide__spyder
spyder/api/shellconnect/mixins.py
{ "start": 2741, "end": 5916 }
class ____(ShellConnectMixin): """ Mixin to connect a plugin composed of stacked widgets to the shell widgets in the IPython console. It is assumed that self.get_widget() returns an instance of ShellConnectMainWidget. """ # ---- Connection to the IPython console # ------------------------------------------------------------------------- @on_plugin_available(plugin=Plugins.IPythonConsole) def on_ipython_console_available(self): """Connect to the IPython console.""" ipyconsole = self.get_plugin(Plugins.IPythonConsole) self.register_ipythonconsole(ipyconsole) @on_plugin_teardown(plugin=Plugins.IPythonConsole) def on_ipython_console_teardown(self): """Disconnect from the IPython console.""" ipyconsole = self.get_plugin(Plugins.IPythonConsole) self.unregister_ipythonconsole(ipyconsole) # ---- Public API # ------------------------------------------------------------------------- def set_shellwidget(self, shellwidget): """ Update the current shellwidget. Parameters ---------- shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget The shell widget. """ self.get_widget().set_shellwidget(shellwidget) def add_shellwidget(self, shellwidget): """ Add a new shellwidget to be registered. This function registers a new widget to display content that comes from shellwidget. Parameters ---------- shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget The shell widget. """ self.get_widget().add_shellwidget(shellwidget) def remove_shellwidget(self, shellwidget): """ Remove a registered shellwidget. Parameters ---------- shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget The shell widget. """ self.get_widget().remove_shellwidget(shellwidget) def add_errored_shellwidget(self, shellwidget): """ Add a new shellwidget whose kernel failed to start. Parameters ---------- shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget The shell widget. """ self.get_widget().add_errored_shellwidget(shellwidget) def current_widget(self): """ Return the current widget displayed at the moment. Returns ------- current_widget: QWidget The widget displayed in the current tab. """ return self.get_widget().current_widget() def get_widget_for_shellwidget(self, shellwidget): """ Return the widget registered with the given shellwidget. Parameters ---------- shellwidget: spyder.plugins.ipyconsole.widgets.shell.ShellWidget The shell widget. Returns ------- current_widget: QWidget The widget corresponding to the shellwidget, or None if not found. """ return self.get_widget().get_widget_for_shellwidget(shellwidget)
ShellConnectPluginMixin
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/utils/test_redshift.py
{ "start": 967, "end": 2350 }
class ____: @mock.patch("boto3.session.Session") def test_build_credentials_block(self, mock_session): access_key = "aws_access_key_id" secret_key = "aws_secret_access_key" token = "aws_secret_token" mock_session.return_value = Session(access_key, secret_key) mock_session.return_value.access_key = access_key mock_session.return_value.secret_key = secret_key mock_session.return_value.token = None credentials_block = build_credentials_block(mock_session.return_value) assert access_key in credentials_block assert secret_key in credentials_block assert token not in credentials_block @mock.patch("boto3.session.Session") def test_build_credentials_block_sts(self, mock_session): access_key = "ASIA_aws_access_key_id" secret_key = "aws_secret_access_key" token = "aws_secret_token" mock_session.return_value = Session(access_key, secret_key) mock_session.return_value.access_key = access_key mock_session.return_value.secret_key = secret_key mock_session.return_value.token = token credentials_block = build_credentials_block(mock_session.return_value) assert access_key in credentials_block assert secret_key in credentials_block assert token in credentials_block
TestS3ToRedshiftTransfer
python
EpistasisLab__tpot
tpot/builtin_modules/genetic_encoders.py
{ "start": 4239, "end": 5530 }
class ____(TransformerMixin, BaseEstimator ): """This class contains the function definition for encoding the input features as a Under Dominance genetic model. The encoding used is AA(0)->2, Aa(1)->0, aa(2)->1. """ def fit(self, X, y=None): """Do nothing and return the estimator unchanged. Dummy function to fit in with the sklearn API and hence work in pipelines. Parameters ---------- X : array-like """ return self def transform(self, X, y=None): """Transform the data by applying the Heterosis encoding. Parameters ---------- X : numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples (number of individuals) and n_components is the number of components (number of features). y : None Unused Returns ------- X_transformed: numpy ndarray, {n_samples, n_components} The encoded feature set """ X = check_array(X) map = {0: 2, 1: 0, 2: 1} mapping_function = np.vectorize(lambda i: map[i] if i in map else i) X_transformed = mapping_function(X) return X_transformed
UnderDominanceEncoder
python
oauthlib__oauthlib
oauthlib/openid/connect/core/exceptions.py
{ "start": 2748, "end": 2966 }
class ____(OpenIDClientError): """ The OP does not support use of the request parameter. """ error = 'request_not_supported' description = 'The request parameter is not supported.'
RequestNotSupported
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/organization_workflow_group_history.py
{ "start": 1090, "end": 2349 }
class ____(OrganizationWorkflowEndpoint): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.ISSUES @extend_schema( operation_id="Retrieve Group Firing History for a Workflow", parameters=[ GlobalParams.ORG_ID_OR_SLUG, WorkflowParams.WORKFLOW_ID, ], responses={ 200: WorkflowGroupHistorySerializer, 401: RESPONSE_UNAUTHORIZED, 403: RESPONSE_FORBIDDEN, 404: RESPONSE_NOT_FOUND, }, ) def get(self, request: Request, organization: Organization, workflow: Workflow) -> Response: per_page = self.get_per_page(request) cursor = self.get_cursor_from_request(request) try: start, end = get_date_range_from_params(request.GET) except InvalidParams: raise ParseError(detail="Invalid start and end dates") results = fetch_workflow_groups_paginated(workflow, start, end, cursor, per_page) response = Response( serialize(results.results, request.user, WorkflowGroupHistorySerializer()) ) self.add_cursor_headers(request, response, results) return response
OrganizationWorkflowGroupHistoryEndpoint
python
getsentry__sentry
src/sentry_plugins/github/webhooks/events/installation_repository.py
{ "start": 209, "end": 1907 }
class ____(Webhook): # https://developer.github.com/v3/activity/events/types/#installationrepositoriesevent def __call__(self, event, organization): installation = event["installation"] integration = integration_service.get_integration( external_id=installation["id"], provider="github_apps" ) if integration is None: raise Integration.DoesNotExist integration_orgs = integration_service.get_organization_integrations( integration_id=integration.id ) organizations = [org.organization_id for org in integration_orgs] repos_added = event["repositories_added"] if repos_added: for org_id in organizations: for r in repos_added: config = {"name": r["full_name"]} repo, created = Repository.objects.get_or_create( organization_id=org_id, name=r["full_name"], provider="github", external_id=r["id"], defaults={ "url": "https://github.com/{}".format(r["full_name"]), "config": config, "integration_id": integration.id, }, ) if not created: repo.config.update(config) repo.integration_id = integration.id repo.save() # TODO(jess): what do we want to do when they're removed? # maybe signify that we've lost access but not deleted?
InstallationRepositoryEventWebhook
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-nvidia/llama_index/llms/nvidia/base.py
{ "start": 869, "end": 10507 }
class ____(OpenAILike, FunctionCallingLLM): """NVIDIA's API Catalog Connector.""" _mode: str = PrivateAttr(default="nvidia") _client: Any = PrivateAttr() _aclient: Any = PrivateAttr() _is_hosted: bool = PrivateAttr(True) def __init__( self, model: Optional[str] = None, nvidia_api_key: Optional[str] = None, api_key: Optional[str] = None, base_url: Optional[str] = os.getenv("NVIDIA_BASE_URL", BASE_URL), max_tokens: Optional[int] = 1024, **kwargs: Any, ) -> None: """ Initialize an instance of the NVIDIA class. This class provides an interface to the NVIDIA NIM. By default, it connects to a hosted NIM, but you can switch to an on-premises NIM by providing a `base_url`. Args: model (str, optional): The model to use for the NIM. nvidia_api_key (str, optional): The API key for the NVIDIA NIM. Defaults to None. api_key (str, optional): An alternative parameter for providing the API key. Defaults to None. base_url (str, optional): The base URL for the NIM. Use this to switch to an on-premises NIM. max_tokens (int, optional): The maximum number of tokens to generate. Defaults to 1024. **kwargs: Additional keyword arguments. API Keys: - The recommended way to provide the API key is through the `NVIDIA_API_KEY` environment variable. Raises: DeprecationWarning: If an API key is not provided for a hosted NIM, a warning is issued. This will become an error in version 0.2.0. """ api_key = get_from_param_or_env( "api_key", nvidia_api_key or api_key, "NVIDIA_API_KEY", "NO_API_KEY_PROVIDED", ) base_url = base_url or BASE_URL super().__init__( api_key=api_key, api_base=base_url, max_tokens=max_tokens, default_headers={"User-Agent": "llama-index-llms-nvidia"}, **kwargs, ) self.model = model self._is_hosted = base_url in KNOWN_URLS or base_url == BASE_URL if self._is_hosted and api_key == "NO_API_KEY_PROVIDED": warnings.warn( "An API key is required for the hosted NIM. This will become an error in 0.2.0.", ) if not self.model: if self._is_hosted: self.model = DEFAULT_MODEL else: self.__get_default_model() if not self.model.startswith("nvdev/"): self._validate_model(self.model) ## validate model self.is_chat_model = self._is_chat_model() or self.is_chat_model self.is_function_calling_model = ( self._is_function_calling_model() or self.is_function_calling_model ) def __get_default_model(self): """Set default model.""" if not self._is_hosted: valid_models = [ model.id for model in self.available_models if not model.base_model or model.base_model == model.id ] self.model = next(iter(valid_models), None) if self.model: warnings.warn( f"Default model is set as: {self.model}. \n" "Set model using model parameter. \n" "To get available models use available_models property.", UserWarning, ) else: raise ValueError("No locally hosted model was found.") else: self.model = DEFAULT_MODEL def _validate_model(self, model_name: str) -> None: """ Validates compatibility of the hosted model with the client. Args: model_name (str): The name of the model. Raises: ValueError: If the model is incompatible with the client. """ if self._is_hosted: if model := determine_model(model_name): if not model.client: warnings.warn(f"Unable to determine validity of {model.id}") elif model.client != self.class_name(): raise ValueError( f"Model {model.id} is incompatible with client {self.class_name()}. " f"Please check `{self.class_name()}.get_available_models`" ) if model.endpoint: self.api_base = model.endpoint else: candidates = [ model for model in self.available_models if model.id == model_name ] assert len(candidates) <= 1, ( f"Multiple candidates for {model_name} " f"in `available_models`: {candidates}" ) if candidates: model = candidates[0] warnings.warn( f"Found {model_name} in available_models, but type is " "unknown and inference may fail." ) else: if model_name.startswith("nvdev/"): # assume valid model = Model(id=model_name) else: raise ValueError( f"Model {model_name} is unknown, check `available_models`" ) else: if model_name not in [model.id for model in self.available_models]: raise ValueError(f"No locally hosted {model_name} was found.") @property def available_models(self) -> List[Model]: models = [] for element in self._get_client().models.list().data: if not (model := determine_model(element.id)): model = Model(id=element.id) models.append(model) # only exclude models in hosted mode. in non-hosted mode, the administrator has control # over the model name and may deploy an excluded name that will work. if self._is_hosted: exclude = { "mistralai/mixtral-8x22b-v0.1", # not a /chat/completion endpoint } models = [model for model in models if model.id not in exclude] return models @classmethod def class_name(cls) -> str: return "NVIDIA" @deprecated( version="0.1.3", reason="Will be removed in 0.2. Construct with `base_url` instead.", ) def mode( self, mode: Optional[Literal["nvidia", "nim"]] = "nvidia", *, base_url: Optional[str] = None, model: Optional[str] = None, api_key: Optional[str] = None, ) -> "NVIDIA": """ Deprecated: use NVIDIA(base_url="...") instead. """ if mode == "nim": if not base_url: raise ValueError("base_url is required for nim mode") if mode == "nvidia": api_key = get_from_param_or_env( "api_key", api_key, "NVIDIA_API_KEY", ) base_url = base_url or BASE_URL self._mode = mode if base_url: self.api_base = base_url if model: self.model = model if api_key: self.api_key = api_key return self def _is_chat_model(self): model = determine_model(self.model) return model and model.id in CHAT_MODEL_TABLE def _is_function_calling_model(self): model = determine_model(self.model) return model and model.supports_tools def _prepare_chat_with_tools( self, tools: List["BaseTool"], user_msg: Optional[Union[str, ChatMessage]] = None, chat_history: Optional[List[ChatMessage]] = None, verbose: bool = False, allow_parallel_tool_calls: bool = False, **kwargs: Any, ) -> Dict[str, Any]: """Prepare the chat with tools.""" # misralai uses the same openai tool format tool_specs = [ tool.metadata.to_openai_tool(skip_length_check=True) for tool in tools ] if isinstance(user_msg, str): user_msg = ChatMessage(role=MessageRole.USER, content=user_msg) messages = chat_history or [] if user_msg: messages.append(user_msg) return { "messages": messages, "tools": tool_specs or None, **kwargs, } def get_tool_calls_from_response( self, response: "ChatResponse", error_on_no_tool_call: bool = True, ) -> List[ToolSelection]: """Predict and call the tool.""" tool_calls = response.message.additional_kwargs.get("tool_calls", []) if len(tool_calls) < 1: if error_on_no_tool_call: raise ValueError( f"Expected at least one tool call, but got {len(tool_calls)} tool calls." ) else: return [] tool_selections = [] for tool_call in tool_calls: # if not isinstance(tool_call, ToolCall): # raise ValueError("Invalid tool_call object") argument_dict = json.loads(tool_call.function.arguments) tool_selections.append( ToolSelection( tool_id=tool_call.id, tool_name=tool_call.function.name, tool_kwargs=argument_dict, ) ) return tool_selections
NVIDIA
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/modifies_run_env/package.py
{ "start": 217, "end": 658 }
class ____(Package): """Dependency package which needs to make shell modifications to run""" homepage = "http://www.example.com" url = "http://www.example.com/a-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") def setup_run_environment(self, env: EnvironmentModifications) -> None: env.set("DEPENDENCY_ENV_VAR", "1") def install(self, spec, prefix): mkdirp(prefix.bin)
ModifiesRunEnv
python
kamyu104__LeetCode-Solutions
Python/minimum-time-to-collect-all-apples-in-a-tree.py
{ "start": 1101, "end": 1901 }
class ____(object): def minTime(self, n, edges, hasApple): """ :type n: int :type edges: List[List[int]] :type hasApple: List[bool] :rtype: int """ def dfs(graph, par, node, hasApple): result, extra = 0, int(hasApple[node]) for nei in graph[node]: if nei == par: continue count, found = dfs(graph, node, nei, hasApple) result += count+found extra |= bool(count+found) return result, extra graph = collections.defaultdict(list) for u, v in edges: graph[u].append(v) graph[v].append(u) return 2*dfs(graph, -1, 0, hasApple)[0] # Time: O(n) # Space: O(n)
Solution_Recu
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/server.py
{ "start": 8191, "end": 13744 }
class ____: def __init__( self, loadable_target_origin: Optional[LoadableTargetOrigin], container_image: Optional[str], entry_point: Sequence[str], container_context: Optional[Mapping[str, Any]], defs_state_info: Optional[DefsStateInfo] = None, ): self._loadable_target_origin = loadable_target_origin self._code_pointers_by_repo_name: dict[str, CodePointer] = {} self._recon_repos_by_name: dict[str, ReconstructableRepository] = {} self._repo_defs_by_name: dict[str, RepositoryDefinition] = {} self._loadable_repository_symbols: list[LoadableRepositorySymbol] = [] self._container_context = container_context # Make sure we have a persistent load context before loading any repositories. DefinitionsLoadContext.set( DefinitionsLoadContext( DefinitionsLoadType.INITIALIZATION, repository_load_data=RepositoryLoadData( defs_state_info=defs_state_info, ), ) ) if not loadable_target_origin: # empty workspace return with enter_loadable_target_origin_load_context(loadable_target_origin): with user_code_error_boundary( DagsterUserCodeLoadError, lambda: "Error occurred during the loading of Dagster definitions in\n" + ", ".join( [ f"{k}={v}" for k, v in loadable_target_origin._asdict().items() if v is not None ] ), ): loadable_targets = get_loadable_targets( python_file=loadable_target_origin.python_file, module_name=loadable_target_origin.module_name, package_name=loadable_target_origin.package_name, working_directory=loadable_target_origin.working_directory, attribute=loadable_target_origin.attribute, autoload_defs_module_name=loadable_target_origin.autoload_defs_module_name, resolve_lazy_defs=True, ) for loadable_target in loadable_targets: pointer = _get_code_pointer(loadable_target_origin, loadable_target) recon_repo = ReconstructableRepository( pointer, container_image, executable_path=loadable_target_origin.executable_path or sys.executable, entry_point=entry_point, container_context=self._container_context, ) with user_code_error_boundary( DagsterUserCodeLoadError, lambda: "Error occurred during the loading of Dagster definitions in " + pointer.describe(), ): repo_def = recon_repo.get_definition() # force load of all lazy constructed code artifacts to prevent # any thread-safety issues loading them later on when serving # definitions from multiple threads repo_def.load_all_definitions() self._code_pointers_by_repo_name[repo_def.name] = pointer self._recon_repos_by_name[repo_def.name] = recon_repo self._repo_defs_by_name[repo_def.name] = repo_def self._loadable_repository_symbols.append( LoadableRepositorySymbol( attribute=loadable_target.attribute, repository_name=repo_def.name, ) ) @property def loadable_repository_symbols(self) -> Sequence[LoadableRepositorySymbol]: return self._loadable_repository_symbols @property def code_pointers_by_repo_name(self) -> Mapping[str, CodePointer]: return self._code_pointers_by_repo_name @property def definitions_by_name(self) -> Mapping[str, RepositoryDefinition]: return self._repo_defs_by_name @property def reconstructables_by_name(self) -> Mapping[str, ReconstructableRepository]: return self._recon_repos_by_name def _get_code_pointer( loadable_target_origin: LoadableTargetOrigin, loadable_repository_symbol: LoadableTarget, ) -> CodePointer: if loadable_target_origin.python_file: return CodePointer.from_python_file( loadable_target_origin.python_file, loadable_repository_symbol.attribute, loadable_target_origin.working_directory, ) elif loadable_target_origin.package_name: return CodePointer.from_python_package( loadable_target_origin.package_name, loadable_repository_symbol.attribute, loadable_target_origin.working_directory, ) elif loadable_target_origin.module_name: return CodePointer.from_module( loadable_target_origin.module_name, loadable_repository_symbol.attribute, loadable_target_origin.working_directory, ) elif loadable_target_origin.autoload_defs_module_name: return AutoloadDefsModuleCodePointer( module=loadable_target_origin.autoload_defs_module_name, working_directory=loadable_target_origin.working_directory, ) else: check.failed("Invalid loadable target origin")
LoadedRepositories
python
fastai__fastai
fastai/data/transforms.py
{ "start": 14252, "end": 15176 }
class ____(DisplayedTransform): "Transform that floatifies targets" loss_func=MSELossFlat() def __init__(self, c=None): store_attr() def encodes(self, o): return tensor(o).float() def decodes(self, o): return TitledFloat(o) if o.ndim==0 else TitledTuple(o_.item() for o_ in o) def setups(self, dsets): if self.c is not None: return try: self.c = len(dsets[0]) if hasattr(dsets[0], '__len__') else 1 except: self.c = 0 # %% ../../nbs/05_data.transforms.ipynb 96 def get_c(dls): if getattr(dls, 'c', False): return dls.c if nested_attr(dls, 'train.after_item.c', False): return dls.train.after_item.c if nested_attr(dls, 'train.after_batch.c', False): return dls.train.after_batch.c vocab = getattr(dls, 'vocab', []) if len(vocab) > 0 and is_listy(vocab[-1]): vocab = vocab[-1] return len(vocab) # %% ../../nbs/05_data.transforms.ipynb 109
RegressionSetup
python
spack__spack
var/spack/test_repos/spack_repo/builder_test/packages/old_style_derived/package.py
{ "start": 210, "end": 672 }
class ____(OldStyleAutotools): """Package used to verify that old-style packages work correctly when executing the installation procedure. """ homepage = "http://www.example.com" url = "http://www.example.com/a-1.0.tar.gz" version("2.0", md5="abcdef0123456789abcdef0123456789") version("1.0", md5="0123456789abcdef0123456789abcdef") def configure_args(self): return ["--with-bar"] + super().configure_args()
OldStyleDerived
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 130365, "end": 131250 }
class ____(Request): """ :param task: Task ID :type task: str """ _service = "events" _action = "get_vector_metrics_and_variants" _version = "2.20" _schema = { "definitions": {}, "properties": {"task": {"description": "Task ID", "type": "string"}}, "required": ["task"], "type": "object", } def __init__(self, task: str, **kwargs: Any) -> None: super(GetVectorMetricsAndVariantsRequest, self).__init__(**kwargs) self.task = task @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value
GetVectorMetricsAndVariantsRequest
python
aio-libs__aiohttp
tests/test_client_exceptions.py
{ "start": 8451, "end": 9632 }
class ____: def test_ctor(self) -> None: err = client.ServerFingerprintMismatch( expected=b"exp", got=b"got", host="example.com", port=8080 ) assert err.expected == b"exp" assert err.got == b"got" assert err.host == "example.com" assert err.port == 8080 def test_pickle(self) -> None: err = client.ServerFingerprintMismatch( expected=b"exp", got=b"got", host="example.com", port=8080 ) err.foo = "bar" # type: ignore[attr-defined] for proto in range(pickle.HIGHEST_PROTOCOL + 1): pickled = pickle.dumps(err, proto) err2 = pickle.loads(pickled) assert err2.expected == b"exp" assert err2.got == b"got" assert err2.host == "example.com" assert err2.port == 8080 assert err2.foo == "bar" def test_repr(self) -> None: err = client.ServerFingerprintMismatch(b"exp", b"got", "example.com", 8080) assert repr(err) == ( "<ServerFingerprintMismatch expected=b'exp' " "got=b'got' host='example.com' port=8080>" )
TestServerFingerprintMismatch
python
jazzband__django-oauth-toolkit
tests/test_rest_framework.py
{ "start": 2429, "end": 2584 }
class ____(BaseAuthentication): def authenticate(self, request): return ( "junk", "junk", )
MissingAuthentication
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE790.py
{ "start": 0, "end": 886 }
class ____: """buzz""" pass if foo: """foo""" pass def multi_statement() -> None: """This is a function.""" pass; print("hello") if foo: pass else: """bar""" pass while True: pass else: """bar""" pass for _ in range(10): pass else: """bar""" pass async for _ in range(10): pass else: """bar""" pass def foo() -> None: """ buzz """ pass async def foo(): """ buzz """ pass try: """ buzz """ pass except ValueError: pass try: bar() except ValueError: """bar""" pass for _ in range(10): """buzz""" pass async for _ in range(10): """buzz""" pass while cond: """buzz""" pass with bar: """buzz""" pass async with bar: """buzz""" pass def foo() -> None: """buzz""" pass # bar
Foo
python
PyCQA__pycodestyle
tests/test_blank_lines.py
{ "start": 183, "end": 462 }
class ____(unittest.TestCase): """ Common code for running blank_lines tests. """ def assertNoErrors(self, actual): """ Check that the actual result from the checker has no errors. """ self.assertEqual([], actual)
BlankLinesTestCase
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/client/utils.py
{ "start": 2535, "end": 2905 }
class ____(NamedTuple): """This class gives information about an InvalidOutputError from submitting a pipeline for execution from GraphQL. Args: step_key (str): key of the step that failed invalid_output_name (str): the name of the invalid output from the given step """ step_key: str invalid_output_name: str
InvalidOutputErrorInfo
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modular_phi4_multimodal.py
{ "start": 26895, "end": 29063 }
class ____(SiglipVisionEmbeddings): def __init__(self, config: Phi4MultimodalVisionConfig): nn.Module.__init__(self) self.config = config self.patch_size = config.patch_size self.num_patches_per_side = config.image_size // self.patch_size self.patch_embedding = nn.Conv2d( in_channels=config.num_channels, out_channels=config.hidden_size, kernel_size=self.patch_size, stride=self.patch_size, padding="valid", ) self.position_embedding = nn.Embedding(self.num_patches_per_side**2, config.hidden_size) def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor) -> torch.Tensor: batch_size = pixel_values.size(0) patch_embeds = self.patch_embedding(pixel_values) embeddings = patch_embeds.flatten(2).transpose(1, 2) max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3) max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side) position_ids = torch.full((batch_size, max_nb_patches_h * max_nb_patches_w), fill_value=0) for batch_idx, p_attn_mask in enumerate(patch_attention_mask): nb_patches_h = p_attn_mask[:, 0].sum() nb_patches_w = p_attn_mask[0].sum() fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h) fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w) bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True) bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True) pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten() position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids position_ids = position_ids.to(self.position_embedding.weight.device) embeddings = embeddings + self.position_embedding(position_ids) return embeddings
Phi4MultimodalVisionEmbeddings
python
tensorflow__tensorflow
tensorflow/python/debug/lib/profiling.py
{ "start": 2107, "end": 3595 }
class ____(object): """Profile summary data for aggregating a number of ProfileDatum.""" def __init__(self, profile_datum): """Constructor. Args: profile_datum: (`ProfileDatum`) an instance of `ProfileDatum` to initialize this object with. """ self.total_op_time = profile_datum.op_time self.total_exec_time = profile_datum.exec_time device_and_node = "%s:%s" % (profile_datum.device_name, profile_datum.node_exec_stats.node_name) self._node_to_exec_count = {device_and_node: 1} def add(self, profile_datum): """Accumulate a new instance of ProfileDatum. Args: profile_datum: (`ProfileDatum`) an instance of `ProfileDatum` to accumulate to this object. """ self.total_op_time += profile_datum.op_time self.total_exec_time += profile_datum.exec_time device_and_node = "%s:%s" % (profile_datum.device_name, profile_datum.node_exec_stats.node_name) device_and_node = "%s:%s" % (profile_datum.device_name, profile_datum.node_exec_stats.node_name) if device_and_node in self._node_to_exec_count: self._node_to_exec_count[device_and_node] += 1 else: self._node_to_exec_count[device_and_node] = 1 @property def node_count(self): return len(self._node_to_exec_count) @property def node_exec_count(self): return sum(self._node_to_exec_count.values())
AggregateProfile
python
hynek__structlog
tests/test_twisted.py
{ "start": 8373, "end": 8879 }
class ____: def test_isLogObserver(self, sio): """ PlainFileLogObserver is an ILogObserver. """ assert ILogObserver.providedBy(PlainFileLogObserver(sio)) def test_writesOnlyMessageWithLF(self, sio): """ PlainFileLogObserver writes only the message and a line feed. """ PlainFileLogObserver(sio)( {"system": "some system", "message": ("hello",)} ) assert "hello\n" == sio.getvalue()
TestPlainFileLogObserver
python
kamyu104__LeetCode-Solutions
Python/binary-search-tree-iterator.py
{ "start": 182, "end": 773 }
class ____(object): # @param root, a binary search tree's root node def __init__(self, root): self.__stk = [] self.__traversalLeft(root) # @return a boolean, whether we have a next smallest number def hasNext(self): return self.__stk # @return an integer, the next smallest number def next(self): node = self.__stk.pop() self.__traversalLeft(node.right) return node.val def __traversalLeft(self, node): while node is not None: self.__stk.append(node) node = node.left
BSTIterator
python
openai__gym
gym/wrappers/gray_scale_observation.py
{ "start": 122, "end": 2079 }
class ____(gym.ObservationWrapper): """Convert the image observation from RGB to gray scale. Example: >>> env = gym.make('CarRacing-v1') >>> env.observation_space Box(0, 255, (96, 96, 3), uint8) >>> env = GrayScaleObservation(gym.make('CarRacing-v1')) >>> env.observation_space Box(0, 255, (96, 96), uint8) >>> env = GrayScaleObservation(gym.make('CarRacing-v1'), keep_dim=True) >>> env.observation_space Box(0, 255, (96, 96, 1), uint8) """ def __init__(self, env: gym.Env, keep_dim: bool = False): """Convert the image observation from RGB to gray scale. Args: env (Env): The environment to apply the wrapper keep_dim (bool): If `True`, a singleton dimension will be added, i.e. observations are of the shape AxBx1. Otherwise, they are of shape AxB. """ super().__init__(env) self.keep_dim = keep_dim assert ( isinstance(self.observation_space, Box) and len(self.observation_space.shape) == 3 and self.observation_space.shape[-1] == 3 ) obs_shape = self.observation_space.shape[:2] if self.keep_dim: self.observation_space = Box( low=0, high=255, shape=(obs_shape[0], obs_shape[1], 1), dtype=np.uint8 ) else: self.observation_space = Box( low=0, high=255, shape=obs_shape, dtype=np.uint8 ) def observation(self, observation): """Converts the colour observation to greyscale. Args: observation: Color observations Returns: Grayscale observations """ import cv2 observation = cv2.cvtColor(observation, cv2.COLOR_RGB2GRAY) if self.keep_dim: observation = np.expand_dims(observation, -1) return observation
GrayScaleObservation
python
pyparsing__pyparsing
tests/test_diagram.py
{ "start": 1366, "end": 10397 }
class ____(unittest.TestCase): def get_temp(self): """ Returns an appropriate temporary file for writing a railroad diagram """ delete_on_close = not running_in_debug() return tempfile.NamedTemporaryFile( dir=".", delete=delete_on_close, mode="w", encoding="utf-8", suffix=".html", ) def generate_railroad( self, expr: pp.ParserElement, label: str, show_results_names: bool = False ) -> List[NamedDiagram]: """ Generate an intermediate list of NamedDiagrams from a pyparsing expression. """ with self.get_temp() as temp: railroad = to_railroad(expr, show_results_names=show_results_names) temp.write(railroad_to_html(railroad)) if running_in_debug(): print(f"{label}: {temp.name}") return railroad def test_example_rr_diags(self): subtests = [ ("jsonObject", jsonObject, 8), ("boolExpr", boolExpr, 6), ("simpleSQL", simpleSQL, 20), ("calendars", calendars, 13), ] for label, example_expr, expected_rr_len in subtests: with self.subTest(f"{label}: test rr diag without results names"): railroad = self.generate_railroad(example_expr, example_expr) if len(railroad) != expected_rr_len: diag_html = railroad_to_html(railroad) for line in diag_html.splitlines(): if 'h1 class="railroad-heading"' in line: print(line) assert ( len(railroad) == expected_rr_len ), f"expected {expected_rr_len}, got {len(railroad)}" with self.subTest(f"{label}: test rr diag with results names"): railroad = self.generate_railroad( example_expr, example_expr, show_results_names=True ) if len(railroad) != expected_rr_len: print(railroad_to_html(railroad)) assert ( len(railroad) == expected_rr_len ), f"expected {expected_rr_len}, got {len(railroad)}" def test_nested_forward_with_inner_and_outer_names(self): outer = pp.Forward().set_name("outer") inner = pp.Word(pp.alphas)[...].set_name("inner") outer <<= inner railroad = self.generate_railroad(outer, "inner_outer_names") assert len(railroad) == 2 railroad = self.generate_railroad( outer, "inner_outer_names", show_results_names=True ) assert len(railroad) == 2 def test_nested_forward_with_inner_name_only(self): outer = pp.Forward() inner = pp.Word(pp.alphas)[...].set_name("inner") outer <<= inner railroad = self.generate_railroad(outer, "inner_only") assert len(railroad) == 1 railroad = self.generate_railroad(outer, "inner_only", show_results_names=True) assert len(railroad) == 1 def test_each_grammar(self): grammar = pp.Each( [ pp.Word(pp.nums), pp.Word(pp.alphas), pp.pyparsing_common.uuid, ] ).set_name("int-word-uuid in any order") railroad = self.generate_railroad(grammar, "each_expression") assert len(railroad) == 2 railroad = self.generate_railroad( grammar, "each_expression", show_results_names=True ) assert len(railroad) == 2 def test_none_name(self): grammar = pp.Or(["foo", "bar"]) railroad = to_railroad(grammar) assert len(railroad) == 1 assert railroad[0].name is not None def test_none_name2(self): grammar = pp.Or(["foo", "bar"]) + pp.Word(pp.nums).set_name("integer") railroad = to_railroad(grammar) assert len(railroad) == 2 assert railroad[0].name is not None railroad = to_railroad(grammar, show_results_names=True) assert len(railroad) == 2 def test_complete_combine_element(self): ints = pp.Word(pp.nums) grammar = pp.Combine( ints("hours") + ":" + ints("minutes") + ":" + ints("seconds") ) railroad = to_railroad(grammar) assert len(railroad) == 1 railroad = to_railroad(grammar, show_results_names=True) assert len(railroad) == 1 def test_create_diagram(self): ints = pp.Word(pp.nums) grammar = pp.Combine( ints("hours") + ":" + ints("minutes") + ":" + ints("seconds") ) diag_strio = StringIO() grammar.create_diagram(output_html=diag_strio) diag_str = diag_strio.getvalue().lower() tags = "<html> </html> <head> </head> <body> </body>".split() assert all(tag in diag_str for tag in tags) def test_create_diagram_embed(self): ints = pp.Word(pp.nums) grammar = pp.Combine( ints("hours") + ":" + ints("minutes") + ":" + ints("seconds") ) diag_strio = StringIO() grammar.create_diagram(output_html=diag_strio, embed=True) diag_str = diag_strio.getvalue().lower() tags = "<html> </html> <head> </head> <body> </body>".split() assert not any(tag in diag_str for tag in tags) def test_create_diagram_for_oneormore_with_stopon(self): wd = pp.Word(pp.alphas) grammar = "start" + wd[1, ...:"end"] + "end" pp.autoname_elements() railroad_diag = to_railroad(grammar) assert len(railroad_diag) == 3 assert isinstance(railroad_diag[1].diagram.items[1].item, railroad.Sequence) assert isinstance( railroad_diag[1].diagram.items[1].item.items[0], AnnotatedItem ) assert isinstance( railroad_diag[1].diagram.items[1].item.items[1], railroad.NonTerminal ) def test_kwargs_pass_thru_create_diagram(self): from io import StringIO # Creates a simple diagram with a blue body and # various other railroad features colored with # a complete disregard for taste # Very simple grammar for demo purposes salutation = pp.Word(pp.alphas).set_name("salutation") subject = pp.rest_of_line.set_name("subject") parse_grammar = salutation + subject # This is used to turn off the railroads # definition of DEFAULT_STYLE. # If this is set to 'None' the default style # will be written as part of each diagram # and will you will not be able to set the # css style globally and the string 'expStyle' # will have no effect. # There is probably a PR to railroad_diagram to # remove some cruft left in the SVG. DEFAULT_STYLE = "" # CSS Code to be placed into head of the html file expStyle = """ <style type="text/css"> body { background-color: blue; } .railroad-heading { font-family: monospace; color: bisque; } svg.railroad-diagram { background-color: hsl(264,45%,85%); } svg.railroad-diagram path { stroke-width: 3; stroke: green; fill: rgba(0,0,0,0); } svg.railroad-diagram text { font: bold 14px monospace; text-anchor: middle; white-space: pre; } svg.railroad-diagram text.diagram-text { font-size: 12px; } svg.railroad-diagram text.diagram-arrow { font-size: 16px; } svg.railroad-diagram text.label { text-anchor: start; } svg.railroad-diagram text.comment { font: italic 12px monospace; } svg.railroad-diagram g.non-terminal text { /*font-style: italic;*/ } svg.railroad-diagram rect { stroke-width: 3; stroke: black; fill: hsl(55, 72%, 69%); } svg.railroad-diagram rect.group-box { stroke: rgb(33, 8, 225); stroke-dasharray: 10 5; fill: none; } svg.railroad-diagram path.diagram-text { stroke-width: 3; stroke: black; fill: white; cursor: help; } svg.railroad-diagram g.diagram-text:hover path.diagram-text { fill: #eee; } </style> """ # the 'css=DEFAULT_STYLE' or 'css=""' is needed to turn off railroad_diagrams styling diag_html_capture = StringIO() parse_grammar.create_diagram( diag_html_capture, vertical=6, show_results_names=True, css=DEFAULT_STYLE, head=expStyle, ) self.assertIn(expStyle, diag_html_capture.getvalue()) if __name__ == "__main__": unittest.main()
TestRailroadDiagrams
python
mlflow__mlflow
mlflow/projects/databricks.py
{ "start": 22005, "end": 24792 }
class ____(SubmittedRun): """ Instance of SubmittedRun corresponding to a Databricks Job run launched to run an MLflow project. Note that run_id may be None, e.g. if we did not launch the run against a tracking server accessible to the local client. Args: databricks_run_id: Run ID of the launched Databricks Job. mlflow_run_id: ID of the MLflow project run. databricks_job_runner: Instance of ``DatabricksJobRunner`` used to make Databricks API requests. """ # How often to poll run status when waiting on a run POLL_STATUS_INTERVAL = 30 def __init__(self, databricks_run_id, mlflow_run_id, databricks_job_runner): super().__init__() self._databricks_run_id = databricks_run_id self._mlflow_run_id = mlflow_run_id self._job_runner = databricks_job_runner def _print_description_and_log_tags(self): _logger.info( "=== Launched MLflow run as Databricks job run with ID %s." " Getting run status page URL... ===", self._databricks_run_id, ) run_info = self._job_runner.jobs_runs_get(self._databricks_run_id) jobs_page_url = run_info["run_page_url"] _logger.info("=== Check the run's status at %s ===", jobs_page_url) host_creds = databricks_utils.get_databricks_host_creds( self._job_runner.databricks_profile_uri ) tracking.MlflowClient().set_tag( self._mlflow_run_id, MLFLOW_DATABRICKS_RUN_URL, jobs_page_url ) tracking.MlflowClient().set_tag( self._mlflow_run_id, MLFLOW_DATABRICKS_SHELL_JOB_RUN_ID, self._databricks_run_id ) tracking.MlflowClient().set_tag( self._mlflow_run_id, MLFLOW_DATABRICKS_WEBAPP_URL, host_creds.host ) job_id = run_info.get("job_id") # In some releases of Databricks we do not return the job ID. We start including it in DB # releases 2.80 and above. if job_id is not None: tracking.MlflowClient().set_tag( self._mlflow_run_id, MLFLOW_DATABRICKS_SHELL_JOB_ID, job_id ) @property def run_id(self): return self._mlflow_run_id def wait(self): result_state = self._job_runner.get_run_result_state(self._databricks_run_id) while result_state is None: time.sleep(self.POLL_STATUS_INTERVAL) result_state = self._job_runner.get_run_result_state(self._databricks_run_id) return result_state == "SUCCESS" def cancel(self): self._job_runner.jobs_runs_cancel(self._databricks_run_id) self.wait() def get_status(self): return self._job_runner.get_status(self._databricks_run_id)
DatabricksSubmittedRun
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 45550, "end": 49906 }
class ____(Operation): def __init__( self, strides=1, padding="valid", output_padding=None, data_format=None, dilation_rate=1, *, name=None, ): super().__init__(name=name) self.strides = strides self.output_padding = output_padding self.padding = padding.lower() self.data_format = data_format self.dilation_rate = dilation_rate def call( self, inputs, kernel, ): return backend.nn.conv_transpose( inputs, kernel, self.strides, self.output_padding, self.padding, self.data_format, self.dilation_rate, ) def compute_output_spec(self, inputs, kernel): kernel_size = kernel.shape[:-2] filters = kernel.shape[-2] output_shape = compute_conv_transpose_output_shape( inputs.shape, kernel_size, filters, self.strides, self.padding, self.output_padding, self.data_format, self.dilation_rate, ) return KerasTensor(output_shape, dtype=inputs.dtype) @keras_export( [ "keras.ops.conv_transpose", "keras.ops.nn.conv_transpose", ] ) def conv_transpose( inputs, kernel, strides=1, padding="valid", output_padding=None, data_format=None, dilation_rate=1, ): """General N-D convolution transpose. Also known as de-convolution. This ops supports 1D, 2D and 3D convolution. Args: inputs: Tensor of rank N+2. `inputs` has shape `(batch_size,) + inputs_spatial_shape + (num_channels,)` if `data_format="channels_last"`, or `(batch_size, num_channels) + inputs_spatial_shape` if `data_format="channels_first"`. kernel: Tensor of rank N+2. `kernel` has shape [kernel_spatial_shape, num_output_channels, num_input_channels], `num_input_channels` should match the number of channels in `inputs`. strides: int or int tuple/list of `len(inputs_spatial_shape)`, specifying the strides of the convolution along each spatial dimension. If `strides` is int, then every spatial dimension shares the same `strides`. padding: string, either `"valid"` or `"same"`. `"valid"` means no padding is applied, and `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input when `strides=1`. output_padding: int or int tuple/list of `len(inputs_spatial_shape)`, specifying the amount of padding along the height and width of the output tensor. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to `None` (default), the output shape is inferred. data_format: A string, either `"channels_last"` or `"channels_first"`. `data_format` determines the ordering of the dimensions in the inputs. If `data_format="channels_last"`, `inputs` is of shape `(batch_size, ..., channels)` while if `data_format="channels_first"`, `inputs` is of shape `(batch_size, channels, ...)`. dilation_rate: int or int tuple/list of `len(inputs_spatial_shape)`, specifying the dilation rate to use for dilated convolution. If `dilation_rate` is int, then every spatial dimension shares the same `dilation_rate`. Returns: A tensor of rank N+2, the result of the conv operation. """ data_format = standardize_data_format(data_format) padding = padding.lower() if any_symbolic_tensors((inputs,)): return ConvTranspose( strides, padding, output_padding, data_format, dilation_rate ).symbolic_call(inputs, kernel) return backend.nn.conv_transpose( inputs, kernel, strides, padding, output_padding, data_format, dilation_rate, )
ConvTranspose
python
PyCQA__pylint
pylint/testutils/_primer/package_to_lint.py
{ "start": 882, "end": 4741 }
class ____: """Represents data about a package to be tested during primer tests.""" url: str """URL of the repository to clone.""" branch: str """Branch of the repository to clone.""" directories: list[str] """Directories within the repository to run pylint over.""" commit: str | None = None """Commit hash to pin the repository on.""" pylint_additional_args: list[str] = field(default_factory=list) """Arguments to give to pylint.""" pylintrc_relpath: str | None = None """Path relative to project's main directory to the pylintrc if it exists.""" minimum_python: str | None = None """Minimum python version supported by the package.""" @property def pylintrc(self) -> Path | Literal[""]: if self.pylintrc_relpath is None: # Fall back to "" to ensure pylint's own pylintrc is not discovered return "" return self.clone_directory / self.pylintrc_relpath @property def clone_name(self) -> str: """Extract repository name from URL.""" return "/".join(self.url.split("/")[-2:]).replace(".git", "") @property def clone_directory(self) -> Path: """Directory to clone repository into.""" return PRIMER_DIRECTORY_PATH / self.clone_name @property def paths_to_lint(self) -> list[str]: """The paths we need to lint.""" return [str(self.clone_directory / path) for path in self.directories] @property def pylint_args(self) -> list[str]: options: list[str] = [] # There is an error if rcfile is given but does not exist options += [f"--rcfile={self.pylintrc}"] return self.paths_to_lint + options + self.pylint_additional_args def lazy_clone(self) -> str: # pragma: no cover """Concatenates the target directory and clones the file. Not expected to be tested as the primer won't work if it doesn't. It's tested in the continuous integration primers, only the coverage is not calculated on everything. If lazy clone breaks for local use we'll probably notice because we'll have a fatal when launching the primer locally. """ logging.info("Lazy cloning %s", self.url) if not self.clone_directory.exists(): return self._clone_repository() return self._pull_repository() def _clone_repository(self) -> str: options: dict[str, str | int] = { "url": self.url, "to_path": str(self.clone_directory), "branch": self.branch, "depth": 1, } logging.info("Directory does not exists, cloning: %s", options) repo = Repo.clone_from( url=self.url, to_path=self.clone_directory, branch=self.branch, depth=1 ) return str(repo.head.object.hexsha) def _pull_repository(self) -> str: remote_sha1_commit = Git().ls_remote(self.url, self.branch).split("\t")[0] local_sha1_commit = Repo(self.clone_directory).head.object.hexsha if remote_sha1_commit != local_sha1_commit: logging.info( "Remote sha is '%s' while local sha is '%s': pulling new commits", remote_sha1_commit, local_sha1_commit, ) try: repo = Repo(self.clone_directory) if repo.is_dirty(): raise DirtyPrimerDirectoryException(self.clone_directory) origin = repo.remotes.origin origin.pull() except GitCommandError as e: raise SystemError( f"Failed to clone repository for {self.clone_directory}" ) from e else: logging.info("Repository already up to date.") return str(remote_sha1_commit)
PackageToLint
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/random/random_ops_test.py
{ "start": 17383, "end": 18887 }
class ____(test.TestCase): def setUp(self): super().setUp() random_seed.set_random_seed(None) config.enable_op_determinism() def tearDown(self): super().tearDown() config.disable_op_determinism() def testDeterministicOpsErrors(self): with self.assertRaisesRegex( RuntimeError, "Random ops require a seed to be set when determinism is enabled."): random_ops.random_normal((1,)) with self.assertRaisesRegex( RuntimeError, "Random ops require a seed to be set when determinism is enabled."): random_ops.truncated_normal((1,)) with self.assertRaisesRegex( RuntimeError, "Random ops require a seed to be set when determinism is enabled."): random_ops.random_uniform((1,)) with self.assertRaisesRegex( errors.InvalidArgumentError, "When determinism is enabled, random ops must have a seed specified"): self.evaluate(gen_random_ops.random_standard_normal((1,), dtypes.float32)) def testErrorNotThrownWithSeed(self): random_ops.random_normal((1,), seed=0) random_seed.set_random_seed(0) random_ops.random_normal((1,)) self.evaluate(gen_random_ops.random_standard_normal((1,), dtypes.float32, seed=1)) self.evaluate(gen_random_ops.random_standard_normal((1,), dtypes.float32, seed2=1)) if __name__ == "__main__": test.main()
DeterministicOpsTest
python
getsentry__sentry
src/sentry/sentry_apps/api/endpoints/group_external_issues.py
{ "start": 863, "end": 1968 }
class ____(GroupEndpoint): owner = ApiOwner.ECOSYSTEM publish_status = { "GET": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="Retrieve custom integration issue links for the given Sentry issue", parameters=[ GlobalParams.ORG_ID_OR_SLUG, IssueParams.ISSUES_OR_GROUPS, IssueParams.ISSUE_ID, ], responses={ 200: inline_sentry_response_serializer( "GroupExternalIssueResponse", list[PlatformExternalIssueSerializerResponse] ), }, examples=SentryAppExamples.GET_PLATFORM_EXTERNAL_ISSUE, ) def get(self, request: Request, group) -> Response: """ Retrieve custom integration issue links for the given Sentry issue """ external_issues = PlatformExternalIssue.objects.filter(group_id=group.id) return self.paginate( request=request, queryset=external_issues, order_by="id", on_results=lambda x: serialize(x, request.user), )
GroupExternalIssuesEndpoint
python
getsentry__sentry
src/sentry/utils/not_set.py
{ "start": 93, "end": 720 }
class ____(Enum): TOKEN = auto() NOT_SET = NotSet.TOKEN T = TypeVar("T") def default_if_not_set(default: T, value: T | NotSet) -> T: """ Used for optionally passing parameters to a function, and defaulting to some value if not passed. This is useful for updating fields on a model, since we can't set those defaults on the function level. Example usage: def my_updater(my_model: SomeModel, val_a: str | NotSet = NOT_SET): my_model.some_field = default_if_not_set(my_model.some_field, val_a) my_model.save() """ if value is NOT_SET: return default return value
NotSet
python
plotly__plotly.py
plotly/graph_objs/_deprecations.py
{ "start": 16056, "end": 16885 }
class ____(dict): """ plotly.graph_objs.YAxis is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.layout.YAxis - plotly.graph_objs.layout.scene.YAxis """ def __init__(self, *args, **kwargs): """ plotly.graph_objs.YAxis is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.layout.YAxis - plotly.graph_objs.layout.scene.YAxis """ warnings.warn( """plotly.graph_objs.YAxis is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.layout.YAxis - plotly.graph_objs.layout.scene.YAxis """, DeprecationWarning, ) super().__init__(*args, **kwargs)
YAxis
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType17.py
{ "start": 256, "end": 542 }
class ____(Generic[A, B]): _dict: dict[A, B] _pair: "X[B, A]" def method(self, a: A, b: B) -> None: self._pair._dict[b] x = X[int, str]() x._pair._dict["foo"] reveal_type(x._pair, expected_text="X[str, int]") reveal_type(x._pair._pair, expected_text="X[int, str]")
X
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/models.py
{ "start": 362, "end": 556 }
class ____: def __init__(self, start: int, end: int): self.start = start self.end = end def __repr__(self) -> str: return f"{self.start} - {self.end}"
SectionLines
python
pytorch__pytorch
torch/_guards.py
{ "start": 15780, "end": 16441 }
class ____(GuardEnvExpr): overlapping_sources: list[Source] non_overlapping_sources: list[Source] """ Checkpointable is an interface for driving state snapshotting, left purposely vague for now. copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that can also be taken in at restore_graphstate(T) calls. When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable does not provide any guarantees around consistency, idempotency, or safety of calling its APIs, yet. In the future, it will have a closer coupling to a generic Checkpoint management system. """
StorageOverlap
python
sqlalchemy__sqlalchemy
test/orm/test_cascade.py
{ "start": 107686, "end": 114513 }
class ____(fixtures.MappedTest): """test that O2M dependency detects a change in parent, does the right thing, and updates the collection/attribute. """ @classmethod def define_tables(cls, metadata): Table( "parent", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), ) Table( "child", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column( "parent_id", Integer, ForeignKey("parent.id"), nullable=False ), ) @classmethod def setup_classes(cls): class Parent(cls.Comparable): pass class Child(cls.Comparable): pass def _do_move_test(self, delete_old): Parent, Child = self.classes.Parent, self.classes.Child with fixture_session(autoflush=False) as sess: p1, p2, c1 = Parent(), Parent(), Child() if Parent.child.property.uselist: p1.child.append(c1) else: p1.child = c1 sess.add_all([p1, c1]) sess.flush() if delete_old: sess.delete(p1) if Parent.child.property.uselist: p2.child.append(c1) else: p2.child = c1 sess.add(p2) sess.flush() eq_(sess.query(Child).filter(Child.parent_id == p2.id).all(), [c1]) def test_o2o_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively( Parent, parent, properties={"child": relationship(Child, uselist=False)}, ) self.mapper_registry.map_imperatively(Child, child) self._do_move_test(True) self._do_move_test(False) def test_o2m_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively( Parent, parent, properties={"child": relationship(Child, uselist=True)}, ) self.mapper_registry.map_imperatively(Child, child) self._do_move_test(True) self._do_move_test(False) def test_o2o_backref_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively( Parent, parent, properties={ "child": relationship( Child, uselist=False, backref=backref( "parent", ), ) }, ) self.mapper_registry.map_imperatively(Child, child) self._do_move_test(True) self._do_move_test(False) def test_o2o_delcascade_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively( Parent, parent, properties={ "child": relationship( Child, uselist=False, cascade="all, delete" ) }, ) self.mapper_registry.map_imperatively(Child, child) self._do_move_test(True) self._do_move_test(False) def test_o2o_delorphan_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively( Parent, parent, properties={ "child": relationship( Child, uselist=False, cascade="all, delete, delete-orphan" ) }, ) self.mapper_registry.map_imperatively(Child, child) self._do_move_test(True) self._do_move_test(False) def test_o2o_delorphan_backref_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively( Parent, parent, properties={ "child": relationship( Child, uselist=False, cascade="all, delete, delete-orphan", backref=backref("parent"), ) }, ) self.mapper_registry.map_imperatively(Child, child) self._do_move_test(True) self._do_move_test(False) def test_o2o_backref_delorphan_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively(Parent, parent) self.mapper_registry.map_imperatively( Child, child, properties={ "parent": relationship( Parent, uselist=False, single_parent=True, backref=backref("child", uselist=False), cascade="all,delete,delete-orphan", ) }, ) self._do_move_test(True) self._do_move_test(False) def test_o2m_backref_delorphan_delete_old(self): Child, Parent, parent, child = ( self.classes.Child, self.classes.Parent, self.tables.parent, self.tables.child, ) self.mapper_registry.map_imperatively(Parent, parent) self.mapper_registry.map_imperatively( Child, child, properties={ "parent": relationship( Parent, uselist=False, single_parent=True, backref=backref("child", uselist=True), cascade="all,delete,delete-orphan", ) }, ) self._do_move_test(True) self._do_move_test(False)
O2MConflictTest
python
Lightning-AI__lightning
src/lightning/pytorch/demos/boring_classes.py
{ "start": 4722, "end": 5846 }
class ____(LightningDataModule): """ .. warning:: This is meant for testing/debugging and is experimental. """ def __init__(self) -> None: super().__init__() self.random_full = RandomDataset(32, 64 * 4) def setup(self, stage: str) -> None: if stage == "fit": self.random_train = Subset(self.random_full, indices=range(64)) if stage in ("fit", "validate"): self.random_val = Subset(self.random_full, indices=range(64, 64 * 2)) if stage == "test": self.random_test = Subset(self.random_full, indices=range(64 * 2, 64 * 3)) if stage == "predict": self.random_predict = Subset(self.random_full, indices=range(64 * 3, 64 * 4)) def train_dataloader(self) -> DataLoader: return DataLoader(self.random_train) def val_dataloader(self) -> DataLoader: return DataLoader(self.random_val) def test_dataloader(self) -> DataLoader: return DataLoader(self.random_test) def predict_dataloader(self) -> DataLoader: return DataLoader(self.random_predict)
BoringDataModule
python
spyder-ide__spyder
spyder/app/restart.py
{ "start": 2319, "end": 10482 }
class ____(QWidget): """Widget in charge of displaying the splash information screen and the error messages. """ def __init__(self): super().__init__() self.ellipsis = ['', '.', '..', '...', '..', '.'] # Widgets self.timer_ellipsis = QTimer(self) self.splash = create_splash_screen(use_previous_factor=True) # Widget setup self.setVisible(False) self.splash.show() self.timer_ellipsis.timeout.connect(self.animate_ellipsis) def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage(text, int(Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute), QColor(Qt.white)) def animate_ellipsis(self): """Animate dots at the end of the splash screen message.""" ellipsis = self.ellipsis.pop(0) text = ' ' * len(ellipsis) + self.splash_text + ellipsis self.ellipsis.append(ellipsis) self._show_message(text) def set_splash_message(self, text): """Sets the text in the bottom of the Splash screen.""" self.splash_text = text self._show_message(text) self.timer_ellipsis.start(500) # Wait 1.2 seconds so we can give feedback to users that a # restart is happening. for __ in range(40): time.sleep(0.03) QApplication.processEvents() def launch_error_message(self, error_type, error=None): """Launch a message box with a predefined error message. Parameters ---------- error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR] Possible error codes when restarting/resetting spyder. error : Exception Actual Python exception error caught. """ messages = {CLOSE_ERROR: _("It was not possible to close the previous " "Spyder instance.\nRestart aborted."), RESET_ERROR: _("Spyder could not reset to factory " "defaults.\nRestart aborted."), RESTART_ERROR: _("It was not possible to restart Spyder.\n" "Operation aborted.")} titles = {CLOSE_ERROR: _("Spyder exit error"), RESET_ERROR: _("Spyder reset error"), RESTART_ERROR: _("Spyder restart error")} if error: e = error.__repr__() message = messages[error_type] + "\n\n{0}".format(e) else: message = messages[error_type] title = titles[error_type] self.splash.hide() QMessageBox.warning(self, title, message, QMessageBox.Ok) raise RuntimeError(message) def main(): #========================================================================== # Proper high DPI scaling is available in Qt >= 5.6.0. This attribute must # be set before creating the application. #========================================================================== env = os.environ.copy() if CONF.get('main', 'high_dpi_custom_scale_factor'): factors = str(CONF.get('main', 'high_dpi_custom_scale_factors')) f = list(filter(None, factors.split(';'))) if len(f) == 1: env['QT_SCALE_FACTOR'] = f[0] else: env['QT_SCREEN_SCALE_FACTORS'] = factors else: env['QT_SCALE_FACTOR'] = '' env['QT_SCREEN_SCALE_FACTORS'] = '' # Splash screen # ------------------------------------------------------------------------- # Start Qt Splash to inform the user of the current status app = qapplication() app.set_font() restarter = Restarter() APP_ICON = QIcon(get_image_path("spyder")) app.setWindowIcon(APP_ICON) restarter.set_splash_message(_('Closing Spyder')) # Get variables spyder_args = env.pop('SPYDER_ARGS', None) pid = env.pop('SPYDER_PID', None) is_bootstrap = env.pop('SPYDER_IS_BOOTSTRAP', None) reset = env.pop('SPYDER_RESET', 'False') # Get the spyder base folder based on this file spyder_dir = osp.dirname(osp.dirname(osp.dirname(osp.abspath(__file__)))) if not any([spyder_args, pid, is_bootstrap, reset]): error = "This script can only be called from within a Spyder instance" raise RuntimeError(error) # Variables were stored as string literals in the environment, so to use # them we need to parse them in a safe manner. is_bootstrap = ast.literal_eval(is_bootstrap) pid = ast.literal_eval(pid) args = ast.literal_eval(spyder_args) reset = ast.literal_eval(reset) # SPYDER_DEBUG takes presedence over SPYDER_ARGS if '--debug' in args: args.remove('--debug') for level in ['minimal', 'verbose']: arg = f'--debug-info={level}' if arg in args: args.remove(arg) # Enforce the --new-instance flag when running spyder if '--new-instance' not in args: if is_bootstrap and '--' not in args: args = args + ['--', '--new-instance'] else: args.append('--new-instance') # Create the arguments needed for resetting if '--' in args: args_reset = ['--', '--reset'] else: args_reset = ['--reset'] # Build the base command if is_bootstrap: script = osp.join(spyder_dir, 'bootstrap.py') else: script = osp.join(spyder_dir, 'spyder', 'app', 'start.py') command = [f'"{SHORTCUT_EXE or sys.executable}"', f'"{script}"'] # Adjust the command and/or arguments to subprocess depending on the OS shell = not IS_WINDOWS # Before launching a new Spyder instance we need to make sure that the # previous one has closed. We wait for a fixed and "reasonable" amount of # time and check, otherwise an error is launched wait_time = 90 if IS_WINDOWS else 30 # Seconds for counter in range(int(wait_time / SLEEP_TIME)): if not is_pid_running(pid): break time.sleep(SLEEP_TIME) # Throttling control QApplication.processEvents() # Needed to refresh the splash else: # The old spyder instance took too long to close and restart aborts restarter.launch_error_message(error_type=CLOSE_ERROR) # Reset Spyder (if required) # ------------------------------------------------------------------------- if reset: restarter.set_splash_message(_('Resetting Spyder to defaults')) try: p = subprocess.Popen(' '.join(command + args_reset), shell=shell, env=env) except Exception as error: restarter.launch_error_message(error_type=RESET_ERROR, error=error) else: p.communicate() pid_reset = p.pid # Before launching a new Spyder instance we need to make sure that the # reset subprocess has closed. We wait for a fixed and "reasonable" # amount of time and check, otherwise an error is launched. wait_time = 20 # Seconds for counter in range(int(wait_time / SLEEP_TIME)): if not is_pid_running(pid_reset): break time.sleep(SLEEP_TIME) # Throttling control QApplication.processEvents() # Needed to refresh the splash else: # The reset subprocess took too long and it is killed try: p.kill() except OSError as error: restarter.launch_error_message(error_type=RESET_ERROR, error=error) else: restarter.launch_error_message(error_type=RESET_ERROR) # Restart # ------------------------------------------------------------------------- restarter.set_splash_message(_('Restarting')) try: subprocess.Popen(' '.join(command + args), shell=shell, env=env) except Exception as error: restarter.launch_error_message(error_type=RESTART_ERROR, error=error) if __name__ == '__main__': main()
Restarter
python
pytorch__pytorch
benchmarks/gpt_fast/model.py
{ "start": 313, "end": 2498 }
class ____: block_size: int = 2048 vocab_size: int = 32000 n_layer: int = 32 n_head: int = 32 dim: int = 4096 intermediate_size: int = None n_local_heads: int = -1 head_dim: int = 64 rope_base: float = 10000 norm_eps: float = 1e-5 def __post_init__(self): if self.n_local_heads == -1: self.n_local_heads = self.n_head if self.intermediate_size is None: hidden_dim = 4 * self.dim n_hidden = int(2 * hidden_dim / 3) self.intermediate_size = find_multiple(n_hidden, 256) self.head_dim = self.dim // self.n_head @classmethod def from_name(cls, name: str): if name in transformer_configs: return cls(**transformer_configs[name]) # fuzzy search config = [ config for config in transformer_configs if config in str(name).upper() or config in str(name) ] # We may have two or more configs matched (e.g. "7B" and "Mistral-7B"). Find the best config match, # take longer name (as it have more symbols matched) if len(config) > 1: config.sort(key=len, reverse=True) assert len(config[0]) != len(config[1]), ( name ) # make sure only one 'best' match return cls(**transformer_configs[config[0]]) transformer_configs = { "CodeLlama-7b-Python-hf": dict( block_size=16384, vocab_size=32000, n_layer=32, dim=4096, rope_base=1000000 ), "7B": dict(n_layer=32, n_head=32, dim=4096), "13B": dict(n_layer=40, n_head=40, dim=5120), "30B": dict(n_layer=60, n_head=52, dim=6656), "34B": dict( n_layer=48, n_head=64, dim=8192, vocab_size=32000, n_local_heads=8, intermediate_size=22016, rope_base=1000000, ), # CodeLlama-34B-Python-hf "70B": dict( n_layer=80, n_head=64, dim=8192, n_local_heads=8, intermediate_size=28672 ), "Mistral-7B": dict( n_layer=32, n_head=32, n_local_heads=8, dim=4096, intermediate_size=14336, vocab_size=32000, ), }
ModelArgs
python
tornadoweb__tornado
tornado/test/http1connection_test.py
{ "start": 333, "end": 1964 }
class ____(AsyncTestCase): code = None # type: typing.Optional[int] def setUp(self): super().setUp() self.asyncSetUp() @gen_test def asyncSetUp(self): listener, port = bind_unused_port() event = Event() def accept_callback(conn, addr): self.server_stream = IOStream(conn) self.addCleanup(self.server_stream.close) event.set() add_accept_handler(listener, accept_callback) self.client_stream = IOStream(socket.socket()) self.addCleanup(self.client_stream.close) yield [self.client_stream.connect(("127.0.0.1", port)), event.wait()] self.io_loop.remove_handler(listener) listener.close() @gen_test def test_http10_no_content_length(self): # Regression test for a bug in which can_keep_alive would crash # for an HTTP/1.0 (not 1.1) response with no content-length. conn = HTTP1Connection(self.client_stream, True) self.server_stream.write(b"HTTP/1.0 200 Not Modified\r\n\r\nhello") self.server_stream.close() event = Event() test = self body = [] class Delegate(HTTPMessageDelegate): def headers_received(self, start_line, headers): test.code = start_line.code def data_received(self, data): body.append(data) def finish(self): event.set() yield conn.read_response(Delegate()) yield event.wait() self.assertEqual(self.code, 200) self.assertEqual(b"".join(body), b"hello")
HTTP1ConnectionTest
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_us_zipcode_within_mile_radius_of_given_zipcode.py
{ "start": 3253, "end": 12783 }
class ____(ColumnMapExpectation): """Expect column values to be US zip codes within a specified number of miles of a given zipcode.""" # These examples will be shown in the public gallery, and also executed as unit tests for your Expectation examples = [ { "data": { "all_zip_codes_within_15mi_radius_of_60201": [ 60202, 60203, 60076, 60091, 60043, 60093, 60201, None, None, None, None, ], "all_zip_codes_within_20mi_radius_of_30338": [ 30360, 30350, 30328, 30346, 30319, 30342, 30341, None, None, None, None, ], "all_zip_codes_within_50mi_radius_of_92130": [ 91911, 92029, 92071, 92091, 92101, 92102, 92109, 92111, 92131, 92140, None, ], }, "tests": [ { "title": "positive_test_with_all_zipcodes_in_15mi_radius_of_60201", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "all_zip_codes_within_15mi_radius_of_60201", "mostly": 1.0, "central_zip": 60201, "radius_in_miles": 15, }, "out": { "success": True, "unexpected_index_list": [], "unexpected_list": [], }, }, { "title": "positive_test_with_all_zipcodes_in_20mi_radius_of_30338", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "all_zip_codes_within_20mi_radius_of_30338", "mostly": 1.0, "central_zip": 30338, "radius_in_miles": 20, }, "out": { "success": True, "unexpected_index_list": [], "unexpected_list": [], }, }, { "title": "negative_test_with_all_zipcodes_in_20mi_radius_of_30338", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "all_zip_codes_within_20mi_radius_of_30338", "mostly": 1.0, "central_zip": 37409, "radius_in_miles": 20, }, "out": { "success": False, "unexpected_index_list": [0, 1, 2, 3, 4, 5, 6], "unexpected_list": [ 30360, 30350, 30328, 30346, 30319, 30342, 30341, ], }, }, { "title": "positive_test_with_all_zipcodes_in_25mi_radius_of_92130", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "all_zip_codes_within_50mi_radius_of_92130", "mostly": 1.0, "central_zip": 92130, "radius_in_miles": 50, }, "out": { "success": True, "unexpected_index_list": [], "unexpected_list": [], }, }, { "title": "negative_test_with_some_zipcodes_in_5mi_radius_of_30338", "exact_match_out": False, "include_in_gallery": True, "in": { "column": "all_zip_codes_within_20mi_radius_of_30338", "mostly": 1.0, "central_zip": 30338, "radius_in_miles": 5, }, "out": { "success": False, }, }, ], } ] # This dictionary contains metadata for display in the public gallery library_metadata = { "tags": [ "experimental", "hackathon-20200123", ], # Tags for this Expectation in the gallery "contributors": [ # Github handles for all contributors to this Expectation. "@sethdmay", "@maximetokman", "@talagluck", "@mmi333", ], "requirements": ["uszipcode", "sqlalchemy"], } # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.us_zipcode_within_radius_of_given_zipcode" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False # Please see {some doc} for more information about domain and success keys, and other arguments to Expectations success_keys = ("mostly", "central_zip", "radius_in_miles") # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This method defines a question Renderer # For more info on Renderers, see {some doc} # !!! This example renderer should render RenderedStringTemplateContent, not just a string # @classmethod # @renderer(renderer_type="renderer.question") # def _question_renderer( # cls, configuration, result=None, runtime_configuration=None # ): # column = configuration.kwargs.get("column") # mostly = configuration.kwargs.get("mostly") # return f'Do at least {mostly * 100}% of values in column "{column}" equal 3?' # This method defines an answer Renderer # !!! This example renderer should render RenderedStringTemplateContent, not just a string # @classmethod # @renderer(renderer_type="renderer.answer") # def _answer_renderer( # cls, configuration=None, result=None, runtime_configuration=None # ): # column = result.expectation_config.kwargs.get("column") # mostly = result.expectation_config.kwargs.get("mostly") # regex = result.expectation_config.kwargs.get("regex") # if result.success: # return f'At least {mostly * 100}% of values in column "{column}" equal 3.' # else: # return f'Less than {mostly * 100}% of values in column "{column}" equal 3.' # This method defines a prescriptive Renderer @classmethod @renderer(renderer_type="renderer.prescriptive") @render_suite_parameter_string def _prescriptive_renderer( cls, configuration: Optional[ExpectationConfiguration] = None, result: Optional[ExpectationValidationResult] = None, runtime_configuration: Optional[dict] = None, **kwargs, ): runtime_configuration = runtime_configuration or {} include_column_name = runtime_configuration.get("include_column_name") is not False styling = runtime_configuration.get("styling") params = substitute_none_for_missing( configuration.kwargs, ["column", "central_zip", "radius_in_miles", "mostly"], ) template_str = "values must be US zip code within $radius_in_miles miles of $central_zip" if params["mostly"] is not None: params["mostly_pct"] = num_to_str( params["mostly"] * 100, precision=15, no_scientific=True ) # params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") template_str += ", at least $mostly_pct % of the time." else: template_str += "." if include_column_name: template_str = "$column " + template_str return [ RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": template_str, "params": params, "styling": styling, }, } ) ] if __name__ == "__main__": ExpectColumnValuesToBeUSZipcodeWithinMileRadiusOfGivenZipcode().print_diagnostic_checklist()
ExpectColumnValuesToBeUSZipcodeWithinMileRadiusOfGivenZipcode
python
sqlalchemy__sqlalchemy
test/dialect/sqlite/test_dialect.py
{ "start": 26439, "end": 28590 }
class ____(fixtures.TestBase, AssertsCompiledSQL): def test_sqlite_autoincrement(self): table = Table( "autoinctable", MetaData(), Column("id", Integer, primary_key=True), Column("x", Integer, default=None), sqlite_autoincrement=True, ) self.assert_compile( schema.CreateTable(table), "CREATE TABLE autoinctable (id INTEGER NOT " "NULL PRIMARY KEY AUTOINCREMENT, x INTEGER)", dialect=sqlite.dialect(), ) def test_sqlite_autoincrement_constraint(self): table = Table( "autoinctable", MetaData(), Column("id", Integer, primary_key=True), Column("x", Integer, default=None), UniqueConstraint("x"), sqlite_autoincrement=True, ) self.assert_compile( schema.CreateTable(table), "CREATE TABLE autoinctable (id INTEGER NOT " "NULL PRIMARY KEY AUTOINCREMENT, x " "INTEGER, UNIQUE (x))", dialect=sqlite.dialect(), ) def test_sqlite_no_autoincrement(self): table = Table( "noautoinctable", MetaData(), Column("id", Integer, primary_key=True), Column("x", Integer, default=None), ) self.assert_compile( schema.CreateTable(table), "CREATE TABLE noautoinctable (id INTEGER " "NOT NULL, x INTEGER, PRIMARY KEY (id))", dialect=sqlite.dialect(), ) def test_sqlite_autoincrement_int_affinity(self): class MyInteger(sqltypes.TypeDecorator): impl = Integer cache_ok = True table = Table( "autoinctable", MetaData(), Column("id", MyInteger, primary_key=True), sqlite_autoincrement=True, ) self.assert_compile( schema.CreateTable(table), "CREATE TABLE autoinctable (id INTEGER NOT " "NULL PRIMARY KEY AUTOINCREMENT)", dialect=sqlite.dialect(), )
AutoIncrementTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingLocalConst1.py
{ "start": 256, "end": 2459 }
class ____: b: int def func1(x: A | B) -> None: is_a = not not isinstance(x, A) if not is_a: reveal_type(x, expected_text="B") else: reveal_type(x, expected_text="A") def func2(x: A | B) -> None: is_a = isinstance(x, A) if random.random() < 0.5: x = B() if is_a: reveal_type(x, expected_text="B | A") else: reveal_type(x, expected_text="B | A") def func3(x: int | None): is_number = x != None if is_number: reveal_type(x, expected_text="int") else: reveal_type(x, expected_text="None") def func4() -> A | None: return A() if random.random() < 0.5 else None maybe_a1 = func4() is_a1 = maybe_a1 if is_a1: reveal_type(maybe_a1, expected_text="A") else: reveal_type(maybe_a1, expected_text="None") maybe_a2 = func4() def func5(): global maybe_a2 maybe_a2 = False is_a2 = maybe_a2 if is_a2: reveal_type(maybe_a2, expected_text="A | None") else: reveal_type(maybe_a2, expected_text="A | None") def func6(x: A | B) -> None: is_a = isinstance(x, A) for y in range(1): if is_a: reveal_type(x, expected_text="A | B") else: reveal_type(x, expected_text="A | B") if random.random() < 0.5: x = B() def get_string() -> str: ... def get_optional_string() -> str | None: ... def func7(val: str | None = None): val = get_optional_string() val_is_none = val is None if val_is_none: val = get_string() reveal_type(val, expected_text="str") def func8(val: str | None = None): val = get_optional_string() val_is_none = val is None val = get_optional_string() if val_is_none: val = get_string() reveal_type(val, expected_text="str | None") def func9(var: str | None = None): if var_not_None := not (var is None): reveal_type(var, expected_text="str") reveal_type(var, expected_text="str | None") if var_not_None: reveal_type(var, expected_text="str") if 1 > 1 + 2: var = None else: var = "a" + "b" if var_not_None: reveal_type(var, expected_text="Literal['ab'] | None")
B
python
openai__openai-python
src/openai/types/webhooks/fine_tuning_job_cancelled_webhook_event.py
{ "start": 247, "end": 332 }
class ____(BaseModel): id: str """The unique ID of the fine-tuning job."""
Data
python
django__django
tests/db_functions/math/test_exp.py
{ "start": 268, "end": 2268 }
class ____(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_exp=Exp("normal")).first() self.assertIsNone(obj.null_exp) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = DecimalModel.objects.annotate(n1_exp=Exp("n1"), n2_exp=Exp("n2")).first() self.assertIsInstance(obj.n1_exp, Decimal) self.assertIsInstance(obj.n2_exp, Decimal) self.assertAlmostEqual(obj.n1_exp, Decimal(math.exp(obj.n1))) self.assertAlmostEqual(obj.n2_exp, Decimal(math.exp(obj.n2))) def test_float(self): FloatModel.objects.create(f1=-27.5, f2=0.33) obj = FloatModel.objects.annotate(f1_exp=Exp("f1"), f2_exp=Exp("f2")).first() self.assertIsInstance(obj.f1_exp, float) self.assertIsInstance(obj.f2_exp, float) self.assertAlmostEqual(obj.f1_exp, math.exp(obj.f1)) self.assertAlmostEqual(obj.f2_exp, math.exp(obj.f2)) def test_integer(self): IntegerModel.objects.create(small=-20, normal=15, big=-1) obj = IntegerModel.objects.annotate( small_exp=Exp("small"), normal_exp=Exp("normal"), big_exp=Exp("big"), ).first() self.assertIsInstance(obj.small_exp, float) self.assertIsInstance(obj.normal_exp, float) self.assertIsInstance(obj.big_exp, float) self.assertAlmostEqual(obj.small_exp, math.exp(obj.small)) self.assertAlmostEqual(obj.normal_exp, math.exp(obj.normal)) self.assertAlmostEqual(obj.big_exp, math.exp(obj.big)) def test_transform(self): with register_lookup(DecimalField, Exp): DecimalModel.objects.create(n1=Decimal("12.0"), n2=Decimal("0")) DecimalModel.objects.create(n1=Decimal("-1.0"), n2=Decimal("0")) obj = DecimalModel.objects.filter(n1__exp__gt=10).get() self.assertEqual(obj.n1, Decimal("12.0"))
ExpTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 10278, "end": 10358 }
class ____(IncrementalShopifyStream): data_field = "metafields"
MetafieldShops
python
euske__pdfminer
pdfminer/pdffont.py
{ "start": 23237, "end": 27098 }
class ____(PDFFont): def __init__(self, rsrcmgr, spec): try: self.basefont = literal_name(spec['BaseFont']) except KeyError: if STRICT: raise PDFFontError('BaseFont is missing') self.basefont = 'unknown' self.cidsysteminfo = dict_value(spec.get('CIDSystemInfo', {})) registry = bytes_value(self.cidsysteminfo.get('Registry', b'unknown')) ordering = bytes_value(self.cidsysteminfo.get('Ordering', b'unknown')) self.cidcoding = (registry + b'-' + ordering).decode('ascii') try: name = literal_name(spec['Encoding']) except KeyError: if STRICT: raise PDFFontError('Encoding is unspecified') name = 'unknown' try: self.cmap = CMapDB.get_cmap(name) except CMapDB.CMapNotFound as e: if STRICT: raise PDFFontError(e) self.cmap = CMap() try: descriptor = dict_value(spec['FontDescriptor']) except KeyError: if STRICT: raise PDFFontError('FontDescriptor is missing') descriptor = {} ttf = None if 'FontFile2' in descriptor: self.fontfile = stream_value(descriptor.get('FontFile2')) ttf = TrueTypeFont(self.basefont, BytesIO(self.fontfile.get_data())) self.unicode_map = None if 'ToUnicode' in spec: strm = stream_value(spec['ToUnicode']) self.unicode_map = FileUnicodeMap() CMapParser(self.unicode_map, BytesIO(strm.get_data())).run() elif self.cidcoding in ('Adobe-Identity', 'Adobe-UCS'): if ttf: try: self.unicode_map = ttf.create_unicode_map() except TrueTypeFont.CMapNotFound: pass else: try: self.unicode_map = CMapDB.get_unicode_map(self.cidcoding, self.cmap.is_vertical()) except CMapDB.CMapNotFound as e: pass self.vertical = self.cmap.is_vertical() if self.vertical: # writing mode: vertical widths = get_widths2(list_value(spec.get('W2', []))) self.disps = dict((cid, (vx, vy)) for (cid, (_, (vx, vy))) in widths.items()) (vy, w) = spec.get('DW2', [880, -1000]) self.default_disp = (None, vy) widths = dict((cid, w) for (cid, (w, _)) in widths.items()) default_width = w else: # writing mode: horizontal self.disps = {} self.default_disp = 0 widths = get_widths(list_value(spec.get('W', []))) default_width = spec.get('DW', 1000) PDFFont.__init__(self, descriptor, widths, default_width=default_width) return def __repr__(self): return '<PDFCIDFont: basefont=%r, cidcoding=%r>' % (self.basefont, self.cidcoding) def is_vertical(self): return self.vertical def is_multibyte(self): return True def decode(self, data): return self.cmap.decode(data) def char_disp(self, cid): "Returns an integer for horizontal fonts, a tuple for vertical fonts." return self.disps.get(cid, self.default_disp) def to_unichr(self, cid): try: if not self.unicode_map: raise KeyError(cid) return self.unicode_map.get_unichr(cid) except KeyError: raise PDFUnicodeNotDefined(self.cidcoding, cid) # main def main(argv): for fname in argv[1:]: with open(fname, 'rb') as fp: #font = TrueTypeFont(fname, fp) font = CFFFont(fname, fp) print(font) return if __name__ == '__main__': sys.exit(main(sys.argv))
PDFCIDFont
python
dagster-io__dagster
python_modules/dagster/dagster/_core/log_manager.py
{ "start": 2753, "end": 3328 }
class ____(TypedDict): """Internal class used to represent the context in which a given message was logged (i.e. the step, run, resource, etc.). This is stored on the `DagsterLogHandler` (and `DagsterLogManager`) and merged into the specific metadata for each log event to form a `DagsterLogRecordMetadata` instance. """ run_id: Optional[str] job_name: Optional[str] job_tags: Mapping[str, str] step_key: Optional[str] op_name: Optional[str] resource_name: Optional[str] resource_fn_name: Optional[str]
DagsterLogHandlerMetadata
python
dagster-io__dagster
python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py
{ "start": 7988, "end": 10001 }
class ____(ConstraintWithMetadata): """Use this class if you have multiple constraints to check over the entire dataframe. Args: description (str): description of the constraint validation_fn_arr(List[Callable[[DataFrame], Tuple[bool, dict[str, Union[dict,list, str, set]]]]]): a list of the validation functions to run over inputted data Each function should return a tuple of a boolean for success or failure, and a dict containing metadata about the test -- this metadata will be passed to the resulting exception if validation fails. resulting_exception (ConstraintWithMetadataException): what response a failed typecheck should induce raise_or_typecheck (Optional[bool]): whether to raise an exception (if set to True) or emit a failed typecheck event (if set to False) when validation fails name (Optional[str]): what to call the constraint, defaults to the class name. """ def __init__( self, description, validation_fn_arr, resulting_exception, raise_or_typecheck=True, name=None, ): validation_fn_arr = check.list_param(validation_fn_arr, "validation_fn_arr") def validation_fn(data, *args, **kwargs): results = [f(data, *args, **kwargs) for f in validation_fn_arr] truthparam = all(item[0] for item in results) metadict = defaultdict(dict) for i, dicta in enumerate(item[1] for item in results): if len(dicta.keys()) > 0: for key in dicta: metadict[key][validation_fn_arr[i].__name__] = dicta[key] return (truthparam, metadict) super().__init__( description, validation_fn, resulting_exception, raise_or_typecheck=raise_or_typecheck, name=name, ) @beta
MultiConstraintWithMetadata
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 8000, "end": 8186 }
class ____(ShowFieldTypeAndContent, PolymorphicModel): uuid_primary_key = models.UUIDField(primary_key=True, default=uuid.uuid1) topic = models.CharField(max_length=30)
UUIDProject
python
sphinx-doc__sphinx
sphinx/util/template.py
{ "start": 2064, "end": 2562 }
class ____(FileRenderer): def __init__( self, template_path: Sequence[str | os.PathLike[str]] | None = None ) -> None: if template_path is None: template_path = (_TEMPLATES_PATH,) super().__init__(template_path) @classmethod def render_from_file( cls: type[FileRenderer], filename: str | os.PathLike[str], context: dict[str, Any], ) -> str: return FileRenderer.render_from_file(filename, context)
SphinxRenderer
python
pytorch__pytorch
test/nn/test_module_hooks.py
{ "start": 3265, "end": 4388 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.net1 = Net() def forward(self, x: torch.Tensor, fail: bool = True) -> torch.Tensor: if fail: raise RuntimeError("failing in forward") return self.net1(x) def kwarg_forward_pre_hook( self: TestCase, fired_hooks: list[int], expected_module: nn.Module, hook_id: int, module: nn.Module, args: tuple[torch.Tensor], kwargs: dict[str, Any], ) -> tuple[Any, Any]: fired_hooks.append(hook_id) self.assertEqual(id(module), id(expected_module)) self.assertEqual(len(args), 1) kwargs["bias"] = 2 * kwargs["bias"] return args, kwargs def kwarg_forward_hook( self: TestCase, fired_hooks: list[int], expected_module: nn.Module, hook_id: int, module: nn.Module, args: tuple[torch.Tensor], kwargs: dict[str, Any], out: torch.Tensor, ) -> Any: fired_hooks.append(hook_id) self.assertEqual(id(module), id(expected_module)) self.assertEqual(len(args), 1) out = out + kwargs["bias"] return out
FailsInForwardModel
python
django-extensions__django-extensions
django_extensions/admin/widgets.py
{ "start": 365, "end": 3337 }
class ____(ForeignKeyRawIdWidget): """ Widget for displaying ForeignKeys in an autocomplete search input instead in a <select> box. """ # Set in subclass to render the widget with a different template widget_template = None # Set this to the patch of the search view search_path = None @property def media(self): js_files = [ static("django_extensions/js/jquery.bgiframe.js"), static("django_extensions/js/jquery.ajaxQueue.js"), static("django_extensions/js/jquery.autocomplete.js"), ] return forms.Media( css={"all": (static("django_extensions/css/jquery.autocomplete.css"),)}, js=js_files, ) def label_for_value(self, value): key = self.rel.get_related_field().name obj = self.rel.model._default_manager.get(**{key: value}) return Truncator(obj).words(14, truncate="...") def __init__(self, rel, search_fields, attrs=None): self.search_fields = search_fields super().__init__(rel, site, attrs) def render(self, name, value, attrs=None, renderer=None): if attrs is None: attrs = {} opts = self.rel.model._meta app_label = opts.app_label model_name = opts.object_name.lower() related_url = reverse("admin:%s_%s_changelist" % (app_label, model_name)) if not self.search_path: self.search_path = urllib.parse.urljoin( related_url, "foreignkey_autocomplete/" ) params = self.url_parameters() if params: url = "?" + "&amp;".join(["%s=%s" % (k, v) for k, v in params.items()]) else: url = "" if "class" not in attrs: attrs["class"] = "vForeignKeyRawIdAdminField" # Call the TextInput render method directly to have more control output = [forms.TextInput.render(self, name, value, attrs)] if value: label = self.label_for_value(value) else: label = "" context = { "url": url, "related_url": related_url, "search_path": self.search_path, "search_fields": ",".join(self.search_fields), "app_label": app_label, "model_name": model_name, "label": label, "name": name, } output.append( render_to_string( self.widget_template or ( "django_extensions/widgets/%s/%s/foreignkey_searchinput.html" % (app_label, model_name), "django_extensions/widgets/%s/foreignkey_searchinput.html" % app_label, "django_extensions/widgets/foreignkey_searchinput.html", ), context, ) ) output.reverse() return mark_safe("".join(output))
ForeignKeySearchInput
python
scikit-image__scikit-image
src/skimage/transform/_geometric.py
{ "start": 11444, "end": 13215 }
class ____(_GeometricTransform): """Transform accepting homogeneous matrix as input.""" def __init__(self, matrix=None, *, dimensionality=None): if matrix is None: d = 2 if dimensionality is None else dimensionality matrix = np.eye(d + 1) else: matrix = np.asarray(matrix) self._check_matrix(matrix, dimensionality) self._check_dims(matrix.shape[0] - 1) self.params = matrix def _check_matrix(self, matrix, dimensionality): if dimensionality is not None: if dimensionality != matrix.shape[0] - 1: raise ValueError( f'Dimensionality {dimensionality} does not match matrix ' f'{matrix}' ) m = matrix.shape[0] if matrix.shape != (m, m): raise ValueError("Invalid shape of transformation matrix") def _check_dims(self, d): if d == 2: return raise NotImplementedError( f'Input for {type(self)} should result in 2D transform' ) @classmethod def identity(cls, dimensionality=None): """Identity transform Parameters ---------- dimensionality : {None, 2}, optional This transform only allows dimensionality of 2, where None corresponds to 2. The parameter exists for compatibility with other transforms. Returns ------- tform : transform Transform such that ``np.all(tform(pts) == pts)``. """ d = 2 if dimensionality is None else dimensionality return cls(matrix=np.eye(d + 1)) @property def dimensionality(self): return self.matrix.shape[0] - 1
_HMatrixTransform
python
getsentry__sentry
src/sentry/integrations/perforce/integration.py
{ "start": 2435, "end": 8697 }
class ____(RepositoryIntegration, CommitContextIntegration): """ Integration for Perforce/Helix Core version control system. Provides stacktrace linking to depot files and suspect commit detection. """ integration_name = "perforce" def __init__( self, model: Integration, organization_id: int, ): super().__init__(model=model, organization_id=organization_id) self._client: PerforceClient | None = None def get_client(self) -> PerforceClient: """Get the Perforce client instance.""" if self._client is None: self._client = PerforceClient() return self._client def on_create_or_update_comment_error(self, api_error: ApiError, metrics_base: str) -> bool: """ Handle errors from PR comment operations. Perforce doesn't have native pull requests, so this always returns False. """ return False def source_url_matches(self, url: str) -> bool: """Check if URL is from this Perforce server.""" return False def check_file(self, repo: Repository, filepath: str, branch: str | None = None) -> str | None: """ Check if a file exists in the Perforce depot and return the URL. Uses the client's check_file method to verify file existence on the P4 server. Args: repo: Repository object filepath: File path (may be absolute depot path or relative path) branch: Branch/stream name (optional) Returns: Formatted URL if the file exists, None otherwise """ return None def format_source_url(self, repo: Repository, filepath: str, branch: str | None) -> str: """ Format source URL for stacktrace linking. The Symbolic transformer includes revision info directly in the filepath using Perforce's file revision syntax (e.g., "processor.cpp#1"). Args: repo: Repository object filepath: File path, may include #revision (e.g., "app/file.cpp#1") branch: Stream name (e.g., "main", "dev") to be inserted after depot path. For Perforce streams: //depot/stream/path/to/file Returns: Formatted URL (p4:// or Swarm web viewer URL) """ return "" def extract_branch_from_source_url(self, repo: Repository, url: str) -> str: """ Extract branch/stream from URL. For Perforce, streams are part of the depot path, not separate refs. Returns empty string as we don't use branch refs. """ return "" def extract_source_path_from_source_url(self, repo: Repository, url: str) -> str: """ Extract file path from URL, removing revision specifiers. Handles URLs with revisions like: - p4://depot/path/file.cpp#42 - https://swarm/files//depot/path/file.cpp?v=42 Returns just the file path without revision info. """ return "" def get_repositories( self, query: str | None = None, page_number_limit: int | None = None ) -> list[dict[str, Any]]: """ Get list of depots/streams from Perforce server. Returns: List of repository dictionaries """ return [] def has_repo_access(self, repo: RpcRepository) -> bool: """Check if integration can access the depot.""" return False def get_unmigratable_repositories(self) -> list[RpcRepository]: """Get repositories that can't be migrated. Perforce doesn't need migration.""" return [] def get_organization_config(self) -> list[dict[str, Any]]: """ Get configuration form fields for organization-level settings. These fields will be displayed in the integration settings UI. """ return [ { "name": "p4port", "type": "string", "label": "P4PORT (Server Address)", "placeholder": "ssl:perforce.company.com:1666", "help": "Perforce server address in P4PORT format. Examples: 'ssl:perforce.company.com:1666' (encrypted), 'perforce.company.com:1666' or 'tcp:perforce.company.com:1666' (plaintext). SSL is strongly recommended for production use.", "required": True, }, { "name": "user", "type": "string", "label": "Perforce Username", "placeholder": "sentry-bot", "help": "Username for authenticating with Perforce. Required for both password and ticket authentication.", "required": True, }, { "name": "password", "type": "secret", "label": "Password or P4 Ticket", "placeholder": "••••••••", "help": "Perforce password OR P4 authentication ticket. Tickets are obtained via 'p4 login -p' and are more secure than passwords. Both are supported in this field.", "required": True, }, { "name": "ssl_fingerprint", "type": "string", "label": "SSL Fingerprint (Required for SSL)", "placeholder": "AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01", "help": "SSL fingerprint for secure connections. Required when using 'ssl:' protocol. Obtain with: p4 -p ssl:host:port trust -y", "required": False, }, { "name": "client", "type": "string", "label": "Perforce Client/Workspace (Optional)", "placeholder": "sentry-workspace", "help": "Optional: Specify a client workspace name", "required": False, }, { "name": "web_url", "type": "string", "label": "Helix Swarm URL (Optional)", "placeholder": "https://swarm.company.com", "help": "Optional: URL to Helix Swarm web viewer for browsing files", "required": False, }, ]
PerforceIntegration
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_integration_proxy.py
{ "start": 1441, "end": 2451 }
class ____(TypedDict, total=False): HTTP_X_SENTRY_SUBNET_ORGANIZATION_INTEGRATION: str HTTP_X_SENTRY_SUBNET_SIGNATURE: str HTTP_X_SENTRY_SUBNET_BASE_URL: str HTTP_X_SENTRY_SUBNET_PATH: str def test_ensure_http_headers_match() -> None: headers = SiloHttpHeaders( HTTP_X_SENTRY_SUBNET_ORGANIZATION_INTEGRATION="hello", HTTP_X_SENTRY_SUBNET_SIGNATURE="world", ) def cgi_header(s: str) -> str: """ Django requests cannot be initialized without request factory, and headers for those requests must follow the CGI spec. This means _ (instead of -) and prefixed with 'HTTP_' https://docs.djangoproject.com/en/4.0/topics/testing/tools/#making-requests """ return f"{HttpHeaders.HTTP_PREFIX}{s.replace('-', '_')}".upper() expected = {cgi_header(s) for s in (PROXY_OI_HEADER, PROXY_SIGNATURE_HEADER)} assert set(headers) == expected SENTRY_SUBNET_SECRET = "hush-hush-im-invisible" @control_silo_test
SiloHttpHeaders
python
getsentry__sentry
src/sentry/migrations/0948_ds_waiver_org_fk_not_db_constr.py
{ "start": 222, "end": 1740 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("sentry", "0947_add_dashboard_last_visited_model"), ] operations = [ migrations.AlterField( model_name="datasecrecywaiver", name="organization", field=sentry.db.models.fields.foreignkey.FlexibleForeignKey( db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="sentry.organization", unique=True, ), ), ]
Migration
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 38440, "end": 38862 }
class ____(_TestBasicOps, __TestCase): def setUp(self): self.case = "string set" self.values = ["a", "b", "c"] self.set = set(self.values) self.dup = set(self.values) self.length = 3 super().setUp() def test_repr(self): self.check_repr_against_values() #------------------------------------------------------------------------------
TestBasicOpsString