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 | PyCQA__pylint | pylint/reporters/ureports/nodes.py | {
"start": 2925,
"end": 3167
} | class ____(Text):
"""A verbatim text, display the raw data.
attributes :
* data : the text value as an encoded or unicode string
"""
# container nodes #############################################################
| VerbatimText |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 67470,
"end": 70971
} | class ____(Request):
"""
Get a list of all hyper parameter sections and names used in tasks within the given project.
:param project: Project ID
:type project: str
:param page: Page number
:type page: int
:param page_size: Page size
:type page_size: int
:param include_subprojects: If set to 'true' and the project field is set then
the result includes hyper parameters from the subproject tasks
:type include_subprojects: bool
"""
_service = "projects"
_action = "get_hyper_parameters"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"include_subprojects": {
"default": True,
"description": "If set to 'true' and the project field is set then the result includes hyper parameters from the subproject tasks",
"type": "boolean",
},
"page": {"default": 0, "description": "Page number", "type": "integer"},
"page_size": {
"default": 500,
"description": "Page size",
"type": "integer",
},
"project": {"description": "Project ID", "type": "string"},
},
"required": ["project"],
"type": "object",
}
def __init__(
self,
project: str,
page: Optional[int] = 0,
page_size: Optional[int] = 500,
include_subprojects: Optional[bool] = True,
**kwargs: Any
) -> None:
super(GetHyperParametersRequest, self).__init__(**kwargs)
self.project = project
self.page = page
self.page_size = page_size
self.include_subprojects = include_subprojects
@schema_property("project")
def project(self) -> str:
return self._property_project
@project.setter
def project(self, value: str) -> None:
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("page")
def page(self) -> Optional[int]:
return self._property_page
@page.setter
def page(self, value: Optional[int]) -> None:
if value is None:
self._property_page = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "page", six.integer_types)
self._property_page = value
@schema_property("page_size")
def page_size(self) -> Optional[int]:
return self._property_page_size
@page_size.setter
def page_size(self, value: Optional[int]) -> None:
if value is None:
self._property_page_size = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "page_size", six.integer_types)
self._property_page_size = value
@schema_property("include_subprojects")
def include_subprojects(self) -> Optional[bool]:
return self._property_include_subprojects
@include_subprojects.setter
def include_subprojects(self, value: Optional[bool]) -> None:
if value is None:
self._property_include_subprojects = None
return
self.assert_isinstance(value, "include_subprojects", (bool,))
self._property_include_subprojects = value
| GetHyperParametersRequest |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 132958,
"end": 152653
} | class ____(Element, _IDProperty, _DescriptionProperty):
"""
VOTABLE_ element: represents an entire file.
The keyword arguments correspond to setting members of the same
name, documented below.
*version* is settable at construction time only, since conformance
tests for building the rest of the structure depend on it.
"""
def __init__(self, ID=None, id=None, config=None, pos=None, version="1.4"):
self._config = config.copy() if config is not None else {}
# Version setter forces the associated version config settings to
# be calculated.
self.version = version
self._pos = pos
Element.__init__(self)
self.ID = resolve_id(ID, id, config, pos)
self.description = None
self._coordinate_systems = HomogeneousList(CooSys)
self._time_systems = HomogeneousList(TimeSys)
self._params = HomogeneousList(Param)
self._infos = HomogeneousList(Info)
self._resources = HomogeneousList(Resource)
self._groups = HomogeneousList(Group)
def __repr__(self):
n_tables = len(list(self.iter_tables()))
return f"<VOTABLE>... {n_tables} tables ...</VOTABLE>"
@property
def config(self):
"""
Configuration used to construct this object. Will always include the
version check values.
"""
return self._config
@property
def version(self):
"""
The version of the VOTable specification that the file uses.
"""
return self._version
@version.setter
def version(self, version):
version = str(version)
if version not in self._version_namespace_map:
allowed_from_map = "', '".join(self._version_namespace_map)
raise ValueError(
f"astropy.io.votable version should be in ('{allowed_from_map}')."
)
self._version = version
# Force config update.
self._config.update(self._get_version_checks())
self._config["version"] = version
@property
def coordinate_systems(self):
"""
A list of coordinate system descriptions for the file. Must
contain only `CooSys` objects.
"""
return self._coordinate_systems
@property
def time_systems(self):
"""
A list of time system descriptions for the file. Must
contain only `TimeSys` objects.
"""
return self._time_systems
@property
def params(self):
"""
A list of parameters (constant-valued columns) that apply to
the entire file. Must contain only `Param` objects.
"""
return self._params
@property
def infos(self):
"""
A list of informational parameters (key-value pairs) for the
entire file. Must only contain `Info` objects.
"""
return self._infos
@property
def resources(self):
"""
A list of resources, in the order they appear in the file.
Must only contain `Resource` objects.
"""
return self._resources
@property
def groups(self):
"""
A list of groups, in the order they appear in the file. Only
supported as a child of the VOTABLE element in VOTable 1.2 or
later.
"""
return self._groups
def _add_param(self, iterator, tag, data, config, pos):
param = Param(self, config=config, pos=pos, **data)
self.params.append(param)
param.parse(iterator, config)
def _add_resource(self, iterator, tag, data, config, pos):
resource = Resource(config=config, pos=pos, **data)
self.resources.append(resource)
resource.parse(self, iterator, config)
def _add_coosys(self, iterator, tag, data, config, pos):
coosys = CooSys(config=config, pos=pos, **data)
self.coordinate_systems.append(coosys)
coosys.parse(iterator, config)
def _add_timesys(self, iterator, tag, data, config, pos):
timesys = TimeSys(config=config, pos=pos, **data)
self.time_systems.append(timesys)
timesys.parse(iterator, config)
def _add_info(self, iterator, tag, data, config, pos):
info = Info(config=config, pos=pos, **data)
self.infos.append(info)
info.parse(iterator, config)
def _add_group(self, iterator, tag, data, config, pos):
if not config.get("version_1_2_or_later"):
warn_or_raise(W26, W26, ("GROUP", "VOTABLE", "1.2"), config, pos)
group = Group(self, config=config, pos=pos, **data)
self.groups.append(group)
group.parse(iterator, config)
def _get_version_checks(self):
config = {}
config["version"] = self.version
config["version_1_1_or_later"] = util.version_compare(self.version, "1.1") >= 0
config["version_1_2_or_later"] = util.version_compare(self.version, "1.2") >= 0
config["version_1_3_or_later"] = util.version_compare(self.version, "1.3") >= 0
config["version_1_4_or_later"] = util.version_compare(self.version, "1.4") >= 0
config["version_1_5_or_later"] = util.version_compare(self.version, "1.5") >= 0
return config
# Map VOTable version numbers to namespace URIs and schema information.
_version_namespace_map = {
# Version 1.0 isn't well-supported, but is allowed on parse (with a warning).
# It used DTD rather than schema, so this information would not be useful.
# By omitting 1.0 from this dict we can use the keys as the list of versions
# that are allowed in various other checks.
"1.1": {
"namespace_uri": "http://www.ivoa.net/xml/VOTable/v1.1",
"schema_location_attr": "xsi:noNamespaceSchemaLocation",
"schema_location_value": "http://www.ivoa.net/xml/VOTable/v1.1",
},
"1.2": {
"namespace_uri": "http://www.ivoa.net/xml/VOTable/v1.2",
"schema_location_attr": "xsi:noNamespaceSchemaLocation",
"schema_location_value": "http://www.ivoa.net/xml/VOTable/v1.2",
},
# With 1.3 we'll be more explicit with the schema location.
# - xsi:schemaLocation uses the namespace name along with the URL
# to reference it.
# - For convenience, but somewhat confusingly, the namespace URIs
# are also usable URLs for accessing an applicable schema.
# However to avoid confusion, we'll use the explicit schema URL.
"1.3": {
"namespace_uri": "http://www.ivoa.net/xml/VOTable/v1.3",
"schema_location_attr": "xsi:schemaLocation",
"schema_location_value": (
"http://www.ivoa.net/xml/VOTable/v1.3"
" http://www.ivoa.net/xml/VOTable/VOTable-1.3.xsd"
),
},
# With 1.4 namespace URIs stopped incrementing with minor version changes
# so we use the same URI as with 1.3. See this IVOA note for more info:
# http://www.ivoa.net/documents/Notes/XMLVers/20180529/
"1.4": {
"namespace_uri": "http://www.ivoa.net/xml/VOTable/v1.3",
"schema_location_attr": "xsi:schemaLocation",
"schema_location_value": (
"http://www.ivoa.net/xml/VOTable/v1.3"
" http://www.ivoa.net/xml/VOTable/VOTable-1.4.xsd"
),
},
"1.5": {
"namespace_uri": "http://www.ivoa.net/xml/VOTable/v1.3",
"schema_location_attr": "xsi:schemaLocation",
"schema_location_value": (
"http://www.ivoa.net/xml/VOTable/v1.3"
" http://www.ivoa.net/xml/VOTable/VOTable-1.5.xsd"
),
},
}
def parse(self, iterator, config):
config["_current_table_number"] = 0
for start, tag, data, pos in iterator:
if start:
if tag == "xml":
pass
elif tag == "VOTABLE":
if "version" not in data:
warn_or_raise(W20, W20, self.version, config, pos)
config["version"] = self.version
else:
config["version"] = self._version = data["version"]
if config["version"].lower().startswith("v"):
warn_or_raise(W29, W29, config["version"], config, pos)
self._version = config["version"] = config["version"][1:]
if config["version"] not in self._version_namespace_map:
vo_warn(W21, config["version"], config, pos)
# Update the configuration of the VOTableFile itself.
# This can not be done via the .version property setter
# because that refuses to allow votable 1.0.
self._config["version"] = config["version"]
self._config.update(self._get_version_checks())
if "xmlns" in data:
ns_info = self._version_namespace_map.get(config["version"], {})
correct_ns = ns_info.get("namespace_uri")
if data["xmlns"] != correct_ns:
vo_warn(W41, (correct_ns, data["xmlns"]), config, pos)
else:
vo_warn(W42, (), config, pos)
break
else:
vo_raise(E19, (), config, pos)
config.update(self._get_version_checks())
tag_mapping = {
"PARAM": self._add_param,
"RESOURCE": self._add_resource,
"COOSYS": self._add_coosys,
"TIMESYS": self._add_timesys,
"INFO": self._add_info,
"DEFINITIONS": self._add_definitions,
"DESCRIPTION": self._ignore_add,
"GROUP": self._add_group,
}
for start, tag, data, pos in iterator:
if start:
tag_mapping.get(tag, self._add_unknown_tag)(
iterator, tag, data, config, pos
)
elif tag == "DESCRIPTION":
if self.description is not None:
warn_or_raise(W17, W17, "VOTABLE", config, pos)
self.description = data or None
if not len(self.resources) and config["version_1_2_or_later"]:
warn_or_raise(W53, W53, (), config, pos)
return self
def to_xml(
self,
fd,
compressed=False,
tabledata_format=None,
_debug_python_based_parser=False,
_astropy_version=None,
):
"""
Write to an XML file.
Parameters
----------
fd : str or file-like
Where to write the file. If a file-like object, must be writable.
compressed : bool, optional
When `True`, write to a gzip-compressed file. (Default:
`False`)
tabledata_format : str, optional
Override the format of the table(s) data to write. Must
be one of ``tabledata`` (text representation), ``binary`` or
``binary2``. By default, use the format that was specified
in each `TableElement` object as it was created or read in. See
:ref:`astropy:votable-serialization`.
"""
if tabledata_format is not None:
if tabledata_format.lower() not in ("tabledata", "binary", "binary2"):
raise ValueError(f"Unknown format type '{format}'")
kwargs = {
"version": self.version,
"tabledata_format": tabledata_format,
"_debug_python_based_parser": _debug_python_based_parser,
"_group_number": 1,
}
kwargs.update(self._get_version_checks())
with util.convert_to_writable_filelike(fd, compressed=compressed) as fh:
w = XMLWriter(fh)
version = self.version
if _astropy_version is None:
lib_version = astropy_version
else:
lib_version = _astropy_version
xml_header = """
<?xml version="1.0" encoding="utf-8"?>
<!-- Produced with astropy.io.votable version {lib_version}
http://www.astropy.org/ -->\n"""
w.write(xml_header.lstrip().format(**locals()))
# Build the VOTABLE tag attributes.
votable_attr = {
"version": version,
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
}
ns_info = self._version_namespace_map.get(version, {})
namespace_uri = ns_info.get("namespace_uri")
if namespace_uri:
votable_attr["xmlns"] = namespace_uri
schema_location_attr = ns_info.get("schema_location_attr")
schema_location_value = ns_info.get("schema_location_value")
if schema_location_attr and schema_location_value:
votable_attr[schema_location_attr] = schema_location_value
with w.tag("VOTABLE", votable_attr):
if self.description is not None:
w.element("DESCRIPTION", self.description, wrap=True)
element_sets = [
self.coordinate_systems,
self.time_systems,
self.params,
self.infos,
self.resources,
]
if kwargs["version_1_2_or_later"]:
element_sets.append(self.groups)
for element_set in element_sets:
for element in element_set:
element.to_xml(w, **kwargs)
def iter_tables(self):
"""
Iterates over all tables in the VOTable file in a "flat" way,
ignoring the nesting of resources etc.
"""
for resource in self.resources:
yield from resource.iter_tables()
def get_first_table(self):
"""
Often, you know there is only one table in the file, and
that's all you need. This method returns that first table.
"""
for table in self.iter_tables():
if not table.is_empty():
return table
raise IndexError("No table found in VOTABLE file.")
get_table_by_id = _lookup_by_attr_factory(
"ID",
True,
"iter_tables",
"TABLE",
"""
Looks up a TABLE_ element by the given ID. Used by the table
"ref" attribute.
""",
)
get_tables_by_utype = _lookup_by_attr_factory(
"utype",
False,
"iter_tables",
"TABLE",
"""
Looks up a TABLE_ element by the given utype, and returns an
iterator emitting all matches.
""",
)
def get_table_by_index(self, idx):
"""
Get a table by its ordinal position in the file.
"""
for i, table in enumerate(self.iter_tables()):
if i == idx:
return table
raise IndexError(f"No table at index {idx:d} found in VOTABLE file.")
def iter_fields_and_params(self):
"""
Recursively iterate over all FIELD_ and PARAM_ elements in the
VOTABLE_ file.
"""
for resource in self.resources:
yield from resource.iter_fields_and_params()
get_field_by_id = _lookup_by_attr_factory(
"ID",
True,
"iter_fields_and_params",
"FIELD",
"""
Looks up a FIELD_ element by the given ID_. Used by the field's
"ref" attribute.
""",
)
get_fields_by_utype = _lookup_by_attr_factory(
"utype",
False,
"iter_fields_and_params",
"FIELD",
"""
Looks up a FIELD_ element by the given utype and returns an
iterator emitting all matches.
""",
)
get_field_by_id_or_name = _lookup_by_id_or_name_factory(
"iter_fields_and_params",
"FIELD",
"""
Looks up a FIELD_ element by the given ID_ or name.
""",
)
def iter_values(self):
"""
Recursively iterate over all VALUES_ elements in the VOTABLE_
file.
"""
for field in self.iter_fields_and_params():
yield field.values
get_values_by_id = _lookup_by_attr_factory(
"ID",
True,
"iter_values",
"VALUES",
"""
Looks up a VALUES_ element by the given ID. Used by the values
"ref" attribute.
""",
)
def iter_groups(self):
"""
Recursively iterate over all GROUP_ elements in the VOTABLE_
file.
"""
for table in self.iter_tables():
yield from table.iter_groups()
get_group_by_id = _lookup_by_attr_factory(
"ID",
True,
"iter_groups",
"GROUP",
"""
Looks up a GROUP_ element by the given ID. Used by the group's
"ref" attribute
""",
)
get_groups_by_utype = _lookup_by_attr_factory(
"utype",
False,
"iter_groups",
"GROUP",
"""
Looks up a GROUP_ element by the given utype and returns an
iterator emitting all matches.
""",
)
def iter_coosys(self):
"""
Recursively iterate over all COOSYS_ elements in the VOTABLE_
file.
"""
yield from self.coordinate_systems
for resource in self.resources:
yield from resource.iter_coosys()
get_coosys_by_id = _lookup_by_attr_factory(
"ID",
True,
"iter_coosys",
"COOSYS",
"""Looks up a COOSYS_ element by the given ID.""",
)
def iter_timesys(self):
"""
Recursively iterate over all TIMESYS_ elements in the VOTABLE_
file.
"""
yield from self.time_systems
for resource in self.resources:
yield from resource.iter_timesys()
get_timesys_by_id = _lookup_by_attr_factory(
"ID",
True,
"iter_timesys",
"TIMESYS",
"""Looks up a TIMESYS_ element by the given ID.""",
)
def iter_info(self):
"""
Recursively iterate over all INFO_ elements in the VOTABLE_
file.
"""
yield from self.infos
for resource in self.resources:
yield from resource.iter_info()
get_info_by_id = _lookup_by_attr_factory(
"ID", True, "iter_info", "INFO", """Looks up a INFO element by the given ID."""
)
get_infos_by_name = _lookup_by_attr_factory(
"name",
False,
"iter_info",
"INFO",
"""Returns all INFO children with the given name.""",
)
def set_all_tables_format(self, format):
"""
Set the output storage format of all tables in the file.
"""
for table in self.iter_tables():
table.format = format
@classmethod
def from_table(cls, table, table_id=None):
"""
Create a `VOTableFile` instance from a given
`astropy.table.Table` instance.
Parameters
----------
table_id : str, optional
Set the given ID attribute on the returned TableElement instance.
"""
votable_file = cls()
resource = Resource()
votable = TableElement.from_table(votable_file, table)
if table_id is not None:
votable.ID = table_id
resource.tables.append(votable)
votable_file.resources.append(resource)
return votable_file
| VOTableFile |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/self_ask_with_search/base.py | {
"start": 1284,
"end": 2755
} | class ____(Agent):
"""Agent for the self-ask-with-search paper."""
output_parser: AgentOutputParser = Field(default_factory=SelfAskOutputParser)
@classmethod
@override
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
return SelfAskOutputParser()
@property
def _agent_type(self) -> str:
"""Return Identifier of an agent type."""
return AgentType.SELF_ASK_WITH_SEARCH
@classmethod
@override
def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:
"""Prompt does not depend on tools."""
return PROMPT
@classmethod
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
validate_tools_single_input(cls.__name__, tools)
super()._validate_tools(tools)
if len(tools) != 1:
msg = f"Exactly one tool must be specified, but got {tools}"
raise ValueError(msg)
tool_names = {tool.name for tool in tools}
if tool_names != {"Intermediate Answer"}:
msg = f"Tool name should be Intermediate Answer, got {tool_names}"
raise ValueError(msg)
@property
def observation_prefix(self) -> str:
"""Prefix to append the observation with."""
return "Intermediate answer: "
@property
def llm_prefix(self) -> str:
"""Prefix to append the LLM call with."""
return ""
@deprecated("0.1.0", removal="1.0")
| SelfAskWithSearchAgent |
python | huggingface__transformers | src/transformers/integrations/ggml.py | {
"start": 26641,
"end": 30330
} | class ____(GemmaConverter):
def __init__(self, tokenizer_dict):
# set dummy data to avoid unnecessary merges calculation
tokenizer_dict["merges"] = ["dummy text"]
self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
self.original_tokenizer = self.proto
self.additional_kwargs = {}
def vocab(self, proto):
original_vocab = list(zip(proto.tokens, proto.scores))
updated_vocab = []
for token, score in original_vocab:
if token == "<0x09>":
updated_vocab.append(("\t", score))
elif " " in token and len(token.strip()) == 0:
underscores = "▁" * len(token)
updated_vocab.append((underscores, score))
else:
updated_vocab.append((token, score))
return updated_vocab
def normalizer(self, proto):
return normalizers.Replace(" ", "▁")
def decoder(self, replacement, add_prefix_space):
sequence = [
decoders.Replace("▁", " "),
decoders.ByteFallback(),
decoders.Fuse(),
]
if add_prefix_space:
sequence += [decoders.Strip(content=" ", left=1)]
return decoders.Sequence(sequence)
def converted(self) -> Tokenizer:
vocab_scores = self.vocab(self.proto)
tokenizer = Tokenizer(
Unigram(
vocab_scores,
unk_id=self.proto.unk_token_id,
byte_fallback=self.handle_byte_fallback,
)
)
normalizer = self.normalizer(self.proto)
if normalizer is not None:
tokenizer.normalizer = normalizer
replacement = "▁"
add_prefix_space = True
if hasattr(self.original_tokenizer, "add_prefix_space"):
add_prefix_space = self.original_tokenizer.add_prefix_space
tokenizer.decoder = self.decoder(replacement, add_prefix_space)
pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
if pre_tokenizer is not None:
tokenizer.pre_tokenizer = pre_tokenizer
return tokenizer
GGUF_TO_FAST_CONVERTERS = {
"llama": GGUFLlamaConverter,
"qwen2": GGUFQwen2Converter,
"qwen2_moe": GGUFQwen2Converter,
"qwen3": GGUFQwen2Converter,
"qwen3_moe": GGUFQwen2Converter,
"phi3": GGUFPhi3Converter,
"bloom": GGUFGPTConverter,
"falcon": GGUFGPTConverter,
"stablelm": GGUFGPTConverter,
"gpt2": GGUFGPTConverter,
"starcoder2": GGUFGPTConverter,
"t5": GGUFT5Converter,
"mamba": GGUFGPTConverter,
"nemotron": GGUFGPTConverter,
"gemma2": GGUFGemmaConverter,
"gemma3_text": GGUFGemmaConverter,
"umt5": GGUFT5Converter,
"deci": GGUFLlamaConverter,
"decilm": GGUFLlamaConverter,
}
def convert_gguf_tokenizer(architecture: str, tokenizer_dict) -> tuple[Tokenizer, dict]:
"""
Utilities to convert a slow tokenizer instance in a fast tokenizer instance.
Args:
architecture (`str`): The model architecture derived from gguf file.
transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]):
Instance of a slow tokenizer to convert in the backend tokenizer for
[`~tokenization_utils_base.PreTrainedTokenizerFast`].
Return:
A instance of [`~tokenizers.Tokenizer`] to be used as the backend tokenizer of a
[`~tokenization_utils_base.PreTrainedTokenizerFast`]
"""
tokenizer_class_name = architecture
converter = GGUF_TO_FAST_CONVERTERS[tokenizer_class_name](tokenizer_dict)
fast_tokenizer = converter.converted()
return fast_tokenizer, converter.additional_kwargs
| GGUFGemmaConverter |
python | getsentry__sentry | src/sentry/insights/models.py | {
"start": 350,
"end": 1021
} | class ____(DefaultFieldsModel):
"""
A starred transaction in Insights
"""
__relocation_scope__ = RelocationScope.Organization
project = FlexibleForeignKey("sentry.Project", on_delete=models.CASCADE)
organization = FlexibleForeignKey("sentry.Organization", on_delete=models.CASCADE)
user_id = HybridCloudForeignKey("sentry.User", on_delete="CASCADE")
segment_name = models.CharField()
class Meta:
app_label = "insights"
db_table = "insights_starred_segments"
unique_together = (("project", "user_id", "segment_name"),)
__repr__ = sane_repr("organization_id", "user_id", "segment_name")
| InsightsStarredSegment |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/api_connexion/exceptions.py | {
"start": 4707,
"end": 5171
} | class ____(ProblemException):
"""Raise when there is some conflict."""
def __init__(
self,
title="Conflict",
detail: str | None = None,
headers: dict | None = None,
**kwargs: Any,
):
super().__init__(
status=HTTPStatus.CONFLICT,
type=EXCEPTIONS_LINK_MAP[409],
title=title,
detail=detail,
headers=headers,
**kwargs,
)
| Conflict |
python | celery__celery | celery/backends/elasticsearch.py | {
"start": 601,
"end": 9582
} | class ____(KeyValueStoreBackend):
"""Elasticsearch Backend.
Raises:
celery.exceptions.ImproperlyConfigured:
if module :pypi:`elasticsearch` is not available.
"""
index = 'celery'
doc_type = None
scheme = 'http'
host = 'localhost'
port = 9200
username = None
password = None
es_retry_on_timeout = False
es_timeout = 10
es_max_retries = 3
def __init__(self, url=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url = url
_get = self.app.conf.get
if elasticsearch is None:
raise ImproperlyConfigured(E_LIB_MISSING)
index = doc_type = scheme = host = port = username = password = None
if url:
scheme, host, port, username, password, path, _ = _parse_url(url)
if scheme == 'elasticsearch':
scheme = None
if path:
path = path.strip('/')
index, _, doc_type = path.partition('/')
self.index = index or self.index
self.doc_type = doc_type or self.doc_type
self.scheme = scheme or self.scheme
self.host = host or self.host
self.port = port or self.port
self.username = username or self.username
self.password = password or self.password
self.es_retry_on_timeout = (
_get('elasticsearch_retry_on_timeout') or self.es_retry_on_timeout
)
es_timeout = _get('elasticsearch_timeout')
if es_timeout is not None:
self.es_timeout = es_timeout
es_max_retries = _get('elasticsearch_max_retries')
if es_max_retries is not None:
self.es_max_retries = es_max_retries
self.es_save_meta_as_text = _get('elasticsearch_save_meta_as_text', True)
self._server = None
def exception_safe_to_retry(self, exc):
if isinstance(exc, elasticsearch.exceptions.ApiError):
# 401: Unauthorized
# 409: Conflict
# 500: Internal Server Error
# 502: Bad Gateway
# 504: Gateway Timeout
# N/A: Low level exception (i.e. socket exception)
if exc.status_code in {401, 409, 500, 502, 504, 'N/A'}:
return True
if isinstance(exc, elasticsearch.exceptions.TransportError):
return True
return False
def get(self, key):
try:
res = self._get(key)
try:
if res['found']:
return res['_source']['result']
except (TypeError, KeyError):
pass
except elasticsearch.exceptions.NotFoundError:
pass
def _get(self, key):
if self.doc_type:
return self.server.get(
index=self.index,
id=key,
doc_type=self.doc_type,
)
else:
return self.server.get(
index=self.index,
id=key,
)
def _set_with_state(self, key, value, state):
body = {
'result': value,
'@timestamp': '{}Z'.format(
datetime.now(timezone.utc).isoformat()[:-9]
),
}
try:
self._index(
id=key,
body=body,
)
except elasticsearch.exceptions.ConflictError:
# document already exists, update it
self._update(key, body, state)
def set(self, key, value):
return self._set_with_state(key, value, None)
def _index(self, id, body, **kwargs):
body = {bytes_to_str(k): v for k, v in body.items()}
if self.doc_type:
return self.server.index(
id=bytes_to_str(id),
index=self.index,
doc_type=self.doc_type,
body=body,
params={'op_type': 'create'},
**kwargs
)
else:
return self.server.index(
id=bytes_to_str(id),
index=self.index,
body=body,
params={'op_type': 'create'},
**kwargs
)
def _update(self, id, body, state, **kwargs):
"""Update state in a conflict free manner.
If state is defined (not None), this will not update ES server if either:
* existing state is success
* existing state is a ready state and current state in not a ready state
This way, a Retry state cannot override a Success or Failure, and chord_unlock
will not retry indefinitely.
"""
body = {bytes_to_str(k): v for k, v in body.items()}
try:
res_get = self._get(key=id)
if not res_get.get('found'):
return self._index(id, body, **kwargs)
# document disappeared between index and get calls.
except elasticsearch.exceptions.NotFoundError:
return self._index(id, body, **kwargs)
try:
meta_present_on_backend = self.decode_result(res_get['_source']['result'])
except (TypeError, KeyError):
pass
else:
if meta_present_on_backend['status'] == states.SUCCESS:
# if stored state is already in success, do nothing
return {'result': 'noop'}
elif meta_present_on_backend['status'] in states.READY_STATES and state in states.UNREADY_STATES:
# if stored state is in ready state and current not, do nothing
return {'result': 'noop'}
# get current sequence number and primary term
# https://www.elastic.co/guide/en/elasticsearch/reference/current/optimistic-concurrency-control.html
seq_no = res_get.get('_seq_no', 1)
prim_term = res_get.get('_primary_term', 1)
# try to update document with current seq_no and primary_term
if self.doc_type:
res = self.server.update(
id=bytes_to_str(id),
index=self.index,
doc_type=self.doc_type,
body={'doc': body},
params={'if_primary_term': prim_term, 'if_seq_no': seq_no},
**kwargs
)
else:
res = self.server.update(
id=bytes_to_str(id),
index=self.index,
body={'doc': body},
params={'if_primary_term': prim_term, 'if_seq_no': seq_no},
**kwargs
)
# result is elastic search update query result
# noop = query did not update any document
# updated = at least one document got updated
if res['result'] == 'noop':
raise elasticsearch.exceptions.ConflictError(
"conflicting update occurred concurrently",
elastic_transport.ApiResponseMeta(409, "HTTP/1.1",
elastic_transport.HttpHeaders(), 0, elastic_transport.NodeConfig(
self.scheme, self.host, self.port)), None)
return res
def encode(self, data):
if self.es_save_meta_as_text:
return super().encode(data)
else:
if not isinstance(data, dict):
return super().encode(data)
if data.get("result"):
data["result"] = self._encode(data["result"])[2]
if data.get("traceback"):
data["traceback"] = self._encode(data["traceback"])[2]
return data
def decode(self, payload):
if self.es_save_meta_as_text:
return super().decode(payload)
else:
if not isinstance(payload, dict):
return super().decode(payload)
if payload.get("result"):
payload["result"] = super().decode(payload["result"])
if payload.get("traceback"):
payload["traceback"] = super().decode(payload["traceback"])
return payload
def mget(self, keys):
return [self.get(key) for key in keys]
def delete(self, key):
if self.doc_type:
self.server.delete(index=self.index, id=key, doc_type=self.doc_type)
else:
self.server.delete(index=self.index, id=key)
def _get_server(self):
"""Connect to the Elasticsearch server."""
http_auth = None
if self.username and self.password:
http_auth = (self.username, self.password)
return elasticsearch.Elasticsearch(
f'{self.scheme}://{self.host}:{self.port}',
retry_on_timeout=self.es_retry_on_timeout,
max_retries=self.es_max_retries,
timeout=self.es_timeout,
http_auth=http_auth,
)
@property
def server(self):
if self._server is None:
self._server = self._get_server()
return self._server
| ElasticsearchBackend |
python | jmcnamara__XlsxWriter | xlsxwriter/test/relationships/test_initialisation.py | {
"start": 309,
"end": 872
} | class ____(unittest.TestCase):
"""
Test initialisation of the Relationships class and call a method.
"""
def setUp(self):
self.fh = StringIO()
self.relationships = Relationships()
self.relationships._set_filehandle(self.fh)
def test_xml_declaration(self):
"""Test Relationships xml_declaration()"""
self.relationships._xml_declaration()
exp = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
| TestInitialisation |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_legend06.py | {
"start": 315,
"end": 1416
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_legend06.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with legend options."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line"})
chart.axis_ids = [79972224, 79973760]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart.set_legend({"fill": {"color": "yellow"}})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 48657,
"end": 48823
} | class ____:
xlExtractData = 2 # from enum XlCorruptLoad
xlNormalLoad = 0 # from enum XlCorruptLoad
xlRepairFile = 1 # from enum XlCorruptLoad
| CorruptLoad |
python | kamyu104__LeetCode-Solutions | Python/removing-minimum-and-maximum-from-array.py | {
"start": 29,
"end": 325
} | class ____(object):
def minimumDeletions(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i, j = nums.index(min(nums)), nums.index(max(nums))
if i > j:
i, j = j, i
return min((i+1)+(len(nums)-j), j+1, len(nums)-i)
| Solution |
python | wandb__wandb | wandb/automations/_generated/input_types.py | {
"start": 1315,
"end": 1421
} | class ____(GQLInput):
no_op: Optional[bool] = Field(alias="noOp", default=None)
| NoOpTriggeredActionInput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 14729,
"end": 15268
} | class ____(sgqlc.types.Enum):
"""The possible reasons that a Dependabot alert was dismissed.
Enumeration Choices:
* `FIX_STARTED`: A fix has already been started
* `INACCURATE`: This alert is inaccurate or incorrect
* `NOT_USED`: Vulnerable code is not actually used
* `NO_BANDWIDTH`: No bandwidth to fix this
* `TOLERABLE_RISK`: Risk is tolerable to this project
"""
__schema__ = github_schema
__choices__ = ("FIX_STARTED", "INACCURATE", "NOT_USED", "NO_BANDWIDTH", "TOLERABLE_RISK")
| DismissReason |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 36390,
"end": 36546
} | class ____(Rank):
"""Constant rank value"""
value: float
def to_dict(self) -> Dict[str, Any]:
return {"$val": self.value}
@dataclass
| Val |
python | networkx__networkx | networkx/classes/tests/test_reportviews.py | {
"start": 29644,
"end": 31940
} | class ____:
GRAPH = nx.Graph
dview = nx.reportviews.DegreeView
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(6, cls.GRAPH())
cls.G.add_edge(1, 3, foo=2)
cls.G.add_edge(1, 3, foo=3)
def test_pickle(self):
import pickle
deg = self.G.degree
pdeg = pickle.loads(pickle.dumps(deg, -1))
assert dict(deg) == dict(pdeg)
def test_str(self):
dv = self.dview(self.G)
rep = str([(0, 1), (1, 3), (2, 2), (3, 3), (4, 2), (5, 1)])
assert str(dv) == rep
dv = self.G.degree()
assert str(dv) == rep
def test_repr(self):
dv = self.dview(self.G)
rep = "DegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})"
assert repr(dv) == rep
def test_iter(self):
dv = self.dview(self.G)
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (0, dv[0])
assert next(idv) == (1, dv[1])
# weighted
dv = self.dview(self.G, weight="foo")
for n, d in dv:
pass
idv = iter(dv)
assert iter(dv) != dv
assert iter(idv) == idv
assert next(idv) == (0, dv[0])
assert next(idv) == (1, dv[1])
def test_nbunch(self):
dv = self.dview(self.G)
dvn = dv(0)
assert dvn == 1
dvn = dv([2, 3])
assert sorted(dvn) == [(2, 2), (3, 3)]
def test_getitem(self):
dv = self.dview(self.G)
assert dv[0] == 1
assert dv[1] == 3
assert dv[2] == 2
assert dv[3] == 3
dv = self.dview(self.G, weight="foo")
assert dv[0] == 1
assert dv[1] == 5
assert dv[2] == 2
assert dv[3] == 5
def test_weight(self):
dv = self.dview(self.G)
dvw = dv(0, weight="foo")
assert dvw == 1
dvw = dv(1, weight="foo")
assert dvw == 5
dvw = dv([2, 3], weight="foo")
assert sorted(dvw) == [(2, 2), (3, 5)]
dvd = dict(dv(weight="foo"))
assert dvd[0] == 1
assert dvd[1] == 5
assert dvd[2] == 2
assert dvd[3] == 5
def test_len(self):
dv = self.dview(self.G)
assert len(dv) == 6
| TestDegreeView |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py | {
"start": 3772,
"end": 9162
} | class ____(GoogleCloudBaseOperator):
"""
Create a new backup in a given project and location.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param service_id: Required. The ID of the metastore service, which is used as the final component of
the metastore service's name. This value must be between 2 and 63 characters long inclusive, begin
with a letter, end with a letter or number, and consist of alphanumeric ASCII characters or
hyphens.
This corresponds to the ``service_id`` field on the ``request`` instance; if ``request`` is
provided, this should not be set.
:param backup: Required. The backup to create. The ``name`` field is ignored. The ID of the created
backup must be provided in the request's ``backup_id`` field.
This corresponds to the ``backup`` field on the ``request`` instance; if ``request`` is provided, this
should not be set.
:param backup_id: Required. The ID of the backup, which is used as the final component of the backup's
name. This value must be between 1 and 64 characters long, begin with a letter, end with a letter or
number, and consist of alphanumeric ASCII characters or hyphens.
This corresponds to the ``backup_id`` field on the ``request`` instance; if ``request`` is provided,
this should not be set.
:param request_id: Optional. A unique id used to identify the request.
:param retry: Optional. Designation of what errors, if any, should be retried.
:param timeout: Optional. The timeout for this request.
:param metadata: Optional. Strings which should be sent along with the request as metadata.
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"project_id",
"backup",
"impersonation_chain",
)
template_fields_renderers = {"backup": "json"}
operator_extra_links = (DataprocMetastoreDetailedLink(),)
def __init__(
self,
*,
project_id: str,
region: str,
service_id: str,
backup: dict | Backup,
backup_id: str,
request_id: str | None = None,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.project_id = project_id
self.region = region
self.service_id = service_id
self.backup = backup
self.backup_id = backup_id
self.request_id = request_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"region": self.region,
"service_id": self.service_id,
"project_id": self.project_id,
}
def execute(self, context: Context) -> dict:
hook = DataprocMetastoreHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
self.log.info("Creating Dataproc Metastore backup: %s", self.backup_id)
try:
operation = hook.create_backup(
project_id=self.project_id,
region=self.region,
service_id=self.service_id,
backup=self.backup,
backup_id=self.backup_id,
request_id=self.request_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
backup = hook.wait_for_operation(self.timeout, operation)
self.log.info("Backup %s created successfully", self.backup_id)
except AlreadyExists:
self.log.info("Backup %s already exists", self.backup_id)
backup = hook.get_backup(
project_id=self.project_id,
region=self.region,
service_id=self.service_id,
backup_id=self.backup_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
DataprocMetastoreDetailedLink.persist(
context=context, url=METASTORE_BACKUP_LINK, resource=self.backup_id
)
return Backup.to_dict(backup)
| DataprocMetastoreCreateBackupOperator |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_task_run_subscriptions.py | {
"start": 8766,
"end": 11091
} | class ____:
async def test_task_queue_scheduled_size_limit(self):
task_key = "test_limit"
max_scheduled_size = 2
task_runs.TaskQueue.configure_task_key(
task_key, scheduled_size=max_scheduled_size, retry_size=1
)
queue = task_runs.TaskQueue.for_key(task_key)
for _ in range(max_scheduled_size):
task_run = ServerTaskRun(
id=uuid4(),
flow_run_id=None,
task_key=task_key,
dynamic_key=f"{task_key}-1",
)
await queue.put(task_run)
with (
patch("asyncio.sleep", return_value=None),
pytest.raises(asyncio.TimeoutError),
):
extra_task_run = ServerTaskRun(
id=uuid4(),
flow_run_id=None,
task_key=task_key,
dynamic_key=f"{task_key}-2",
)
await asyncio.wait_for(queue.put(extra_task_run), timeout=0.01)
assert queue._scheduled_queue.qsize() == max_scheduled_size, (
"Queue size should be at its configured limit"
)
async def test_task_queue_retry_size_limit(self):
task_key = "test_retry_limit"
max_retry_size = 1
task_runs.TaskQueue.configure_task_key(
task_key, scheduled_size=2, retry_size=max_retry_size
)
queue = task_runs.TaskQueue.for_key(task_key)
task_run = ServerTaskRun(
id=uuid4(), flow_run_id=None, task_key=task_key, dynamic_key=f"{task_key}-1"
)
await queue.retry(task_run)
with (
patch("asyncio.sleep", return_value=None),
pytest.raises(asyncio.TimeoutError),
):
extra_task_run = ServerTaskRun(
id=uuid4(),
flow_run_id=None,
task_key=task_key,
dynamic_key=f"{task_key}-2",
)
await asyncio.wait_for(queue.retry(extra_task_run), timeout=0.01)
assert queue._retry_queue.qsize() == max_retry_size, (
"Retry queue size should be at its configured limit"
)
@pytest.fixture
def reset_tracker():
models.task_workers.task_worker_tracker.reset()
yield
models.task_workers.task_worker_tracker.reset()
| TestQueueLimit |
python | cython__cython | docs/examples/userguide/language_basics/optional_subclassing.py | {
"start": 191,
"end": 291
} | class ____(B):
@cython.ccall
def foo(self, x=True, k:cython.int = 3):
print("C", x, k)
| C |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 18627,
"end": 18996
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear1 = torch.nn.Linear(10, 10)
self.scale = torch.nn.Parameter(torch.randn(1, 10))
def forward(self, x):
if not requires_grad1(self):
return F.relu(self.linear1(x)) * self.scale
else:
return x + 1
| ParametersModule1 |
python | astropy__astropy | astropy/units/format/unicode_format.py | {
"start": 247,
"end": 1956
} | class ____(console.Console):
"""
Output-only format to display pretty formatting at the console
using Unicode characters.
For example::
>>> import astropy.units as u
>>> print(u.bar.decompose().to_string('unicode'))
100000 kg m⁻¹ s⁻²
>>> print(u.bar.decompose().to_string('unicode', fraction='multiline'))
kg
100000 ────
m s²
>>> print(u.bar.decompose().to_string('unicode', fraction='inline'))
100000 kg / (m s²)
"""
_times: ClassVar[str] = "×"
_line: ClassVar[str] = "─"
@classmethod
def _format_mantissa(cls, m: str) -> str:
return m.replace("-", "−")
@classmethod
def _format_unit_power(cls, unit: NamedUnit, power: UnitPower = 1) -> str:
name = unit._get_format_name(cls.name)
# Check for superscript units
if power != 1:
if name in ("°", "e⁻", "″", "′", "ʰ"):
name = unit.short_names[0]
name += cls._format_power(power)
return name
@classmethod
def _format_superscript(cls, number: str) -> str:
mapping = str.maketrans(
{
"0": "⁰",
"1": "¹",
"2": "²",
"3": "³",
"4": "⁴",
"5": "⁵",
"6": "⁶",
"7": "⁷",
"8": "⁸",
"9": "⁹",
"-": "⁻",
"−": "⁻",
# This is actually a "raised omission bracket", but it's
# the closest thing I could find to a superscript solidus.
"/": "⸍",
}
)
return number.translate(mapping)
| Unicode |
python | spack__spack | lib/spack/spack/llnl/util/lang.py | {
"start": 29770,
"end": 30979
} | class ____:
"""A generic mechanism to coalesce multiple exceptions and preserve tracebacks."""
def __init__(self):
self.exceptions: List[Tuple[str, Exception, List[str]]] = []
def __bool__(self):
"""Whether any exceptions were handled."""
return bool(self.exceptions)
def forward(self, context: str, base: type = BaseException) -> "GroupedExceptionForwarder":
"""Return a contextmanager which extracts tracebacks and prefixes a message."""
return GroupedExceptionForwarder(context, self, base)
def _receive_forwarded(self, context: str, exc: Exception, tb: List[str]):
self.exceptions.append((context, exc, tb))
def grouped_message(self, with_tracebacks: bool = True) -> str:
"""Print out an error message coalescing all the forwarded errors."""
each_exception_message = [
"\n\t{0} raised {1}: {2}\n{3}".format(
context, exc.__class__.__name__, exc, f"\n{''.join(tb)}" if with_tracebacks else ""
)
for context, exc, tb in self.exceptions
]
return "due to the following failures:\n{0}".format("\n".join(each_exception_message))
| GroupedExceptionHandler |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 136799,
"end": 139855
} | class ____(fixtures.TestBase):
def teardown_test(self):
clear_mappers()
@testing.variation("arg_style", ["string", "table", "lambda_"])
def test_secondary_arg_styles(self, arg_style):
Base = declarative_base()
c = Table(
"c",
Base.metadata,
Column("a_id", ForeignKey("a.id")),
Column("b_id", ForeignKey("b.id")),
)
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String)
if arg_style.string:
bs = relationship("B", secondary="c")
elif arg_style.table:
bs = relationship("B", secondary=c)
elif arg_style.lambda_:
bs = relationship("B", secondary=lambda: c)
else:
arg_style.fail()
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
is_(inspect(A).relationships.bs.secondary, c)
def test_no_eval_in_secondary(self):
"""test #10564"""
Base = declarative_base()
Table(
"c",
Base.metadata,
Column("a_id", ForeignKey("a.id")),
Column("b_id", ForeignKey("b.id")),
)
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String)
bs = relationship("B", secondary="c.c.a_id.table")
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
with expect_raises_message(
exc.InvalidRequestError,
r"When initializing mapper Mapper\[A\(a\)\], expression "
r"'c.c.a_id.table' failed to locate a name \('c.c.a_id.table'\). ",
):
Base.registry.configure()
@testing.combinations((True,), (False,))
def test_informative_message_on_cls_as_secondary(self, string):
Base = declarative_base()
class C(Base):
__tablename__ = "c"
id = Column(Integer, primary_key=True)
a_id = Column(ForeignKey("a.id"))
b_id = Column(ForeignKey("b.id"))
if string:
c_arg = "C"
else:
c_arg = C
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String)
bs = relationship("B", secondary=c_arg)
class B(Base):
__tablename__ = "b"
id = Column(Integer, primary_key=True)
assert_raises_message(
exc.ArgumentError,
r"secondary argument <class .*C.*> passed to to "
r"relationship\(\) A.bs "
"must be a Table object or other FROM clause; can't send a "
"mapped class directly as rows in 'secondary' are persisted "
"independently of a class that is mapped to that same table.",
configure_mappers,
)
| SecondaryArgTest |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 59910,
"end": 62110
} | class ____(ASTBase):
def __init__(
self, args: list[ASTType | ASTTemplateArgConstant], packExpansion: bool
) -> None:
assert args is not None
self.args = args
self.packExpansion = packExpansion
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTTemplateArgs):
return NotImplemented
return self.args == other.args and self.packExpansion == other.packExpansion
def __hash__(self) -> int:
return hash((self.args, self.packExpansion))
def get_id(self, version: int) -> str:
if version == 1:
res: list[str] = []
res.extend((
':',
'.'.join(a.get_id(version) for a in self.args),
':',
))
return ''.join(res)
res = ['I']
if len(self.args) > 0:
for a in self.args[:-1]:
res.append(a.get_id(version))
if self.packExpansion:
res.append('J')
res.append(self.args[-1].get_id(version))
if self.packExpansion:
res.append('E')
res.append('E')
return ''.join(res)
def _stringify(self, transform: StringifyTransform) -> str:
res = ', '.join(transform(a) for a in self.args)
if self.packExpansion:
res += '...'
return '<' + res + '>'
def describe_signature(
self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol
) -> None:
verify_description_mode(mode)
signode += addnodes.desc_sig_punctuation('<', '<')
first = True
for a in self.args:
if not first:
signode += addnodes.desc_sig_punctuation(',', ',')
signode += addnodes.desc_sig_space()
first = False
a.describe_signature(signode, 'markType', env, symbol=symbol)
if self.packExpansion:
signode += addnodes.desc_sig_punctuation('...', '...')
signode += addnodes.desc_sig_punctuation('>', '>')
# Main part of declarations
################################################################################
| ASTTemplateArgs |
python | doocs__leetcode | lcof2/剑指 Offer II 099. 最小路径之和/Solution.py | {
"start": 0,
"end": 481
} | class ____:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [[grid[0][0]] * n for _ in range(m)]
for i in range(1, m):
dp[i][0] = dp[i - 1][0] + grid[i][0]
for j in range(1, n):
dp[0][j] = dp[0][j - 1] + grid[0][j]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
return dp[-1][-1]
| Solution |
python | huggingface__transformers | src/transformers/models/mvp/modeling_mvp.py | {
"start": 3446,
"end": 10588
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: Optional[float] = 0.0,
is_decoder: Optional[bool] = False,
bias: Optional[bool] = True,
layer_idx: Optional[bool] = None,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
self.layer_idx = layer_idx
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
attn_prompt: Optional[torch.Tensor] = None,
output_attentions: bool = False,
cache_position: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
bsz, tgt_len, _ = hidden_states.size()
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
is_updated = False
if past_key_values is not None:
if isinstance(past_key_values, EncoderDecoderCache):
is_updated = past_key_values.is_updated.get(self.layer_idx)
if is_cross_attention:
# after the first generated id, we can subsequently re-use all key/value_states from cache
curr_past_key_values = past_key_values.cross_attention_cache
else:
curr_past_key_values = past_key_values.self_attention_cache
else:
curr_past_key_values = past_key_values
current_states = key_value_states if is_cross_attention else hidden_states
if is_cross_attention and past_key_values is not None and is_updated:
# reuse k,v, cross_attentions
key_states = curr_past_key_values.layers[self.layer_idx].keys
value_states = curr_past_key_values.layers[self.layer_idx].values
else:
key_states = self.k_proj(current_states)
value_states = self.v_proj(current_states)
key_states = key_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
if past_key_values is not None:
# save all key/value_states to cache to be re-used for fast auto-regressive generation
cache_position = cache_position if not is_cross_attention else None
key_states, value_states = curr_past_key_values.update(
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
)
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
past_key_values.is_updated[self.layer_idx] = True
if attn_prompt is not None:
key_states = torch.cat([attn_prompt[0].expand(bsz, -1, -1, -1), key_states], dim=2)
value_states = torch.cat([attn_prompt[1].expand(bsz, -1, -1, -1), value_states], dim=2)
if attention_mask is not None:
prompt_mask = torch.zeros(bsz, 1, tgt_len, attn_prompt[0].size(1)).to(attention_mask.device)
attention_mask = torch.cat([prompt_mask, attention_mask], dim=(-1))
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = query_states.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
query_states = query_states.reshape(*proj_shape)
key_states = key_states.reshape(*proj_shape)
value_states = value_states.reshape(*proj_shape)
src_len = key_states.size(1)
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
raise ValueError(
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
if output_attentions:
# this operation is a bit awkward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to be reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
else:
attn_weights_reshaped = None
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
attn_output = torch.bmm(attn_probs, value_states)
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
raise ValueError(
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
f" {attn_output.size()}"
)
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
attn_output = attn_output.transpose(1, 2)
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
# partitioned across GPUs when using tensor-parallelism.
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights_reshaped
| MvpAttention |
python | kamyu104__LeetCode-Solutions | Python/airplane-seat-assignment-probability.py | {
"start": 805,
"end": 1105
} | class ____(object):
def nthPersonGetsNthSeat(self, n):
"""
:type n: int
:rtype: float
"""
dp = [0.0]*2
dp[0] = 1.0 # zero-indexed
for i in xrange(2, n+1):
dp[(i-1)%2] = 1.0/i+dp[(i-2)%2]*(i-2)/i
return dp[(n-1)%2]
| Solution2 |
python | google__pytype | pytype/pytd/parse/node_test.py | {
"start": 989,
"end": 1282
} | class ____(Node):
"""A node with its own VisitNode function."""
x: Any
y: Any
def VisitNode(self, visitor):
"""Allow a visitor to modify our children. Returns modified node."""
# only visit x, not y
x = self.x.Visit(visitor)
return NodeWithVisit(x, self.y)
| NodeWithVisit |
python | huggingface__transformers | tests/models/aria/test_modeling_aria.py | {
"start": 6283,
"end": 7885
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
"""
Model tester for `AriaForConditionalGeneration`.
"""
all_model_classes = (AriaModel, AriaForConditionalGeneration) if is_torch_available() else ()
_is_composite = True
def setUp(self):
self.model_tester = AriaVisionText2TextModelTester(self)
self.config_tester = ConfigTester(self, config_class=AriaConfig, has_text_modality=False)
@unittest.skip(
reason="This architecture seems to not compute gradients for the last vision-layernorm because the model uses hidden states pre-norm"
)
def test_training_gradient_checkpointing(self):
pass
@unittest.skip(
reason="This architecture seems to not compute gradients for the last vision-layernorm because the model uses hidden states pre-norm"
)
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip(
reason="This architecture seems to not compute gradients for the last vision-layernorm because the model uses hidden states pre-norm"
)
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
SKIP = False
torch_accelerator_module = getattr(torch, torch_device)
memory = 23 # skip on T4 / A10
if hasattr(torch_accelerator_module, "get_device_properties"):
if torch_accelerator_module.get_device_properties(0).total_memory / 1024**3 < memory:
SKIP = True
@unittest.skipIf(SKIP, reason="A10 doesn't have enough GPU memory for this tests")
@require_torch
@slow
| AriaForConditionalGenerationModelTest |
python | plotly__plotly.py | plotly/graph_objs/layout/polar/angularaxis/_tickformatstop.py | {
"start": 235,
"end": 8557
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.polar.angularaxis"
_path_str = "layout.polar.angularaxis.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
"""
return self["dtickrange"]
@dtickrange.setter
def dtickrange(self, val):
self["dtickrange"] = val
@property
def enabled(self):
"""
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["enabled"]
@enabled.setter
def enabled(self, val):
self["enabled"] = val
@property
def name(self):
"""
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["name"]
@name.setter
def name(self, val):
self["name"] = val
@property
def templateitemname(self):
"""
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["templateitemname"]
@templateitemname.setter
def templateitemname(self, val):
self["templateitemname"] = val
@property
def value(self):
"""
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["value"]
@value.setter
def value(self, val):
self["value"] = val
@property
def _prop_descriptions(self):
return """\
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
"""
def __init__(
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs,
):
"""
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.polar.a
ngularaxis.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
"""
super().__init__("tickformatstops")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.layout.polar.angularaxis.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.polar.angularaxis.Tickformatstop`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("dtickrange", arg, dtickrange)
self._set_property("enabled", arg, enabled)
self._set_property("name", arg, name)
self._set_property("templateitemname", arg, templateitemname)
self._set_property("value", arg, value)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Tickformatstop |
python | apache__airflow | providers/dbt/cloud/src/airflow/providers/dbt/cloud/operators/dbt.py | {
"start": 16322,
"end": 18389
} | class ____(BaseOperator):
"""
List jobs in a dbt Cloud project.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DbtCloudListJobsOperator`
Retrieves metadata for all jobs tied to a specified dbt Cloud account. If a ``project_id`` is
supplied, only jobs pertaining to this project id will be retrieved.
:param account_id: Optional. If an account ID is not provided explicitly,
the account ID from the dbt Cloud connection will be used.
:param order_by: Optional. Field to order the result by. Use '-' to indicate reverse order.
For example, to use reverse order by the run ID use ``order_by=-id``.
:param project_id: Optional. The ID of a dbt Cloud project.
:param hook_params: Extra arguments passed to the DbtCloudHook constructor.
"""
template_fields = (
"account_id",
"project_id",
)
def __init__(
self,
*,
dbt_cloud_conn_id: str = DbtCloudHook.default_conn_name,
account_id: int | None = None,
project_id: int | None = None,
order_by: str | None = None,
hook_params: dict[str, Any] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.dbt_cloud_conn_id = dbt_cloud_conn_id
self.account_id = account_id
self.project_id = project_id
self.order_by = order_by
self.hook_params = hook_params or {}
def execute(self, context: Context) -> list:
hook = DbtCloudHook(self.dbt_cloud_conn_id, **self.hook_params)
list_jobs_response = hook.list_jobs(
account_id=self.account_id, order_by=self.order_by, project_id=self.project_id
)
buffer = []
for job_metadata in list_jobs_response:
for job in job_metadata.json()["data"]:
buffer.append(job["id"])
self.log.info("Jobs in the specified dbt Cloud account are: %s", ", ".join(map(str, buffer)))
return buffer
| DbtCloudListJobsOperator |
python | zarr-developers__zarr-python | tests/test_store/test_memory.py | {
"start": 2546,
"end": 4555
} | class ____(StoreTests[GpuMemoryStore, gpu.Buffer]):
store_cls = GpuMemoryStore
buffer_cls = gpu.Buffer
async def set(self, store: GpuMemoryStore, key: str, value: gpu.Buffer) -> None: # type: ignore[override]
store._store_dict[key] = value
async def get(self, store: MemoryStore, key: str) -> Buffer:
return store._store_dict[key]
@pytest.fixture(params=[None, True])
def store_kwargs(self, request: pytest.FixtureRequest) -> dict[str, Any]:
kwargs: dict[str, Any]
if request.param is True:
kwargs = {"store_dict": {}}
else:
kwargs = {"store_dict": None}
return kwargs
@pytest.fixture
async def store(self, store_kwargs: dict[str, Any]) -> GpuMemoryStore:
return self.store_cls(**store_kwargs)
def test_store_repr(self, store: GpuMemoryStore) -> None:
assert str(store) == f"gpumemory://{id(store._store_dict)}"
def test_store_supports_writes(self, store: GpuMemoryStore) -> None:
assert store.supports_writes
def test_store_supports_listing(self, store: GpuMemoryStore) -> None:
assert store.supports_listing
async def test_list_prefix(self, store: GpuMemoryStore) -> None:
assert True
def test_dict_reference(self, store: GpuMemoryStore) -> None:
store_dict: dict[str, Any] = {}
result = GpuMemoryStore(store_dict=store_dict)
assert result._store_dict is store_dict
def test_from_dict(self) -> None:
d = {
"a": gpu.Buffer.from_bytes(b"aaaa"),
"b": cpu.Buffer.from_bytes(b"bbbb"),
}
msg = "Creating a zarr.buffer.gpu.Buffer with an array that does not support the __cuda_array_interface__ for zero-copy transfers, falling back to slow copy based path"
with pytest.warns(ZarrUserWarning, match=msg):
result = GpuMemoryStore.from_dict(d)
for v in result._store_dict.values():
assert type(v) is gpu.Buffer
| TestGpuMemoryStore |
python | doocs__leetcode | solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.py | {
"start": 0,
"end": 323
} | class ____:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
nums = sorted(set(nums))
ans, j = n, 0
for i, v in enumerate(nums):
while j < len(nums) and nums[j] - v <= n - 1:
j += 1
ans = min(ans, n - (j - i))
return ans
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1013911,
"end": 1014346
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnpinIssue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "issue")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
issue = sgqlc.types.Field("Issue", graphql_name="issue")
"""The issue that was unpinned"""
| UnpinIssuePayload |
python | ansible__ansible | lib/ansible/plugins/shell/__init__.py | {
"start": 1351,
"end": 10975
} | class ____(AnsiblePlugin):
def __init__(self):
super(ShellBase, self).__init__()
# Not used but here for backwards compatibility.
# ansible.posix.fish uses (but does not actually use) this value.
# https://github.com/ansible-collections/ansible.posix/blob/f41f08e9e3d3129e709e122540b5ae6bc19932be/plugins/shell/fish.py#L38-L39
self.env = {}
self.tmpdir = None
self.executable = None
def _normalize_system_tmpdirs(self):
# Normalize the tmp directory strings. We don't use expanduser/expandvars because those
# can vary between remote user and become user. Therefore the safest practice will be for
# this to always be specified as full paths)
normalized_paths = [d.rstrip('/') for d in self.get_option('system_tmpdirs')]
# Make sure all system_tmpdirs are absolute otherwise they'd be relative to the login dir
# which is almost certainly going to fail in a cornercase.
if not all(os.path.isabs(d) for d in normalized_paths):
raise AnsibleError('The configured system_tmpdirs contains a relative path: {0}. All'
' system_tmpdirs must be absolute'.format(to_native(normalized_paths)))
self.set_option('system_tmpdirs', normalized_paths)
def set_options(self, task_keys=None, var_options=None, direct=None):
super(ShellBase, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
# We can remove the try: except in the future when we make ShellBase a proper subset of
# *all* shells. Right now powershell and third party shells which do not use the
# shell_common documentation fragment (and so do not have system_tmpdirs) will fail
try:
self._normalize_system_tmpdirs()
except KeyError:
pass
@staticmethod
def _generate_temp_dir_name():
return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), secrets.randbelow(2**48))
def env_prefix(self, **kwargs):
return ' '.join(['%s=%s' % (k, self.quote(str(v))) for k, v in kwargs.items()])
def join_path(self, *args):
return os.path.join(*args)
# some shells (eg, powershell) are snooty about filenames/extensions, this lets the shell plugin have a say
def get_remote_filename(self, pathname):
base_name = os.path.basename(pathname.strip())
return base_name.strip()
def path_has_trailing_slash(self, path):
return path.endswith('/')
def chmod(self, paths, mode):
cmd = ['chmod', mode]
cmd.extend(paths)
return self.join(cmd)
def chown(self, paths, user):
cmd = ['chown', user]
cmd.extend(paths)
return self.join(cmd)
def chgrp(self, paths, group):
cmd = ['chgrp', group]
cmd.extend(paths)
return self.join(cmd)
def set_user_facl(self, paths, user, mode):
"""Only sets acls for users as that's really all we need"""
cmd = ['setfacl', '-m', 'u:%s:%s' % (user, mode)]
cmd.extend(paths)
return self.join(cmd)
def remove(self, path, recurse=False):
path = self.quote(path)
cmd = 'rm -f '
if recurse:
cmd += '-r '
return cmd + "%s %s" % (path, self._SHELL_REDIRECT_ALLNULL)
def exists(self, path):
cmd = ['test', '-e', self.quote(path)]
return ' '.join(cmd)
def mkdtemp(
self,
basefile: str | None = None,
system: bool = False,
mode: int = 0o700,
tmpdir: str | None = None,
) -> str:
if not basefile:
basefile = self.__class__._generate_temp_dir_name()
# When system is specified we have to create this in a directory where
# other users can read and access the tmp directory.
# This is because we use system to create tmp dirs for unprivileged users who are
# sudo'ing to a second unprivileged user.
# The 'system_tmpdirs' setting defines directories we can use for this purpose
# the default are, /tmp and /var/tmp.
# So we only allow one of those locations if system=True, using the
# passed in tmpdir if it is valid or the first one from the setting if not.
if system:
if tmpdir:
tmpdir = tmpdir.rstrip('/')
if tmpdir in self.get_option('system_tmpdirs'):
basetmpdir = tmpdir
else:
basetmpdir = self.get_option('system_tmpdirs')[0]
else:
if tmpdir is None:
basetmpdir = self.get_option('remote_tmp')
else:
basetmpdir = tmpdir
basetmp = self.join_path(basetmpdir, basefile)
# use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us
cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT)
cmd += '%s mkdir %s echo %s %s' % (self._SHELL_AND, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
# change the umask in a subshell to achieve the desired mode
# also for directories created with `mkdir -p`
if mode:
tmp_umask = 0o777 & ~mode
cmd = '%s umask %o %s %s %s' % (self._SHELL_GROUP_LEFT, tmp_umask, self._SHELL_AND, cmd, self._SHELL_GROUP_RIGHT)
return cmd
def _mkdtemp2(
self,
basefile: str | None = None,
system: bool = False,
mode: int = 0o700,
tmpdir: str | None = None,
) -> _ShellCommand:
"""Gets command info to create a temporary directory.
This is an internal API that should not be used publicly.
:args basefile: The base name of the temporary directory.
:args system: If True, create the directory in a system-wide location.
:args mode: The permissions mode for the directory.
:args tmpdir: The directory in which to create the temporary directory.
:returns: The shell command to run to create the temp directory.
"""
cmd = self.mkdtemp(basefile=basefile, system=system, mode=mode, tmpdir=tmpdir)
return _ShellCommand(command=cmd, input_data=None)
def expand_user(
self,
user_home_path: str,
username: str = '',
) -> str:
""" Return a command to expand tildes in a path
It can be either "~" or "~username". We just ignore $HOME
We use the POSIX definition of a username:
http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap03.html#tag_03_426
http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap03.html#tag_03_276
Falls back to 'current working directory' as we assume 'home is where the remote user ends up'
"""
# Check that the user_path to expand is safe
if user_home_path != '~':
if not _USER_HOME_PATH_RE.match(user_home_path):
user_home_path = self.quote(user_home_path)
elif username:
# if present the user name is appended to resolve "that user's home"
user_home_path += username
return 'echo %s' % user_home_path
def _expand_user2(
self,
user_home_path: str,
username: str = '',
) -> _ShellCommand:
"""Gets command to expand user path.
This is an internal API that should not be used publicly.
:args user_home_path: The path to expand.
:args username: The username to use for expansion.
:returns: The shell command to run to get the expanded user path.
"""
cmd = self.expand_user(user_home_path, username=username)
return _ShellCommand(command=cmd, input_data=None)
def pwd(self):
"""Return the working directory after connecting"""
return 'echo %spwd%s' % (self._SHELL_SUB_LEFT, self._SHELL_SUB_RIGHT)
def build_module_command(self, env_string, shebang, cmd, arg_path=None):
env_string = env_string.strip()
if env_string:
env_string += ' '
if shebang is None:
shebang = ''
cmd_parts = [
shebang.removeprefix('#!').strip(),
cmd.strip(),
arg_path,
]
cleaned_up_cmd = self.join(
stripped_cmd_part for raw_cmd_part in cmd_parts
if raw_cmd_part and (stripped_cmd_part := raw_cmd_part.strip())
)
return ''.join((env_string, cleaned_up_cmd))
def append_command(self, cmd, cmd_to_append):
"""Append an additional command if supported by the shell"""
if self._SHELL_AND:
cmd += ' %s %s' % (self._SHELL_AND, cmd_to_append)
return cmd
def wrap_for_exec(self, cmd):
"""wrap script execution with any necessary decoration (eg '&' for quoted powershell script paths)"""
display.deprecated(
msg='The Shell.wrap_for_exec method is deprecated.',
help_text="Contact plugin author to update their plugin to not use this method.",
version='2.24',
)
return cmd
def quote(self, cmd):
"""Returns a shell-escaped string that can be safely used as one token in a shell command line"""
return shlex.quote(cmd)
def join(self, cmd_parts):
"""Returns a shell-escaped string from a list that can be safely used in a shell command line"""
return shlex.join(cmd_parts)
| ShellBase |
python | coleifer__peewee | tests/regressions.py | {
"start": 4097,
"end": 6411
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [DiA, DiB, DiC, DiD, DiBA]
def test_delete_instance_regression(self):
with self.database.atomic():
a1, a2, a3 = [DiA.create(a=a) for a in ('a1', 'a2', 'a3')]
for a in (a1, a2, a3):
for j in (1, 2):
b = DiB.create(a=a, b='%s-b%s' % (a.a, j))
c = DiC.create(b=b, c='%s-c' % (b.b))
d = DiD.create(c=c, d='%s-d' % (c.c))
DiBA.create(a=a, b='%s-b%s' % (a.a, j))
# (a1 (b1 (c (d))), (b2 (c (d)))), (a2 ...), (a3 ...)
with self.assertQueryCount(5):
a2.delete_instance(recursive=True)
self.assertHistory(5, [
('DELETE FROM "di_d" WHERE ("di_d"."c_id" IN ('
'SELECT "t1"."id" FROM "di_c" AS "t1" WHERE ("t1"."b_id" IN ('
'SELECT "t2"."id" FROM "di_b" AS "t2" WHERE ("t2"."a_id" = ?)'
'))))', [2]),
('DELETE FROM "di_c" WHERE ("di_c"."b_id" IN ('
'SELECT "t1"."id" FROM "di_b" AS "t1" WHERE ("t1"."a_id" = ?)'
'))', [2]),
('DELETE FROM "di_ba" WHERE ("di_ba"."a_id" = ?)', ['a2']),
('DELETE FROM "di_b" WHERE ("di_b"."a_id" = ?)', [2]),
('DELETE FROM "di_a" WHERE ("di_a"."id" = ?)', [2])
])
# a1 & a3 exist, plus their relations.
self.assertTrue(DiA.select().count(), 2)
for rel in (DiB, DiBA, DiC, DiD):
self.assertTrue(rel.select().count(), 4) # 2x2
with self.assertQueryCount(5):
a1.delete_instance(recursive=True)
# Only the objects related to a3 exist still.
self.assertTrue(DiA.select().count(), 1)
self.assertEqual(DiA.get(DiA.a == 'a3').id, a3.id)
self.assertEqual([d.d for d in DiD.select().order_by(DiD.d)],
['a3-b1-c-d', 'a3-b2-c-d'])
self.assertEqual([c.c for c in DiC.select().order_by(DiC.c)],
['a3-b1-c', 'a3-b2-c'])
self.assertEqual([b.b for b in DiB.select().order_by(DiB.b)],
['a3-b1', 'a3-b2'])
self.assertEqual([ba.b for ba in DiBA.select().order_by(DiBA.b)],
['a3-b1', 'a3-b2'])
| TestDeleteInstanceRegression |
python | doocs__leetcode | solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/Solution2.py | {
"start": 0,
"end": 957
} | class ____:
def longestSubarray(self, nums: List[int], limit: int) -> int:
def check(k: int) -> bool:
min_q = deque()
max_q = deque()
for i, x in enumerate(nums):
if min_q and i - min_q[0] + 1 > k:
min_q.popleft()
if max_q and i - max_q[0] + 1 > k:
max_q.popleft()
while min_q and nums[min_q[-1]] >= x:
min_q.pop()
while max_q and nums[max_q[-1]] <= x:
max_q.pop()
min_q.append(i)
max_q.append(i)
if i >= k - 1 and nums[max_q[0]] - nums[min_q[0]] <= limit:
return True
return False
l, r = 1, len(nums)
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l
| Solution |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/control.py | {
"start": 1695,
"end": 6657
} | class ____:
"""A renderable that inserts a control code (non printable but may move cursor).
Args:
*codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a
tuple of ControlType and an integer parameter
"""
__slots__ = ["segment"]
def __init__(self, *codes: Union[ControlType, ControlCode]) -> None:
control_codes: List[ControlCode] = [
(code,) if isinstance(code, ControlType) else code for code in codes
]
_format_map = CONTROL_CODES_FORMAT
rendered_codes = "".join(
_format_map[code](*parameters) for code, *parameters in control_codes
)
self.segment = Segment(rendered_codes, None, control_codes)
@classmethod
def bell(cls) -> "Control":
"""Ring the 'bell'."""
return cls(ControlType.BELL)
@classmethod
def home(cls) -> "Control":
"""Move cursor to 'home' position."""
return cls(ControlType.HOME)
@classmethod
def move(cls, x: int = 0, y: int = 0) -> "Control":
"""Move cursor relative to current position.
Args:
x (int): X offset.
y (int): Y offset.
Returns:
~Control: Control object.
"""
def get_codes() -> Iterable[ControlCode]:
control = ControlType
if x:
yield (
control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD,
abs(x),
)
if y:
yield (
control.CURSOR_DOWN if y > 0 else control.CURSOR_UP,
abs(y),
)
control = cls(*get_codes())
return control
@classmethod
def move_to_column(cls, x: int, y: int = 0) -> "Control":
"""Move to the given column, optionally add offset to row.
Returns:
x (int): absolute x (column)
y (int): optional y offset (row)
Returns:
~Control: Control object.
"""
return (
cls(
(ControlType.CURSOR_MOVE_TO_COLUMN, x),
(
ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP,
abs(y),
),
)
if y
else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x))
)
@classmethod
def move_to(cls, x: int, y: int) -> "Control":
"""Move cursor to absolute position.
Args:
x (int): x offset (column)
y (int): y offset (row)
Returns:
~Control: Control object.
"""
return cls((ControlType.CURSOR_MOVE_TO, x, y))
@classmethod
def clear(cls) -> "Control":
"""Clear the screen."""
return cls(ControlType.CLEAR)
@classmethod
def show_cursor(cls, show: bool) -> "Control":
"""Show or hide the cursor."""
return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR)
@classmethod
def alt_screen(cls, enable: bool) -> "Control":
"""Enable or disable alt screen."""
if enable:
return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME)
else:
return cls(ControlType.DISABLE_ALT_SCREEN)
@classmethod
def title(cls, title: str) -> "Control":
"""Set the terminal window title
Args:
title (str): The new terminal window title
"""
return cls((ControlType.SET_WINDOW_TITLE, title))
def __str__(self) -> str:
return self.segment.text
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
if self.segment.text:
yield self.segment
def strip_control_codes(
text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE
) -> str:
"""Remove control codes from text.
Args:
text (str): A string possibly contain control codes.
Returns:
str: String with control codes removed.
"""
return text.translate(_translate_table)
def escape_control_codes(
text: str,
_translate_table: Dict[int, str] = CONTROL_ESCAPE,
) -> str:
"""Replace control codes with their "escaped" equivalent in the given text.
(e.g. "\b" becomes "\\b")
Args:
text (str): A string possibly containing control codes.
Returns:
str: String with control codes replaced with their escaped version.
"""
return text.translate(_translate_table)
if __name__ == "__main__": # pragma: no cover
from pipenv.patched.pip._vendor.rich.console import Console
console = Console()
console.print("Look at the title of your terminal window ^")
# console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!")))
for i in range(10):
console.set_window_title("🚀 Loading" + "." * i)
time.sleep(0.5)
| Control |
python | kamyu104__LeetCode-Solutions | Python/strobogrammatic-number-ii.py | {
"start": 39,
"end": 491
} | class ____(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
result = ['0', '1', '8'] if n%2 else ['']
for i in xrange(n%2, n, 2):
result = [a + num + b for a, b in lookup.iteritems() if i != n-2 or a != '0' for num in result]
return result
# Time: O(n * 5^(n/2))
# Space: O(n)
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_hash.py | {
"start": 462,
"end": 606
} | class ____:
def __hash__(self):
return return_int() # [invalid-hash-return]
# These testcases should NOT raise errors
| ComplexReturn |
python | google__jax | jax/_src/pjit.py | {
"start": 30391,
"end": 35700
} | class ____(stages.Wrapped):
def eval_shape(self, *args, **kwargs):
"""See ``jax.eval_shape``."""
raise NotImplementedError
def trace(self, *args, **kwargs) -> stages.Traced:
raise NotImplementedError
# in_shardings and out_shardings can't be None as the default value
# because `None` means that the input is fully replicated.
@partial(api_boundary, repro_api_name="pjit.pjit")
def pjit(
fun: Callable,
in_shardings: Any = UNSPECIFIED,
out_shardings: Any = UNSPECIFIED,
static_argnums: int | Sequence[int] | None = None,
static_argnames: str | Iterable[str] | None = None,
donate_argnums: int | Sequence[int] | None = None,
donate_argnames: str | Iterable[str] | None = None,
keep_unused: bool = False,
device: xc.Device | None = None,
backend: str | None = None,
inline: bool = False,
abstracted_axes: Any | None = None,
compiler_options: dict[str, Any] | None = None,
) -> JitWrapped:
"""`jax.experimental.pjit.pjit` has been deprecated. Please use `jax.jit`."""
return make_jit(
fun, in_shardings=in_shardings, out_shardings=out_shardings,
static_argnums=static_argnums, static_argnames=static_argnames,
donate_argnums=donate_argnums, donate_argnames=donate_argnames,
keep_unused=keep_unused, device=device, backend=backend, inline=inline,
abstracted_axes=abstracted_axes, compiler_options=compiler_options,
use_resource_env=True)
def hashable_pytree(pytree):
vals, treedef = tree_flatten(pytree)
vals = tuple(vals)
return HashableFunction(lambda: tree_unflatten(treedef, vals),
closure=(treedef, vals))
def _create_sharding_for_array(mesh, x, name, api_name):
if x is None:
if api_name == 'jit' or mesh.empty:
return UNSPECIFIED
return sharding_impls.cached_named_sharding(mesh, PartitionSpec())
if isinstance(x, (AUTO, UnspecifiedValue, Sharding)):
return x
if mesh.empty:
raise RuntimeError(
f'{api_name} requires a non-empty mesh in context if you are passing'
f' `PartitionSpec`s to {name}. You can define a context mesh via'
' `jax.set_mesh(mesh)`. Alternatively, provide `Sharding`s to'
f' {name} and then the mesh context manager is not required.')
assert isinstance(x, PartitionSpec), x
return sharding_impls.cached_named_sharding(mesh, x)
def _create_sharding_with_device_backend(device, backend):
if device is not None:
assert backend is None
out = SingleDeviceSharding(device)
elif backend is not None:
assert device is None
out = SingleDeviceSharding(xb.get_backend(backend).local_devices()[0])
else:
raise AssertionError('Unreachable!')
out._device_backend = True
return out
def flatten_axis_resources(what, tree, shardings, tupled_args):
try:
return tuple(flatten_axes(what, tree, shardings, tupled_args=tupled_args))
except ValueError:
pass # Raise a tree prefix error below
# Tree leaves are always valid prefixes, so if there was a prefix error as
# assumed here, axis_resources must not be a leaf.
assert not treedef_is_leaf(tree_structure(shardings))
# Check the type directly rather than using isinstance because of namedtuples.
if tupled_args and (type(shardings) is not tuple or
len(shardings) != len(tree.children())):
# We know axis_resources is meant to be a tuple corresponding to the args
# tuple, but while it is a non-leaf pytree, either it wasn't a tuple or it
# wasn't the right length.
msg = (f"{what} specification must be a tree prefix of the positional "
f"arguments tuple. In particular, {what} must either be a Sharding, "
"a PartitionSpec, or a tuple of length equal to the number of "
"positional arguments.")
# If `tree` represents an args tuple, then `axis_resources` must be a tuple.
# TODO(mattjj,apaszke): disable implicit list casts, remove 'or list' below
if type(shardings) is not tuple:
msg += f" But {what} is not a tuple: got {type(shardings)} instead."
elif len(shardings) != len(tree.children()):
msg += (f" But {what} is the wrong length: got a tuple or list of length "
f"{len(shardings)} for an args tuple of length "
f"{len(tree.children())}.")
# As an extra hint, let's check if the user just forgot to wrap
# shardings in a singleton tuple.
if len(tree.children()) == 1:
try: flatten_axes(what, tree, (shardings,))
except ValueError: pass # That's not the issue.
else:
msg += (f" Given the corresponding argument being "
f"passed, it looks like {what} might need to be wrapped in "
f"a singleton tuple.")
raise ValueError(msg)
axis_tree = shardings
# Because we only have the `tree` treedef and not the full pytree here,
# we construct a dummy tree to compare against. Revise this in callers?
dummy_tree = tree_unflatten(tree, [PytreeLeaf()] * tree.num_leaves)
errors = prefix_errors(axis_tree, dummy_tree)
if errors:
e = errors[0] # Only show information about the first disagreement found.
raise e(what)
# At this point we've failed to find a tree prefix error.
assert False, "Please open a bug report!" # This should be unreachable.
| JitWrapped |
python | django__django | tests/admin_views/models.py | {
"start": 21690,
"end": 22088
} | class ____(models.Model):
name = models.CharField(max_length=100)
pubdate = models.DateField()
status = models.CharField(
max_length=20,
choices=(("option one", "Option One"), ("option two", "Option Two")),
)
slug1 = models.SlugField(blank=True)
slug2 = models.SlugField(blank=True)
slug3 = models.SlugField(blank=True, allow_unicode=True)
| MainPrepopulated |
python | sphinx-doc__sphinx | sphinx/transforms/__init__.py | {
"start": 6712,
"end": 7267
} | class ____(SphinxTransform):
"""Register IDs of tables, figures and literal_blocks to assign numbers."""
default_priority = 210
def apply(self, **kwargs: Any) -> None:
domain: StandardDomain = self.env.domains.standard_domain
for node in self.document.findall(nodes.Element):
if (
domain.is_enumerable_node(node)
and domain.get_numfig_title(node) is not None
and node['ids'] == []
):
self.document.note_implicit_target(node)
| AutoNumbering |
python | doocs__leetcode | solution/1900-1999/1945.Sum of Digits of String After Convert/Solution.py | {
"start": 0,
"end": 233
} | class ____:
def getLucky(self, s: str, k: int) -> int:
s = ''.join(str(ord(c) - ord('a') + 1) for c in s)
for _ in range(k):
t = sum(int(c) for c in s)
s = str(t)
return int(s)
| Solution |
python | wandb__wandb | wandb/automations/events.py | {
"start": 6140,
"end": 6980
} | class ____(FilterEventFields): # from: FilterEventTriggeringCondition
"""A triggering event from a saved automation."""
event_type: Annotated[EventType, Field(frozen=True)] # type: ignore[assignment]
# We override the type of the `filter` field in order to enforce the expected
# structure for the JSON data when validating and serializing.
filter: JsonEncoded[
Union[_WrappedSavedEventFilter, RunMetricFilter, RunStateFilter]
]
"""The condition(s) under which this event triggers an automation."""
# ------------------------------------------------------------------------------
# Input types: for creating or updating automations
# Note: The GQL input for `eventFilter` does NOT wrap the filter in an extra
# `filter` key, unlike the `eventFilter` in GQL responses for saved automations.
| SavedEvent |
python | walkccc__LeetCode | solutions/448. Find All Numbers Disappeared in an Array/448.py | {
"start": 0,
"end": 229
} | class ____:
def findDisappearedNumbers(self, nums: list[int]) -> list[int]:
for num in nums:
index = abs(num) - 1
nums[index] = -abs(nums[index])
return [i + 1 for i, num in enumerate(nums) if num > 0]
| Solution |
python | spyder-ide__spyder | spyder/plugins/switcher/container.py | {
"start": 620,
"end": 3544
} | class ____(PluginMainContainer):
# ---- PluginMainContainer API
# -------------------------------------------------------------------------
def setup(self):
self.switcher = Switcher(self._plugin.get_main())
# Switcher shortcuts
self.create_action(
SwitcherActions.FileSwitcherAction,
_('File switcher...'),
icon=self._plugin.get_icon(),
tip=_('Fast switch between files'),
triggered=self.open_switcher,
register_shortcut=True,
context=Qt.ApplicationShortcut,
shortcut_context="_",
)
self.create_action(
SwitcherActions.SymbolFinderAction,
_('Symbol finder...'),
icon=self.create_icon('symbol_find'),
tip=_('Fast symbol search in file'),
triggered=self.open_symbolfinder,
register_shortcut=True,
context=Qt.ApplicationShortcut,
shortcut_context="_",
)
def update_actions(self):
pass
# ---- Public API
# -------------------------------------------------------------------------
def open_switcher(self, symbol=False):
"""Open switcher dialog."""
switcher = self.switcher
if switcher is not None and switcher.isVisible():
switcher.clear()
switcher.hide()
return
# Set mode and setup
if symbol:
# Avoid emitting sig_search_text_available
with signals_blocked(switcher.edit):
switcher.set_search_text('@')
# Manually set mode and emit sig_mode_selected so that symbols are
# shown instantly.
switcher._mode_on = "@"
switcher.sig_mode_selected.emit("@")
else:
switcher.set_search_text('')
# Setup
switcher.setup()
# Set position
mainwindow = self._plugin.get_main()
# Note: The +3 pixels makes it vertically align with the main menu or
# main menu + toolbar
default_top_without_toolbar = (
mainwindow.menuBar().geometry().height()
+ 3
)
default_top_with_toolbar = (
int(APP_TOOLBAR_STYLESHEET.BUTTON_HEIGHT.split("px")[0])
+ default_top_without_toolbar
)
current_window = QApplication.activeWindow()
if current_window == mainwindow:
if self.get_conf('toolbars_visible', section='toolbar'):
delta_top = default_top_with_toolbar
else:
delta_top = default_top_without_toolbar
else:
delta_top = default_top_with_toolbar
switcher.set_position(delta_top, current_window)
switcher.show()
def open_symbolfinder(self):
"""Open symbol list management dialog box."""
self.open_switcher(symbol=True)
| SwitcherContainer |
python | redis__redis-py | tests/ssl_utils.py | {
"start": 208,
"end": 1408
} | class ____(str, enum.Enum):
client = "client"
server = "server"
TLSFiles = namedtuple("TLSFiles", ["certfile", "keyfile", "ca_certfile"])
def get_tls_certificates(
subdir: str = "standalone",
cert_type: CertificateType = CertificateType.client,
):
root = os.path.join(os.path.dirname(__file__), "..")
cert_subdir = ("dockers", subdir, "tls")
cert_dir = os.path.abspath(os.path.join(root, *cert_subdir))
if not os.path.isdir(cert_dir): # github actions package validation case
cert_dir = os.path.abspath(os.path.join(root, "..", *cert_subdir))
if not os.path.isdir(cert_dir):
raise OSError(f"No SSL certificates found. They should be in {cert_dir}")
if cert_type == CertificateType.client:
return TLSFiles(
os.path.join(cert_dir, CLIENT_CERT_NAME),
os.path.join(cert_dir, CLIENT_KEY_NAME),
os.path.join(cert_dir, CA_CERT_NAME),
)
elif cert_type == CertificateType.server:
return TLSFiles(
os.path.join(cert_dir, SERVER_CERT_NAME),
os.path.join(cert_dir, SERVER_KEY_NAME),
os.path.join(cert_dir, CA_CERT_NAME),
)
| CertificateType |
python | huggingface__transformers | src/transformers/models/xlm_roberta/modular_xlm_roberta.py | {
"start": 20001,
"end": 23436
} | class ____(RobertaForQuestionAnswering):
def __init__(self, config):
super().__init__(config)
del self.xlm_roberta
self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
start_positions: Optional[torch.LongTensor] = None,
end_positions: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
r"""
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
>= 2. All the value in this tensor should be always < type_vocab_size.
[What are token type IDs?](../glossary#token-type-ids)
"""
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
__all__ = [
"XLMRobertaForCausalLM",
"XLMRobertaForMaskedLM",
"XLMRobertaForMultipleChoice",
"XLMRobertaForQuestionAnswering",
"XLMRobertaForSequenceClassification",
"XLMRobertaForTokenClassification",
"XLMRobertaModel",
"XLMRobertaPreTrainedModel",
]
| XLMRobertaForQuestionAnswering |
python | openai__openai-python | examples/parsing_tools_stream.py | {
"start": 122,
"end": 948
} | class ____(BaseModel):
city: str
country: str
client = OpenAI()
with client.chat.completions.stream(
model="gpt-4o-2024-08-06",
messages=[
{
"role": "user",
"content": "What's the weather like in SF and New York?",
},
],
tools=[
# because we're using `.parse_stream()`, the returned tool calls
# will be automatically deserialized into this `GetWeather` type
openai.pydantic_function_tool(GetWeather, name="get_weather"),
],
parallel_tool_calls=True,
) as stream:
for event in stream:
if event.type == "tool_calls.function.arguments.delta" or event.type == "tool_calls.function.arguments.done":
rich.get_console().print(event, width=80)
print("----\n")
rich.print(stream.get_final_completion())
| GetWeather |
python | scikit-learn__scikit-learn | sklearn/ensemble/_forest.py | {
"start": 41346,
"end": 58108
} | class ____(ForestClassifier):
"""
A random forest classifier.
A random forest is a meta estimator that fits a number of decision tree
classifiers on various sub-samples of the dataset and uses averaging to
improve the predictive accuracy and control over-fitting.
Trees in the forest use the best split strategy, i.e. equivalent to passing
`splitter="best"` to the underlying :class:`~sklearn.tree.DecisionTreeClassifier`.
The sub-sample size is controlled with the `max_samples` parameter if
`bootstrap=True` (default), otherwise the whole dataset is used to build
each tree.
For a comparison between tree-based ensemble models see the example
:ref:`sphx_glr_auto_examples_ensemble_plot_forest_hist_grad_boosting_comparison.py`.
This estimator has native support for missing values (NaNs). During training,
the tree grower learns at each split point whether samples with missing values
should go to the left or right child, based on the potential gain. When predicting,
samples with missing values are assigned to the left or right child consequently.
If no missing values were encountered for a given feature during training, then
samples with missing values are mapped to whichever child has the most samples.
Read more in the :ref:`User Guide <forest>`.
Parameters
----------
n_estimators : int, default=100
The number of trees in the forest.
.. versionchanged:: 0.22
The default value of ``n_estimators`` changed from 10 to 100
in 0.22.
criterion : {"gini", "entropy", "log_loss"}, default="gini"
The function to measure the quality of a split. Supported criteria are
"gini" for the Gini impurity and "log_loss" and "entropy" both for the
Shannon information gain, see :ref:`tree_mathematical_formulation`.
Note: This parameter is tree-specific.
max_depth : int, default=None
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int or float, default=2
The minimum number of samples required to split an internal node:
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a fraction and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
.. versionchanged:: 0.18
Added float values for fractions.
min_samples_leaf : int or float, default=1
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least ``min_samples_leaf`` training samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression.
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a fraction and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
.. versionchanged:: 0.18
Added float values for fractions.
min_weight_fraction_leaf : float, default=0.0
The minimum weighted fraction of the sum total of weights (of all
the input samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided.
max_features : {"sqrt", "log2", None}, int or float, default="sqrt"
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a fraction and
`max(1, int(max_features * n_features_in_))` features are considered at each
split.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
.. versionchanged:: 1.1
The default of `max_features` changed from `"auto"` to `"sqrt"`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
max_leaf_nodes : int, default=None
Grow trees with ``max_leaf_nodes`` in best-first fashion.
Best nodes are defined as relative reduction in impurity.
If None then unlimited number of leaf nodes.
min_impurity_decrease : float, default=0.0
A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.
The weighted impurity decrease equation is the following::
N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)
where ``N`` is the total number of samples, ``N_t`` is the number of
samples at the current node, ``N_t_L`` is the number of samples in the
left child, and ``N_t_R`` is the number of samples in the right child.
``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
if ``sample_weight`` is passed.
.. versionadded:: 0.19
bootstrap : bool, default=True
Whether bootstrap samples are used when building trees. If False, the
whole dataset is used to build each tree.
oob_score : bool or callable, default=False
Whether to use out-of-bag samples to estimate the generalization score.
By default, :func:`~sklearn.metrics.accuracy_score` is used.
Provide a callable with signature `metric(y_true, y_pred)` to use a
custom metric. Only available if `bootstrap=True`.
For an illustration of out-of-bag (OOB) error estimation, see the example
:ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`.
n_jobs : int, default=None
The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
:meth:`decision_path` and :meth:`apply` are all parallelized over the
trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`
context. ``-1`` means using all processors. See :term:`Glossary
<n_jobs>` for more details.
random_state : int, RandomState instance or None, default=None
Controls both the randomness of the bootstrapping of the samples used
when building trees (if ``bootstrap=True``) and the sampling of the
features to consider when looking for the best split at each node
(if ``max_features < n_features``).
See :term:`Glossary <random_state>` for details.
verbose : int, default=0
Controls the verbosity when fitting and predicting.
warm_start : bool, default=False
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble, otherwise, just fit a whole
new forest. See :term:`Glossary <warm_start>` and
:ref:`tree_ensemble_warm_start` for details.
class_weight : {"balanced", "balanced_subsample"}, dict or list of dicts, \
default=None
Weights associated with classes in the form ``{class_label: weight}``.
If not given, all classes are supposed to have weight one. For
multi-output problems, a list of dicts can be provided in the same
order as the columns of y.
Note that for multioutput (including multilabel) weights should be
defined for each class of every column in its own dict. For example,
for four-class multilabel classification weights should be
[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of
[{1:1}, {2:5}, {3:1}, {4:1}].
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
The "balanced_subsample" mode is the same as "balanced" except that
weights are computed based on the bootstrap sample for every tree
grown.
For multi-output, the weights of each column of y will be multiplied.
Note that these weights will be multiplied with sample_weight (passed
through the fit method) if sample_weight is specified.
ccp_alpha : non-negative float, default=0.0
Complexity parameter used for Minimal Cost-Complexity Pruning. The
subtree with the largest cost complexity that is smaller than
``ccp_alpha`` will be chosen. By default, no pruning is performed. See
:ref:`minimal_cost_complexity_pruning` for details. See
:ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py`
for an example of such pruning.
.. versionadded:: 0.22
max_samples : int or float, default=None
If bootstrap is True, the number of samples to draw from X
to train each base estimator.
- If None (default), then draw `X.shape[0]` samples.
- If int, then draw `max_samples` samples.
- If float, then draw `max(round(n_samples * max_samples), 1)` samples. Thus,
`max_samples` should be in the interval `(0.0, 1.0]`.
.. versionadded:: 0.22
monotonic_cst : array-like of int of shape (n_features), default=None
Indicates the monotonicity constraint to enforce on each feature.
- 1: monotonic increase
- 0: no constraint
- -1: monotonic decrease
If monotonic_cst is None, no constraints are applied.
Monotonicity constraints are not supported for:
- multiclass classifications (i.e. when `n_classes > 2`),
- multioutput classifications (i.e. when `n_outputs_ > 1`),
- classifications trained on data with missing values.
The constraints hold over the probability of the positive class.
Read more in the :ref:`User Guide <monotonic_cst_gbdt>`.
.. versionadded:: 1.4
Attributes
----------
estimator_ : :class:`~sklearn.tree.DecisionTreeClassifier`
The child estimator template used to create the collection of fitted
sub-estimators.
.. versionadded:: 1.2
`base_estimator_` was renamed to `estimator_`.
estimators_ : list of DecisionTreeClassifier
The collection of fitted sub-estimators.
classes_ : ndarray of shape (n_classes,) or a list of such arrays
The classes labels (single output problem), or a list of arrays of
class labels (multi-output problem).
n_classes_ : int or list
The number of classes (single output problem), or a list containing the
number of classes for each output (multi-output problem).
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
n_outputs_ : int
The number of outputs when ``fit`` is performed.
feature_importances_ : ndarray of shape (n_features,)
The impurity-based feature importances.
The higher, the more important the feature.
The importance of a feature is computed as the (normalized)
total reduction of the criterion brought by that feature. It is also
known as the Gini importance.
Warning: impurity-based feature importances can be misleading for
high cardinality features (many unique values). See
:func:`sklearn.inspection.permutation_importance` as an alternative.
oob_score_ : float
Score of the training dataset obtained using an out-of-bag estimate.
This attribute exists only when ``oob_score`` is True.
oob_decision_function_ : ndarray of shape (n_samples, n_classes) or \
(n_samples, n_classes, n_outputs)
Decision function computed with out-of-bag estimate on the training
set. If n_estimators is small it might be possible that a data point
was never left out during the bootstrap. In this case,
`oob_decision_function_` might contain NaN. This attribute exists
only when ``oob_score`` is True.
estimators_samples_ : list of arrays
The subset of drawn samples (i.e., the in-bag samples) for each base
estimator. Each subset is defined by an array of the indices selected.
.. versionadded:: 1.4
See Also
--------
sklearn.tree.DecisionTreeClassifier : A decision tree classifier.
sklearn.ensemble.ExtraTreesClassifier : Ensemble of extremely randomized
tree classifiers.
sklearn.ensemble.HistGradientBoostingClassifier : A Histogram-based Gradient
Boosting Classification Tree, very fast for big datasets (n_samples >=
10_000).
Notes
-----
The default values for the parameters controlling the size of the trees
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
unpruned trees which can potentially be very large on some data sets. To
reduce memory consumption, the complexity and size of the trees should be
controlled by setting those parameter values.
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data,
``max_features=n_features`` and ``bootstrap=False``, if the improvement
of the criterion is identical for several splits enumerated during the
search of the best split. To obtain a deterministic behaviour during
fitting, ``random_state`` has to be fixed.
References
----------
.. [1] :doi:`L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001.
<10.1023/A:1010933404324>`
Examples
--------
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
... n_informative=2, n_redundant=0,
... random_state=0, shuffle=False)
>>> clf = RandomForestClassifier(max_depth=2, random_state=0)
>>> clf.fit(X, y)
RandomForestClassifier(...)
>>> print(clf.predict([[0, 0, 0, 0]]))
[1]
"""
_parameter_constraints: dict = {
**ForestClassifier._parameter_constraints,
**DecisionTreeClassifier._parameter_constraints,
"class_weight": [
StrOptions({"balanced_subsample", "balanced"}),
dict,
list,
None,
],
}
_parameter_constraints.pop("splitter")
def __init__(
self,
n_estimators=100,
*,
criterion="gini",
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.0,
max_features="sqrt",
max_leaf_nodes=None,
min_impurity_decrease=0.0,
bootstrap=True,
oob_score=False,
n_jobs=None,
random_state=None,
verbose=0,
warm_start=False,
class_weight=None,
ccp_alpha=0.0,
max_samples=None,
monotonic_cst=None,
):
super().__init__(
estimator=DecisionTreeClassifier(),
n_estimators=n_estimators,
estimator_params=(
"criterion",
"max_depth",
"min_samples_split",
"min_samples_leaf",
"min_weight_fraction_leaf",
"max_features",
"max_leaf_nodes",
"min_impurity_decrease",
"random_state",
"ccp_alpha",
"monotonic_cst",
),
bootstrap=bootstrap,
oob_score=oob_score,
n_jobs=n_jobs,
random_state=random_state,
verbose=verbose,
warm_start=warm_start,
class_weight=class_weight,
max_samples=max_samples,
)
self.criterion = criterion
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.max_leaf_nodes = max_leaf_nodes
self.min_impurity_decrease = min_impurity_decrease
self.monotonic_cst = monotonic_cst
self.ccp_alpha = ccp_alpha
| RandomForestClassifier |
python | kubernetes-client__python | kubernetes/client/models/v1_csi_node_driver.py | {
"start": 383,
"end": 8698
} | 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 = {
'allocatable': 'V1VolumeNodeResources',
'name': 'str',
'node_id': 'str',
'topology_keys': 'list[str]'
}
attribute_map = {
'allocatable': 'allocatable',
'name': 'name',
'node_id': 'nodeID',
'topology_keys': 'topologyKeys'
}
def __init__(self, allocatable=None, name=None, node_id=None, topology_keys=None, local_vars_configuration=None): # noqa: E501
"""V1CSINodeDriver - 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._allocatable = None
self._name = None
self._node_id = None
self._topology_keys = None
self.discriminator = None
if allocatable is not None:
self.allocatable = allocatable
self.name = name
self.node_id = node_id
if topology_keys is not None:
self.topology_keys = topology_keys
@property
def allocatable(self):
"""Gets the allocatable of this V1CSINodeDriver. # noqa: E501
:return: The allocatable of this V1CSINodeDriver. # noqa: E501
:rtype: V1VolumeNodeResources
"""
return self._allocatable
@allocatable.setter
def allocatable(self, allocatable):
"""Sets the allocatable of this V1CSINodeDriver.
:param allocatable: The allocatable of this V1CSINodeDriver. # noqa: E501
:type: V1VolumeNodeResources
"""
self._allocatable = allocatable
@property
def name(self):
"""Gets the name of this V1CSINodeDriver. # noqa: E501
name represents the name of the CSI driver that this object refers to. This MUST be the same name returned by the CSI GetPluginName() call for that driver. # noqa: E501
:return: The name of this V1CSINodeDriver. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this V1CSINodeDriver.
name represents the name of the CSI driver that this object refers to. This MUST be the same name returned by the CSI GetPluginName() call for that driver. # noqa: E501
:param name: The name of this V1CSINodeDriver. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = name
@property
def node_id(self):
"""Gets the node_id of this V1CSINodeDriver. # noqa: E501
nodeID of the node from the driver point of view. This field enables Kubernetes to communicate with storage systems that do not share the same nomenclature for nodes. For example, Kubernetes may refer to a given node as \"node1\", but the storage system may refer to the same node as \"nodeA\". When Kubernetes issues a command to the storage system to attach a volume to a specific node, it can use this field to refer to the node name using the ID that the storage system will understand, e.g. \"nodeA\" instead of \"node1\". This field is required. # noqa: E501
:return: The node_id of this V1CSINodeDriver. # noqa: E501
:rtype: str
"""
return self._node_id
@node_id.setter
def node_id(self, node_id):
"""Sets the node_id of this V1CSINodeDriver.
nodeID of the node from the driver point of view. This field enables Kubernetes to communicate with storage systems that do not share the same nomenclature for nodes. For example, Kubernetes may refer to a given node as \"node1\", but the storage system may refer to the same node as \"nodeA\". When Kubernetes issues a command to the storage system to attach a volume to a specific node, it can use this field to refer to the node name using the ID that the storage system will understand, e.g. \"nodeA\" instead of \"node1\". This field is required. # noqa: E501
:param node_id: The node_id of this V1CSINodeDriver. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and node_id is None: # noqa: E501
raise ValueError("Invalid value for `node_id`, must not be `None`") # noqa: E501
self._node_id = node_id
@property
def topology_keys(self):
"""Gets the topology_keys of this V1CSINodeDriver. # noqa: E501
topologyKeys is the list of keys supported by the driver. When a driver is initialized on a cluster, it provides a set of topology keys that it understands (e.g. \"company.com/zone\", \"company.com/region\"). When a driver is initialized on a node, it provides the same topology keys along with values. Kubelet will expose these topology keys as labels on its own node object. When Kubernetes does topology aware provisioning, it can use this list to determine which labels it should retrieve from the node object and pass back to the driver. It is possible for different nodes to use different topology keys. This can be empty if driver does not support topology. # noqa: E501
:return: The topology_keys of this V1CSINodeDriver. # noqa: E501
:rtype: list[str]
"""
return self._topology_keys
@topology_keys.setter
def topology_keys(self, topology_keys):
"""Sets the topology_keys of this V1CSINodeDriver.
topologyKeys is the list of keys supported by the driver. When a driver is initialized on a cluster, it provides a set of topology keys that it understands (e.g. \"company.com/zone\", \"company.com/region\"). When a driver is initialized on a node, it provides the same topology keys along with values. Kubelet will expose these topology keys as labels on its own node object. When Kubernetes does topology aware provisioning, it can use this list to determine which labels it should retrieve from the node object and pass back to the driver. It is possible for different nodes to use different topology keys. This can be empty if driver does not support topology. # noqa: E501
:param topology_keys: The topology_keys of this V1CSINodeDriver. # noqa: E501
:type: list[str]
"""
self._topology_keys = topology_keys
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, V1CSINodeDriver):
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, V1CSINodeDriver):
return True
return self.to_dict() != other.to_dict()
| V1CSINodeDriver |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-seller-partner/components.py | {
"start": 10787,
"end": 13302
} | class ____(TypeTransformer):
config: Dict[str, Any] = None
MARKETPLACE_DATE_FORMAT_MAP = dict(
# eu
A2VIGQ35RCS4UG="%d/%m/%y", # AE
A1PA6795UKMFR9="%d.%m.%y", # DE
A1C3SOZRARQ6R3="%d/%m/%y", # PL
ARBP9OOSHTCHU="%d/%m/%y", # EG
A1RKKUPIHCS9HS="%d/%m/%y", # ES
A13V1IB3VIYZZH="%d/%m/%y", # FR
A21TJRUUN4KGV="%d/%m/%y", # IN
APJ6JRA9NG5V4="%d/%m/%y", # IT
A1805IZSGTT6HS="%d/%m/%y", # NL
A17E79C6D8DWNP="%d/%m/%y", # SA
A2NODRKZP88ZB9="%Y-%m-%d", # SE
A33AVAJ2PDY3EV="%d/%m/%y", # TR
A1F83G8C2ARO7P="%d/%m/%y", # UK
AMEN7PMS3EDWL="%d/%m/%y", # BE
# fe
A39IBJ37TRP1C6="%d/%m/%y", # AU
A1VC38T7YXB528="%y/%m/%d", # JP
A19VAU5U5O7RUS="%d/%m/%y", # SG
# na
ATVPDKIKX0DER="%m/%d/%y", # US
A2Q3Y263D00KWC="%d/%m/%y", # BR
A2EUQ1WTGCTBG2="%d/%m/%y", # CA
A1AM78C64UM0Y8="%d/%m/%y", # MX
)
def __init__(self, *args, config, **kwargs):
self.marketplace_id = config.get("marketplace_id")
config = TransformConfig.DefaultSchemaNormalization | TransformConfig.CustomSchemaNormalization
super().__init__(config)
self.registerCustomTransform(self.get_transform_function())
def get_transform_function(self):
def transform_function(original_value: Any, field_schema: Dict[str, Any]) -> Any:
if original_value and field_schema.get("format") == "date":
date_format = self.MARKETPLACE_DATE_FORMAT_MAP.get(self.marketplace_id)
# Checks if the date is already in the target format -- this will be the case for dataEndTime field
try:
dt.strptime(original_value, "%Y-%m-%d")
return original_value
except ValueError:
pass
if not date_format:
raise KeyError(f"Date format not found for Marketplace ID: {self.marketplace_id}")
try:
return dt.strptime(original_value, date_format).strftime("%Y-%m-%d")
except ValueError as e:
raise ValueError(
f"Error parsing date: {original_value} is expected to be in format {date_format} for marketplace_id: {self.marketplace_id}"
) from e
return original_value
return transform_function
| SellerFeedbackReportsTypeTransformer |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 2618,
"end": 2863
} | class ____(HTTPError):
"""Raised when a socket timeout error occurs.
Catching this error will catch both :exc:`ReadTimeoutErrors
<ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.
"""
pass
| TimeoutError |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 227145,
"end": 228714
} | class ____(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
if isinstance(axis, int):
axis = [axis]
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.mean(x, axis=self.axis, keepdims=self.keepdims)
def compute_output_spec(self, x):
ori_dtype = backend.standardize_dtype(x.dtype)
compute_dtype = dtypes.result_type(x.dtype, "float32")
if "int" in ori_dtype or ori_dtype == "bool":
result_dtype = compute_dtype
else:
result_dtype = ori_dtype
sparse = getattr(x, "sparse", False)
return KerasTensor(
reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
dtype=result_dtype,
sparse=sparse,
)
@keras_export(["keras.ops.mean", "keras.ops.numpy.mean"])
def mean(x, axis=None, keepdims=False):
"""Compute the arithmetic mean along the specified axes.
Args:
x: Input tensor.
axis: Axis or axes along which the means are computed. The default
is to compute the mean of the flattened tensor.
keepdims: If this is set to `True`, the axes which are reduced are left
in the result as dimensions with size one.
Returns:
Output tensor containing the mean values.
"""
if any_symbolic_tensors((x,)):
return Mean(axis=axis, keepdims=keepdims).symbolic_call(x)
return backend.numpy.mean(x, axis=axis, keepdims=keepdims)
| Mean |
python | streamlit__streamlit | lib/streamlit/components/v2/component_manifest_handler.py | {
"start": 864,
"end": 4187
} | class ____:
"""Handles component registration from parsed ComponentManifest objects."""
def __init__(self) -> None:
# Component metadata from pyproject.toml
self._metadata: MutableMapping[str, ComponentManifest] = {}
# Resolved asset roots keyed by fully-qualified component name
self._asset_roots: MutableMapping[str, Path] = {}
def process_manifest(
self, manifest: ComponentManifest, package_root: Path
) -> dict[str, dict[str, Any]]:
"""Process a manifest and return component definitions to register.
Parameters
----------
manifest : ComponentManifest
The manifest to process
package_root : Path
The package root directory
Returns
-------
dict[str, dict[str, Any]]
Dictionary mapping component names to their definitions
Raises
------
StreamlitComponentRegistryError
If a declared ``asset_dir`` does not exist, is not a directory, or
resolves (after following symlinks) outside of ``package_root``.
"""
base_name = manifest.name
component_definitions = {}
# Process each component in the manifest
for comp_config in manifest.components:
comp_name = comp_config.name
component_name = f"{base_name}.{comp_name}"
# Parse and persist asset_dir if provided. This is the component's
# root directory for all future file references.
asset_root = comp_config.resolve_asset_root(package_root)
if asset_root is not None:
self._asset_roots[component_name] = asset_root
# Create component definition data
component_definitions[component_name] = {
"name": component_name,
}
# Store metadata
self._metadata[component_name] = manifest
return component_definitions
def get_metadata(self, component_name: str) -> ComponentManifest | None:
"""Get metadata for a specific component.
Parameters
----------
component_name : str
Fully-qualified component name (e.g., ``"package.component"``).
Returns
-------
ComponentManifest | None
The manifest that declared this component, or ``None`` if unknown.
"""
return self._metadata.get(component_name)
def get_asset_root(self, component_name: str) -> Path | None:
"""Get the absolute asset root directory for a component if declared.
Parameters
----------
component_name : str
Fully-qualified component name (e.g. "package.component").
Returns
-------
Path | None
Absolute path to the component's asset root if present, otherwise None.
"""
return self._asset_roots.get(component_name)
def get_asset_watch_roots(self) -> dict[str, Path]:
"""Get a mapping of component names to their asset root directories.
Returns
-------
dict[str, Path]
A shallow copy mapping fully-qualified component names to absolute
asset root directories.
"""
return dict(self._asset_roots)
| ComponentManifestHandler |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 17505,
"end": 19055
} | class ____:
async def test_sync_task_run_inside_sync_flow(self):
@task
def foo(x):
return x
@flow
def bar():
return foo(1, return_state=True)
task_state = bar()
assert isinstance(task_state, State)
assert await task_state.result() == 1
async def test_async_task_run_inside_async_flow(self):
@task
async def foo(x):
return x
@flow
async def bar():
return await foo(1, return_state=True)
task_state = await bar()
assert isinstance(task_state, State)
assert await task_state.result() == 1
async def test_sync_task_run_inside_async_flow(self):
@task
def foo(x):
return x
@flow
async def bar():
return foo(1, return_state=True)
task_state = await bar()
assert isinstance(task_state, State)
assert await task_state.result() == 1
def test_task_failure_does_not_affect_flow(self):
@task
def foo():
raise ValueError("Test")
@flow
def bar():
foo(return_state=True)
return "bar"
assert bar() == "bar"
async def test_task_with_return_state_true(self):
@task
def foo(x):
return x
@flow
def bar():
return foo(1, return_state=True)
task_state = bar()
assert isinstance(task_state, State)
assert await task_state.result() == 1
| TestTaskRun |
python | pandas-dev__pandas | pandas/tests/series/methods/test_pct_change.py | {
"start": 116,
"end": 2602
} | class ____:
def test_pct_change(self, datetime_series):
rs = datetime_series.pct_change()
tm.assert_series_equal(rs, datetime_series / datetime_series.shift(1) - 1)
rs = datetime_series.pct_change(2)
filled = datetime_series.ffill()
tm.assert_series_equal(rs, filled / filled.shift(2) - 1)
rs = datetime_series.pct_change(freq="5D")
filled = datetime_series.ffill()
tm.assert_series_equal(
rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled)
)
def test_pct_change_with_duplicate_axis(self):
# GH#28664
common_idx = date_range("2019-11-14", periods=5, freq="D")
result = Series(range(5), common_idx).pct_change(freq="B")
# the reason that the expected should be like this is documented at PR 28681
expected = Series([np.nan, np.inf, np.nan, np.nan, 3.0], common_idx)
tm.assert_series_equal(result, expected)
def test_pct_change_shift_over_nas(self):
s = Series([1.0, 1.5, np.nan, 2.5, 3.0])
chg = s.pct_change()
expected = Series([np.nan, 0.5, np.nan, np.nan, 0.2])
tm.assert_series_equal(chg, expected)
@pytest.mark.parametrize("freq, periods", [("5B", 5), ("3B", 3), ("14B", 14)])
def test_pct_change_periods_freq(self, freq, periods, datetime_series):
# GH#7292
rs_freq = datetime_series.pct_change(freq=freq)
rs_periods = datetime_series.pct_change(periods)
tm.assert_series_equal(rs_freq, rs_periods)
empty_ts = Series(index=datetime_series.index, dtype=object)
rs_freq = empty_ts.pct_change(freq=freq)
rs_periods = empty_ts.pct_change(periods)
tm.assert_series_equal(rs_freq, rs_periods)
def test_pct_change_with_duplicated_indices():
# GH30463
s = Series([np.nan, 1, 2, 3, 9, 18], index=["a", "b"] * 3)
result = s.pct_change()
expected = Series([np.nan, np.nan, 1.0, 0.5, 2.0, 1.0], index=["a", "b"] * 3)
tm.assert_series_equal(result, expected)
def test_pct_change_no_warning_na_beginning():
# GH#54981
ser = Series([None, None, 1, 2, 3])
result = ser.pct_change()
expected = Series([np.nan, np.nan, np.nan, 1, 0.5])
tm.assert_series_equal(result, expected)
def test_pct_change_empty():
# GH 57056
ser = Series([], dtype="float64")
expected = ser.copy()
result = ser.pct_change(periods=0)
tm.assert_series_equal(expected, result)
| TestSeriesPctChange |
python | django__django | tests/admin_inlines/models.py | {
"start": 8235,
"end": 8316
} | class ____(models.Model):
name = models.CharField(max_length=1)
| SomeParentModel |
python | pypa__setuptools | setuptools/namespaces.py | {
"start": 124,
"end": 3014
} | class ____:
nspkg_ext = '-nspkg.pth'
def install_namespaces(self) -> None:
nsp = self._get_all_ns_packages()
if not nsp:
return
filename = self._get_nspkg_file()
self.outputs.append(filename)
log.info("Installing %s", filename)
lines = map(self._gen_nspkg_line, nsp)
if self.dry_run:
# always generate the lines, even in dry run
list(lines)
return
with open(filename, 'wt', encoding=py312.PTH_ENCODING) as f:
# Python<3.13 requires encoding="locale" instead of "utf-8"
# See: python/cpython#77102
f.writelines(lines)
def uninstall_namespaces(self) -> None:
filename = self._get_nspkg_file()
if not os.path.exists(filename):
return
log.info("Removing %s", filename)
os.remove(filename)
def _get_nspkg_file(self):
filename, _ = os.path.splitext(self._get_target())
return filename + self.nspkg_ext
def _get_target(self):
return self.target
_nspkg_tmpl = (
"import sys, types, os",
"p = os.path.join(%(root)s, *%(pth)r)",
"importlib = __import__('importlib.util')",
"__import__('importlib.machinery')",
(
"m = "
"sys.modules.setdefault(%(pkg)r, "
"importlib.util.module_from_spec("
"importlib.machinery.PathFinder.find_spec(%(pkg)r, "
"[os.path.dirname(p)])))"
),
("m = m or sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))"),
"mp = (m or []) and m.__dict__.setdefault('__path__',[])",
"(p not in mp) and mp.append(p)",
)
"lines for the namespace installer"
_nspkg_tmpl_multi = ('m and setattr(sys.modules[%(parent)r], %(child)r, m)',)
"additional line(s) when a parent package is indicated"
def _get_root(self):
return "sys._getframe(1).f_locals['sitedir']"
def _gen_nspkg_line(self, pkg):
pth = tuple(pkg.split('.'))
root = self._get_root()
tmpl_lines = self._nspkg_tmpl
parent, sep, child = pkg.rpartition('.')
if parent:
tmpl_lines += self._nspkg_tmpl_multi
return ';'.join(tmpl_lines) % locals() + '\n'
def _get_all_ns_packages(self):
"""Return sorted list of all package namespaces"""
pkgs = self.distribution.namespace_packages or []
return sorted(set(flatten(map(self._pkg_names, pkgs))))
@staticmethod
def _pkg_names(pkg):
"""
Given a namespace package, yield the components of that
package.
>>> names = Installer._pkg_names('a.b.c')
>>> set(names) == set(['a', 'a.b', 'a.b.c'])
True
"""
parts = pkg.split('.')
while parts:
yield '.'.join(parts)
parts.pop()
| Installer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 22931,
"end": 23554
} | class ____(SemiIncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#list-releases
"""
cursor_field = "created_at"
def transform(self, record: MutableMapping[str, Any], stream_slice: Mapping[str, Any]) -> MutableMapping[str, Any]:
record = super().transform(record=record, stream_slice=stream_slice)
assets = record.get("assets", [])
for asset in assets:
uploader = asset.pop("uploader", None)
asset["uploader_id"] = uploader.get("id") if uploader else None
return record
| Releases |
python | walkccc__LeetCode | solutions/1868. Product of Two Run-Length Encoded Arrays/1868.py | {
"start": 0,
"end": 641
} | class ____:
def findRLEArray(self, encoded1: list[list[int]],
encoded2: list[list[int]]) -> list[list[int]]:
ans = []
i = 0 # encoded1's index
j = 0 # encoded2's index
while i < len(encoded1) and j < len(encoded2):
mult = encoded1[i][0] * encoded2[j][0]
minFreq = min(encoded1[i][1], encoded2[j][1])
if ans and mult == ans[-1][0]:
ans[-1][1] += minFreq
else:
ans.append([mult, minFreq])
encoded1[i][1] -= minFreq
encoded2[j][1] -= minFreq
if encoded1[i][1] == 0:
i += 1
if encoded2[j][1] == 0:
j += 1
return ans
| Solution |
python | pandas-dev__pandas | pandas/core/reshape/merge.py | {
"start": 82366,
"end": 84422
} | class ____(_MergeOperation):
_merge_type = "ordered_merge"
def __init__(
self,
left: DataFrame | Series,
right: DataFrame | Series,
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_index: bool = False,
right_index: bool = False,
suffixes: Suffixes = ("_x", "_y"),
fill_method: str | None = None,
how: JoinHow | Literal["asof"] = "outer",
) -> None:
self.fill_method = fill_method
_MergeOperation.__init__(
self,
left,
right,
on=on,
left_on=left_on,
left_index=left_index,
right_index=right_index,
right_on=right_on,
how=how,
suffixes=suffixes,
sort=True, # factorize sorts
)
def get_result(self) -> DataFrame:
join_index, left_indexer, right_indexer = self._get_join_info()
left_join_indexer: npt.NDArray[np.intp] | None
right_join_indexer: npt.NDArray[np.intp] | None
if self.fill_method == "ffill":
if left_indexer is None:
left_join_indexer = None
else:
left_join_indexer = libjoin.ffill_indexer(left_indexer)
if right_indexer is None:
right_join_indexer = None
else:
right_join_indexer = libjoin.ffill_indexer(right_indexer)
elif self.fill_method is None:
left_join_indexer = left_indexer
right_join_indexer = right_indexer
else:
raise ValueError("fill_method must be 'ffill' or None")
result = self._reindex_and_concat(
join_index, left_join_indexer, right_join_indexer
)
self._maybe_add_join_keys(result, left_indexer, right_indexer)
return result
def _asof_by_function(direction: str):
name = f"asof_join_{direction}_on_X_by_Y"
return getattr(libjoin, name, None)
| _OrderedMerge |
python | great-expectations__great_expectations | great_expectations/metrics/batch/sample_values.py | {
"start": 153,
"end": 213
} | class ____(MetricResult[pd.DataFrame]): ...
| SampleValuesResult |
python | neetcode-gh__leetcode | python/0876-middle-of-the-linked-list.py | {
"start": 0,
"end": 286
} | class ____:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow
| Solution |
python | lepture__authlib | authlib/jose/drafts/_jwe_enc_cryptodome.py | {
"start": 315,
"end": 1848
} | class ____(JWEEncAlgorithm):
# Use of an IV of size 192 bits is REQUIRED with this algorithm.
# https://datatracker.ietf.org/doc/html/draft-amringer-jose-chacha-02#section-4.1
IV_SIZE = 192
def __init__(self, key_size):
self.name = "XC20P"
self.description = "XChaCha20-Poly1305"
self.key_size = key_size
self.CEK_SIZE = key_size
def encrypt(self, msg, aad, iv, key):
"""Content Encryption with AEAD_XCHACHA20_POLY1305.
:param msg: text to be encrypt in bytes
:param aad: additional authenticated data in bytes
:param iv: initialization vector in bytes
:param key: encrypted key in bytes
:return: (ciphertext, tag)
"""
self.check_iv(iv)
chacha = Cryptodome_ChaCha20_Poly1305.new(key=key, nonce=iv)
chacha.update(aad)
ciphertext, tag = chacha.encrypt_and_digest(msg)
return ciphertext, tag
def decrypt(self, ciphertext, aad, iv, tag, key):
"""Content Decryption with AEAD_XCHACHA20_POLY1305.
:param ciphertext: ciphertext in bytes
:param aad: additional authenticated data in bytes
:param iv: initialization vector in bytes
:param tag: authentication tag in bytes
:param key: encrypted key in bytes
:return: message
"""
self.check_iv(iv)
chacha = Cryptodome_ChaCha20_Poly1305.new(key=key, nonce=iv)
chacha.update(aad)
return chacha.decrypt_and_verify(ciphertext, tag)
| XC20PEncAlgorithm |
python | pandas-dev__pandas | pandas/tests/groupby/test_timegrouper.py | {
"start": 1735,
"end": 34276
} | class ____:
def test_groupby_with_timegrouper(self, using_infer_string):
# GH 4161
# TimeGrouper requires a sorted index
# also verifies that the resultant index has the correct name
df_original = DataFrame(
{
"Buyer": "Carl Carl Carl Carl Joe Carl".split(),
"Quantity": [18, 3, 5, 1, 9, 3],
"Date": [
datetime(2013, 9, 1, 13, 0),
datetime(2013, 9, 1, 13, 5),
datetime(2013, 10, 1, 20, 0),
datetime(2013, 10, 3, 10, 0),
datetime(2013, 12, 2, 12, 0),
datetime(2013, 9, 2, 14, 0),
],
}
)
# GH 6908 change target column's order
df_reordered = df_original.sort_values(by="Quantity")
for df in [df_original, df_reordered]:
df = df.set_index(["Date"])
exp_dti = date_range(
"20130901",
"20131205",
freq="5D",
name="Date",
inclusive="left",
unit=df.index.unit,
)
expected = DataFrame(
{"Buyer": "" if using_infer_string else 0, "Quantity": 0},
index=exp_dti,
)
# Cast to object/str to avoid implicit cast when setting
# entry to "CarlCarlCarl"
expected = expected.astype({"Buyer": object})
if using_infer_string:
expected = expected.astype({"Buyer": "str"})
expected.iloc[0, 0] = "CarlCarlCarl"
expected.iloc[6, 0] = "CarlCarl"
expected.iloc[18, 0] = "Joe"
expected.iloc[[0, 6, 18], 1] = np.array([24, 6, 9], dtype="int64")
result1 = df.resample("5D").sum()
tm.assert_frame_equal(result1, expected)
df_sorted = df.sort_index()
result2 = df_sorted.groupby(Grouper(freq="5D")).sum()
tm.assert_frame_equal(result2, expected)
result3 = df.groupby(Grouper(freq="5D")).sum()
tm.assert_frame_equal(result3, expected)
@pytest.mark.parametrize("should_sort", [True, False])
def test_groupby_with_timegrouper_methods(self, should_sort):
# GH 3881
# make sure API of timegrouper conforms
df = DataFrame(
{
"Branch": "A A A A A B".split(),
"Buyer": "Carl Mark Carl Joe Joe Carl".split(),
"Quantity": [1, 3, 5, 8, 9, 3],
"Date": [
datetime(2013, 1, 1, 13, 0),
datetime(2013, 1, 1, 13, 5),
datetime(2013, 10, 1, 20, 0),
datetime(2013, 10, 2, 10, 0),
datetime(2013, 12, 2, 12, 0),
datetime(2013, 12, 2, 14, 0),
],
}
)
if should_sort:
df = df.sort_values(by="Quantity", ascending=False)
df = df.set_index("Date", drop=False)
g = df.groupby(Grouper(freq="6ME"))
assert g.group_keys
assert isinstance(g._grouper, BinGrouper)
groups = g.groups
assert isinstance(groups, dict)
assert len(groups) == 3
def test_timegrouper_with_reg_groups(self):
# GH 3794
# allow combination of timegrouper/reg groups
df_original = DataFrame(
{
"Branch": "A A A A A A A B".split(),
"Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(),
"Quantity": [1, 3, 5, 1, 8, 1, 9, 3],
"Date": [
datetime(2013, 1, 1, 13, 0),
datetime(2013, 1, 1, 13, 5),
datetime(2013, 10, 1, 20, 0),
datetime(2013, 10, 2, 10, 0),
datetime(2013, 10, 1, 20, 0),
datetime(2013, 10, 2, 10, 0),
datetime(2013, 12, 2, 12, 0),
datetime(2013, 12, 2, 14, 0),
],
}
).set_index("Date")
df_sorted = df_original.sort_values(by="Quantity", ascending=False)
for df in [df_original, df_sorted]:
expected = DataFrame(
{
"Buyer": "Carl Joe Mark".split(),
"Quantity": [10, 18, 3],
"Date": [
datetime(2013, 12, 31, 0, 0),
datetime(2013, 12, 31, 0, 0),
datetime(2013, 12, 31, 0, 0),
],
}
).set_index(["Date", "Buyer"])
msg = "The default value of numeric_only"
result = df.groupby([Grouper(freq="YE"), "Buyer"]).sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
expected = DataFrame(
{
"Buyer": "Carl Mark Carl Joe".split(),
"Quantity": [1, 3, 9, 18],
"Date": [
datetime(2013, 1, 1, 0, 0),
datetime(2013, 1, 1, 0, 0),
datetime(2013, 7, 1, 0, 0),
datetime(2013, 7, 1, 0, 0),
],
}
).set_index(["Date", "Buyer"])
result = df.groupby([Grouper(freq="6MS"), "Buyer"]).sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
df_original = DataFrame(
{
"Branch": "A A A A A A A B".split(),
"Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(),
"Quantity": [1, 3, 5, 1, 8, 1, 9, 3],
"Date": [
datetime(2013, 10, 1, 13, 0),
datetime(2013, 10, 1, 13, 5),
datetime(2013, 10, 1, 20, 0),
datetime(2013, 10, 2, 10, 0),
datetime(2013, 10, 1, 20, 0),
datetime(2013, 10, 2, 10, 0),
datetime(2013, 10, 2, 12, 0),
datetime(2013, 10, 2, 14, 0),
],
}
).set_index("Date")
df_sorted = df_original.sort_values(by="Quantity", ascending=False)
for df in [df_original, df_sorted]:
expected = DataFrame(
{
"Buyer": "Carl Joe Mark Carl Joe".split(),
"Quantity": [6, 8, 3, 4, 10],
"Date": [
datetime(2013, 10, 1, 0, 0),
datetime(2013, 10, 1, 0, 0),
datetime(2013, 10, 1, 0, 0),
datetime(2013, 10, 2, 0, 0),
datetime(2013, 10, 2, 0, 0),
],
}
).set_index(["Date", "Buyer"])
result = df.groupby([Grouper(freq="1D"), "Buyer"]).sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
result = df.groupby([Grouper(freq="1ME"), "Buyer"]).sum(numeric_only=True)
expected = DataFrame(
{
"Buyer": "Carl Joe Mark".split(),
"Quantity": [10, 18, 3],
"Date": [
datetime(2013, 10, 31, 0, 0),
datetime(2013, 10, 31, 0, 0),
datetime(2013, 10, 31, 0, 0),
],
}
).set_index(["Date", "Buyer"])
tm.assert_frame_equal(result, expected)
# passing the name
df = df.reset_index()
result = df.groupby([Grouper(freq="1ME", key="Date"), "Buyer"]).sum(
numeric_only=True
)
tm.assert_frame_equal(result, expected)
with pytest.raises(KeyError, match="'The grouper name foo is not found'"):
df.groupby([Grouper(freq="1ME", key="foo"), "Buyer"]).sum()
# passing the level
df = df.set_index("Date")
result = df.groupby([Grouper(freq="1ME", level="Date"), "Buyer"]).sum(
numeric_only=True
)
tm.assert_frame_equal(result, expected)
result = df.groupby([Grouper(freq="1ME", level=0), "Buyer"]).sum(
numeric_only=True
)
tm.assert_frame_equal(result, expected)
with pytest.raises(ValueError, match="The level foo is not valid"):
df.groupby([Grouper(freq="1ME", level="foo"), "Buyer"]).sum()
# multi names
df = df.copy()
df["Date"] = df.index + offsets.MonthEnd(2)
result = df.groupby([Grouper(freq="1ME", key="Date"), "Buyer"]).sum(
numeric_only=True
)
expected = DataFrame(
{
"Buyer": "Carl Joe Mark".split(),
"Quantity": [10, 18, 3],
"Date": [
datetime(2013, 11, 30, 0, 0),
datetime(2013, 11, 30, 0, 0),
datetime(2013, 11, 30, 0, 0),
],
}
).set_index(["Date", "Buyer"])
tm.assert_frame_equal(result, expected)
# error as we have both a level and a name!
msg = "The Grouper cannot specify both a key and a level!"
with pytest.raises(ValueError, match=msg):
df.groupby(
[Grouper(freq="1ME", key="Date", level="Date"), "Buyer"]
).sum()
# single groupers
expected = DataFrame(
[[31]],
columns=["Quantity"],
index=DatetimeIndex(
[datetime(2013, 10, 31, 0, 0)], freq=offsets.MonthEnd(), name="Date"
),
)
result = df.groupby(Grouper(freq="1ME")).sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
result = df.groupby([Grouper(freq="1ME")]).sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
expected.index = expected.index.shift(1)
assert expected.index.freq == offsets.MonthEnd()
result = df.groupby(Grouper(freq="1ME", key="Date")).sum(numeric_only=True)
tm.assert_frame_equal(result, expected)
result = df.groupby([Grouper(freq="1ME", key="Date")]).sum(
numeric_only=True
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("freq", ["D", "ME", "YE", "QE-APR"])
def test_timegrouper_with_reg_groups_freq(self, freq):
# GH 6764 multiple grouping with/without sort
df = DataFrame(
{
"date": pd.to_datetime(
[
"20121002",
"20121007",
"20130130",
"20130202",
"20130305",
"20121002",
"20121207",
"20130130",
"20130202",
"20130305",
"20130202",
"20130305",
]
),
"user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5],
"whole_cost": [
1790,
364,
280,
259,
201,
623,
90,
312,
359,
301,
359,
801,
],
"cost1": [12, 15, 10, 24, 39, 1, 0, 90, 45, 34, 1, 12],
}
).set_index("date")
expected = (
df.groupby("user_id")["whole_cost"]
.resample(freq)
.sum(min_count=1) # XXX
.dropna()
.reorder_levels(["date", "user_id"])
.sort_index()
.astype("int64")
)
expected.name = "whole_cost"
result1 = (
df.sort_index().groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum()
)
tm.assert_series_equal(result1, expected)
result2 = df.groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum()
tm.assert_series_equal(result2, expected)
def test_timegrouper_get_group(self):
# GH 6914
df_original = DataFrame(
{
"Buyer": "Carl Joe Joe Carl Joe Carl".split(),
"Quantity": [18, 3, 5, 1, 9, 3],
"Date": [
datetime(2013, 9, 1, 13, 0),
datetime(2013, 9, 1, 13, 5),
datetime(2013, 10, 1, 20, 0),
datetime(2013, 10, 3, 10, 0),
datetime(2013, 12, 2, 12, 0),
datetime(2013, 9, 2, 14, 0),
],
}
)
df_reordered = df_original.sort_values(by="Quantity")
# single grouping
expected_list = [
df_original.iloc[[0, 1, 5]],
df_original.iloc[[2, 3]],
df_original.iloc[[4]],
]
dt_list = ["2013-09-30", "2013-10-31", "2013-12-31"]
for df in [df_original, df_reordered]:
grouped = df.groupby(Grouper(freq="ME", key="Date"))
for t, expected in zip(dt_list, expected_list):
dt = Timestamp(t)
result = grouped.get_group(dt)
tm.assert_frame_equal(result, expected)
# multiple grouping
expected_list = [
df_original.iloc[[1]],
df_original.iloc[[3]],
df_original.iloc[[4]],
]
g_list = [("Joe", "2013-09-30"), ("Carl", "2013-10-31"), ("Joe", "2013-12-31")]
for df in [df_original, df_reordered]:
grouped = df.groupby(["Buyer", Grouper(freq="ME", key="Date")])
for (b, t), expected in zip(g_list, expected_list):
dt = Timestamp(t)
result = grouped.get_group((b, dt))
tm.assert_frame_equal(result, expected)
# with index
df_original = df_original.set_index("Date")
df_reordered = df_original.sort_values(by="Quantity")
expected_list = [
df_original.iloc[[0, 1, 5]],
df_original.iloc[[2, 3]],
df_original.iloc[[4]],
]
for df in [df_original, df_reordered]:
grouped = df.groupby(Grouper(freq="ME"))
for t, expected in zip(dt_list, expected_list):
dt = Timestamp(t)
result = grouped.get_group(dt)
tm.assert_frame_equal(result, expected)
def test_timegrouper_apply_return_type_series(self):
# Using `apply` with the `TimeGrouper` should give the
# same return type as an `apply` with a `Grouper`.
# Issue #11742
df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]})
df_dt = df.copy()
df_dt["date"] = pd.to_datetime(df_dt["date"])
def sumfunc_series(x):
return Series([x["value"].sum()], ("sum",))
expected = df.groupby(Grouper(key="date")).apply(sumfunc_series)
result = df_dt.groupby(Grouper(freq="ME", key="date")).apply(sumfunc_series)
tm.assert_frame_equal(
result.reset_index(drop=True), expected.reset_index(drop=True)
)
def test_timegrouper_apply_return_type_value(self):
# Using `apply` with the `TimeGrouper` should give the
# same return type as an `apply` with a `Grouper`.
# Issue #11742
df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]})
df_dt = df.copy()
df_dt["date"] = pd.to_datetime(df_dt["date"])
def sumfunc_value(x):
return x.value.sum()
expected = df.groupby(Grouper(key="date")).apply(sumfunc_value)
result = df_dt.groupby(Grouper(freq="ME", key="date")).apply(sumfunc_value)
tm.assert_series_equal(
result.reset_index(drop=True), expected.reset_index(drop=True)
)
def test_groupby_groups_datetimeindex(self):
# GH#1430
periods = 1000
ind = date_range(start="2012/1/1", freq="5min", periods=periods)
df = DataFrame(
{"high": np.arange(periods), "low": np.arange(periods)}, index=ind
)
grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day))
# it works!
groups = grouped.groups
assert isinstance(next(iter(groups.keys())), datetime)
def test_groupby_groups_datetimeindex2(self):
# GH#11442
index = date_range("2015/01/01", periods=5, name="date")
df = DataFrame({"A": [5, 6, 7, 8, 9], "B": [1, 2, 3, 4, 5]}, index=index)
result = df.groupby(level="date").groups
dates = ["2015-01-05", "2015-01-04", "2015-01-03", "2015-01-02", "2015-01-01"]
expected = {
Timestamp(date): DatetimeIndex([date], name="date") for date in dates
}
tm.assert_dict_equal(result, expected)
grouped = df.groupby(level="date")
for date in dates:
result = grouped.get_group(date)
data = [[df.loc[date, "A"], df.loc[date, "B"]]]
expected_index = DatetimeIndex(
[date], name="date", freq="D", dtype=index.dtype
)
expected = DataFrame(data, columns=list("AB"), index=expected_index)
tm.assert_frame_equal(result, expected)
def test_groupby_groups_datetimeindex_tz(self):
# GH 3950
dates = [
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
]
df = DataFrame(
{
"label": ["a", "a", "a", "b", "b", "b"],
"datetime": dates,
"value1": np.arange(6, dtype="int64"),
"value2": [1, 2] * 3,
}
)
df["datetime"] = df["datetime"].apply(lambda d: Timestamp(d, tz="US/Pacific"))
exp_idx1 = DatetimeIndex(
[
"2011-07-19 07:00:00",
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
"2011-07-19 09:00:00",
],
tz="US/Pacific",
name="datetime",
)
exp_idx2 = Index(["a", "b"] * 3, name="label")
exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2])
expected = DataFrame(
{"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]},
index=exp_idx,
columns=["value1", "value2"],
)
result = df.groupby(["datetime", "label"]).sum()
tm.assert_frame_equal(result, expected)
# by level
didx = DatetimeIndex(dates, tz="Asia/Tokyo")
df = DataFrame(
{"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]},
index=didx,
)
exp_idx = DatetimeIndex(
["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],
tz="Asia/Tokyo",
)
expected = DataFrame(
{"value1": [3, 5, 7], "value2": [2, 4, 6]},
index=exp_idx,
columns=["value1", "value2"],
)
result = df.groupby(level=0).sum()
tm.assert_frame_equal(result, expected)
def test_frame_datetime64_handling_groupby(self):
# it works!
df = DataFrame(
[(3, np.datetime64("2012-07-03")), (3, np.datetime64("2012-07-04"))],
columns=["a", "date"],
)
result = df.groupby("a").first()
assert result["date"][3] == Timestamp("2012-07-03")
def test_groupby_multi_timezone(self):
# combining multiple / different timezones yields UTC
df = DataFrame(
{
"value": range(5),
"date": [
"2000-01-28 16:47:00",
"2000-01-29 16:48:00",
"2000-01-30 16:49:00",
"2000-01-31 16:50:00",
"2000-01-01 16:50:00",
],
"tz": [
"America/Chicago",
"America/Chicago",
"America/Los_Angeles",
"America/Chicago",
"America/New_York",
],
}
)
result = df.groupby("tz", group_keys=False).date.apply(
lambda x: pd.to_datetime(x).dt.tz_localize(x.name)
)
expected = Series(
[
Timestamp("2000-01-28 16:47:00-0600", tz="America/Chicago"),
Timestamp("2000-01-29 16:48:00-0600", tz="America/Chicago"),
Timestamp("2000-01-30 16:49:00-0800", tz="America/Los_Angeles"),
Timestamp("2000-01-31 16:50:00-0600", tz="America/Chicago"),
Timestamp("2000-01-01 16:50:00-0500", tz="America/New_York"),
],
name="date",
dtype=object,
)
tm.assert_series_equal(result, expected)
tz = "America/Chicago"
res_values = df.groupby("tz").date.get_group(tz)
result = pd.to_datetime(res_values).dt.tz_localize(tz)
exp_values = Series(
["2000-01-28 16:47:00", "2000-01-29 16:48:00", "2000-01-31 16:50:00"],
index=[0, 1, 3],
name="date",
)
expected = pd.to_datetime(exp_values).dt.tz_localize(tz)
tm.assert_series_equal(result, expected)
def test_groupby_groups_periods(self):
dates = [
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
]
df = DataFrame(
{
"label": ["a", "a", "a", "b", "b", "b"],
"period": [pd.Period(d, freq="h") for d in dates],
"value1": np.arange(6, dtype="int64"),
"value2": [1, 2] * 3,
}
)
exp_idx1 = pd.PeriodIndex(
[
"2011-07-19 07:00:00",
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
"2011-07-19 09:00:00",
],
freq="h",
name="period",
)
exp_idx2 = Index(["a", "b"] * 3, name="label")
exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2])
expected = DataFrame(
{"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]},
index=exp_idx,
columns=["value1", "value2"],
)
result = df.groupby(["period", "label"]).sum()
tm.assert_frame_equal(result, expected)
# by level
didx = pd.PeriodIndex(dates, freq="h")
df = DataFrame(
{"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]},
index=didx,
)
exp_idx = pd.PeriodIndex(
["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],
freq="h",
)
expected = DataFrame(
{"value1": [3, 5, 7], "value2": [2, 4, 6]},
index=exp_idx,
columns=["value1", "value2"],
)
result = df.groupby(level=0).sum()
tm.assert_frame_equal(result, expected)
def test_groupby_first_datetime64(self):
df = DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)])
df[1] = df[1].astype("M8[ns]")
assert issubclass(df[1].dtype.type, np.datetime64)
result = df.groupby(level=0).first()
got_dt = result[1].dtype
assert issubclass(got_dt.type, np.datetime64)
result = df[1].groupby(level=0).first()
got_dt = result.dtype
assert issubclass(got_dt.type, np.datetime64)
def test_groupby_max_datetime64(self):
# GH 5869
# datetimelike dtype conversion from int
df = DataFrame({"A": Timestamp("20130101").as_unit("s"), "B": np.arange(5)})
# TODO: can we retain second reso in .apply here?
expected = df.groupby("A")["A"].apply(lambda x: x.max()).astype("M8[s]")
result = df.groupby("A")["A"].max()
tm.assert_series_equal(result, expected)
def test_groupby_datetime64_32_bit(self):
# GH 6410 / numpy 4328
# 32-bit under 1.9-dev indexing issue
df = DataFrame({"A": range(2), "B": [Timestamp("2000-01-1")] * 2})
result = df.groupby("A")["B"].transform("min")
expected = Series([Timestamp("2000-01-1")] * 2, name="B")
tm.assert_series_equal(result, expected)
def test_groupby_with_timezone_selection(self):
# GH 11616
# Test that column selection returns output in correct timezone.
df = DataFrame(
{
"factor": np.random.default_rng(2).integers(0, 3, size=60),
"time": date_range("01/01/2000 00:00", periods=60, freq="s", tz="UTC"),
}
)
df1 = df.groupby("factor").max()["time"]
df2 = df.groupby("factor")["time"].max()
tm.assert_series_equal(df1, df2)
def test_timezone_info(self):
# see gh-11682: Timezone info lost when broadcasting
# scalar datetime to DataFrame
utc = timezone.utc
df = DataFrame({"a": [1], "b": [datetime.now(utc)]})
assert df["b"][0].tzinfo == utc
df = DataFrame({"a": [1, 2, 3]})
df["b"] = datetime.now(utc)
assert df["b"][0].tzinfo == utc
def test_datetime_count(self):
df = DataFrame(
{"a": [1, 2, 3] * 2, "dates": date_range("now", periods=6, freq="min")}
)
result = df.groupby("a").dates.count()
expected = Series([2, 2, 2], index=Index([1, 2, 3], name="a"), name="dates")
tm.assert_series_equal(result, expected)
def test_first_last_max_min_on_time_data(self):
# GH 10295
# Verify that NaT is not in the result of max, min, first and last on
# Dataframe with datetime or timedelta values.
df_test = DataFrame(
{
"dt": [
np.nan,
"2015-07-24 10:10",
"2015-07-25 11:11",
"2015-07-23 12:12",
np.nan,
],
"td": [
np.nan,
timedelta(days=1),
timedelta(days=2),
timedelta(days=3),
np.nan,
],
}
)
df_test.dt = pd.to_datetime(df_test.dt)
df_test["group"] = "A"
df_ref = df_test[df_test.dt.notna()]
grouped_test = df_test.groupby("group")
grouped_ref = df_ref.groupby("group")
tm.assert_frame_equal(grouped_ref.max(), grouped_test.max())
tm.assert_frame_equal(grouped_ref.min(), grouped_test.min())
tm.assert_frame_equal(grouped_ref.first(), grouped_test.first())
tm.assert_frame_equal(grouped_ref.last(), grouped_test.last())
def test_nunique_with_timegrouper_and_nat(self):
# GH 17575
test = DataFrame(
{
"time": [
Timestamp("2016-06-28 09:35:35"),
pd.NaT,
Timestamp("2016-06-28 16:46:28"),
],
"data": ["1", "2", "3"],
}
)
grouper = Grouper(key="time", freq="h")
result = test.groupby(grouper)["data"].nunique()
expected = test[test.time.notnull()].groupby(grouper)["data"].nunique()
expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
def test_scalar_call_versus_list_call(self):
# Issue: 17530
data_frame = {
"location": ["shanghai", "beijing", "shanghai"],
"time": Series(
["2017-08-09 13:32:23", "2017-08-11 23:23:15", "2017-08-11 22:23:15"],
dtype="datetime64[ns]",
),
"value": [1, 2, 3],
}
data_frame = DataFrame(data_frame).set_index("time")
grouper = Grouper(freq="D")
grouped = data_frame.groupby(grouper)
result = grouped.count()
grouped = data_frame.groupby([grouper])
expected = grouped.count()
tm.assert_frame_equal(result, expected)
def test_grouper_period_index(self):
# GH 32108
periods = 2
index = pd.period_range(
start="2018-01", periods=periods, freq="M", name="Month"
)
period_series = Series(range(periods), index=index)
result = period_series.groupby(period_series.index.month).sum()
expected = Series(
range(periods), index=Index(range(1, periods + 1), name=index.name)
)
tm.assert_series_equal(result, expected)
def test_groupby_apply_timegrouper_with_nat_dict_returns(
self, groupby_with_truncated_bingrouper
):
# GH#43500 case where gb._grouper.result_index and gb._grouper.group_keys_seq
# have different lengths that goes through the `isinstance(values[0], dict)`
# path
gb = groupby_with_truncated_bingrouper
res = gb["Quantity"].apply(lambda x: {"foo": len(x)})
df = gb.obj
unit = df["Date"]._values.unit
dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date", unit=unit)
mi = MultiIndex.from_arrays([dti, ["foo"] * len(dti)])
expected = Series([3, 0, 0, 0, 0, 0, 2], index=mi, name="Quantity")
tm.assert_series_equal(res, expected)
def test_groupby_apply_timegrouper_with_nat_scalar_returns(
self, groupby_with_truncated_bingrouper
):
# GH#43500 Previously raised ValueError bc used index with incorrect
# length in wrap_applied_result
gb = groupby_with_truncated_bingrouper
res = gb["Quantity"].apply(lambda x: x.iloc[0] if len(x) else np.nan)
df = gb.obj
unit = df["Date"]._values.unit
dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date", unit=unit)
expected = Series(
[18, np.nan, np.nan, np.nan, np.nan, np.nan, 5],
index=dti._with_freq(None),
name="Quantity",
)
tm.assert_series_equal(res, expected)
def test_groupby_apply_timegrouper_with_nat_apply_squeeze(
self, frame_for_truncated_bingrouper
):
df = frame_for_truncated_bingrouper
# We need to create a GroupBy object with only one non-NaT group,
# so use a huge freq so that all non-NaT dates will be grouped together
tdg = Grouper(key="Date", freq="100YE")
gb = df.groupby(tdg)
# check that we will go through the singular_series path
# in _wrap_applied_output_series
assert gb.ngroups == 1
assert gb._selected_obj.index.nlevels == 1
# function that returns a Series
res = gb.apply(lambda x: x["Quantity"] * 2)
dti = Index([Timestamp("2013-12-31")], dtype=df["Date"].dtype, name="Date")
expected = DataFrame(
[[36, 6, 6, 10, 2]],
index=dti,
columns=Index([0, 1, 5, 2, 3], name="Quantity"),
)
tm.assert_frame_equal(res, expected)
@pytest.mark.single_cpu
def test_groupby_agg_numba_timegrouper_with_nat(
self, groupby_with_truncated_bingrouper
):
pytest.importorskip("numba")
# See discussion in GH#43487
gb = groupby_with_truncated_bingrouper
result = gb["Quantity"].aggregate(
lambda values, index: np.nanmean(values), engine="numba"
)
expected = gb["Quantity"].aggregate("mean")
tm.assert_series_equal(result, expected)
result_df = gb[["Quantity"]].aggregate(
lambda values, index: np.nanmean(values), engine="numba"
)
expected_df = gb[["Quantity"]].aggregate("mean")
tm.assert_frame_equal(result_df, expected_df)
| TestGroupBy |
python | facebook__pyre-check | client/language_server/code_navigation_request.py | {
"start": 2321,
"end": 2686
} | class ____:
path: Path
content: Optional[str]
client_id: str
def to_json(self) -> List[object]:
return [
"FileOpened",
{
"path": f"{self.path}",
"content": self.content,
"client_id": self.client_id,
},
]
@dataclasses.dataclass(frozen=True)
| FileOpened |
python | Textualize__textual | examples/five_by_five.py | {
"start": 4028,
"end": 4392
} | class ____(Widget):
"""The main playable grid of game cells."""
def compose(self) -> ComposeResult:
"""Compose the game grid.
Returns:
ComposeResult: The result of composing the game grid.
"""
for row in range(Game.SIZE):
for col in range(Game.SIZE):
yield GameCell(row, col)
| GameGrid |
python | scipy__scipy | scipy/special/_sf_error.py | {
"start": 266,
"end": 375
} | class ____(Exception):
"""Exception that can be raised by special functions."""
pass
| SpecialFunctionError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 36964,
"end": 37238
} | class ____(_SelectIsNotFrom, _NoTextCoercion, RoleImpl):
__slots__ = ()
def _post_coercion(self, element, **kw):
if "dml_table" in element._annotations:
return element._annotations["dml_table"]
else:
return element
| DMLTableImpl |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 195136,
"end": 195625
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "invitation", "message")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
invitation = sgqlc.types.Field(
"EnterpriseAdministratorInvitation", graphql_name="invitation"
)
message = sgqlc.types.Field(String, graphql_name="message")
| AcceptEnterpriseAdministratorInvitationPayload |
python | pdm-project__pdm | src/pdm/models/project_info.py | {
"start": 276,
"end": 3523
} | class ____:
name: str
version: str
summary: str = ""
author: str = ""
email: str = ""
license: str = ""
requires_python: str = ""
platform: str = ""
keywords: str = ""
homepage: str = ""
project_urls: list[str] = field(default_factory=list)
latest_stable_version: str = ""
installed_version: str = ""
@classmethod
def from_distribution(cls, data: Distribution) -> ProjectInfo:
metadata = cast(Message, data.metadata)
keywords = metadata.get("Keywords", "").replace(",", ", ")
platform = metadata.get("Platform", "").replace(",", ", ")
if "Project-URL" in metadata:
project_urls = {
k.strip(): v.strip() for k, v in (row.split(",") for row in metadata.get_all("Project-URL", []))
}
else:
project_urls = {}
return cls(
name=metadata.get("Name", ""),
version=metadata.get("Version", ""),
summary=metadata.get("Summary", ""),
author=metadata.get("Author", ""),
email=metadata.get("Author-email", ""),
license=metadata.get("License", ""),
requires_python=metadata.get("Requires-Python", ""),
platform=platform,
keywords=keywords,
homepage=metadata.get("Home-page", ""),
project_urls=[": ".join(parts) for parts in project_urls.items()],
)
@classmethod
def from_metadata(cls, metadata: dict[str, Any]) -> ProjectInfo:
def get_str(key: str) -> str:
if key in metadata.get("dynamic", []):
return DYNAMIC
return metadata.get(key, "")
authors = metadata.get("authors", [])
author = authors[0]["name"] if authors else ""
email = authors[0]["email"] if authors else ""
return cls(
name=metadata["name"],
version=get_str("version"),
summary=get_str("description"),
author=author,
email=email,
license=metadata.get("license", {}).get("text", ""),
requires_python=get_str("requires-python"),
keywords=",".join(get_str("keywords")),
project_urls=[": ".join(parts) for parts in metadata.get("urls", {}).items()],
)
def generate_rows(self) -> Iterator[tuple[str, str]]:
yield "[primary]Name[/]:", self.name
yield "[primary]Latest version[/]:", self.version
if self.latest_stable_version:
yield ("[primary]Latest stable version[/]:", self.latest_stable_version)
if self.installed_version:
yield ("[primary]Installed version[/]:", self.installed_version)
yield "[primary]Summary[/]:", self.summary
yield "[primary]Requires Python:", self.requires_python
yield "[primary]Author[/]:", self.author
yield "[primary]Author email[/]:", self.email
yield "[primary]License[/]:", self.license
yield "[primary]Homepage[/]:", self.homepage
yield from itertools.zip_longest(("[primary]Project URLs[/]:",), self.project_urls, fillvalue="")
yield "[primary]Platform[/]:", self.platform
yield "[primary]Keywords[/]:", self.keywords
| ProjectInfo |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 26989,
"end": 28157
} | class ____(ASTBase):
def __init__(self, arg: ASTTypeWithInit | None, ellipsis: bool = False) -> None:
self.arg = arg
self.ellipsis = ellipsis
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTFunctionParameter):
return NotImplemented
return self.arg == other.arg and self.ellipsis == other.ellipsis
def __hash__(self) -> int:
return hash((self.arg, self.ellipsis))
def get_id(self, version: int, objectType: str, symbol: Symbol) -> str:
# the anchor will be our parent
return symbol.parent.declaration.get_id(version, prefixed=False)
def _stringify(self, transform: StringifyTransform) -> str:
if self.ellipsis:
return '...'
else:
return transform(self.arg)
def describe_signature(
self, signode: Any, mode: str, env: BuildEnvironment, symbol: Symbol
) -> None:
verify_description_mode(mode)
if self.ellipsis:
signode += addnodes.desc_sig_punctuation('...', '...')
else:
self.arg.describe_signature(signode, mode, env, symbol=symbol)
| ASTFunctionParameter |
python | google__pytype | pytype/abstract/abstract_test.py | {
"start": 11194,
"end": 26490
} | class ____(AbstractTestBase):
def _make_pytd_function(self, params, name="f"):
pytd_params = []
for i, p in enumerate(params):
p_type = pytd.ClassType(p.name)
p_type.cls = p
pytd_params.append(
pytd.Parameter(
function.argname(i),
p_type,
pytd.ParameterKind.REGULAR,
False,
None,
)
)
pytd_sig = pytd.Signature(
tuple(pytd_params), None, None, pytd.AnythingType(), (), ()
)
sig = abstract.PyTDSignature(name, pytd_sig, self._ctx)
return abstract.PyTDFunction(
name, (sig,), pytd.MethodKind.METHOD, (), self._ctx
)
def _call_pytd_function(self, f, args):
b = f.to_binding(self._ctx.root_node)
return f.call(self._ctx.root_node, b, function.Args(posargs=args))
def test_call_with_empty_arg(self):
self.assertRaises(
AssertionError,
self._call_pytd_function,
self._make_pytd_function(params=()),
(self._ctx.program.NewVariable(),),
)
def test_call_with_bad_arg(self):
f = self._make_pytd_function((
self._ctx.loader.lookup_pytd("builtins", "str"),
))
arg = self._ctx.convert.primitive_instances[int].to_variable(
self._ctx.root_node
)
self.assertRaises(
error_types.WrongArgTypes, self._call_pytd_function, f, (arg,)
)
def test_simple_call(self):
f = self._make_pytd_function((
self._ctx.loader.lookup_pytd("builtins", "str"),
))
arg = self._ctx.convert.primitive_instances[str].to_variable(
self._ctx.root_node
)
node, ret = self._call_pytd_function(f, (arg,))
self.assertIs(node, self._ctx.root_node)
(retval,) = ret.bindings
self.assertIs(retval.data, self._ctx.convert.unsolvable)
def test_call_with_multiple_arg_bindings(self):
f = self._make_pytd_function((
self._ctx.loader.lookup_pytd("builtins", "str"),
))
arg = self._ctx.program.NewVariable()
arg.AddBinding(
self._ctx.convert.primitive_instances[str], [], self._ctx.root_node
)
arg.AddBinding(
self._ctx.convert.primitive_instances[int], [], self._ctx.root_node
)
node, ret = self._call_pytd_function(f, (arg,))
self.assertIs(node, self._ctx.root_node)
(retval,) = ret.bindings
self.assertIs(retval.data, self._ctx.convert.unsolvable)
def test_call_with_skipped_combination(self):
f = self._make_pytd_function((
self._ctx.loader.lookup_pytd("builtins", "str"),
))
node = self._ctx.root_node.ConnectNew()
arg = self._ctx.convert.primitive_instances[str].to_variable(node)
node, ret = self._call_pytd_function(f, (arg,))
self.assertIs(node, self._ctx.root_node)
self.assertFalse(ret.bindings)
def test_signature_from_pytd(self):
# def f(self: Any, *args: Any)
self_param = pytd.Parameter(
"self", pytd.AnythingType(), pytd.ParameterKind.REGULAR, False, None
)
args_param = pytd.Parameter(
"args", pytd.AnythingType(), pytd.ParameterKind.REGULAR, True, None
)
sig = function.Signature.from_pytd(
self._ctx,
"f",
pytd.Signature(
(self_param,), args_param, None, pytd.AnythingType(), (), ()
),
)
self.assertEqual(repr(sig), "def f(self: Any, *args: Any) -> Any")
self.assertEqual(sig.name, "f")
self.assertSequenceEqual(sig.param_names, ("self",))
self.assertEqual(sig.varargs_name, "args")
self.assertFalse(sig.kwonly_params)
self.assertIs(sig.kwargs_name, None)
self.assertSetEqual(set(sig.annotations), {"self", "args", "return"})
self.assertTrue(sig.has_return_annotation)
self.assertTrue(sig.has_param_annotations)
def test_signature_from_callable(self):
# Callable[[int, str], Any]
params = {0: self._ctx.convert.int_type, 1: self._ctx.convert.str_type}
params[abstract_utils.ARGS] = abstract.Union(
(params[0], params[1]), self._ctx
)
params[abstract_utils.RET] = self._ctx.convert.unsolvable
callable_val = abstract.CallableClass(
self._ctx.convert.function_type, params, self._ctx
)
sig = function.Signature.from_callable(callable_val)
self.assertEqual(repr(sig), "def <callable>(_0: int, _1: str) -> Any")
self.assertEqual(sig.name, "<callable>")
self.assertSequenceEqual(sig.param_names, ("_0", "_1"))
self.assertIs(sig.varargs_name, None)
self.assertFalse(sig.kwonly_params)
self.assertIs(sig.kwargs_name, None)
self.assertCountEqual(sig.annotations.keys(), sig.param_names + ("return",))
self.assertTrue(sig.has_return_annotation)
self.assertTrue(sig.has_param_annotations)
def test_signature_annotations(self):
# def f(self: Any, *args: Any)
self_param = pytd.Parameter(
"self", pytd.AnythingType(), pytd.ParameterKind.REGULAR, False, None
)
# Imitate the parser's conversion of '*args: Any' to '*args: Tuple[Any]'.
tup = pytd.ClassType("builtins.tuple")
tup.cls = self._ctx.convert.tuple_type.pytd_cls
any_tuple = pytd.GenericType(tup, (pytd.AnythingType(),))
args_param = pytd.Parameter(
"args", any_tuple, pytd.ParameterKind.REGULAR, True, None
)
sig = function.Signature.from_pytd(
self._ctx,
"f",
pytd.Signature(
(self_param,), args_param, None, pytd.AnythingType(), (), ()
),
)
self.assertEqual(
repr(sig), "def f(self: Any, *args: tuple[Any, ...]) -> Any"
)
self.assertIs(sig.annotations["self"], self._ctx.convert.unsolvable)
args_type = sig.annotations["args"]
self.assertIsInstance(args_type, abstract.ParameterizedClass)
self.assertIs(args_type.base_cls, self._ctx.convert.tuple_type)
self.assertListEqual(
list(args_type.formal_type_parameters.items()),
[(abstract_utils.T, self._ctx.convert.unsolvable)],
)
self.assertIs(sig.drop_first_parameter().annotations["args"], args_type)
def test_signature_annotations_existence(self):
# def f(v: "X") -> "Y"
sig = function.Signature(
name="f",
param_names=("v",),
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name=None,
defaults={},
annotations={},
)
self.assertFalse(sig.has_param_annotations)
self.assertFalse(sig.has_return_annotation)
sig.set_annotation("v", self._ctx.convert.unsolvable)
self.assertTrue(sig.has_param_annotations)
self.assertFalse(sig.has_return_annotation)
sig.set_annotation("return", self._ctx.convert.unsolvable)
self.assertTrue(sig.has_param_annotations)
self.assertTrue(sig.has_return_annotation)
def test_signature_posarg_only_param_count(self):
# def f(x): ...
sig = function.Signature(
name="f",
param_names=("x",),
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name=None,
defaults={},
annotations={},
)
self.assertEqual(repr(sig), "def f(x) -> Any")
self.assertEqual(sig.mandatory_param_count(), 1)
self.assertEqual(sig.maximum_param_count(), 1)
def test_signature_posarg_and_kwarg_param_count(self):
# def f(x, y=None): ...
sig = function.Signature(
name="f",
param_names=(
"x",
"y",
),
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name=None,
defaults={"y": self._ctx.convert.none.to_variable(self._node)},
annotations={},
)
self.assertEqual(repr(sig), "def f(x, y = None) -> Any")
self.assertEqual(sig.mandatory_param_count(), 1)
self.assertEqual(sig.maximum_param_count(), 2)
def test_signature_varargs_param_count(self):
# def f(*args): ...
sig = function.Signature(
name="f",
param_names=(),
posonly_count=0,
varargs_name="args",
kwonly_params=(),
kwargs_name=None,
defaults={},
annotations={},
)
self.assertEqual(repr(sig), "def f(*args) -> Any")
self.assertEqual(sig.mandatory_param_count(), 0)
self.assertIsNone(sig.maximum_param_count())
def test_signature_kwargs_param_count(self):
# def f(**kwargs): ...
sig = function.Signature(
name="f",
param_names=(),
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name="kwargs",
defaults={},
annotations={},
)
self.assertEqual(repr(sig), "def f(**kwargs) -> Any")
self.assertEqual(sig.mandatory_param_count(), 0)
self.assertIsNone(sig.maximum_param_count())
def test_signature_kwonly_param_count(self):
# def f(*, y=None): ...
sig = function.Signature(
name="f",
param_names=(),
posonly_count=0,
varargs_name=None,
kwonly_params=("y",),
kwargs_name=None,
defaults={"y": self._ctx.convert.none.to_variable(self._node)},
annotations={},
)
self.assertEqual(repr(sig), "def f(*, y = None) -> Any")
self.assertEqual(sig.mandatory_param_count(), 0)
self.assertEqual(sig.maximum_param_count(), 1)
def test_signature_has_param(self):
# def f(x, *args, y, **kwargs): ...
sig = function.Signature(
name="f",
param_names=("x",),
posonly_count=0,
varargs_name="args",
kwonly_params={"y"},
kwargs_name="kwargs",
defaults={},
annotations={},
)
self.assertEqual(repr(sig), "def f(x, *args, y, **kwargs) -> Any")
for param in ("x", "args", "y", "kwargs"):
self.assertTrue(sig.has_param(param))
self.assertFalse(sig.has_param("rumpelstiltskin"))
def test_signature_insert_varargs_and_kwargs(self):
# def f(x, *args, y, **kwargs): ...
sig = function.Signature(
name="f",
param_names=("x",),
posonly_count=0,
varargs_name="args",
kwonly_params={"y"},
kwargs_name="kwargs",
defaults={},
annotations={},
)
# f(1, 2, y=3, z=4)
int_inst = self._ctx.convert.primitive_instances[int]
int_binding = int_inst.to_binding(self._node)
arg_dict = {
"x": int_binding,
"_1": int_binding,
"y": int_binding,
"z": int_binding,
}
sig = sig.insert_varargs_and_kwargs(arg_dict)
self.assertEqual(sig.name, "f")
self.assertSequenceEqual(sig.param_names, ("x", "_1", "z"))
self.assertEqual(sig.varargs_name, "args")
self.assertSetEqual(sig.kwonly_params, {"y"})
self.assertEqual(sig.kwargs_name, "kwargs")
self.assertFalse(sig.annotations)
def test_signature_del_param_annotation(self):
# def f(x) -> int: ...
sig = function.Signature(
name="f",
param_names=("x",),
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name=None,
defaults={},
annotations={
"x": self._ctx.convert.unsolvable,
"return": self._ctx.convert.unsolvable,
},
)
sig.del_annotation("x")
self.assertCountEqual(sig.annotations.keys(), {"return"})
self.assertFalse(sig.has_param_annotations)
self.assertTrue(sig.has_return_annotation)
def test_signature_del_return_annotation(self):
# def f(x) -> int: ...
sig = function.Signature(
name="f",
param_names=("x",),
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name=None,
defaults={},
annotations={
"x": self._ctx.convert.unsolvable,
"return": self._ctx.convert.unsolvable,
},
)
sig.del_annotation("return")
self.assertCountEqual(sig.annotations.keys(), {"x"})
self.assertTrue(sig.has_param_annotations)
self.assertFalse(sig.has_return_annotation)
def test_signature_del_nonexistent_annotation(self):
# def f(): ...
sig = function.Signature(
name="f",
param_names=(),
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name=None,
defaults={},
annotations={},
)
self.assertRaises(KeyError, sig.del_annotation, "rumpelstiltskin")
def test_constructor_args(self):
f = abstract.PyTDFunction.make("open", self._ctx, "builtins")
self.assertEqual(f.full_name, "builtins.open")
self.assertCountEqual(
{sig.pytd_sig for sig in f.signatures},
self._ctx.loader.lookup_pytd("builtins", "open").signatures,
)
self.assertIs(f.kind, pytd.MethodKind.METHOD)
self.assertIs(f.ctx.vm, self._ctx.vm)
def test_constructor_args_pyval_name(self):
f = abstract.PyTDFunction.make(
"blah", self._ctx, "builtins", pyval_name="open"
)
self.assertEqual(f.full_name, "builtins.blah")
self.assertEqual(f.signatures[0].signature.name, "builtins.blah")
def test_get_constructor_args(self):
f = abstract.PyTDFunction.make(
"TypeVar", self._ctx, "typing", pyval_name="_typevar_new"
)
self.assertEqual(f.full_name, "typing.TypeVar")
self.assertCountEqual(
{sig.pytd_sig for sig in f.signatures},
self._ctx.loader.lookup_pytd("typing", "_typevar_new").signatures,
)
self.assertIs(f.kind, pytd.MethodKind.METHOD)
self.assertIs(f.ctx.vm, self._ctx.vm)
def test_bound_function_repr(self):
f = self._make_pytd_function(params=())
callself = self._ctx.program.NewVariable(
[abstract.BaseValue(name, self._ctx) for name in ("test1", "test2")],
[],
self._ctx.root_node,
)
bound = abstract.BoundFunction(callself, f)
self.assertCountEqual(bound.repr_names(), ["test1.f", "test2.f"])
self.assertRegex(repr(bound), r"test(1|2)\.f")
def test_bound_function_callself_repr(self):
f = self._make_pytd_function(params=())
callself = self._ctx.program.NewVariable(
[abstract.BaseValue("test", self._ctx)], [], self._ctx.root_node
)
bound = abstract.BoundFunction(callself, f)
callself_repr = lambda v: v.name + "foo"
self.assertCountEqual(bound.repr_names(callself_repr), ["testfoo.f"])
def test_bound_function_nested_repr(self):
f = self._make_pytd_function(params=())
callself1 = self._ctx.program.NewVariable(
[abstract.BaseValue("test1", self._ctx)], [], self._ctx.root_node
)
bound1 = abstract.BoundFunction(callself1, f)
callself2 = self._ctx.program.NewVariable(
[abstract.BaseValue("test2", self._ctx)], [], self._ctx.root_node
)
bound2 = abstract.BoundFunction(callself2, bound1)
# `bound2` is BoundFunction(test2, BoundFunction(test1, f))
self.assertCountEqual(bound2.repr_names(), ["test2.f"])
def test_bound_function_repr_no_callself(self):
f = self._make_pytd_function(params=())
callself = self._ctx.program.NewVariable()
bound = abstract.BoundFunction(callself, f)
self.assertCountEqual(bound.repr_names(), ["<class>.f"])
def test_bound_function_repr_replace_parent(self):
f = self._make_pytd_function(params=(), name="foo.f")
callself = self._ctx.program.NewVariable(
[abstract.BaseValue("test", self._ctx)], [], self._ctx.root_node
)
bound = abstract.BoundFunction(callself, f)
self.assertCountEqual(bound.repr_names(), ["test.f"])
| FunctionTest |
python | tiangolo__fastapi | tests/test_pydantic_v1_v2_multifile/modelsv2b.py | {
"start": 115,
"end": 277
} | class ____(BaseModel):
dup_title: str
dup_size: int
dup_description: Union[str, None] = None
dup_sub: SubItem
dup_multi: List[SubItem] = []
| Item |
python | huggingface__transformers | src/transformers/models/cpmant/tokenization_cpmant.py | {
"start": 1378,
"end": 2345
} | class ____:
def __init__(self, vocab, unk_token="<unk>", max_input_chars_per_word=200):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, token):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
return [self.unk_token]
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
sub_tokens.append(self.unk_token)
start += 1
else:
sub_tokens.append(cur_substr)
start = end
return sub_tokens
| WordpieceTokenizer |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 1159357,
"end": 1169230
} | class ____(DatumChannelMixin, core.ScaleDatumDef):
"""
YOffsetDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
datum : str, bool, dict, float, :class:`ExprRef`, :class:`DateTime`, :class:`RepeatRef`, :class:`PrimitiveValue`, None
A constant value in data domain.
scale : dict, :class:`Scale`, None
An object defining properties of the channel's scale, which is the function that
transforms values in the data domain (numbers, dates, strings, etc) to visual values
(pixels, colors, sizes) of the encoding channels.
If ``null``, the scale will be `disabled and the data value will be directly encoded
<https://vega.github.io/vega-lite/docs/scale.html#disable>`__.
**Default value:** If undefined, default `scale properties
<https://vega.github.io/vega-lite/docs/scale.html>`__ are applied.
**See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
type : :class:`Type`, Literal['quantitative', 'ordinal', 'temporal', 'nominal', 'geojson']
The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or
``"nominal"``) for the encoded field or constant value (``datum``). It can also be a
``"geojson"`` type for encoding `'geoshape'
<https://vega.github.io/vega-lite/docs/geoshape.html>`__.
Vega-Lite automatically infers data types in many cases as discussed below. However,
type is required for a field if: (1) the field is not nominal and the field encoding
has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale
type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal
scale for a field with ``bin`` or ``timeUnit``.
**Default value:**
1) For a data ``field``, ``"nominal"`` is the default data type unless the field
encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or
``timeUnit`` that satisfies the following criteria:
* ``"quantitative"`` is the default type if (1) the encoded field contains ``bin``
or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is
``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a
quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__.
* ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit``
or (2) the specified scale type is a time or utc scale
* ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort
order
<https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__,
(2) the specified scale type is an ordinal/point/band scale, or (3) the encoding
channel is ``order``.
2) For a constant value in data domain (``datum``):
* ``"quantitative"`` if the datum is a number
* ``"nominal"`` if the datum is a string
* ``"temporal"`` if the datum is `a date time object
<https://vega.github.io/vega-lite/docs/datetime.html>`__
**Note:**
* Data ``type`` describes the semantics of the data rather than the primitive data
types (number, string, etc.). The same primitive data type can have different
types of measurement. For example, numeric data can represent quantitative,
ordinal, or nominal data.
* Data values for a temporal field can be either a date-time string (e.g.,
``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a
timestamp number (e.g., ``1552199579097``).
* When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the
``type`` property can be either ``"quantitative"`` (for using a linear bin scale)
or `"ordinal" (for using an ordinal bin scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `timeUnit
<https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property
can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal"
(for using an ordinal scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `aggregate
<https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property
refers to the post-aggregation data type. For example, we can calculate count
``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct",
"field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``.
* Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have
``type`` as they must have exactly the same type as their primary channels (e.g.,
``x``, ``y``).
**See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__
documentation.
"""
_class_is_valid_at_instantiation = False
_encoding_name = "yOffset"
@overload
def bandPosition(self, _: float, /) -> YOffsetDatum: ...
@overload
def scale(self, _: Scale | None, /) -> YOffsetDatum: ...
@overload
def scale(
self,
*,
align: Optional[float | Parameter | SchemaBase | Map] = Undefined,
base: Optional[float | Parameter | SchemaBase | Map] = Undefined,
bins: Optional[SchemaBase | Sequence[float] | Map] = Undefined,
clamp: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
constant: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domain: Optional[
Parameter
| SchemaBase
| Literal["unaggregated"]
| Sequence[
str | bool | float | Temporal | Parameter | SchemaBase | Map | None
]
| Map
] = Undefined,
domainMax: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainMid: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domainMin: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainRaw: Optional[Parameter | SchemaBase | Map] = Undefined,
exponent: Optional[float | Parameter | SchemaBase | Map] = Undefined,
interpolate: Optional[
Parameter | SchemaBase | Map | ScaleInterpolateEnum_T
] = Undefined,
nice: Optional[
bool | float | Parameter | SchemaBase | Map | TimeInterval_T
] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingInner: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingOuter: Optional[float | Parameter | SchemaBase | Map] = Undefined,
range: Optional[
SchemaBase
| Sequence[str | float | Parameter | SchemaBase | Sequence[float] | Map]
| Map
| RangeEnum_T
] = Undefined,
rangeMax: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
rangeMin: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
reverse: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
round: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
scheme: Optional[Parameter | SchemaBase | Map | ColorScheme_T] = Undefined,
type: Optional[SchemaBase | ScaleType_T] = Undefined,
zero: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
) -> YOffsetDatum: ...
@overload
def title(self, _: str | Sequence[str] | None, /) -> YOffsetDatum: ...
@overload
def type(self, _: Type_T, /) -> YOffsetDatum: ...
def __init__(
self,
datum,
bandPosition: Optional[float] = Undefined,
scale: Optional[SchemaBase | Map | None] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
type: Optional[SchemaBase | Type_T] = Undefined,
**kwds,
):
super().__init__(
datum=datum,
bandPosition=bandPosition,
scale=scale,
title=title,
type=type,
**kwds,
)
@with_property_setters
| YOffsetDatum |
python | kamyu104__LeetCode-Solutions | Python/number-of-strings-that-appear-as-substrings-in-word.py | {
"start": 429,
"end": 2542
} | class ____(object):
def step(self, letter):
while self.__node and letter not in self.__node.children:
self.__node = self.__node.suffix
self.__node = self.__node.children[letter] if self.__node else self.__root
return self.__get_ac_node_outputs(self.__node)
def __init__(self, patterns):
self.__root = self.__create_ac_trie(patterns)
self.__node = self.__create_ac_suffix_and_output_links(self.__root)
self.__lookup = set() # modified
def __create_ac_trie(self, patterns): # Time: O(n * l), Space: O(t)
root = AhoNode()
for i, pattern in enumerate(patterns):
node = root
for c in pattern:
node = node.children[c]
node.indices.append(i)
return root
def __create_ac_suffix_and_output_links(self, root): # Time: O(n * l), Space: O(t)
queue = collections.deque()
for node in root.children.itervalues():
queue.append(node)
node.suffix = root
while queue:
node = queue.popleft()
for c, child in node.children.iteritems():
queue.append(child)
suffix = node.suffix
while suffix and c not in suffix.children:
suffix = suffix.suffix
child.suffix = suffix.children[c] if suffix else root
child.output = child.suffix if child.suffix.indices else child.suffix.output
return root
def __get_ac_node_outputs(self, node): # Total Time: O(n), modified
result = []
if node not in self.__lookup: # modified
self.__lookup.add(node) # modified
for i in node.indices:
result.append(i)
output = node.output
while output and output not in self.__lookup: # modified
self.__lookup.add(output) # modified
for i in output.indices:
result.append(i)
output = output.output
return result
# ac automata solution
| AhoTrie |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 6874,
"end": 7114
} | class ____(BaseFactsTest):
__test__ = True
gather_subset = ['!all', 'distribution']
valid_subsets = ['distribution']
fact_namespace = 'ansible_distribution'
collector_class = DistributionFactCollector
| TestDistributionFacts |
python | django__django | tests/field_subclassing/fields.py | {
"start": 738,
"end": 832
} | class ____(models.CharField):
descriptor_class = CustomDeferredAttribute
| CustomDescriptorField |
python | great-expectations__great_expectations | tests/actions/test_core_actions.py | {
"start": 32784,
"end": 37689
} | class ____:
@pytest.mark.unit
def test_equality(self):
"""I kow, this one seems silly. But this was a bug for other actions."""
a = UpdateDataDocsAction(name="my_action")
b = UpdateDataDocsAction(name="my_action")
assert a == b
@pytest.mark.unit
def test_run(self, mocker: MockerFixture, checkpoint_result: CheckpointResult):
# Arrange
context = mocker.Mock(spec=AbstractDataContext)
set_context(context)
site_names = ["site_a", "site_b"]
site_urls = [
f"/gx/uncommitted/data_docs/{site_names[0]}/index.html",
f"/gx/uncommitted/data_docs/{site_names[1]}/index.html",
]
context.get_docs_sites_urls.return_value = [
{
"site_url": site_urls[0],
"site_name": site_names[0],
},
{
"site_url": site_urls[1],
"site_name": site_names[1],
},
]
# Act
action = UpdateDataDocsAction(name="my_action", site_names=site_names)
res = action.run(checkpoint_result=checkpoint_result)
# Assert
validation_identifier_a, validation_identifier_b = tuple(
checkpoint_result.run_results.keys()
)
assert context.build_data_docs.call_count == 2, (
"Data Docs should be incrementally built (once per validation result)"
)
context.build_data_docs.assert_has_calls(
[
mock.call(
build_index=True,
dry_run=False,
resource_identifiers=[
validation_identifier_a,
ExpectationSuiteIdentifier(name=SUITE_A),
],
site_names=site_names,
),
mock.call(
build_index=True,
dry_run=False,
resource_identifiers=[
validation_identifier_b,
ExpectationSuiteIdentifier(name=SUITE_B),
],
site_names=site_names,
),
]
)
assert res == {
validation_identifier_a: {
site_names[0]: site_urls[0],
site_names[1]: site_urls[1],
},
validation_identifier_b: {
site_names[0]: site_urls[0],
site_names[1]: site_urls[1],
},
}
@pytest.mark.cloud
def test_run_with_cloud(self, mocker: MockerFixture, checkpoint_result: CheckpointResult):
# Arrange
context = mocker.Mock(spec=CloudDataContext)
set_context(context)
site_names = ["site_a", "site_b"]
site_urls = [
f"http://app.greatexpectations.io/data_docs/{site_names[0]}",
f"http://app.greatexpectations.io/data_docs/{site_names[1]}",
]
context.get_docs_sites_urls.return_value = [
{
"site_url": site_urls[0],
"site_name": site_names[0],
},
{
"site_url": site_urls[1],
"site_name": site_names[1],
},
]
# Act
action = UpdateDataDocsAction(name="my_docs_action", site_names=site_names)
res = action.run(checkpoint_result=checkpoint_result)
# Assert
validation_identifier_a, validation_identifier_b = tuple(
checkpoint_result.run_results.keys()
)
assert context.build_data_docs.call_count == 2, (
"Data Docs should be incrementally built (once per validation result)"
)
context.build_data_docs.assert_has_calls(
[
mock.call(
build_index=True,
dry_run=False,
resource_identifiers=[
validation_identifier_a,
GXCloudIdentifier(
resource_type=GXCloudRESTResource.EXPECTATION_SUITE,
resource_name=SUITE_A,
),
],
site_names=site_names,
),
mock.call(
build_index=True,
dry_run=False,
resource_identifiers=[
validation_identifier_b,
GXCloudIdentifier(
resource_type=GXCloudRESTResource.EXPECTATION_SUITE,
resource_name=SUITE_B,
),
],
site_names=site_names,
),
]
)
assert res == {
validation_identifier_a: {},
validation_identifier_b: {},
}
| TestUpdateDataDocsAction |
python | facebook__pyre-check | tools/incremental_test/specification.py | {
"start": 2590,
"end": 4969
} | class ____(ABC):
@abstractmethod
def to_json(self) -> Dict[str, Any]:
raise NotImplementedError()
@abstractmethod
def update_steps(self) -> List["SingleUpdate"]:
raise NotImplementedError()
@staticmethod
def from_json(input_json: Dict[str, Any]) -> "RepositoryUpdate":
try:
kind = input_json["kind"]
if kind == "hg":
return HgRepositoryUpdate(commit_hash=input_json["commit_hash"])
elif kind == "patch":
return PatchRepositoryUpdate(
patch=input_json["patch"],
patch_flags=input_json.get("patch_flags", ""),
)
elif kind == "file":
changes = input_json.get("changes", {})
removals = input_json.get("removals", [])
if not isinstance(changes, dict):
raise InvalidSpecificationException(
"File changes must be specified as dicts"
)
if not isinstance(removals, list):
raise InvalidSpecificationException(
"File removals must be specified as lists"
)
if len(changes) == 0 and len(removals) == 0:
raise InvalidSpecificationException("No file change is given")
return FileRepositoryUpdate(changes=changes, removals=removals)
elif kind == "batch":
updates = input_json["updates"]
if not isinstance(updates, list):
raise InvalidSpecificationException(
"Batch updates must be specified as lists"
)
parsed_updates: List[SingleUpdate] = []
for update in updates:
parsed_update = RepositoryUpdate.from_json(update)
parsed_updates.extend(parsed_update.update_steps())
return BatchRepositoryUpdate(parsed_updates)
else:
raise InvalidSpecificationException(
"Cannot create RepositoryUpdate due to unrecognized kind"
)
except KeyError as key:
raise InvalidSpecificationException(
f"Cannot create RepositoryUpdate due to missing field '{key}'"
)
| RepositoryUpdate |
python | bokeh__bokeh | src/bokeh/models/widgets/pickers.py | {
"start": 2468,
"end": 3399
} | class ____(HasProps):
""" Common properties for time-like picker widgets. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
hour_increment = Positive(Int)(default=1, help="""
Defines the granularity of hour value incremements in the UI.
""")
minute_increment = Positive(Int)(default=1, help="""
Defines the granularity of minute value incremements in the UI.
""")
second_increment = Positive(Int)(default=1, help="""
Defines the granularity of second value incremements in the UI.
""")
seconds = Bool(default=False, help="""
Allows to select seconds. By default only hours and minutes are
selectable, and AM/PM depending on ``clock`` option.
""")
clock = Enum("12h", "24h", default="24h", help="""
Whether to use 12 hour or 24 hour clock.
""")
| TimeCommon |
python | openai__openai-python | src/openai/types/beta/realtime/response_text_delta_event.py | {
"start": 200,
"end": 721
} | class ____(BaseModel):
content_index: int
"""The index of the content part in the item's content array."""
delta: str
"""The text delta."""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the item."""
output_index: int
"""The index of the output item in the response."""
response_id: str
"""The ID of the response."""
type: Literal["response.text.delta"]
"""The event type, must be `response.text.delta`."""
| ResponseTextDeltaEvent |
python | PrefectHQ__prefect | tests/infrastructure/provisioners/test_ecs.py | {
"start": 38050,
"end": 41254
} | class ____:
async def test_get_task_count_requires_provisioning(self, execution_role_resource):
count = await execution_role_resource.get_task_count()
assert count == 1
@pytest.mark.usefixtures("existing_execution_role")
async def test_get_task_count_does_not_require_provisioning(
self, execution_role_resource
):
count = await execution_role_resource.get_task_count()
assert count == 0
async def test_requires_provisioning_true(self, execution_role_resource):
requires_provisioning = await execution_role_resource.requires_provisioning()
assert requires_provisioning is True
@pytest.mark.usefixtures("existing_execution_role")
async def test_requires_provisioning_false(self, execution_role_resource):
requires_provisioning = await execution_role_resource.requires_provisioning()
assert requires_provisioning is False
async def test_get_planned_actions_requires_provisioning(
self, execution_role_resource
):
actions = await execution_role_resource.get_planned_actions()
assert actions == [
"Creating an IAM role assigned to ECS tasks:"
" [blue]PrefectEcsTaskExecutionRole[/]"
]
@pytest.mark.usefixtures("existing_execution_role")
async def test_get_planned_actions_does_not_require_provisioning(
self, execution_role_resource
):
actions = await execution_role_resource.get_planned_actions()
assert actions == []
async def test_provision_requires_provisioning(self, execution_role_resource):
advance_mock = MagicMock()
arn = await execution_role_resource.provision(
base_job_template={
"variables": {
"type": "object",
"properties": {
"execution_role_arn": {},
},
}
},
advance=advance_mock,
)
assert arn == "arn:aws:iam::123456789012:role/PrefectEcsTaskExecutionRole"
advance_mock.assert_called_once()
@pytest.mark.usefixtures("existing_execution_role")
async def test_provision_does_not_require_provisioning(
self, execution_role_resource
):
advance_mock = MagicMock()
arn = await execution_role_resource.provision(
base_job_template={
"variables": {
"type": "object",
"properties": {
"execution_role_arn": {},
},
}
},
advance=advance_mock,
)
assert arn == "arn:aws:iam::123456789012:role/PrefectEcsTaskExecutionRole"
advance_mock.assert_not_called()
@pytest.fixture
def container_repository_resource():
return ContainerRepositoryResource(
work_pool_name="test-work-pool", repository_name="prefect-flows"
)
@pytest.fixture
def existing_ecr_repository():
ecr_client = boto3.client("ecr")
ecr_client.create_repository(repositoryName="prefect-flows")
yield
ecr_client.delete_repository(repositoryName="prefect-flows")
| TestExecutionRoleResource |
python | keras-team__keras | guides/custom_train_step_in_torch.py | {
"start": 2878,
"end": 5654
} | class ____(keras.Model):
def train_step(self, data):
# Unpack the data. Its structure depends on your model and
# on what you pass to `fit()`.
x, y = data
# Call torch.nn.Module.zero_grad() to clear the leftover gradients
# for the weights from the previous train step.
self.zero_grad()
# Compute loss
y_pred = self(x, training=True) # Forward pass
loss = self.compute_loss(y=y, y_pred=y_pred)
# Call torch.Tensor.backward() on the loss to compute gradients
# for the weights.
loss.backward()
trainable_weights = [v for v in self.trainable_weights]
gradients = [v.value.grad for v in trainable_weights]
# Update weights
with torch.no_grad():
self.optimizer.apply(gradients, trainable_weights)
# Update metrics (includes the metric that tracks the loss)
for metric in self.metrics:
if metric.name == "loss":
metric.update_state(loss)
else:
metric.update_state(y, y_pred)
# Return a dict mapping metric names to current value
# Note that it will include the loss (tracked in self.metrics).
return {m.name: m.result() for m in self.metrics}
"""
Let's try this out:
"""
# Construct and compile an instance of CustomModel
inputs = keras.Input(shape=(32,))
outputs = keras.layers.Dense(1)(inputs)
model = CustomModel(inputs, outputs)
model.compile(optimizer="adam", loss="mse", metrics=["mae"])
# Just use `fit` as usual
x = np.random.random((1000, 32))
y = np.random.random((1000, 1))
model.fit(x, y, epochs=3)
"""
## Going lower-level
Naturally, you could just skip passing a loss function in `compile()`, and instead do
everything *manually* in `train_step`. Likewise for metrics.
Here's a lower-level example, that only uses `compile()` to configure the optimizer:
- We start by creating `Metric` instances to track our loss and a MAE score (in `__init__()`).
- We implement a custom `train_step()` that updates the state of these metrics
(by calling `update_state()` on them), then query them (via `result()`) to return their current average value,
to be displayed by the progress bar and to be pass to any callback.
- Note that we would need to call `reset_states()` on our metrics between each epoch! Otherwise
calling `result()` would return an average since the start of training, whereas we usually work
with per-epoch averages. Thankfully, the framework can do that for us: just list any metric
you want to reset in the `metrics` property of the model. The model will call `reset_states()`
on any object listed here at the beginning of each `fit()` epoch or at the beginning of a call to
`evaluate()`.
"""
| CustomModel |
python | falconry__falcon | examples/recipes/header_name_case_app.py | {
"start": 117,
"end": 431
} | class ____:
def on_get(self, req, resp):
resp.set_header('X-Funky-Header', 'test')
resp.media = {'message': 'Hello'}
app = falcon.App()
app.add_route('/test', FunkyResource())
app = CustomHeadersMiddleware(
app,
custom_capitalization={'x-funky-header': 'X-FuNkY-HeADeR'},
)
| FunkyResource |
python | huggingface__transformers | tests/models/owlv2/test_modeling_owlv2.py | {
"start": 7647,
"end": 11142
} | class ____:
def __init__(
self,
parent,
batch_size=12,
num_queries=4,
seq_length=16,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden_size=64,
num_hidden_layers=12,
num_attention_heads=4,
intermediate_size=37,
dropout=0.1,
attention_dropout=0.1,
max_position_embeddings=16,
initializer_range=0.02,
scope=None,
):
self.parent = parent
self.batch_size = batch_size
self.num_queries = num_queries
self.seq_length = seq_length
self.is_training = is_training
self.use_input_mask = use_input_mask
self.use_labels = use_labels
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.dropout = dropout
self.attention_dropout = attention_dropout
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.scope = scope
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size * self.num_queries, self.seq_length], self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = random_attention_mask([self.batch_size * self.num_queries, self.seq_length])
if input_mask is not None:
num_text, seq_length = input_mask.shape
rnd_start_indices = np.random.randint(1, seq_length - 1, size=(num_text,))
for idx, start_index in enumerate(rnd_start_indices):
input_mask[idx, :start_index] = 1
input_mask[idx, start_index:] = 0
config = self.get_config()
return config, input_ids, input_mask
def get_config(self):
return Owlv2TextConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
dropout=self.dropout,
attention_dropout=self.attention_dropout,
max_position_embeddings=self.max_position_embeddings,
initializer_range=self.initializer_range,
)
def create_and_check_model(self, config, input_ids, input_mask):
model = Owlv2TextModel(config=config).to(torch_device)
model.eval()
with torch.no_grad():
result = model(input_ids=input_ids, attention_mask=input_mask)
self.parent.assertEqual(
result.last_hidden_state.shape, (self.batch_size * self.num_queries, self.seq_length, self.hidden_size)
)
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size * self.num_queries, self.hidden_size))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, input_ids, input_mask = config_and_inputs
inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
# Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTTextModelTest with OwlViT->Owlv2, OWL-ViT->OwlV2, OWLVIT->OWLV2, owlvit-base-patch32->owlv2-base-patch16-ensemble
| Owlv2TextModelTester |
python | plotly__plotly.py | plotly/graph_objs/sankey/node/_line.py | {
"start": 233,
"end": 4565
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sankey.node"
_path_str = "sankey.node.line"
_valid_props = {"color", "colorsrc", "width", "widthsrc"}
@property
def color(self):
"""
Sets the color of the `line` around each `node`.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def width(self):
"""
Sets the width (in px) of the `line` around each `node`.
The 'width' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def widthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `width`.
The 'widthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["widthsrc"]
@widthsrc.setter
def widthsrc(self, val):
self["widthsrc"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the color of the `line` around each `node`.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
width
Sets the width (in px) of the `line` around each
`node`.
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
"""
def __init__(
self, arg=None, color=None, colorsrc=None, width=None, widthsrc=None, **kwargs
):
"""
Construct a new Line object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sankey.node.Line`
color
Sets the color of the `line` around each `node`.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
width
Sets the width (in px) of the `line` around each
`node`.
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
Returns
-------
Line
"""
super().__init__("line")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.sankey.node.Line
constructor must be a dict or
an instance of :class:`plotly.graph_objs.sankey.node.Line`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("width", arg, width)
self._set_property("widthsrc", arg, widthsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Line |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/node_provider.py | {
"start": 2296,
"end": 2662
} | class ____(Exception):
"""
An base error class that represents an error that happened in the cloud instance
provider.
"""
# The timestamp of the error occurred in nanoseconds.
timestamp_ns: int
def __init__(self, msg, timestamp_ns) -> None:
super().__init__(msg)
self.timestamp_ns = timestamp_ns
| CloudInstanceProviderError |
python | kamyu104__LeetCode-Solutions | Python/univalued-binary-tree.py | {
"start": 621,
"end": 953
} | class ____(object):
def isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return (not root.left or (root.left.val == root.val and self.isUnivalTree(root.left))) and \
(not root.right or (root.right.val == root.val and self.isUnivalTree(root.right)))
| Solution2 |
python | doocs__leetcode | solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution2.py | {
"start": 0,
"end": 401
} | class ____:
def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:
f = [0] * (k + 1)
for nums in piles:
s = list(accumulate(nums, initial=0))
for j in range(k, -1, -1):
for h, w in enumerate(s):
if j < h:
break
f[j] = max(f[j], f[j - h] + w)
return f[k]
| Solution |
python | Netflix__metaflow | test/core/tests/recursive_switch_inside_foreach.py | {
"start": 63,
"end": 1578
} | class ____(MetaflowTest):
PRIORITY = 2
ONLY_GRAPHS = ["recursive_switch_inside_foreach"]
@steps(0, ["start"], required=True)
def step_start(self):
self.items = [
{"id": "A", "iterations": 3},
{"id": "B", "iterations": 5},
{"id": "C", "iterations": 2},
]
@steps(0, ["loop_start"], required=True)
def step_start_loop_for_item(self):
self.item_id = self.input["id"]
self.max_loops = self.input["iterations"]
self.item_loop_count = 0
@steps(0, ["loop_body"], required=True)
def step_loop_body(self):
self.item_loop_count += 1
self.should_continue = str(self.item_loop_count < self.max_loops)
@steps(0, ["loop_exit"], required=True)
def step_exit_item_loop(self):
assert_equals(self.max_loops, self.item_loop_count)
self.result = (
f"Item {self.item_id} finished after {self.item_loop_count} iterations."
)
@steps(0, ["join-foreach"], required=True)
def step_join(self, inputs):
self.results = sorted([inp.result for inp in inputs])
@steps(1, ["end"], required=True)
def step_end(self):
pass
def check_results(self, flow, checker):
expected = [
"Item A finished after 3 iterations.",
"Item B finished after 5 iterations.",
"Item C finished after 2 iterations.",
]
checker.assert_artifact("join", "results", expected)
| RecursiveSwitchInsideForeachFlowTest |
python | pallets__werkzeug | src/werkzeug/sansio/multipart.py | {
"start": 562,
"end": 643
} | class ____(Event):
data: bytes
more_data: bool
@dataclass(frozen=True)
| Data |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 12031,
"end": 13075
} | class ____(NamedTuple):
"""Stores edges for border / outline."""
top: tuple[EdgeType, Color]
right: tuple[EdgeType, Color]
bottom: tuple[EdgeType, Color]
left: tuple[EdgeType, Color]
def __bool__(self) -> bool:
(top, _), (right, _), (bottom, _), (left, _) = self
return bool(top or right or bottom or left)
def __rich_repr__(self) -> rich.repr.Result:
top, right, bottom, left = self
if top[0]:
yield "top", top
if right[0]:
yield "right", right
if bottom[0]:
yield "bottom", bottom
if left[0]:
yield "left", left
@property
def spacing(self) -> Spacing:
"""Get spacing created by borders.
Returns:
Spacing for top, right, bottom, and left.
"""
(top, _), (right, _), (bottom, _), (left, _) = self
return Spacing(
1 if top else 0,
1 if right else 0,
1 if bottom else 0,
1 if left else 0,
)
| Edges |
python | numpy__numpy | numpy/typing/tests/data/pass/scalars.py | {
"start": 335,
"end": 393
} | class ____:
def __int__(self) -> int:
return 4
| B |
python | numpy__numpy | numpy/lib/_index_tricks_impl.py | {
"start": 19834,
"end": 20816
} | class ____:
"""
Multidimensional index iterator.
Return an iterator yielding pairs of array coordinates and values.
Parameters
----------
arr : ndarray
Input array.
See Also
--------
ndindex, flatiter
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> for index, x in np.ndenumerate(a):
... print(index, x)
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
"""
def __init__(self, arr):
self.iter = np.asarray(arr).flat
def __next__(self):
"""
Standard iterator method, returns the index tuple and array value.
Returns
-------
coords : tuple of ints
The indices of the current iteration.
val : scalar
The array element of the current iteration.
"""
return self.iter.coords, next(self.iter)
def __iter__(self):
return self
@set_module('numpy')
| ndenumerate |
python | django__django | tests/migrations/test_migrations_squashed_double/0005_squashed_0003_and_0004.py | {
"start": 43,
"end": 680
} | class ____(migrations.Migration):
replaces = [
("migrations", "0003_squashed_0001_and_0002"),
("migrations", "0004_auto"),
]
operations = [
migrations.CreateModel(
name="A",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("foo", models.BooleanField(default=False)),
],
),
]
| Migration |
python | pandas-dev__pandas | pandas/tests/indexes/datetimelike_/test_equals.py | {
"start": 4976,
"end": 6582
} | class ____(EqualsTests):
@pytest.fixture
def index(self):
"""Fixture for creating a TimedeltaIndex for use in equality tests."""
return timedelta_range("1 day", periods=10)
def test_equals2(self):
# GH#13107
idx = TimedeltaIndex(["1 days", "2 days", "NaT"])
assert idx.equals(idx)
assert idx.equals(idx.copy())
assert idx.equals(idx.astype(object))
assert idx.astype(object).equals(idx)
assert idx.astype(object).equals(idx.astype(object))
assert not idx.equals(list(idx))
assert not idx.equals(pd.Series(idx))
idx2 = TimedeltaIndex(["2 days", "1 days", "NaT"])
assert not idx.equals(idx2)
assert not idx.equals(idx2.copy())
assert not idx.equals(idx2.astype(object))
assert not idx.astype(object).equals(idx2)
assert not idx.astype(object).equals(idx2.astype(object))
assert not idx.equals(list(idx2))
assert not idx.equals(pd.Series(idx2))
# Check that we dont raise OverflowError on comparisons outside the
# implementation range GH#28532
oob = Index([timedelta(days=10**6)] * 3, dtype=object)
assert not idx.equals(oob)
assert not idx2.equals(oob)
oob2 = Index([np.timedelta64(x) for x in oob], dtype=object)
assert (oob == oob2).all()
assert not idx.equals(oob2)
assert not idx2.equals(oob2)
oob3 = oob.map(np.timedelta64)
assert (oob3 == oob).all()
assert not idx.equals(oob3)
assert not idx2.equals(oob3)
| TestTimedeltaIndexEquals |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.