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 | python-poetry__poetry | src/poetry/installation/wheel_installer.py | {
"start": 718,
"end": 2021
} | class ____(SchemeDictionaryDestination):
""" """
def write_to_fs(
self,
scheme: Scheme,
path: str,
stream: BinaryIO,
is_executable: bool,
) -> RecordEntry:
from installer.records import Hash
from installer.records import RecordEntry
from installer.utils import copyfileobj_with_hashing
from installer.utils import make_file_executable
target_path = Path(self.scheme_dict[scheme]) / path
if target_path.exists():
# Contrary to the base library we don't raise an error here since it can
# break pkgutil-style and pkg_resource-style namespace packages.
logger.warning(f"Installing {target_path} over existing file")
parent_folder = target_path.parent
if not parent_folder.exists():
# Due to the parallel installation it can happen
# that two threads try to create the directory.
parent_folder.mkdir(parents=True, exist_ok=True)
with target_path.open("wb") as f:
hash_, size = copyfileobj_with_hashing(stream, f, self.hash_algorithm)
if is_executable:
make_file_executable(target_path)
return RecordEntry(path, Hash(self.hash_algorithm, hash_), size)
| WheelDestination |
python | walkccc__LeetCode | solutions/3137. Minimum Number of Operations to Make Word K-Periodic/3137.py | {
"start": 0,
"end": 215
} | class ____:
def minimumOperationsToMakeKPeriodic(self, word: str, k: int) -> int:
count = collections.Counter(word[i:i + k] for i in range(0, len(word), k))
return len(word) // k - max(count.values())
| Solution |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 75797,
"end": 76251
} | class ____(BuiltinFunctionT):
_id = "breakpoint"
_inputs: list = []
_warned = False
def fetch_call_return(self, node):
if not self._warned:
vyper_warn("`breakpoint` should only be used for debugging!", node)
self._warned = True
return None
@process_inputs
def build_IR(self, expr, args, kwargs, context):
return IRnode.from_list("breakpoint", annotation="breakpoint()")
| Breakpoint |
python | huggingface__transformers | src/transformers/models/rembert/modeling_rembert.py | {
"start": 31710,
"end": 36112
} | class ____(RemBertPreTrainedModel, GenerationMixin):
def __init__(self, config):
super().__init__(config)
if not config.is_decoder:
logger.warning("If you want to use `RemBertForCausalLM` as a standalone, add `is_decoder=True.`")
self.rembert = RemBertModel(config, add_pooling_layer=False)
self.cls = RemBertOnlyMLMHead(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Cache] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs,
) -> Union[tuple, CausalLMOutputWithCrossAttentions]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
Example:
```python
>>> from transformers import AutoTokenizer, RemBertForCausalLM, RemBertConfig
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> config = RemBertConfig.from_pretrained("google/rembert")
>>> config.is_decoder = True
>>> model = RemBertForCausalLM.from_pretrained("google/rembert", config=config)
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> prediction_logits = outputs.logits
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.rembert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.cls(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
cross_attentions=outputs.cross_attentions,
)
@auto_docstring(
custom_intro="""
RemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
pooled output) e.g. for GLUE tasks.
"""
)
| RemBertForCausalLM |
python | viewflow__viewflow | viewflow/forms/renderers.py | {
"start": 15418,
"end": 18510
} | class ____:
"""Default form layout."""
def append_non_field_errors(self, form: forms.Form, root: ElementTree.Element):
errors = form.non_field_errors()
errors.extend(
error
for bound_field in form.hidden_fields()
if bound_field.errors
for error in bound_field.errors
)
if errors:
wrapper = ElementTree.SubElement(root, "div", {"class": "vf-form__errors"})
for error in errors:
child = ElementTree.SubElement(
wrapper,
"div",
{
"class": "vf-form__error",
},
)
child.text = str(error)
def append_hidden_fields(self, form: forms.Form, root: ElementTree.Element):
hidden_fields = form.hidden_fields()
if hidden_fields:
wrapper = ElementTree.SubElement(
root, "div", {"class": "vf-form__hiddenfields"}
)
for bound_field in hidden_fields:
self.append_field(wrapper, bound_field)
def append_visible_fields(self, form: forms.Form, root: ElementTree.Element):
visible_fields = form.visible_fields()
if visible_fields:
wrapper = ElementTree.SubElement(
root, "div", {"class": "vf-form__visiblefields mdc-layout-grid__inner"}
)
for bound_field in form.visible_fields():
container = ElementTree.SubElement(
wrapper,
"div",
{"class": "mdc-layout-grid__cell mdc-layout-grid__cell--span-12"},
)
self.append_field(container, bound_field)
def append_field(
self,
root: ElementTree.Element,
bound_field: forms.BoundField,
renderer_class=None,
layout_node=None,
):
if renderer_class is None:
renderer_class = WidgetRenderer.get_renderer(bound_field.field.widget)
widget = bound_field.field.widget
if bound_field.field.localize:
widget.is_localized = True
attrs = bound_field.build_widget_attrs({}, widget)
if bound_field.auto_id and "id" not in widget.attrs:
attrs.setdefault("id", bound_field.auto_id)
widget.render(
name=bound_field.html_name,
value=bound_field.value(),
attrs=attrs,
renderer=renderer_class(root, bound_field, layout_node),
)
def render_form(self, form: forms.Form) -> ElementTree.Element:
root = ElementTree.Element("div", {"class": "vf-form mdc-layout-grid"})
self.append_non_field_errors(form, root)
self.append_hidden_fields(form, root)
self.append_visible_fields(form, root)
return root
def render(self, form: forms.Form, default_layout: "FormLayout" = None):
return ElementTree.tostring(
self.render_form(form),
encoding="unicode",
method="html",
)
| FormLayout |
python | wandb__wandb | wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py | {
"start": 569,
"end": 869
} | class ____(GQLResult):
typename__: Typename[
Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"]
]
state: ArtifactCollectionState
DeleteArtifactPortfolio.model_rebuild()
DeleteArtifactPortfolioResult.model_rebuild()
| DeleteArtifactPortfolioResultArtifactCollection |
python | modin-project__modin | modin/tests/pandas/native_df_interoperability/test_compiler_caster.py | {
"start": 5634,
"end": 6220
} | class ____(CalculatorTestQc):
"Represents a query compiler with very few resources"
def get_backend(self):
return "Pico"
@classmethod
def max_cost(cls):
return QCCoercionCost.COST_LOW
def move_to_cost(self, other_qc_cls, api_cls_name, op, arguments):
return {
CloudQC: QCCoercionCost.COST_LOW,
CloudQCHighSelf: QCCoercionCost.COST_LOW,
ClusterQC: QCCoercionCost.COST_LOW,
LocalMachineQC: QCCoercionCost.COST_LOW,
PicoQC: QCCoercionCost.COST_ZERO,
}.get(other_qc_cls)
| PicoQC |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/test_connection_wrapper.py | {
"start": 1633,
"end": 2787
} | class ____:
@pytest.mark.parametrize("extra", [{"foo": "bar", "spam": "egg"}, '{"foo": "bar", "spam": "egg"}', None])
def test_compat_with_connection(self, extra):
"""Simple compatibility test with `airflow.models.connection.Connection`."""
conn_kwargs = {
"conn_id": MOCK_AWS_CONN_ID,
"conn_type": "aws",
"login": "mock-login",
"password": "mock-password",
"extra": extra,
# AwsBaseHook never use this attributes from airflow.models.Connection
"host": "mock-host",
"schema": "mock-schema",
"port": 42,
}
conn = Connection(**conn_kwargs)
conn_meta = _ConnectionMetadata(**conn_kwargs)
assert conn.conn_id == conn_meta.conn_id
assert conn.conn_type == conn_meta.conn_type
assert conn.login == conn_meta.login
assert conn.password == conn_meta.password
assert conn.host == conn_meta.host
assert conn.schema == conn_meta.schema
assert conn.port == conn_meta.port
assert conn.extra_dejson == conn_meta.extra_dejson
| TestsConnectionMetadata |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cloud/exceptions.py | {
"start": 899,
"end": 1004
} | class ____(DbtCloudException):
"""Raised when unable to retrieve dbt Cloud job."""
| DbtCloudGetJobFailed |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 92044,
"end": 92119
} | class ____(Binop):
operation = operator.and_
_operator_repr = "&"
| And |
python | astropy__astropy | astropy/table/tests/test_masked.py | {
"start": 1350,
"end": 3614
} | class ____:
"""Test the filled method in MaskedColumn and Table"""
def setup_method(self, method):
mask = [True, False, False]
self.meta = {"a": 1, "b": [2, 3]}
self.a = MaskedColumn(
name="a", data=[1, 2, 3], fill_value=10, mask=mask, meta={"a": 1}
)
self.b = MaskedColumn(
name="b", data=[4.0, 5.0, 6.0], fill_value=10.0, mask=mask
)
self.c = MaskedColumn(name="c", data=["7", "8", "9"], fill_value="1", mask=mask)
def test_filled_column(self):
f = self.a.filled()
assert np.all(f == [10, 2, 3])
assert isinstance(f, Column)
assert not isinstance(f, MaskedColumn)
# Confirm copy, not ref
assert f.meta["a"] == 1
f.meta["a"] = 2
f[1] = 100
assert self.a[1] == 2
assert self.a.meta["a"] == 1
# Fill with arg fill_value not column fill_value
f = self.a.filled(20)
assert np.all(f == [20, 2, 3])
f = self.b.filled()
assert np.all(f == [10.0, 5.0, 6.0])
assert isinstance(f, Column)
f = self.c.filled()
assert np.all(f == ["1", "8", "9"])
assert isinstance(f, Column)
def test_filled_masked_table(self, tableclass):
t = tableclass([self.a, self.b, self.c], meta=self.meta)
f = t.filled()
assert isinstance(f, Table)
assert f.masked is False
assert np.all(f["a"] == [10, 2, 3])
assert np.allclose(f["b"], [10.0, 5.0, 6.0])
assert np.all(f["c"] == ["1", "8", "9"])
# Confirm copy, not ref
assert f.meta["b"] == [2, 3]
f.meta["b"][0] = 20
assert t.meta["b"] == [2, 3]
f["a"][2] = 100
assert t["a"][2] == 3
def test_filled_unmasked_table(self, tableclass):
t = tableclass([(1, 2), ("3", "4")], names=("a", "b"), meta=self.meta)
f = t.filled()
assert isinstance(f, Table)
assert f.masked is False
assert np.all(f["a"] == t["a"])
assert np.all(f["b"] == t["b"])
# Confirm copy, not ref
assert f.meta["b"] == [2, 3]
f.meta["b"][0] = 20
assert t.meta["b"] == [2, 3]
f["a"][1] = 100
assert t["a"][1] == 2
| TestFilled |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/ref.py | {
"start": 2778,
"end": 3519
} | class ____(PathRef, ABC):
"""Base class that checks if a executable can be references via symlink/copy."""
def __init__(self, src, must=RefMust.NA, when=RefWhen.ANY) -> None:
super().__init__(src, must, when)
self._can_run = None
@property
def can_symlink(self):
if self.FS_SUPPORTS_SYMLINK:
return self.can_run
return False
@property
def can_run(self):
if self._can_run is None:
mode = self.src.stat().st_mode
for key in [S_IXUSR, S_IXGRP, S_IXOTH]:
if mode & key:
self._can_run = True
break
else:
self._can_run = False
return self._can_run
| ExePathRef |
python | joke2k__faker | faker/providers/file/en_US/__init__.py | {
"start": 42,
"end": 81
} | class ____(FileProvider):
pass
| Provider |
python | getsentry__sentry | src/sentry/uptime/types.py | {
"start": 2761,
"end": 3194
} | class ____:
"""
Represents a check entry response from the EAP API.
"""
uptime_check_id: str
timestamp: datetime
scheduled_check_time: datetime
check_status: CheckStatus
check_status_reason: CheckStatusReasonType | None
http_status_code: int | None
duration_ms: int
trace_id: str
incident_status: IncidentStatus
environment: str
region: str
@dataclass(frozen=True)
| EapCheckEntry |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 102337,
"end": 109144
} | class ____(TestCase):
class CustomIterDataPipe(IterDataPipe):
def add_v(self, x):
return x + self.v
def __init__(self, source_dp, v=1):
self._dp = source_dp.map(self.add_v)
self.v = 1
def __iter__(self):
yield from self._dp
def __hash__(self):
raise NotImplementedError
def test_simple_traverse(self):
numbers_dp = NumbersDataset(size=50)
shuffled_dp = numbers_dp.shuffle()
sharded_dp = shuffled_dp.sharding_filter()
mapped_dp = sharded_dp.map(lambda x: x * 10)
graph = traverse_dps(mapped_dp)
expected: dict[Any, Any] = {
id(mapped_dp): (
mapped_dp,
{
id(sharded_dp): (
sharded_dp,
{
id(shuffled_dp): (
shuffled_dp,
{id(numbers_dp): (numbers_dp, {})},
)
},
)
},
)
}
self.assertEqual(expected, graph)
dps = torch.utils.data.graph_settings.get_all_graph_pipes(graph)
self.assertEqual(len(dps), 4)
for datapipe in (numbers_dp, shuffled_dp, sharded_dp, mapped_dp):
self.assertTrue(datapipe in dps)
def test_traverse_forked(self):
numbers_dp = NumbersDataset(size=50)
dp0, dp1, dp2 = numbers_dp.fork(num_instances=3)
dp0_upd = dp0.map(lambda x: x * 10)
dp1_upd = dp1.filter(lambda x: x % 3 == 1)
combined_dp = dp0_upd.mux(dp1_upd, dp2)
graph = traverse_dps(combined_dp)
expected = {
id(combined_dp): (
combined_dp,
{
id(dp0_upd): (
dp0_upd,
{
id(dp0): (
dp0,
{
id(dp0.main_datapipe): (
dp0.main_datapipe,
{
id(dp0.main_datapipe.main_datapipe): (
dp0.main_datapipe.main_datapipe,
{},
)
},
)
},
)
},
),
id(dp1_upd): (
dp1_upd,
{
id(dp1): (
dp1,
{
id(dp1.main_datapipe): (
dp1.main_datapipe,
{
id(dp1.main_datapipe.main_datapipe): (
dp1.main_datapipe.main_datapipe,
{},
)
},
)
},
)
},
),
id(dp2): (
dp2,
{
id(dp2.main_datapipe): (
dp2.main_datapipe,
{
id(dp2.main_datapipe.main_datapipe): (
dp2.main_datapipe.main_datapipe,
{},
)
},
)
},
),
},
)
}
self.assertEqual(expected, graph)
dps = torch.utils.data.graph_settings.get_all_graph_pipes(graph)
self.assertEqual(len(dps), 8)
for _dp in [
numbers_dp,
dp0.main_datapipe,
dp0,
dp1,
dp2,
dp0_upd,
dp1_upd,
combined_dp,
]:
self.assertTrue(_dp in dps)
def test_traverse_mapdatapipe(self):
source_dp = dp.map.SequenceWrapper(range(10))
map_dp = source_dp.map(partial(_fake_add, 1))
graph = traverse_dps(map_dp)
expected: dict[Any, Any] = {
id(map_dp): (map_dp, {id(source_dp): (source_dp, {})})
}
self.assertEqual(expected, graph)
def test_traverse_mixdatapipe(self):
source_map_dp = dp.map.SequenceWrapper(range(10))
iter_dp = dp.iter.IterableWrapper(source_map_dp)
graph = traverse_dps(iter_dp)
expected: dict[Any, Any] = {
id(iter_dp): (iter_dp, {id(source_map_dp): (source_map_dp, {})})
}
self.assertEqual(expected, graph)
def test_traverse_circular_datapipe(self):
source_iter_dp = dp.iter.IterableWrapper(list(range(10)))
circular_dp = TestGraph.CustomIterDataPipe(source_iter_dp)
graph = traverse_dps(circular_dp)
# See issue: https://github.com/pytorch/data/issues/535
expected: dict[Any, Any] = {
id(circular_dp): (
circular_dp,
{
id(circular_dp._dp): (
circular_dp._dp,
{id(source_iter_dp): (source_iter_dp, {})},
)
},
)
}
self.assertEqual(expected, graph)
dps = torch.utils.data.graph_settings.get_all_graph_pipes(graph)
self.assertEqual(len(dps), 3)
for _dp in [circular_dp, circular_dp._dp, source_iter_dp]:
self.assertTrue(_dp in dps)
def test_traverse_unhashable_datapipe(self):
source_iter_dp = dp.iter.IterableWrapper(list(range(10)))
unhashable_dp = TestGraph.CustomIterDataPipe(source_iter_dp)
graph = traverse_dps(unhashable_dp)
with self.assertRaises(NotImplementedError):
hash(unhashable_dp)
expected: dict[Any, Any] = {
id(unhashable_dp): (
unhashable_dp,
{
id(unhashable_dp._dp): (
unhashable_dp._dp,
{id(source_iter_dp): (source_iter_dp, {})},
)
},
)
}
self.assertEqual(expected, graph)
def unbatch(x):
return x[0]
| TestGraph |
python | Netflix__metaflow | metaflow/decorators.py | {
"start": 901,
"end": 1478
} | class ____(MetaflowException):
headline = "Syntax error"
def __init__(self, deco, func):
msg = (
"You tried to apply decorator '{deco}' on '{func}' which is "
"not declared as a @step. Make sure you apply this decorator "
"on a function which has @step on the line just before the "
"function name and @{deco} is above @step.".format(
deco=deco, func=getattr(func, "__name__", str(func))
)
)
super(BadStepDecoratorException, self).__init__(msg)
| BadStepDecoratorException |
python | bokeh__bokeh | src/bokeh/models/widgets/sliders.py | {
"start": 4076,
"end": 4560
} | class ____(AbstractSlider):
""" Base class for numerical sliders. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
format = Either(String, Instance(TickFormatter), help="""
""")
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
| NumericalSlider |
python | walkccc__LeetCode | solutions/1486. XOR Operation in an Array/1486.py | {
"start": 0,
"end": 174
} | class ____:
def xorOperation(self, n: int, start: int) -> int:
return functools.reduce(operator.xor,
[start + 2 * i for i in range(n)])
| Solution |
python | huggingface__transformers | src/transformers/models/data2vec/modular_data2vec_audio.py | {
"start": 4431,
"end": 4487
} | class ____(Wav2Vec2Adapter):
pass
| Data2VecAudioAdapter |
python | tiangolo__fastapi | tests/test_additional_responses_custom_model_in_callback.py | {
"start": 200,
"end": 5895
} | class ____(BaseModel):
a: int
app = FastAPI()
callback_router = APIRouter(default_response_class=JSONResponse)
@callback_router.get(
"{$callback_url}/callback/", responses={400: {"model": CustomModel}}
)
def callback_route():
pass # pragma: no cover
@app.post("/", callbacks=callback_router.routes)
def main_route(callback_url: HttpUrl):
pass # pragma: no cover
client = TestClient(app)
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == {
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/": {
"post": {
"summary": "Main Route",
"operationId": "main_route__post",
"parameters": [
{
"required": True,
"schema": IsDict(
{
"title": "Callback Url",
"minLength": 1,
"type": "string",
"format": "uri",
}
)
# TODO: remove when deprecating Pydantic v1
| IsDict(
{
"title": "Callback Url",
"maxLength": 2083,
"minLength": 1,
"type": "string",
"format": "uri",
}
),
"name": "callback_url",
"in": "query",
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
"callbacks": {
"callback_route": {
"{$callback_url}/callback/": {
"get": {
"summary": "Callback Route",
"operationId": "callback_route__callback_url__callback__get",
"responses": {
"400": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CustomModel"
}
}
},
"description": "Bad Request",
},
"200": {
"description": "Successful Response",
"content": {
"application/json": {"schema": {}}
},
},
},
}
}
}
},
}
}
},
"components": {
"schemas": {
"CustomModel": {
"title": "CustomModel",
"required": ["a"],
"type": "object",
"properties": {"a": {"title": "A", "type": "integer"}},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {"$ref": "#/components/schemas/ValidationError"},
}
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
}
},
}
| CustomModel |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_clear_tool_uses_20250919_edit_param.py | {
"start": 698,
"end": 1485
} | class ____(TypedDict, total=False):
type: Required[Literal["clear_tool_uses_20250919"]]
clear_at_least: Optional[BetaInputTokensClearAtLeastParam]
"""Minimum number of tokens that must be cleared when triggered.
Context will only be modified if at least this many tokens can be removed.
"""
clear_tool_inputs: Union[bool, SequenceNotStr[str], None]
"""Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)"""
exclude_tools: Optional[SequenceNotStr[str]]
"""Tool names whose uses are preserved from clearing"""
keep: BetaToolUsesKeepParam
"""Number of tool uses to retain in the conversation"""
trigger: Trigger
"""Condition that triggers the context management strategy"""
| BetaClearToolUses20250919EditParam |
python | kamyu104__LeetCode-Solutions | Python/course-schedule.py | {
"start": 950,
"end": 1670
} | class ____(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
adj = collections.defaultdict(list)
in_degree = collections.Counter()
for u, v in prerequisites:
in_degree[u] += 1
adj[v].append(u)
result = []
stk = [u for u in xrange(numCourses) if u not in in_degree]
while stk:
u = stk.pop()
result.append(u)
for v in adj[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
stk.append(v)
return len(result) == numCourses
| Solution2 |
python | run-llama__llama_index | llama-index-integrations/evaluation/llama-index-evaluation-tonic-validate/llama_index/evaluation/tonic_validate/retrieval_precision.py | {
"start": 360,
"end": 2007
} | class ____(BaseEvaluator):
"""
Tonic Validate's retrieval precision metric.
The output score is a float between 0.0 and 1.0.
See https://docs.tonic.ai/validate/ for more details.
Args:
openai_service(OpenAIService): The OpenAI service to use. Specifies the chat
completion model to use as the LLM evaluator. Defaults to "gpt-4".
"""
def __init__(self, openai_service: Optional[Any] = None):
if openai_service is None:
openai_service = OpenAIService("gpt-4")
self.openai_service = openai_service
self.metric = RetrievalPrecisionMetric()
async def aevaluate(
self,
query: Optional[str] = None,
response: Optional[str] = None,
contexts: Optional[Sequence[str]] = None,
**kwargs: Any,
) -> EvaluationResult:
from tonic_validate.classes.benchmark import BenchmarkItem
from tonic_validate.classes.llm_response import LLMResponse
benchmark_item = BenchmarkItem(question=query, answer=response)
llm_response = LLMResponse(
llm_answer=response,
llm_context_list=contexts,
benchmark_item=benchmark_item,
)
score = self.metric.score(llm_response, self.openai_service)
return EvaluationResult(
query=query, contexts=contexts, response=response, score=score
)
def _get_prompts(self) -> PromptDictType:
return {}
def _get_prompt_modules(self) -> PromptMixinType:
return {}
def _update_prompts(self, prompts_dict: PromptDictType) -> None:
return
| RetrievalPrecisionEvaluator |
python | pytorch__pytorch | torch/_inductor/fx_passes/control_dependencies.py | {
"start": 557,
"end": 7926
} | class ____(HigherOrderOperator):
"""
Higher-order operator that enforces ordering by making dependencies explicit.
Schema: control_deps(additional_deps, target, *args, **kwargs) -> result
where:
- additional_deps: tuple of tensors that must be computed before this op
- subgraph: GraphModule containing the exact operation to execute
- args/kwargs: arguments for the target function
This ensures all tensors in additional_deps are computed before the target
executes, creating explicit scheduling dependencies.
"""
def __init__(self) -> None:
super().__init__("control_deps")
def __call__(self, additional_deps, subgraph, *args, **kwargs):
"""Call the operator with dependencies and subgraph.
Args:
additional_deps: Tuple of tensors that must be computed first
subgraph: GraphModule containing the exact operation to execute
*args: Arguments to pass to the subgraph
"""
if not isinstance(additional_deps, (tuple, list)):
raise TypeError(
f"additional_deps must be tuple/list, got {type(additional_deps).__name__}"
)
if not (isinstance(subgraph, fx.GraphModule) or callable(subgraph)):
raise TypeError(
f"subgraph must be GraphModule or callable, got {type(subgraph).__name__}"
)
return super().__call__(additional_deps, subgraph, *args, **kwargs)
control_deps = ControlDeps()
# Register fake implementation for tracing
@register_fake(control_deps)
def _(additional_deps, subgraph, *args, **kwargs):
"""Fake tensor implementation - execute the subgraph."""
return subgraph(*args, **kwargs)
def get_subgraph_name(gm: fx.GraphModule, name):
name = f"subgraph_{name}"
if not hasattr(gm, name):
return name
i = 0
while hasattr(gm, f"{name}_{i}"):
i += 1
return f"{name}_{i}"
def preserve_node_ordering(
graph: fx.Graph,
additional_deps_map: dict[fx.Node, OrderedSet[fx.Node]],
verbose: bool = False,
) -> None:
"""
Preserve node ordering using control_deps HOP with subgraph.
This function wraps operations with control_deps that:
1. Makes additional dependencies explicit (first argument)
2. Creates a subgraph internally to preserve the exact original operation
3. Preserves the original node names
Args:
graph: The FX graph to modify
additional_deps_map: Mapping from dependent nodes to their dependencies
verbose: If True, print debug information
"""
if not additional_deps_map:
return
# Track replacements so we can update dependencies
replacements: dict[fx.Node, fx.Node] = {}
# Process each node that needs additional dependencies
for dependent_node, dep_nodes in additional_deps_map.items():
assert dependent_node.op == "call_function", dependent_node.op
original_name = dependent_node.name
original_args = dependent_node.args
original_kwargs = dependent_node.kwargs
original_meta = dependent_node.meta.copy()
updated_dep_nodes = [replacements.get(dep, dep) for dep in dep_nodes]
# Create a subgraph that preserves the exact original operation
subgraph_module = _create_subgraph_for_node(graph, dependent_node)
owning_mod = graph.owning_module
assert owning_mod is not None
subgraph_attr_name = get_subgraph_name(owning_mod, original_name)
setattr(graph.owning_module, subgraph_attr_name, subgraph_module)
# Create control_deps call with:
# 1. Additional dependencies as first arg (explicit)
# 2. Subgraph via get_attr (like b2b gemm pass)
# 3. Original arguments (only fx.Node args and kwargs are passed)
with graph.inserting_before(dependent_node):
# Create get_attr node for the subgraph
get_subgraph = graph.get_attr(subgraph_attr_name)
# add additional args
node_args = [a for a in original_args if isinstance(a, fx.Node)]
for value in original_kwargs.values():
if isinstance(value, fx.Node):
node_args.append(value)
# Create with temporary name first
ordered_node = graph.call_function(
control_deps,
args=(
tuple(updated_dep_nodes), # additional_deps
get_subgraph, # subgraph via get_attr (like b2b gemm)
*node_args, # original node arguments (from both args and kwargs)
),
kwargs={},
name=f"__temp_{original_name}", # Temporary name to avoid conflict
)
# Copy metadata from original node
ordered_node.meta = original_meta
# this will be constrained on the target node in subgraph if it exists
ordered_node.meta.pop("eager_input_vals", None)
# Replace all uses of the original node with the ordered version
dependent_node.replace_all_uses_with(ordered_node)
# Remove the original node from the graph
graph.erase_node(dependent_node)
# Now rename the ordered node to the original name
ordered_node.name = original_name # PRESERVE ORIGINAL NAME
# Track the replacement for future dependencies
replacements[dependent_node] = ordered_node
def _create_subgraph_for_node(graph: fx.Graph, node: fx.Node) -> fx.GraphModule:
"""
Create a subgraph that exactly recreates a node's operation.
The subgraph takes only the fx.Node arguments and recreates the operation
with the exact target, args structure, and kwargs.
Args:
graph: The parent graph
node: The node to wrap in a subgraph
Returns:
A GraphModule containing the subgraph
"""
# Get the owning module
# torch.distributed.breakpoint(0)
owning_module = graph.owning_module
# Create a new graph for the subgraph
subgraph = fx.Graph(owning_module)
new_args: list[Any] = []
placeholder_idx = 0
for _, arg in enumerate(node.args):
if not isinstance(arg, fx.Node):
new_args.append(arg)
continue
placeholder = subgraph.placeholder(f"arg_{placeholder_idx}")
placeholder_idx += 1
if "val" in arg.meta:
placeholder.meta.update(arg.meta)
new_args.append(placeholder) # type: ignore[arg-type]
new_kwargs: dict[str, Any] = {}
for key, value in node.kwargs.items():
if not isinstance(value, fx.Node):
new_kwargs[key] = value
continue
placeholder = subgraph.placeholder(f"kwarg_{key}")
if "val" in value.meta:
placeholder.meta.update(value.meta)
new_kwargs[key] = placeholder # type: ignore[assignment]
# Recreate the exact original operation in the subgraph
assert callable(node.target)
result = subgraph.call_function(
node.target,
tuple(new_args),
new_kwargs, # type: ignore[arg-type]
)
# Copy metadata from the original node
result.meta.update(node.meta)
out = subgraph.output(result)
if "val" in result.meta:
out.meta["val"] = result.meta["val"]
return fx.GraphModule(owning_module, subgraph)
| ControlDeps |
python | kubernetes-client__python | kubernetes/client/models/v1_volume_error.py | {
"start": 383,
"end": 5618
} | 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 = {
'error_code': 'int',
'message': 'str',
'time': 'datetime'
}
attribute_map = {
'error_code': 'errorCode',
'message': 'message',
'time': 'time'
}
def __init__(self, error_code=None, message=None, time=None, local_vars_configuration=None): # noqa: E501
"""V1VolumeError - 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._error_code = None
self._message = None
self._time = None
self.discriminator = None
if error_code is not None:
self.error_code = error_code
if message is not None:
self.message = message
if time is not None:
self.time = time
@property
def error_code(self):
"""Gets the error_code of this V1VolumeError. # noqa: E501
errorCode is a numeric gRPC code representing the error encountered during Attach or Detach operations. This is an optional, beta field that requires the MutableCSINodeAllocatableCount feature gate being enabled to be set. # noqa: E501
:return: The error_code of this V1VolumeError. # noqa: E501
:rtype: int
"""
return self._error_code
@error_code.setter
def error_code(self, error_code):
"""Sets the error_code of this V1VolumeError.
errorCode is a numeric gRPC code representing the error encountered during Attach or Detach operations. This is an optional, beta field that requires the MutableCSINodeAllocatableCount feature gate being enabled to be set. # noqa: E501
:param error_code: The error_code of this V1VolumeError. # noqa: E501
:type: int
"""
self._error_code = error_code
@property
def message(self):
"""Gets the message of this V1VolumeError. # noqa: E501
message represents the error encountered during Attach or Detach operation. This string may be logged, so it should not contain sensitive information. # noqa: E501
:return: The message of this V1VolumeError. # noqa: E501
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""Sets the message of this V1VolumeError.
message represents the error encountered during Attach or Detach operation. This string may be logged, so it should not contain sensitive information. # noqa: E501
:param message: The message of this V1VolumeError. # noqa: E501
:type: str
"""
self._message = message
@property
def time(self):
"""Gets the time of this V1VolumeError. # noqa: E501
time represents the time the error was encountered. # noqa: E501
:return: The time of this V1VolumeError. # noqa: E501
:rtype: datetime
"""
return self._time
@time.setter
def time(self, time):
"""Sets the time of this V1VolumeError.
time represents the time the error was encountered. # noqa: E501
:param time: The time of this V1VolumeError. # noqa: E501
:type: datetime
"""
self._time = time
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, V1VolumeError):
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, V1VolumeError):
return True
return self.to_dict() != other.to_dict()
| V1VolumeError |
python | getsentry__sentry | src/sentry/api/helpers/group_index/validators/group.py | {
"start": 787,
"end": 4755
} | class ____(serializers.Serializer[Group]):
inbox = serializers.BooleanField(
help_text="If true, marks the issue as reviewed by the requestor."
)
status = serializers.ChoiceField(
help_text="Limit mutations to only issues with the given status.",
choices=list(zip(STATUS_UPDATE_CHOICES.keys(), STATUS_UPDATE_CHOICES.keys())),
)
statusDetails = StatusDetailsValidator(
help_text="Additional details about the resolution. Status detail updates that include release data are only allowed for issues within a single project."
)
substatus = serializers.ChoiceField(
choices=list(zip(SUBSTATUS_UPDATE_CHOICES.keys(), SUBSTATUS_UPDATE_CHOICES.keys())),
allow_null=True,
help_text="The new substatus of the issue.",
)
hasSeen = serializers.BooleanField(
help_text="If true, marks the issue as seen by the requestor."
)
isBookmarked = serializers.BooleanField(
help_text="If true, bookmarks the issue for the requestor."
)
isPublic = serializers.BooleanField(help_text="If true, publishes the issue.")
isSubscribed = serializers.BooleanField(
help_text="If true, subscribes the requestor to the issue."
)
merge = serializers.BooleanField(help_text="If true, merges the issues together.")
discard = serializers.BooleanField(
help_text="If true, discards the issues instead of updating them."
)
assignedTo = ActorField(
help_text="The user or team that should be assigned to the issues. Values take the form of `<user_id>`, `user:<user_id>`, `<username>`, `<user_primary_email>`, or `team:<team_id>`."
)
priority = serializers.ChoiceField(
help_text="The priority that should be set for the issues",
choices=list(
zip(
[p.to_str() for p in PriorityLevel],
[p.to_str() for p in PriorityLevel],
)
),
)
####################################################
# These fields are not documented in the API docs. #
####################################################
# These are already covered by the `statusDetails` serializer field.
ignoreDuration = serializers.IntegerField()
ignoreCount = serializers.IntegerField()
ignoreWindow = serializers.IntegerField(max_value=7 * 24 * 60)
ignoreUserCount = serializers.IntegerField()
ignoreUserWindow = serializers.IntegerField(max_value=7 * 24 * 60)
# The `inboxDetails`` field is empty.
inboxDetails = InboxDetailsValidator()
# The `snooze` field is deprecated.
# TODO(dcramer): remove in 9.0
# for the moment, the CLI sends this for any issue update, so allow nulls
snoozeDuration = serializers.IntegerField(allow_null=True)
def validate_assignedTo(self, value: Actor) -> Actor:
if (
value
and value.is_user
and not self.context["project"].member_set.filter(user_id=value.id).exists()
):
raise serializers.ValidationError("Cannot assign to non-team member")
if (
value
and value.is_team
and not self.context["project"].teams.filter(id=value.id).exists()
):
raise serializers.ValidationError(
"Cannot assign to a team without access to the project"
)
return value
def validate_discard(self, value: bool) -> bool:
access = self.context.get("access")
if value and (not access or not access.has_scope("event:admin")):
raise serializers.ValidationError("You do not have permission to discard events")
return value
def validate(self, attrs: Mapping[str, Any]) -> Mapping[str, Any]:
attrs = super().validate(attrs)
if len(attrs) > 1 and "discard" in attrs:
raise serializers.ValidationError("Other attributes cannot be updated when discarding")
return attrs
| GroupValidator |
python | coleifer__peewee | tests/prefetch_tests.py | {
"start": 704,
"end": 808
} | class ____(TestModel):
note = ForeignKeyField(Note, backref='flags')
is_spam = BooleanField()
| Flag |
python | pandas-dev__pandas | pandas/io/html.py | {
"start": 3555,
"end": 16986
} | class ____:
"""
Base class for parsers that parse HTML into DataFrames.
Parameters
----------
io : str or file-like
This can be either a string path, a valid URL using the HTTP,
FTP, or FILE protocols or a file-like object.
match : str or regex
The text to match in the document.
attrs : dict
List of HTML <table> element attributes to match.
encoding : str
Encoding to be used by parser
displayed_only : bool
Whether or not items with "display:none" should be ignored
extract_links : {None, "all", "header", "body", "footer"}
Table elements in the specified section(s) with <a> tags will have their
href extracted.
Attributes
----------
io : str or file-like
raw HTML, URL, or file-like object
match : regex
The text to match in the raw HTML
attrs : dict-like
A dictionary of valid table attributes to use to search for table
elements.
encoding : str
Encoding to be used by parser
displayed_only : bool
Whether or not items with "display:none" should be ignored
extract_links : {None, "all", "header", "body", "footer"}
Table elements in the specified section(s) with <a> tags will have their
href extracted.
Notes
-----
To subclass this class effectively you must override the following methods:
* :func:`_build_doc`
* :func:`_attr_getter`
* :func:`_href_getter`
* :func:`_text_getter`
* :func:`_parse_td`
* :func:`_parse_thead_tr`
* :func:`_parse_tbody_tr`
* :func:`_parse_tfoot_tr`
* :func:`_parse_tables`
* :func:`_equals_tag`
See each method's respective documentation for details on their
functionality.
"""
def __init__(
self,
io: FilePath | ReadBuffer[str] | ReadBuffer[bytes],
match: str | Pattern,
attrs: dict[str, str] | None,
encoding: str,
displayed_only: bool,
extract_links: Literal["header", "footer", "body", "all"] | None,
storage_options: StorageOptions = None,
) -> None:
self.io = io
self.match = match
self.attrs = attrs
self.encoding = encoding
self.displayed_only = displayed_only
self.extract_links = extract_links
self.storage_options = storage_options
def parse_tables(self):
"""
Parse and return all tables from the DOM.
Returns
-------
list of parsed (header, body, footer) tuples from tables.
"""
tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
return (self._parse_thead_tbody_tfoot(table) for table in tables)
def _attr_getter(self, obj, attr):
"""
Return the attribute value of an individual DOM node.
Parameters
----------
obj : node-like
A DOM node.
attr : str or unicode
The attribute, such as "colspan"
Returns
-------
str or unicode
The attribute value.
"""
# Both lxml and BeautifulSoup have the same implementation:
return obj.get(attr)
def _href_getter(self, obj) -> str | None:
"""
Return a href if the DOM node contains a child <a> or None.
Parameters
----------
obj : node-like
A DOM node.
Returns
-------
href : str or unicode
The href from the <a> child of the DOM node.
"""
raise AbstractMethodError(self)
def _text_getter(self, obj):
"""
Return the text of an individual DOM node.
Parameters
----------
obj : node-like
A DOM node.
Returns
-------
text : str or unicode
The text from an individual DOM node.
"""
raise AbstractMethodError(self)
def _parse_td(self, obj):
"""
Return the td elements from a row element.
Parameters
----------
obj : node-like
A DOM <tr> node.
Returns
-------
list of node-like
These are the elements of each row, i.e., the columns.
"""
raise AbstractMethodError(self)
def _parse_thead_tr(self, table):
"""
Return the list of thead row elements from the parsed table element.
Parameters
----------
table : a table element that contains zero or more thead elements.
Returns
-------
list of node-like
These are the <tr> row elements of a table.
"""
raise AbstractMethodError(self)
def _parse_tbody_tr(self, table):
"""
Return the list of tbody row elements from the parsed table element.
HTML5 table bodies consist of either 0 or more <tbody> elements (which
only contain <tr> elements) or 0 or more <tr> elements. This method
checks for both structures.
Parameters
----------
table : a table element that contains row elements.
Returns
-------
list of node-like
These are the <tr> row elements of a table.
"""
raise AbstractMethodError(self)
def _parse_tfoot_tr(self, table):
"""
Return the list of tfoot row elements from the parsed table element.
Parameters
----------
table : a table element that contains row elements.
Returns
-------
list of node-like
These are the <tr> row elements of a table.
"""
raise AbstractMethodError(self)
def _parse_tables(self, document, match, attrs):
"""
Return all tables from the parsed DOM.
Parameters
----------
document : the DOM from which to parse the table element.
match : str or regular expression
The text to search for in the DOM tree.
attrs : dict
A dictionary of table attributes that can be used to disambiguate
multiple tables on a page.
Raises
------
ValueError : `match` does not match any text in the document.
Returns
-------
list of node-like
HTML <table> elements to be parsed into raw data.
"""
raise AbstractMethodError(self)
def _equals_tag(self, obj, tag) -> bool:
"""
Return whether an individual DOM node matches a tag
Parameters
----------
obj : node-like
A DOM node.
tag : str
Tag name to be checked for equality.
Returns
-------
boolean
Whether `obj`'s tag name is `tag`
"""
raise AbstractMethodError(self)
def _build_doc(self):
"""
Return a tree-like object that can be used to iterate over the DOM.
Returns
-------
node-like
The DOM from which to parse the table element.
"""
raise AbstractMethodError(self)
def _parse_thead_tbody_tfoot(self, table_html):
"""
Given a table, return parsed header, body, and foot.
Parameters
----------
table_html : node-like
Returns
-------
tuple of (header, body, footer), each a list of list-of-text rows.
Notes
-----
Header and body are lists-of-lists. Top level list is a list of
rows. Each row is a list of str text.
Logic: Use <thead>, <tbody>, <tfoot> elements to identify
header, body, and footer, otherwise:
- Put all rows into body
- Move rows from top of body to header only if
all elements inside row are <th>
- Move rows from bottom of body to footer only if
all elements inside row are <th>
"""
header_rows = self._parse_thead_tr(table_html)
body_rows = self._parse_tbody_tr(table_html)
footer_rows = self._parse_tfoot_tr(table_html)
def row_is_all_th(row):
return all(self._equals_tag(t, "th") for t in self._parse_td(row))
if not header_rows:
# The table has no <thead>. Move the top all-<th> rows from
# body_rows to header_rows. (This is a common case because many
# tables in the wild have no <thead> or <tfoot>
while body_rows and row_is_all_th(body_rows[0]):
header_rows.append(body_rows.pop(0))
header, rem = self._expand_colspan_rowspan(header_rows, section="header")
body, rem = self._expand_colspan_rowspan(
body_rows,
section="body",
remainder=rem,
overflow=len(footer_rows) > 0,
)
footer, _ = self._expand_colspan_rowspan(
footer_rows, section="footer", remainder=rem, overflow=False
)
return header, body, footer
def _expand_colspan_rowspan(
self,
rows,
section: Literal["header", "footer", "body"],
remainder: list[tuple[int, str | tuple, int]] | None = None,
overflow: bool = True,
) -> tuple[list[list], list[tuple[int, str | tuple, int]]]:
"""
Given a list of <tr>s, return a list of text rows.
Parameters
----------
rows : list of node-like
List of <tr>s
section : the section that the rows belong to (header, body or footer).
remainder: list[tuple[int, str | tuple, int]] | None
Any remainder from the expansion of previous section
overflow: bool
If true, return any partial rows as 'remainder'. If not, use up any
partial rows. True by default.
Returns
-------
list of list
Each returned row is a list of str text, or tuple (text, link)
if extract_links is not None.
remainder
Remaining partial rows if any. If overflow is False, an empty list
is returned.
Notes
-----
Any cell with ``rowspan`` or ``colspan`` will have its contents copied
to subsequent cells.
"""
all_texts = [] # list of rows, each a list of str
text: str | tuple
remainder = remainder if remainder is not None else []
for tr in rows:
texts = [] # the output for this row
next_remainder = []
index = 0
tds = self._parse_td(tr)
for td in tds:
# Append texts from previous rows with rowspan>1 that come
# before this <td>
while remainder and remainder[0][0] <= index:
prev_i, prev_text, prev_rowspan = remainder.pop(0)
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text, prev_rowspan - 1))
index += 1
# Append the text from this <td>, colspan times
text = _remove_whitespace(self._text_getter(td))
if self.extract_links in ("all", section):
href = self._href_getter(td)
text = (text, href)
rowspan = int(self._attr_getter(td, "rowspan") or 1)
colspan = int(self._attr_getter(td, "colspan") or 1)
for _ in range(colspan):
texts.append(text)
if rowspan > 1:
next_remainder.append((index, text, rowspan - 1))
index += 1
# Append texts from previous rows at the final position
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text, prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
if not overflow:
# Append rows that only appear because the previous row had non-1
# rowspan
while remainder:
next_remainder = []
texts = []
for prev_i, prev_text, prev_rowspan in remainder:
texts.append(prev_text)
if prev_rowspan > 1:
next_remainder.append((prev_i, prev_text, prev_rowspan - 1))
all_texts.append(texts)
remainder = next_remainder
return all_texts, remainder
def _handle_hidden_tables(self, tbl_list, attr_name: str):
"""
Return list of tables, potentially removing hidden elements
Parameters
----------
tbl_list : list of node-like
Type of list elements will vary depending upon parser used
attr_name : str
Name of the accessor for retrieving HTML attributes
Returns
-------
list of node-like
Return type matches `tbl_list`
"""
if not self.displayed_only:
return tbl_list
return [
x
for x in tbl_list
if "display:none"
not in getattr(x, attr_name).get("style", "").replace(" ", "")
]
| _HtmlFrameParser |
python | pytorch__pytorch | test/ao/sparsity/test_kernels.py | {
"start": 9178,
"end": 9413
} | class ____(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
self.linear = nn.Linear(in_channels, out_channels)
def forward(self, x):
return self.linear(x)
| SparseQuantizedModel |
python | huggingface__transformers | tests/models/bert_japanese/test_tokenization_bert_japanese.py | {
"start": 17885,
"end": 18187
} | class ____(unittest.TestCase):
def test_tokenizer_bert_japanese(self):
EXAMPLE_BERT_JAPANESE_ID = "cl-tohoku/bert-base-japanese"
tokenizer = AutoTokenizer.from_pretrained(EXAMPLE_BERT_JAPANESE_ID)
self.assertIsInstance(tokenizer, BertJapaneseTokenizer)
| AutoTokenizerCustomTest |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 37132,
"end": 37323
} | class ____(Base):
key: Mapped[str] = mapped_column(index=True)
value: Mapped[dict[str, Any]] = mapped_column(JSON)
__table_args__: Any = (sa.UniqueConstraint("key"),)
| Configuration |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_escapes08.py | {
"start": 315,
"end": 1008
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("escapes08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file. Check encoding of url strings."""
workbook = Workbook(self.got_filename)
# Turn off default URL format for testing.
workbook.default_url_format = None
worksheet = workbook.add_worksheet()
worksheet.write_url(
"A1", "http://example.com/%5b0%5d", None, "http://example.com/[0]"
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 95443,
"end": 95692
} | class ____:
xlPivotLineBlank = 3 # from enum XlPivotLineType
xlPivotLineGrandTotal = 2 # from enum XlPivotLineType
xlPivotLineRegular = 0 # from enum XlPivotLineType
xlPivotLineSubtotal = 1 # from enum XlPivotLineType
| PivotLineType |
python | spyder-ide__spyder | spyder/widgets/emptymessage.py | {
"start": 764,
"end": 11593
} | class ____(QFrame, SvgToScaledPixmap, SpyderFontsMixin):
"""Widget to show a friendly message when another one is empty."""
def __init__(
self,
parent,
icon_filename: str | None = None,
text: str | None = None,
description: str | None = None,
top_stretch: int = 1,
middle_stretch: int = 1,
bottom_stretch: int = 0,
spinner: bool = False,
adjust_on_resize: bool = False,
highlight_on_focus_in: bool = True,
):
super().__init__(parent)
# Attributes
self._description = description
self._adjust_on_resize = adjust_on_resize
self._highlight_on_focus_in = highlight_on_focus_in
self._is_shown = False
self._spin = None
self._min_height = None
self._is_visible = False
# This is public so it can be overridden in subclasses
self.css = qstylizer.style.StyleSheet()
# This is necessary to make Qt reduce the size of all widgets on
# vertical resizes
if self._adjust_on_resize:
self.setMinimumHeight(150)
interface_font_size = self.get_font(
SpyderFontType.Interface).pointSize()
# Image (icon)
image_label_qss = qstylizer.style.StyleSheet()
image_label_qss.QLabel.setValues(border="0px")
self._image_label = None
if icon_filename:
self._image_label = QLabel(self)
self._image_label.setPixmap(
self.svg_to_scaled_pixmap(icon_filename, rescale=0.8)
)
self._image_label.setAlignment(Qt.AlignCenter)
self._image_label.setStyleSheet(image_label_qss.toString())
# Main text
if text is not None:
text_label = QLabel(text, parent=self)
text_label.setAlignment(Qt.AlignCenter)
text_label.setWordWrap(True)
text_label_qss = qstylizer.style.StyleSheet()
text_label_qss.QLabel.setValues(
fontSize=f"{interface_font_size + 5}pt", border="0px"
)
text_label.setStyleSheet(text_label_qss.toString())
# Description text
self._description_label = None
if self._description is not None:
self._description_label = QLabel(self._description, parent=self)
self._description_label.setAlignment(Qt.AlignCenter)
self._description_label.setWordWrap(True)
self._description_label.setScaledContents(True)
description_label_qss = qstylizer.style.StyleSheet()
description_label_qss.QLabel.setValues(
fontSize=f"{interface_font_size}pt",
backgroundColor=SpyderPalette.COLOR_OCCURRENCE_3,
border="0px",
padding="20px",
)
self._description_label.setStyleSheet(
description_label_qss.toString()
)
# Setup layout
pane_empty_layout = QVBoxLayout()
# Add the top stretch
pane_empty_layout.addStretch(top_stretch)
# Add the image_label (icon)
if icon_filename is not None:
pane_empty_layout.addWidget(self._image_label)
# Display spinner if requested
if spinner:
spin_widget = qta.IconWidget()
self._spin = qta.Spin(spin_widget, interval=3, autostart=False)
spin_icon = qta.icon(
"mdi.loading",
color=ima.MAIN_FG_COLOR,
animation=self._spin
)
spin_widget.setIconSize(QSize(32, 32))
spin_widget.setIcon(spin_icon)
spin_widget.setStyleSheet(image_label_qss.toString())
spin_widget.setAlignment(Qt.AlignCenter)
pane_empty_layout.addWidget(spin_widget)
pane_empty_layout.addItem(QSpacerItem(20, 20))
# If text, display text and stretch
if text is not None:
pane_empty_layout.addWidget(text_label)
pane_empty_layout.addStretch(middle_stretch)
# If description, display description
if self._description is not None:
pane_empty_layout.addWidget(self._description_label)
pane_empty_layout.addStretch(bottom_stretch)
pane_empty_layout.setContentsMargins(20, 20, 20, 20)
self.setLayout(pane_empty_layout)
# Setup style
self.setFocusPolicy(Qt.StrongFocus)
self._apply_stylesheet(False)
# ---- Public methods
# -------------------------------------------------------------------------
def setup(self, *args, **kwargs):
"""
This method is needed when using this widget to show a "no connected
console" message in plugins that inherit from ShellConnectMainWidget.
"""
pass
def set_visibility(self, visible):
"""Adjustments when the widget's visibility changes."""
self._is_visible = visible
if self._adjust_on_resize and self._image_label is not None:
if visible:
if (
self._min_height is not None
and self.height() >= self._min_height
):
self._image_label.show()
else:
self._image_label.hide()
# ---- Qt methods
# -------------------------------------------------------------------------
def showEvent(self, event):
"""Adjustments when the widget is shown."""
if not self._is_shown:
self._start_spinner()
self._is_shown = True
if self._adjust_on_resize and self._min_height is None:
self._min_height = self.minimumSizeHint().height()
super().showEvent(event)
def hideEvent(self, event):
"""Adjustments when the widget is hidden."""
self._stop_spinner()
self._is_shown = False
super().hideEvent(event)
def focusInEvent(self, event):
if self._highlight_on_focus_in:
self._apply_stylesheet(True)
super().focusOutEvent(event)
def focusOutEvent(self, event):
if self._highlight_on_focus_in:
self._apply_stylesheet(False)
super().focusOutEvent(event)
def resizeEvent(self, event):
super().resizeEvent(event)
if self._adjust_on_resize:
self._on_resize_event()
# ---- Private methods
# -------------------------------------------------------------------------
def _apply_stylesheet(self, focus):
if focus:
border_color = SpyderPalette.COLOR_ACCENT_3
else:
border_color = SpyderPalette.COLOR_BACKGROUND_4
self.css.QFrame.setValues(
border=f'1px solid {border_color}',
margin='0px',
padding='0px',
borderRadius=SpyderPalette.SIZE_BORDER_RADIUS
)
self.setStyleSheet(self.css.toString())
def _start_spinner(self):
"""
Start spinner when requested, in case the widget has one (it's stopped
by default).
"""
if self._spin is not None:
self._spin.start()
def _stop_spinner(self):
"""Stop spinner when requested, in case the widget has one."""
if self._spin is not None:
self._spin.stop()
@qdebounced(timeout=30)
def _on_resize_event(self):
"""Actions to take when widget is resized."""
# Hide/show image label when necessary
if self._image_label is not None:
if (
# This is necessary to prevent and error when the widget hasn't
# been made visible yet.
# Fixes spyder-ide/spyder#24280
self._min_height is None
# We need to do this validation because sometimes
# minimumSizeHint doesn't give the right min_height in
# showEvent (e.g. when adding an _ErroredMessageWidget to
# plugins that are not visible).
or self._min_height < self.minimumSizeHint().height()
):
self._min_height = self.minimumSizeHint().height()
if self.height() <= self._min_height:
self._image_label.hide()
else:
if self._is_visible:
self._image_label.show()
# Elide description when necessary
if self._description is not None:
metrics = QFontMetrics(self._description_label.font())
# All margins are the same, so we only take the left one
margin = self._description_label.contentsMargins().left()
# Height of a single line of text
text_line_height = metrics.height()
# Allow a max of two lines of text in the description
max_height = 2 * text_line_height + 2 * margin
# Compute the width and height of the description text according to
# max_height and the width of its label.
# Solution taken from https://forum.qt.io/post/313343
rect = metrics.boundingRect(
# Rectangle in which the text needs to fit
QRect(
0,
0,
self._description_label.width() - 2 * margin,
max_height,
),
self._description_label.alignment() | Qt.TextWordWrap,
self._description
)
# Elide text if it were to occupy more than two lines
if rect.height() > 2 * text_line_height:
# Replace description with elided text
elided_text = metrics.elidedText(
self._description, Qt.ElideRight, rect.width()
)
self._description_label.setText(elided_text)
# Show full description in tooltip
self._description_label.setToolTip(
'\n'.join(textwrap.wrap(self._description, 50))
)
# This prevents flickering when the widget's width is
# continuously reduced because Qt wraps the elided text
self._description_label.setMaximumHeight(
text_line_height + 2 * margin
)
else:
# Restore full description if there's enough space
if "…" in self._description_label.text():
# Restore description
self._description_label.setText(self._description)
# No tooltip is necessary in this case
self._description_label.setToolTip("")
# Restore max height
self._description_label.setMaximumHeight(max_height)
| EmptyMessageWidget |
python | Textualize__textual | docs/examples/widgets/header.py | {
"start": 80,
"end": 230
} | class ____(App):
def compose(self) -> ComposeResult:
yield Header()
if __name__ == "__main__":
app = HeaderApp()
app.run()
| HeaderApp |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 58974,
"end": 59910
} | class ____(ASTBase):
def __init__(self, value: ASTExpression) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTTemplateArgConstant):
return NotImplemented
return self.value == other.value
def __hash__(self) -> int:
return hash(self.value)
def _stringify(self, transform: StringifyTransform) -> str:
return transform(self.value)
def get_id(self, version: int) -> str:
if version == 1:
return str(self).replace(' ', '-')
if version == 2:
return 'X' + str(self) + 'E'
return 'X' + self.value.get_id(version) + 'E'
def describe_signature(
self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol
) -> None:
verify_description_mode(mode)
self.value.describe_signature(signode, mode, env, symbol)
| ASTTemplateArgConstant |
python | Pylons__pyramid | tests/test_traversal.py | {
"start": 30159,
"end": 32196
} | class ____(unittest.TestCase):
def _callFUT(self, resource, *elements):
from pyramid.traversal import resource_path_tuple
return resource_path_tuple(resource, *elements)
def test_it(self):
baz = DummyContext()
bar = DummyContext(baz)
foo = DummyContext(bar)
root = DummyContext(foo)
root.__parent__ = None
root.__name__ = None
foo.__parent__ = root
foo.__name__ = 'foo '
bar.__parent__ = foo
bar.__name__ = 'bar'
baz.__parent__ = bar
baz.__name__ = 'baz'
result = self._callFUT(baz, 'this/theotherthing', 'that')
self.assertEqual(
result, ('', 'foo ', 'bar', 'baz', 'this/theotherthing', 'that')
)
def test_root_default(self):
root = DummyContext()
root.__parent__ = None
root.__name__ = None
result = self._callFUT(root)
self.assertEqual(result, ('',))
def test_root_default_emptystring_name(self):
root = DummyContext()
root.__parent__ = None
root.__name__ = ''
other = DummyContext()
other.__parent__ = root
other.__name__ = 'other'
result = self._callFUT(other)
self.assertEqual(result, ('', 'other'))
def test_nonroot_default(self):
root = DummyContext()
root.__parent__ = None
root.__name__ = None
other = DummyContext()
other.__parent__ = root
other.__name__ = 'other'
result = self._callFUT(other)
self.assertEqual(result, ('', 'other'))
def test_path_with_None_itermediate_names(self):
root = DummyContext()
root.__parent__ = None
root.__name__ = None
other = DummyContext()
other.__parent__ = root
other.__name__ = None
other2 = DummyContext()
other2.__parent__ = other
other2.__name__ = 'other2'
result = self._callFUT(other2)
self.assertEqual(result, ('', '', 'other2'))
| ResourcePathTupleTests |
python | django-extensions__django-extensions | django_extensions/management/jobs.py | {
"start": 613,
"end": 661
} | class ____(BaseJob):
when = "weekly"
| WeeklyJob |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_reflection.py | {
"start": 12510,
"end": 13642
} | class ____(fixtures.TestBase):
__sparse_driver_backend__ = True
__requires__ = ("temp_table_reflection",)
@testing.fixture
def tablename(self):
return get_temp_table_name(
config, config.db, f"ident_tmp_{config.ident}"
)
@testing.requires.identity_columns
def test_reflect_identity(self, tablename, connection, metadata):
Table(
tablename,
metadata,
Column("id", Integer, Identity(), primary_key=True),
)
metadata.create_all(connection)
insp = inspect(connection)
eq_(insp.get_columns(tablename)[0]["identity"]["start"], 1)
@testing.requires.temp_table_comment_reflection
def test_reflect_comments(self, tablename, connection, metadata):
Table(
tablename,
metadata,
Column("id", Integer, primary_key=True),
Column("foobar", Integer, comment="some comment"),
)
metadata.create_all(connection)
insp = inspect(connection)
eq_(insp.get_columns(tablename)[1]["comment"], "some comment")
| TempTableElementsTest |
python | doocs__leetcode | solution/2300-2399/2380.Time Needed to Rearrange a Binary String/Solution2.py | {
"start": 0,
"end": 246
} | class ____:
def secondsToRemoveOccurrences(self, s: str) -> int:
ans = cnt = 0
for c in s:
if c == '0':
cnt += 1
elif cnt:
ans = max(ans + 1, cnt)
return ans
| Solution |
python | django__django | tests/postgres_tests/models.py | {
"start": 1358,
"end": 1455
} | class ____(PostgreSQLModel):
field = ArrayField(models.CharField(max_length=10))
| CharArrayModel |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 27200,
"end": 27427
} | class ____(NamedTuple):
sharded_avals: Sequence[core.AbstractValue]
out_sharded_avals: Sequence[core.ShapedArray]
global_sharded_avals: Sequence[core.AbstractValue]
num_local_shards: int
num_global_shards: int
| ShardInfo |
python | pytorch__pytorch | test/fx/test_pass_infra.py | {
"start": 439,
"end": 1206
} | class ____(PassBase):
def call(self, gm) -> PassResult:
modified = False
for node in gm.graph.nodes:
if node.op == "call_function" and node.target == torch.add:
node.target = torch.mul
modified = True
return PassResult(gm, modified)
# Pass that is a callable and returns a PassResult
def replace_mul_with_div_pass(gm) -> PassResult:
modified = False
for node in gm.graph.nodes:
if node.op == "call_function" and node.target == torch.mul:
node.target = torch.div
modified = True
return PassResult(gm, modified)
# Pass that is a PassBase and does not return a PassResult
# Need to wrap with pass_result_wrapper or else it will fail
| ReplaceAddWithMulPass |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-sharepoint/source_microsoft_sharepoint/utils.py | {
"start": 653,
"end": 4378
} | class ____(RemoteFile):
download_url: str
created_at: datetime
def filter_http_urls(files, logger):
for file in files:
if file.download_url.startswith("http") and not file.download_url.startswith("https"): # ignore-https-check
logger.error(f"Cannot open file {file.uri}. The URL returned by SharePoint is not secure.")
else:
yield file
def execute_query_with_retry(obj, max_retries=5, initial_retry_after=5, max_retry_after=300, max_total_wait_time=600):
"""
Executes a query with retry logic on encountering specific HTTP errors.
This function attempts to execute `obj.execute_query()` method, applying exponential backoff
retry logic for HTTP status codes 429 (Too Many Requests) and 503 (Service Unavailable). It
respects the 'Retry-After' header from the response, if present.
Parameters:
obj (object): The object that has the `execute_query` method to be executed.
max_retries (int): Maximum number of retry attempts. Defaults to 5.
initial_retry_after (int): Initial waiting time (in seconds) before the first retry. Defaults to 5 seconds.
max_retry_after (int): Maximum waiting time (in seconds) between retries. Defaults to 300 seconds.
max_total_wait_time (int): Maximum total waiting time (in seconds) for all retries. Defaults to 600 seconds.
Raises:
AirbyteTracedException: If the maximum total wait time or the maximum number of retries is exceeded.
Returns:
The result of `obj.execute_query()` if successful within the retry constraints.
"""
retries = 0
start_time = datetime.now()
retry_after = initial_retry_after
while retries < max_retries:
try:
return obj.execute_query()
except Exception as ex:
if hasattr(ex, "response") and ex.response.status_code in (HTTPStatus.TOO_MANY_REQUESTS, HTTPStatus.SERVICE_UNAVAILABLE):
current_time = datetime.now()
elapsed_time = (current_time - start_time).total_seconds()
retry_after_header = ex.response.headers.get("Retry-After", None)
if retry_after_header:
retry_after = int(retry_after_header)
if elapsed_time + retry_after > max_total_wait_time:
message = (
f"Maximum total wait time of {max_total_wait_time} seconds exceeded for execute_query. "
f"The latest response status code is {ex.response.status_code}."
)
if retry_after_header:
message += f" Retry-After header: {retry_after_header}"
raise AirbyteTracedException(message, message, failure_type=FailureType.system_error)
time.sleep(retry_after)
retries += 1
retry_after = min(retry_after * 2, max_retry_after) # Double the wait time for next retry, up to a max limit
elif hasattr(ex, "response") and ex.response.status_code == HTTPStatus.NOT_FOUND:
error_message = f"Requested item/folder could not be found: url: {ex.response.url}"
LOGGER.warning(error_message)
raise FolderNotFoundException(error_message)
else:
# Re-raise exceptions that are not related to rate limits or service availability
raise AirbyteTracedException.from_exception(ex, message="Caught unexpected exception")
message = f"Maximum number of retries of {max_retries} exceeded for execute_query."
raise AirbyteTracedException(message, message, failure_type=FailureType.system_error)
| MicrosoftSharePointRemoteFile |
python | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 14588,
"end": 14695
} | class ____(hp.HasProps, hp.Local):
f0 = Int(default=3)
f1 = List(Int, default=[3, 4, 5])
| Some0HasProps |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC501_numpy.py | {
"start": 0,
"end": 3031
} | class ____(Exception):
...
# OK
def calculate_speed(distance: float, time: float) -> float:
"""
Calculate speed as distance divided by time.
Parameters
----------
distance : float
Distance traveled.
time : float
Time spent traveling.
Returns
-------
float
Speed as distance divided by time.
Raises
------
FasterThanLightError
If speed is greater than the speed of light.
"""
try:
return distance / time
except ZeroDivisionError as exc:
raise FasterThanLightError from exc
# DOC501
def calculate_speed(distance: float, time: float) -> float:
"""
Calculate speed as distance divided by time.
Parameters
----------
distance : float
Distance traveled.
time : float
Time spent traveling.
Returns
-------
float
Speed as distance divided by time.
"""
try:
return distance / time
except ZeroDivisionError as exc:
raise FasterThanLightError from exc
# DOC501
def calculate_speed(distance: float, time: float) -> float:
"""
Calculate speed as distance divided by time.
Parameters
----------
distance : float
Distance traveled.
time : float
Time spent traveling.
Returns
-------
float
Speed as distance divided by time.
"""
try:
return distance / time
except ZeroDivisionError as exc:
raise FasterThanLightError from exc
except:
raise ValueError
# DOC501
def calculate_speed(distance: float, time: float) -> float:
"""Calculate speed as distance divided by time.
ACalculate speed as distance divided by time.
Parameters
----------
distance : float
Distance traveled.
time : float
Time spent traveling.
Returns
-------
float
Speed as distance divided by time.
Raises
------
ZeroDivisionError
If attempting to divide by zero.
"""
try:
return distance / time
except ZeroDivisionError:
print("Oh no, why would you divide something by zero?")
raise
except TypeError:
print("Not a number? Shame on you!")
raise
# This is fine
def calculate_speed(distance: float, time: float) -> float:
"""
Calculate speed as distance divided by time.
Parameters
----------
distance : float
Distance traveled.
time : float
Time spent traveling.
Returns
-------
float
Speed as distance divided by time.
"""
try:
return distance / time
except Exception as e:
print(f"Oh no, we encountered {e}")
raise
def foo():
"""Foo.
Returns
-------
int
42
"""
if True:
raise TypeError # DOC501
else:
raise TypeError # no DOC501 here because we already emitted a diagnostic for the earlier `raise TypeError`
raise ValueError # DOC501
return 42
| FasterThanLightError |
python | ray-project__ray | python/ray/train/v2/_internal/execution/train_fn_utils.py | {
"start": 835,
"end": 5488
} | class ____(ABC):
"""Utility class providing an abstraction layer between user-facing APIs
and :class:`~ray.train.v2.api.context.TrainContext`.
It should be set before the users' training function is called.
This class can be patched if new user APIs behaviors is wanted.
"""
@abstractmethod
def report(
self,
metrics: Dict[str, Any],
checkpoint: Optional["Checkpoint"] = None,
checkpoint_dir_name: Optional[str] = None,
checkpoint_upload_mode: CheckpointUploadMode = CheckpointUploadMode.SYNC,
delete_local_checkpoint_after_upload: Optional[bool] = None,
checkpoint_upload_fn: Optional[
Callable[["Checkpoint", str], "Checkpoint"]
] = None,
validate_fn: Optional[Callable[["Checkpoint", Optional[Dict]], Dict]] = None,
validate_config: Optional[Dict] = None,
) -> None:
"""Upload checkpoint to remote storage and put a training result on the result queue.
Args:
metrics: The metrics to report.
checkpoint: The checkpoint to report.
checkpoint_dir_name: The name of the checkpoint dir
in this iteration. Note: If not set, the checkpoint will
be stored in the default storage path. If set, make sure
this value is unique for each iteration.
checkpoint_upload_mode: The manner in which we want to upload the checkpoint.
Defaults to uploading the checkpoint synchronously.
This works when no checkpoint is provided but is not useful in that case.
delete_local_checkpoint_after_upload: Whether to delete the checkpoint after it is uploaded.
checkpoint_upload_fn: A user defined function that will be called with the
checkpoint to upload it. If not provided, defaults to using the `pyarrow.fs.copy_files`
utility for copying to the destination `storage_path`.
validate_fn: If provided, Ray Train will validate the checkpoint using
this function.
validate_config: Configuration passed to the validate_fn. Can contain info
like the validation dataset.
"""
pass
@abstractmethod
def get_checkpoint(self) -> Optional["Checkpoint"]:
"""Get the latest checkpoint to resume training from.
Returns:
The latest checkpoint if available, None otherwise.
"""
pass
@abstractmethod
def get_all_reported_checkpoints(
self,
consistency_mode: CheckpointConsistencyMode = CheckpointConsistencyMode.VALIDATED,
) -> List["ReportedCheckpoint"]:
"""Get all the checkpoints reported by the workers.
Args:
consistency_mode: Read semantics for checkpoint retrieval. Defaults to VALIDATED.
Returns:
A list of ReportedCheckpoint objects that represent the checkpoints and
corresponding metrics reported by the workers.
"""
pass
@abstractmethod
def get_dataset_shard(self, dataset_info: DatasetShardMetadata) -> DataIterator:
"""Get the dataset shard for this training process.
Args:
dataset_info: The metadata of the dataset to get the shard for.
Returns:
The DataIterator shard for this worker.
"""
pass
@abstractmethod
def get_context(self) -> ExternalTrainContext:
"""Get the TrainContext for this training process.
The specific type of TrainContext returned depends on the implementation of TrainFnUtils.
Returns:
The train context for this training process.
"""
pass
@abstractmethod
def is_distributed(self) -> bool:
pass
@abstractmethod
def barrier(self) -> None:
"""Create a barrier across all workers.
All workers must call this method before the training function can continue.
This method is used by the public API function :func:`ray.train.collective.barrier`.
Users should typically call ``ray.train.collective.barrier()`` instead of calling this method directly.
"""
pass
@abstractmethod
def broadcast_from_rank_zero(self, data: Any) -> Any:
"""Broadcast data from the rank 0 worker to all other workers.
This method is used by the public API function :func:`ray.train.collective.broadcast_from_rank_zero`.
Users should typically call ``ray.train.collective.broadcast_from_rank_zero()`` instead of calling this method directly.
"""
pass
| TrainFnUtils |
python | wandb__wandb | wandb/vendor/pygments/lexers/configs.py | {
"start": 20636,
"end": 23071
} | class ____(RegexLexer):
"""
Lexer for `terraformi .tf files <https://www.terraform.io/>`_.
.. versionadded:: 2.1
"""
name = 'Terraform'
aliases = ['terraform', 'tf']
filenames = ['*.tf']
mimetypes = ['application/x-tf', 'application/x-terraform']
tokens = {
'root': [
include('string'),
include('punctuation'),
include('curly'),
include('basic'),
include('whitespace'),
(r'[0-9]+', Number),
],
'basic': [
(words(('true', 'false'), prefix=r'\b', suffix=r'\b'), Keyword.Type),
(r'\s*/\*', Comment.Multiline, 'comment'),
(r'\s*#.*\n', Comment.Single),
(r'(.*?)(\s*)(=)', bygroups(Name.Attribute, Text, Operator)),
(words(('variable', 'resource', 'provider', 'provisioner', 'module'),
prefix=r'\b', suffix=r'\b'), Keyword.Reserved, 'function'),
(words(('ingress', 'egress', 'listener', 'default', 'connection'),
prefix=r'\b', suffix=r'\b'), Keyword.Declaration),
('\$\{', String.Interpol, 'var_builtin'),
],
'function': [
(r'(\s+)(".*")(\s+)', bygroups(Text, String, Text)),
include('punctuation'),
include('curly'),
],
'var_builtin': [
(r'\$\{', String.Interpol, '#push'),
(words(('concat', 'file', 'join', 'lookup', 'element'),
prefix=r'\b', suffix=r'\b'), Name.Builtin),
include('string'),
include('punctuation'),
(r'\s+', Text),
(r'\}', String.Interpol, '#pop'),
],
'string': [
(r'(".*")', bygroups(String.Double)),
],
'punctuation': [
(r'[\[\](),.]', Punctuation),
],
# Keep this seperate from punctuation - we sometimes want to use different
# Tokens for { }
'curly': [
(r'\{', Text.Punctuation),
(r'\}', Text.Punctuation),
],
'comment': [
(r'[^*/]', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline)
],
'whitespace': [
(r'\n', Text),
(r'\s+', Text),
(r'\\\n', Text),
],
}
| TerraformLexer |
python | pytorch__pytorch | torch/_export/utils.py | {
"start": 58257,
"end": 58835
} | class ____(torch.nn.Module):
def __init__(self, method):
super().__init__()
# share state of method's self module
_sync_state(method.__self__, self)
# redirect forward to method
self.forward = method
def wrap_method(method):
"""
Wrap a method as a module so that it can be exported.
The wrapped module's forward points to the method, and
the method's original module state is shared.
"""
assert ismethod(
method,
), f"Expected {method} to be a method"
return _WrappedMethod(method)
| _WrappedMethod |
python | pydantic__pydantic | pydantic/_internal/_decorators.py | {
"start": 2120,
"end": 3050
} | class ____:
"""A container for data from `@field_validator` so that we can access it
while building the pydantic-core schema.
Attributes:
decorator_repr: A class variable representing the decorator string, '@field_validator'.
fields: A tuple of field names the validator should be called on.
mode: The proposed validator mode.
check_fields: Whether to check that the fields actually exist on the model.
json_schema_input_type: The input type of the function. This is only used to generate
the appropriate JSON Schema (in validation mode) and can only specified
when `mode` is either `'before'`, `'plain'` or `'wrap'`.
"""
decorator_repr: ClassVar[str] = '@field_validator'
fields: tuple[str, ...]
mode: FieldValidatorModes
check_fields: bool | None
json_schema_input_type: Any
@dataclass(**slots_true)
| FieldValidatorDecoratorInfo |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/AirbyteInternal.py | {
"start": 221,
"end": 643
} | class ____(BaseModel):
class Config:
extra = Extra.allow
sl: Optional[Literal[0, 100, 200, 300]] = None
ql: Optional[Literal[0, 100, 200, 300, 400, 500, 600]] = None
isEnterprise: Optional[bool] = False
requireVersionIncrementsInPullRequests: Optional[bool] = Field(
True,
description="When false, version increment checks will be skipped for this connector",
)
| AirbyteInternal |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 2443,
"end": 2845
} | class ____(ModelOutput):
r"""
logits (`torch.FloatTensor` of shape `(batch_size, num_labels)`):
Output of the basic decoder.
"""
logits: Optional[torch.FloatTensor] = None
cross_attentions: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for Perceiver's masked language model outputs.
"""
)
| PerceiverDecoderOutput |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/datasets.py | {
"start": 6677,
"end": 7179
} | class ____(Dataset):
def __init__(self, dataset_len=300, sequence_len=100):
self.dataset_len = dataset_len
self.sequence_len = sequence_len
self.input_seq = torch.randn(dataset_len, sequence_len, 10)
top, bottom = self.input_seq.chunk(2, -1)
self.output_seq = top + bottom.roll(shifts=1, dims=-1)
def __len__(self):
return self.dataset_len
def __getitem__(self, item):
return self.input_seq[item], self.output_seq[item]
| AverageDataset |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 993117,
"end": 994503
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"is_one_time_payment",
"is_sponsor_opted_into_email",
"maintainer",
"privacy_level",
"sponsor",
"sponsor_entity",
"sponsorable",
"tier",
"tier_selected_at",
)
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="createdAt"
)
is_one_time_payment = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="isOneTimePayment"
)
is_sponsor_opted_into_email = sgqlc.types.Field(
Boolean, graphql_name="isSponsorOptedIntoEmail"
)
maintainer = sgqlc.types.Field(
sgqlc.types.non_null("User"), graphql_name="maintainer"
)
privacy_level = sgqlc.types.Field(
sgqlc.types.non_null(SponsorshipPrivacy), graphql_name="privacyLevel"
)
sponsor = sgqlc.types.Field("User", graphql_name="sponsor")
sponsor_entity = sgqlc.types.Field("Sponsor", graphql_name="sponsorEntity")
sponsorable = sgqlc.types.Field(
sgqlc.types.non_null(Sponsorable), graphql_name="sponsorable"
)
tier = sgqlc.types.Field(SponsorsTier, graphql_name="tier")
tier_selected_at = sgqlc.types.Field(DateTime, graphql_name="tierSelectedAt")
| Sponsorship |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-make-array-equalindromic.py | {
"start": 2001,
"end": 2671
} | class ____(object):
def minimumCost(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def nearest_palindromic(x):
n = str(x)
l = len(n)
result = {10**l+1, 10**(l-1)-1}
prefix = int(n[:(l+1)/2])
for i in map(str, (prefix-1, prefix, prefix+1)):
result.add(int(i+[i, i[:-1]][l%2][::-1]))
return result
nums.sort()
median = nums[len(nums)//2]
if len(nums)%2 == 0:
median = (median+nums[len(nums)//2-1])//2
return min(sum(abs(x-p) for x in nums) for p in nearest_palindromic(median))
| Solution2 |
python | huggingface__transformers | src/transformers/models/kosmos2/modeling_kosmos2.py | {
"start": 3064,
"end": 5076
} | class ____(ModelOutput):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
`config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
input) to speed up sequential decoding.
image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
the weighted average in the self-attention heads.
vision_model_output (`BaseModelOutputWithPooling`, *optional*):
The output of the [`Kosmos2VisionModel`].
"""
last_hidden_state: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
image_embeds: Optional[torch.FloatTensor] = None
projection_attentions: Optional[tuple[torch.FloatTensor]] = None
vision_model_output: BaseModelOutputWithPooling = None
def to_tuple(self) -> tuple[Any]:
return tuple(
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
for k in self.keys()
)
@dataclass
@auto_docstring(
custom_intro="""
Model output class for `Kosmos2ForConditionalGeneration`.
"""
)
| Kosmos2ModelOutput |
python | pytorch__pytorch | test/profiler/test_record_function.py | {
"start": 1070,
"end": 8324
} | class ____(TestCase):
def _record_function_with_param(self):
u = torch.randn(3, 4, 5, requires_grad=True)
with _profile(
with_stack=True, use_kineto=kineto_available(), record_shapes=True
) as prof:
with record_function("## TEST 1 ##", "1, 2, 3"):
rf_handle = _record_function_with_args_enter(
"## TEST 2 ##", 1, False, 2.5, [u, u], "hello", u
)
_record_function_with_args_exit(rf_handle)
with record_function("## TEST 3 ##"):
rf_handle = _record_function_with_args_enter("## TEST 4 ##")
_record_function_with_args_exit(rf_handle)
return prof
def test_record_function(self):
prof_result = self._record_function_with_param()
found_test_1 = False
found_test_2 = False
found_test_3 = False
found_test_4 = False
for e in prof_result.function_events:
if "## TEST 1 ##" == e.name:
found_test_1 = True
self.assertTrue(e.input_shapes == [[]])
elif "## TEST 2 ##" == e.name:
found_test_2 = True
self.assertTrue(e.input_shapes == [[], [], [], [], [], [3, 4, 5]])
elif "## TEST 3 ##" == e.name:
found_test_3 = True
self.assertTrue(e.input_shapes == [])
elif "## TEST 4 ##" == e.name:
found_test_4 = True
self.assertTrue(e.input_shapes == [])
self.assertTrue(found_test_1)
self.assertTrue(found_test_2)
self.assertTrue(found_test_3)
self.assertTrue(found_test_4)
def test_datapipe_with_record_function(self):
with _profile(
with_stack=True, use_kineto=kineto_available(), record_shapes=True
) as prof:
input_dp1 = dp.iter.IterableWrapper(range(4))
input_dp2 = dp.iter.IterableWrapper(range(4, 8))
input_dp3 = dp.iter.IterableWrapper(range(8, 12))
output_dp = input_dp1.mux(input_dp2, input_dp3)
output = list(output_dp)
has_iter = False
has_mux = False
for e in prof.function_events:
if has_iter and has_mux:
break
if not has_iter and "IterableWrapper" in e.name:
has_iter = True
if not has_mux and "Multiplexer" in e.name:
has_mux = True
self.assertTrue(has_iter)
self.assertTrue(has_mux)
def test_datapipe_delegation_with_profiler(self):
class IDPIterator(torch.utils.data.IterDataPipe):
def __init__(self) -> None:
self.data = list(range(10))
self._idx = 0
def __iter__(self):
return self
def __next__(self):
if self._idx >= 10:
self._idx = 0
raise StopIteration
self._idx += 1
return self.data[self._idx - 1]
def get_value(self, idx):
return self.data[idx]
dp1 = IDPIterator() # The object itself is an iterator
self.assertEqual(5, dp1.get_value(5))
it_dp1 = iter(dp1) # This creates the 1st iterator
self.assertEqual(5, it_dp1.get_value(5)) # type: ignore[attr-defined]
self.assertEqual(list(range(10)), list(it_dp1))
class IDPDelegator(torch.utils.data.IterDataPipe):
def __init__(self, datapipe):
self.datapipe = datapipe
def __iter__(self):
return iter(self.datapipe)
dp2 = IDPDelegator(dp1)
it_dp2 = iter(dp2)
self.assertEqual(5, it_dp2.get_value(5))
self.assertEqual(list(range(10)), list(it_dp2))
def test_datapipe_with_record_function_fork(self):
with _profile(
with_stack=True, use_kineto=kineto_available(), record_shapes=True
) as prof:
input_dp = dp.iter.IterableWrapper(range(10))
dp1, dp2, dp3 = input_dp.fork(num_instances=3)
output1 = list(dp1)
has_iter = False
has_child = False
for e in prof.function_events:
if has_iter and has_child:
break
if not has_iter and "IterableWrapper" in e.name:
has_iter = True
if not has_child and "_ChildDataPipe" in e.name:
has_child = True
self.assertTrue(has_iter)
self.assertTrue(has_child)
def test_python_dispatch_mode_record_function(self):
from torch.utils._python_dispatch import TorchDispatchMode
class TestDispatchMode(TorchDispatchMode):
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
return func(*args, **kwargs)
with _profile() as prof:
with enable_python_dispatcher():
with TestDispatchMode():
x = torch.randn(3, 4)
y = torch.sin(x)
found_python_dispatch_mode = False
for e in prof.function_events:
if e.name == "PythonDispatchMode":
found_python_dispatch_mode = True
break
self.assertTrue(
found_python_dispatch_mode,
"PythonDispatchMode record function not found in profiler events",
)
def test_python_subclass_record_function(self):
class TestTensorSubclass(torch.Tensor):
@staticmethod
def __new__(cls, elem):
r = torch.Tensor._make_wrapper_subclass(
cls,
elem.size(),
dtype=elem.dtype,
device=elem.device,
requires_grad=elem.requires_grad,
)
r.elem = elem
return r
@classmethod
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
def unwrap(x):
return x.elem if isinstance(x, TestTensorSubclass) else x
def wrap(x):
return TestTensorSubclass(x) if isinstance(x, torch.Tensor) else x
unwrapped_args = tuple(unwrap(arg) for arg in args)
unwrapped_kwargs = {k: unwrap(v) for k, v in kwargs.items()}
result = func(*unwrapped_args, **unwrapped_kwargs)
if isinstance(result, torch.Tensor):
return TestTensorSubclass(result)
return result
with _profile() as prof:
with enable_python_dispatcher():
x = TestTensorSubclass(torch.randn(3, 4))
y = torch.sin(x)
found_python_subclass = False
for e in prof.function_events:
if e.name == "PythonSubclass":
found_python_subclass = True
break
self.assertTrue(
found_python_subclass,
"PythonSubclass record function not found in profiler events",
)
if __name__ == "__main__":
run_tests()
| TestRecordFunction |
python | cython__cython | tests/run/py3k_super.py | {
"start": 352,
"end": 2105
} | class ____(A):
"""
>>> obj = B()
>>> obj.method()
1
>>> B.class_method()
2
>>> B.static_method(obj)
3
>>> list(obj.generator_test())
[1, 2, 3]
>>> obj.star_method()
1
>>> obj.starstar_method()
1
>>> obj.starstarstar_method()
1
>>> obj.star_class_method()
2
>>> obj.starstar_class_method()
2
>>> obj.starstarstar_class_method()
2
>>> obj.star_static_method(obj)
3
>>> obj.starstar_static_method(obj)
3
>>> obj.starstarstar_static_method(obj)
3
"""
def method(self):
return super().method()
@classmethod
def class_method(cls):
return super().class_method()
@staticmethod
def static_method(instance):
return super().static_method()
def generator_test(self):
for i in super().generator_test():
yield i
def star_method(self, *args):
return super().method()
def starstar_method(self, **kwargs):
return super().method()
def starstarstar_method(cls, *args, **kwargs):
return super().method()
@classmethod
def star_class_method(cls, *args):
return super().class_method()
@classmethod
def starstar_class_method(cls, **kwargs):
return super().class_method()
@classmethod
def starstarstar_class_method(cls, *args, **kwargs):
return super().class_method()
@staticmethod
def star_static_method(instance, *args):
return super().static_method()
@staticmethod
def starstar_static_method(instance, **kwargs):
return super().static_method()
@staticmethod
def starstarstar_static_method(instance, *args, **kwargs):
return super().static_method()
| B |
python | walkccc__LeetCode | solutions/2672. Number of Adjacent Elements With the Same Color/2672.py | {
"start": 0,
"end": 544
} | class ____:
def colorTheArray(self, n: int, queries: list[list[int]]) -> list[int]:
ans = []
arr = [0] * n
sameColors = 0
for i, color in queries:
if i + 1 < n:
if arr[i + 1] > 0 and arr[i + 1] == arr[i]:
sameColors -= 1
if arr[i + 1] == color:
sameColors += 1
if i > 0:
if arr[i - 1] > 0 and arr[i - 1] == arr[i]:
sameColors -= 1
if arr[i - 1] == color:
sameColors += 1
arr[i] = color
ans.append(sameColors)
return ans
| Solution |
python | celery__celery | celery/utils/threads.py | {
"start": 1028,
"end": 3213
} | class ____(threading.Thread):
"""Background service thread."""
def __init__(self, name=None, **kwargs):
super().__init__()
self.__is_shutdown = threading.Event()
self.__is_stopped = threading.Event()
self.daemon = True
self.name = name or self.__class__.__name__
def body(self):
raise NotImplementedError()
def on_crash(self, msg, *fmt, **kwargs):
print(msg.format(*fmt), file=sys.stderr)
traceback.print_exc(None, sys.stderr)
def run(self):
body = self.body
shutdown_set = self.__is_shutdown.is_set
try:
while not shutdown_set():
try:
body()
except Exception as exc: # pylint: disable=broad-except
try:
self.on_crash('{0!r} crashed: {1!r}', self.name, exc)
self._set_stopped()
finally:
sys.stderr.flush()
os._exit(1) # exiting by normal means won't work
finally:
self._set_stopped()
def _set_stopped(self):
try:
self.__is_stopped.set()
except TypeError: # pragma: no cover
# we lost the race at interpreter shutdown,
# so gc collected built-in modules.
pass
def stop(self):
"""Graceful shutdown."""
self.__is_shutdown.set()
self.__is_stopped.wait()
if self.is_alive():
self.join(THREAD_TIMEOUT_MAX)
def release_local(local):
"""Release the contents of the local for the current context.
This makes it possible to use locals without a manager.
With this function one can release :class:`Local` objects as well as
:class:`StackLocal` objects. However it's not possible to
release data held by proxies that way, one always has to retain
a reference to the underlying local object in order to be able
to release it.
Example:
>>> loc = Local()
>>> loc.foo = 42
>>> release_local(loc)
>>> hasattr(loc, 'foo')
False
"""
local.__release_local__()
| bgThread |
python | sphinx-doc__sphinx | sphinx/builders/gettext.py | {
"start": 4290,
"end": 4573
} | class ____(Tags):
"""Dummy tags module for I18nBuilder.
To ensure that all text inside ``only`` nodes is translated,
this class always returns ``True`` regardless the defined tags.
"""
def eval_condition(self, condition: Any) -> bool:
return True
| I18nTags |
python | openai__openai-python | tests/api_resources/audio/test_translations.py | {
"start": 393,
"end": 2283
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_create(self, client: OpenAI) -> None:
translation = client.audio.translations.create(
file=b"raw file contents",
model="whisper-1",
)
assert_matches_type(TranslationCreateResponse, translation, path=["response"])
@parametrize
def test_method_create_with_all_params(self, client: OpenAI) -> None:
translation = client.audio.translations.create(
file=b"raw file contents",
model="whisper-1",
prompt="prompt",
response_format="json",
temperature=0,
)
assert_matches_type(TranslationCreateResponse, translation, path=["response"])
@parametrize
def test_raw_response_create(self, client: OpenAI) -> None:
response = client.audio.translations.with_raw_response.create(
file=b"raw file contents",
model="whisper-1",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
translation = response.parse()
assert_matches_type(TranslationCreateResponse, translation, path=["response"])
@parametrize
def test_streaming_response_create(self, client: OpenAI) -> None:
with client.audio.translations.with_streaming_response.create(
file=b"raw file contents",
model="whisper-1",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
translation = response.parse()
assert_matches_type(TranslationCreateResponse, translation, path=["response"])
assert cast(Any, response.is_closed) is True
| TestTranslations |
python | pandas-dev__pandas | pandas/core/interchange/dataframe_protocol.py | {
"start": 2989,
"end": 4678
} | class ____(ABC):
"""
Data in the buffer is guaranteed to be contiguous in memory.
Note that there is no dtype attribute present, a buffer can be thought of
as simply a block of memory. However, if the column that the buffer is
attached to has a dtype that's supported by DLPack and ``__dlpack__`` is
implemented, then that dtype information will be contained in the return
value from ``__dlpack__``.
This distinction is useful to support both data exchange via DLPack on a
buffer and (b) dtypes like variable-length strings which do not have a
fixed number of bytes per element.
"""
@property
@abstractmethod
def bufsize(self) -> int:
"""
Buffer size in bytes.
"""
@property
@abstractmethod
def ptr(self) -> int:
"""
Pointer to start of the buffer as an integer.
"""
@abstractmethod
def __dlpack__(self):
"""
Produce DLPack capsule (see array API standard).
Raises:
- TypeError : if the buffer contains unsupported dtypes.
- NotImplementedError : if DLPack support is not implemented
Useful to have to connect to array libraries. Support optional because
it's not completely trivial to implement for a Python-only library.
"""
raise NotImplementedError("__dlpack__")
@abstractmethod
def __dlpack_device__(self) -> tuple[DlpackDeviceType, int | None]:
"""
Device type and device ID for where the data in the buffer resides.
Uses device type codes matching DLPack.
Note: must be implemented even if ``__dlpack__`` is not.
"""
| Buffer |
python | google__pytype | pytype/overlays/named_tuple.py | {
"start": 2629,
"end": 2848
} | class ____:
"""Args for both collections.namedtuple and typing.NamedTuple."""
name: str
field_names: list[str]
field_types: list[Any] | None = None
defaults: list[Any] | None = None
rename: bool = False
| _Args |
python | huggingface__transformers | tests/models/mobilevit/test_image_processing_mobilevit.py | {
"start": 1219,
"end": 3535
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_center_crop=True,
crop_size=None,
do_flip_channel_order=True,
do_reduce_labels=False,
):
size = size if size is not None else {"shortest_edge": 20}
crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18}
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.do_resize = do_resize
self.size = size
self.do_center_crop = do_center_crop
self.crop_size = crop_size
self.do_flip_channel_order = do_flip_channel_order
self.do_reduce_labels = do_reduce_labels
def prepare_image_processor_dict(self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_flip_channel_order": self.do_flip_channel_order,
"do_reduce_labels": self.do_reduce_labels,
}
def expected_output_image_shape(self, images):
return self.num_channels, self.crop_size["height"], self.crop_size["width"]
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
return prepare_image_inputs(
batch_size=self.batch_size,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
numpify=numpify,
torchify=torchify,
)
def prepare_semantic_single_inputs():
ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
example = ds[0]
return example["image"], example["map"]
def prepare_semantic_batch_inputs():
ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
return list(ds["image"][:2]), list(ds["map"][:2])
@require_torch
@require_vision
| MobileViTImageProcessingTester |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/asm.py | {
"start": 703,
"end": 1777
} | class ____(Task.Task):
color = 'BLUE'
run_str = '${AS} ${ASFLAGS} ${ASMPATH_ST:INCPATHS} ${DEFINES_ST:DEFINES} ${AS_SRC_F}${SRC} ${AS_TGT_F}${TGT}'
def scan(self):
if self.env.ASM_NAME == 'gas':
return c_preproc.scan(self)
Logs.warn('There is no dependency scanner for Nasm!')
return [[], []]
elif self.env.ASM_NAME == 'nasm':
Logs.warn('The Nasm dependency scanner is incomplete!')
try:
incn = self.generator.includes_nodes
except AttributeError:
raise Errors.WafError('%r is missing the "asm" feature' % self.generator)
if c_preproc.go_absolute:
nodepaths = incn
else:
nodepaths = [x for x in incn if x.is_child_of(x.ctx.srcnode) or x.is_child_of(x.ctx.bldnode)]
tmp = asm_parser(nodepaths)
tmp.start(self.inputs[0], self.env)
return (tmp.nodes, tmp.names)
@extension('.s', '.S', '.asm', '.ASM', '.spp', '.SPP')
def asm_hook(self, node):
return self.create_compiled_task('asm', node)
| asm |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 14873,
"end": 14996
} | class ____(PydanticTypeError):
code = 'enum_instance'
msg_template = '{value} is not a valid Enum instance'
| EnumError |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py | {
"start": 5410,
"end": 6277
} | class ____(Model):
"""Permission pair comprised of an Action + Resource combo."""
__tablename__ = "ab_permission_view"
__table_args__ = (UniqueConstraint("permission_id", "view_menu_id"),)
id: Mapped[int] = mapped_column(
Integer,
Sequence("ab_permission_view_id_seq", start=1, increment=1, minvalue=1, cycle=False),
primary_key=True,
)
action_id: Mapped[int] = mapped_column("permission_id", Integer, ForeignKey("ab_permission.id"))
action: Mapped[Action] = relationship("Action", lazy="joined", uselist=False)
resource_id: Mapped[int] = mapped_column("view_menu_id", Integer, ForeignKey("ab_view_menu.id"))
resource: Mapped[Resource] = relationship("Resource", lazy="joined", uselist=False)
def __repr__(self):
return str(self.action).replace("_", " ") + f" on {str(self.resource)}"
| Permission |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 649076,
"end": 649488
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("EnterpriseRepositoryInfo", graphql_name="node")
"""The item at the end of the edge."""
| EnterpriseRepositoryInfoEdge |
python | hyperopt__hyperopt | hyperopt/mongoexp.py | {
"start": 39822,
"end": 49353
} | class ____(Ctrl):
"""
Attributes:
current_trial - current job document
jobs - MongoJobs object in which current_trial resides
read_only - True means don't change the db
"""
def __init__(self, trials, current_trial, read_only):
self.trials = trials
self.current_trial = current_trial
self.read_only = read_only
def debug(self, *args, **kwargs):
# XXX: This is supposed to log to db
return logger.debug(*args, **kwargs)
def info(self, *args, **kwargs):
# XXX: This is supposed to log to db
return logger.info(*args, **kwargs)
def warn(self, *args, **kwargs):
# XXX: This is supposed to log to db
return logger.warn(*args, **kwargs)
def error(self, *args, **kwargs):
# XXX: This is supposed to log to db
return logger.error(*args, **kwargs)
def checkpoint(self, result=None):
if not self.read_only:
handle = self.trials.handle
handle.refresh(self.current_trial)
if result is not None:
return handle.update(self.current_trial, dict(result=result))
@property
def attachments(self):
"""
Support syntax for load: self.attachments[name]
Support syntax for store: self.attachments[name] = value
"""
return self.trials.trial_attachments(trial=self.current_trial)
@property
def set_attachment(self):
# XXX: Is there a better deprecation error?
raise RuntimeError(
"set_attachment deprecated. Use `self.attachments[name] = value`"
)
def exec_import(cmd_module, cmd):
worker_fn = None
exec(f"import {cmd_module}; worker_fn = {cmd}")
return worker_fn
def as_mongo_str(s):
if s.startswith("mongo://"):
return s
return "mongo://%s" % s
def number_of_jobs_in_db(options):
mj = MongoJobs.new_from_connection_str(as_mongo_str(options.mongo) + "/jobs")
final_num = mj.jobs.find().count()
return final_num
def main_worker_helper(options, args):
N = int(options.max_jobs)
if options.last_job_timeout is not None:
end_time = time.time() + float(options.last_job_timeout)
else:
end_time = None
def sighandler_shutdown(signum, frame):
logger.info("Caught signal %i, shutting down." % signum)
raise Shutdown(signum)
def sighandler_wait_quit(signum, frame):
logger.info("Caught signal %i, shutting down." % signum)
raise WaitQuit(signum)
is_windows = os.name == "nt"
if not is_windows:
signal.signal(signal.SIGHUP, sighandler_shutdown)
signal.signal(signal.SIGUSR1, sighandler_wait_quit)
signal.signal(signal.SIGINT, sighandler_shutdown)
signal.signal(signal.SIGTERM, sighandler_shutdown)
if N > 1:
proc = None
cons_errs = 0
while N and cons_errs < int(options.max_consecutive_failures):
# exit due to time limit:
if end_time and time.time() > end_time:
logger.info("Exiting due to last_job_timeout")
return
# exit due to threshold on number of jobs:
if (
options.max_jobs_in_db is not None
and options.max_jobs_in_db != sys.maxsize
):
num_jobs_db = number_of_jobs_in_db(options)
if int(num_jobs_db) >= int(options.max_jobs_in_db):
logger.info(
"Exiting because there are "
+ str(num_jobs_db)
+ " jobs in the database, but the limit is "
+ str(options.max_jobs_in_db)
)
return
# try to run one MongoWorker
try:
if options.use_subprocesses:
# recursive Popen, dropping N from the argv
# By using another process to run this job
# we protect ourselves from memory leaks, bad cleanup
# and other annoying details.
# The tradeoff is that a large dataset must be reloaded once for
# each subprocess.
sub_argv = [
sys.argv[0],
"--poll-interval=%s" % options.poll_interval,
"--max-jobs=1",
"--mongo=%s" % options.mongo,
"--reserve-timeout=%s" % options.reserve_timeout,
]
if options.workdir is not None:
sub_argv.append("--workdir=%s" % options.workdir)
if options.exp_key is not None:
sub_argv.append("--exp-key=%s" % options.exp_key)
proc = subprocess.Popen(sub_argv)
retcode = proc.wait()
proc = None
else:
current_mongo_str = as_mongo_str(options.mongo)
# Remove this if not necessary:
if "/jobs" not in current_mongo_str:
current_mongo_str += "/jobs"
mj = MongoJobs.new_from_connection_str(current_mongo_str)
mworker = MongoWorker(
mj,
float(options.poll_interval),
workdir=options.workdir,
exp_key=options.exp_key,
)
mworker.run_one(reserve_timeout=float(options.reserve_timeout))
retcode = 0
except Shutdown:
# this is the normal way to stop the infinite loop (if originally N=-1)
if proc:
# proc.terminate() is only available as of 2.6
os.kill(
proc.pid, signal.CTRL_C_EVENT if is_windows else signal.SIGTERM
)
return proc.wait()
return 0
except WaitQuit:
# -- sending SIGUSR1 to a looping process will cause it to
# break out of the loop after the current subprocess finishes
# normally.
if proc:
return proc.wait()
return 0
if retcode != 0:
cons_errs += 1
else:
cons_errs = 0
N -= 1
logger.info(
"exiting with N=%i after %i consecutive exceptions" % (N, cons_errs)
)
elif N == 1:
# XXX: the name of the jobs collection is a parameter elsewhere,
# so '/jobs' should not be hard-coded here
mj = MongoJobs.new_from_connection_str(as_mongo_str(options.mongo) + "/jobs")
mworker = MongoWorker(
mj,
float(options.poll_interval),
workdir=options.workdir,
exp_key=options.exp_key,
)
mworker.run_one(reserve_timeout=float(options.reserve_timeout))
else:
raise ValueError("N <= 0")
def main():
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
sys.exit(main_worker())
def main_worker():
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option(
"--exp-key",
dest="exp_key",
default=None,
metavar="str",
help="identifier for this workers's jobs",
)
parser.add_option(
"--last-job-timeout",
dest="last_job_timeout",
metavar="T",
default=None,
help="Do not reserve a job after T seconds have passed",
)
parser.add_option(
"--max-consecutive-failures",
dest="max_consecutive_failures",
metavar="N",
default=4,
help="stop if N consecutive jobs fail (default: 4)",
)
parser.add_option(
"--max-jobs",
dest="max_jobs",
default=sys.maxsize,
help="stop after running this many jobs (default: inf)",
)
parser.add_option(
"--mongo",
dest="mongo",
default="localhost/hyperopt",
help="<host>[:port]/<db> for IPC and job storage",
)
parser.add_option(
"--poll-interval",
dest="poll_interval",
metavar="N",
default=5,
help="check work queue every 1 < T < N seconds (default: 5",
)
parser.add_option(
"--reserve-timeout",
dest="reserve_timeout",
metavar="T",
default=120.0,
help="poll database for up to T seconds to reserve a job",
)
parser.add_option(
"--workdir",
dest="workdir",
default=None,
help="root workdir (default: load from mongo)",
metavar="DIR",
)
parser.add_option(
"--no-subprocesses",
dest="use_subprocesses",
default=True,
action="store_false",
help="do not use sub-processes for each objective evaluation, the objective function will run in the same "
"python process (useful to keep in memory large data across objective evals) but you have to pay "
"attention to memory leaks (default: False)",
)
parser.add_option(
"--max-jobs-in-db",
dest="max_jobs_in_db",
default=sys.maxsize,
help="max jobs in db (default: " + str(sys.maxsize) + ")",
)
(options, args) = parser.parse_args()
if args:
parser.print_help()
return -1
return main_worker_helper(options, args)
| MongoCtrl |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 857069,
"end": 858037
} | class ____(sgqlc.types.Type):
"""Iteration field configuration for a project."""
__schema__ = github_schema
__field_names__ = ("completed_iterations", "duration", "iterations", "start_day")
completed_iterations = sgqlc.types.Field(
sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null("ProjectV2IterationFieldIteration"))),
graphql_name="completedIterations",
)
"""The iteration's completed iterations"""
duration = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="duration")
"""The iteration's duration in days"""
iterations = sgqlc.types.Field(
sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null("ProjectV2IterationFieldIteration"))), graphql_name="iterations"
)
"""The iteration's iterations"""
start_day = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="startDay")
"""The iteration's start day of the week"""
| ProjectV2IterationFieldConfiguration |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/pubsub.py | {
"start": 32447,
"end": 39386
} | class ____(GoogleCloudBaseOperator):
"""
Pulls messages from a PubSub subscription and passes them through XCom.
If the queue is empty, returns empty list - never waits for messages.
If you do need to wait, please use :class:`airflow.providers.google.cloud.sensors.PubSubPullSensor`
instead.
.. seealso::
For more information on how to use this operator and the PubSubPullSensor, take a look at the guide:
:ref:`howto/operator:PubSubPullSensor`
This operator will pull up to ``max_messages`` messages from the
specified PubSub subscription. When the subscription returns messages,
the messages will be returned immediately from the operator and passed through XCom for downstream tasks.
If ``ack_messages`` is set to True, messages will be immediately
acknowledged before being returned, otherwise, downstream tasks will be
responsible for acknowledging them.
``project_id `` and ``subscription`` are templated so you can use Jinja templating in their values.
:param project_id: the Google Cloud project ID for the subscription (templated)
:param subscription: the Pub/Sub subscription name. Do not include the
full subscription path.
:param max_messages: The maximum number of messages to retrieve per
PubSub pull request
:param ack_messages: If True, each message will be acknowledged
immediately rather than by any downstream tasks
:param gcp_conn_id: The connection ID to use connecting to
Google Cloud.
:param messages_callback: (Optional) Callback to process received messages.
Its return value will be saved to XCom.
If you are pulling large messages, you probably want to provide a custom callback.
If not provided, the default implementation will convert `ReceivedMessage` objects
into JSON-serializable dicts using `google.protobuf.json_format.MessageToDict` function.
: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).
:param deferrable: If True, run the task in the deferrable mode.
:param poll_interval: Time (seconds) to wait between two consecutive calls to check the job.
The default is 300 seconds.
"""
template_fields: Sequence[str] = (
"project_id",
"subscription",
"impersonation_chain",
)
def __init__(
self,
*,
project_id: str,
subscription: str,
max_messages: int = 5,
ack_messages: bool = False,
messages_callback: Callable[[list[ReceivedMessage], Context], Any] | None = None,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
poll_interval: int = 300,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.gcp_conn_id = gcp_conn_id
self.project_id = project_id
self.subscription = subscription
self.max_messages = max_messages
self.ack_messages = ack_messages
self.messages_callback = messages_callback
self.impersonation_chain = impersonation_chain
self.deferrable = deferrable
self.poll_interval = poll_interval
def execute(self, context: Context) -> list:
if self.deferrable:
self.defer(
trigger=PubsubPullTrigger(
subscription=self.subscription,
project_id=self.project_id,
max_messages=self.max_messages,
ack_messages=self.ack_messages,
gcp_conn_id=self.gcp_conn_id,
poke_interval=self.poll_interval,
impersonation_chain=self.impersonation_chain,
),
method_name=GOOGLE_DEFAULT_DEFERRABLE_METHOD_NAME,
)
hook = PubSubHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
pulled_messages = hook.pull(
project_id=self.project_id,
subscription=self.subscription,
max_messages=self.max_messages,
return_immediately=True,
)
handle_messages = self.messages_callback or self._default_message_callback
ret = handle_messages(pulled_messages, context)
if pulled_messages and self.ack_messages:
hook.acknowledge(
project_id=self.project_id,
subscription=self.subscription,
messages=pulled_messages,
)
return ret
def execute_complete(self, context: Context, event: dict[str, Any]):
"""If messages_callback is provided, execute it; otherwise, return immediately with trigger event message."""
if event["status"] == "success":
self.log.info("Sensor pulls messages: %s", event["message"])
messages_callback = self.messages_callback or self._default_message_callback
_return_value = messages_callback(event["message"], context)
return _return_value
self.log.info("Sensor failed: %s", event["message"])
raise AirflowException(event["message"])
def _default_message_callback(
self,
pulled_messages: list[ReceivedMessage],
context: Context,
) -> list:
"""
Act as a default message callback.
This method can be overridden by subclasses or by `messages_callback` constructor argument.
This default implementation converts `ReceivedMessage` objects into JSON-serializable dicts.
:param pulled_messages: messages received from the topic.
:param context: same as in `execute`
:return: value to be saved to XCom.
"""
messages_json = [ReceivedMessage.to_dict(m) for m in pulled_messages]
return messages_json
def get_openlineage_facets_on_complete(self, _) -> OperatorLineage:
from airflow.providers.common.compat.openlineage.facet import Dataset
from airflow.providers.openlineage.extractors import OperatorLineage
output_dataset = [
Dataset(namespace="pubsub", name=f"subscription:{self.project_id}:{self.subscription}")
]
return OperatorLineage(outputs=output_dataset)
| PubSubPullOperator |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py | {
"start": 21416,
"end": 22167
} | class ____(graphene.ObjectType):
name = graphene.NonNull(graphene.String)
partition_keys = non_null_list(graphene.String)
type = graphene.NonNull(GraphenePartitionDefinitionType)
class Meta:
name = "DimensionPartitionKeys"
types = [
GraphenePartition,
GraphenePartitionRunConfig,
GraphenePartitionRunConfigOrError,
GraphenePartitions,
GraphenePartitionSet,
GraphenePartitionSetOrError,
GraphenePartitionSets,
GraphenePartitionSetsOrError,
GraphenePartitionsOrError,
GraphenePartitionStatus,
GraphenePartitionStatusCounts,
GraphenePartitionStatuses,
GraphenePartitionStatusesOrError,
GraphenePartitionTags,
GraphenePartitionTagsOrError,
]
| GrapheneDimensionPartitionKeys |
python | modin-project__modin | modin/core/execution/dask/implementations/pandas_on_dask/partitioning/partition_manager.py | {
"start": 1205,
"end": 2199
} | class ____(PandasDataframePartitionManager):
"""The class implements the interface in `PandasDataframePartitionManager`."""
# This object uses PandasOnDaskDataframePartition objects as the underlying store.
_partition_class = PandasOnDaskDataframePartition
_column_partitions_class = PandasOnDaskDataframeColumnPartition
_row_partition_class = PandasOnDaskDataframeRowPartition
_execution_wrapper = DaskWrapper
@classmethod
def wait_partitions(cls, partitions):
"""
Wait on the objects wrapped by `partitions` in parallel, without materializing them.
This method will block until all computations in the list have completed.
Parameters
----------
partitions : np.ndarray
NumPy array with ``PandasDataframePartition``-s.
"""
cls._execution_wrapper.wait(
[block for partition in partitions for block in partition.list_of_blocks]
)
| PandasOnDaskDataframePartitionManager |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2.py | {
"start": 165551,
"end": 171895
} | class ____(
CategoricalColumn,
fc_old._SequenceCategoricalColumn, # pylint: disable=protected-access
collections.namedtuple('SequenceCategoricalColumn',
('categorical_column'))):
"""Represents sequences of categorical data."""
@property
def _is_v2_column(self):
return (
isinstance(self.categorical_column, fc_types.FeatureColumn)
and self.categorical_column._is_v2_column
) # pylint: disable=protected-access
@property
def name(self):
"""See `FeatureColumn` base class."""
return self.categorical_column.name
@property
def parse_example_spec(self):
"""See `FeatureColumn` base class."""
return self.categorical_column.parse_example_spec
@property
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _parse_example_spec(self):
return self.categorical_column._parse_example_spec # pylint: disable=protected-access
def transform_feature(self, transformation_cache, state_manager):
"""See `FeatureColumn` base class."""
return self.categorical_column.transform_feature(transformation_cache,
state_manager)
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _transform_feature(self, inputs):
return self.categorical_column._transform_feature(inputs) # pylint: disable=protected-access
@property
def num_buckets(self):
"""Returns number of buckets in this sparse feature."""
return self.categorical_column.num_buckets
@property
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _num_buckets(self):
return self.categorical_column._num_buckets # pylint: disable=protected-access
def _get_sparse_tensors_helper(self, sparse_tensors):
id_tensor = sparse_tensors.id_tensor
weight_tensor = sparse_tensors.weight_tensor
# Expands third dimension, if necessary so that embeddings are not
# combined during embedding lookup. If the tensor is already 3D, leave
# as-is.
shape = array_ops.shape(id_tensor)
# Compute the third dimension explicitly instead of setting it to -1, as
# that doesn't work for dynamically shaped tensors with 0-length at runtime.
# This happens for empty sequences.
target_shape = [shape[0], shape[1], math_ops.reduce_prod(shape[2:])]
id_tensor = sparse_ops.sparse_reshape(id_tensor, target_shape)
if weight_tensor is not None:
weight_tensor = sparse_ops.sparse_reshape(weight_tensor, target_shape)
return CategoricalColumn.IdWeightPair(id_tensor, weight_tensor)
def get_sparse_tensors(self, transformation_cache, state_manager):
"""Returns an IdWeightPair.
`IdWeightPair` is a pair of `SparseTensor`s which represents ids and
weights.
`IdWeightPair.id_tensor` is typically a `batch_size` x `num_buckets`
`SparseTensor` of `int64`. `IdWeightPair.weight_tensor` is either a
`SparseTensor` of `float` or `None` to indicate all weights should be
taken to be 1. If specified, `weight_tensor` must have exactly the same
shape and indices as `sp_ids`. Expected `SparseTensor` is same as parsing
output of a `VarLenFeature` which is a ragged matrix.
Args:
transformation_cache: A `FeatureTransformationCache` object to access
features.
state_manager: A `StateManager` to create / access resources such as
lookup tables.
"""
sparse_tensors = self.categorical_column.get_sparse_tensors(
transformation_cache, state_manager)
return self._get_sparse_tensors_helper(sparse_tensors)
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _get_sparse_tensors(self,
inputs,
weight_collections=None,
trainable=None):
sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access
return self._get_sparse_tensors_helper(sparse_tensors)
@property
def parents(self):
"""See 'FeatureColumn` base class."""
return [self.categorical_column]
def get_config(self):
"""See 'FeatureColumn` base class."""
from tensorflow.python.feature_column.serialization import serialize_feature_column # pylint: disable=g-import-not-at-top
config = dict(zip(self._fields, self))
config['categorical_column'] = serialize_feature_column(
self.categorical_column)
return config
@classmethod
def from_config(cls, config, custom_objects=None, columns_by_name=None):
"""See 'FeatureColumn` base class."""
from tensorflow.python.feature_column.serialization import deserialize_feature_column # pylint: disable=g-import-not-at-top
_check_config_keys(config, cls._fields)
kwargs = _standardize_and_copy_config(config)
kwargs['categorical_column'] = deserialize_feature_column(
config['categorical_column'], custom_objects, columns_by_name)
return cls(**kwargs)
def _check_config_keys(config, expected_keys):
"""Checks that a config has all expected_keys."""
if set(config.keys()) != set(expected_keys):
raise ValueError('Invalid config: {}, expected keys: {}'.format(
config, expected_keys))
def _standardize_and_copy_config(config):
"""Returns a shallow copy of config with lists turned to tuples.
Keras serialization uses nest to listify everything.
This causes problems with the NumericColumn shape, which becomes
unhashable. We could try to solve this on the Keras side, but that
would require lots of tracking to avoid changing existing behavior.
Instead, we ensure here that we revive correctly.
Args:
config: dict that will be used to revive a Feature Column
Returns:
Shallow copy of config with lists turned to tuples.
"""
kwargs = config.copy()
for k, v in kwargs.items():
if isinstance(v, list):
kwargs[k] = tuple(v)
return kwargs
def _sanitize_column_name_for_variable_scope(name):
"""Sanitizes user-provided feature names for use as variable scopes."""
invalid_char = re.compile('[^A-Za-z0-9_.\\-]')
return invalid_char.sub('_', name)
| SequenceCategoricalColumn |
python | walkccc__LeetCode | solutions/1605. Find Valid Matrix Given Row and Column Sums/1605.py | {
"start": 0,
"end": 371
} | class ____:
def restoreMatrix(self, rowSum: list[int],
colSum: list[int]) -> list[list[int]]:
m = len(rowSum)
n = len(colSum)
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
ans[i][j] = min(rowSum[i], colSum[j])
rowSum[i] -= ans[i][j]
colSum[j] -= ans[i][j]
return ans
| Solution |
python | modin-project__modin | modin/core/execution/dispatching/factories/factories.py | {
"start": 2871,
"end": 3270
} | class ____(typing.NamedTuple):
"""
Structure that stores information about factory.
Parameters
----------
engine : str
Name of underlying execution engine.
partition : str
Name of the partition format.
experimental : bool
Whether underlying engine is experimental-only.
"""
engine: str
partition: str
experimental: bool
| FactoryInfo |
python | django__django | tests/migrations/migrations_test_apps/with_generic_model/models.py | {
"start": 657,
"end": 787
} | class ____(Child[T1, T3, T2], models.Model):
"""A model inheriting from a custom subclass of typing.Generic."""
| CustomGenericModel |
python | lepture__mistune | src/mistune/directives/_base.py | {
"start": 340,
"end": 1655
} | class ____(ABCMeta):
name = "directive"
@staticmethod
@abstractmethod
def parse_type(m: Match[str]) -> str:
raise NotImplementedError()
@staticmethod
@abstractmethod
def parse_title(m: Match[str]) -> str:
raise NotImplementedError()
@staticmethod
@abstractmethod
def parse_content(m: Match[str]) -> str:
raise NotImplementedError()
@classmethod
def parse_tokens(cls, block: "BlockParser", text: str, state: "BlockState") -> Iterable[Dict[str, Any]]:
if state.depth() >= block.max_nested_level - 1 and cls.name in block.rules:
rules = list(block.rules)
rules.remove(cls.name)
else:
rules = block.rules
child = state.child_state(text)
block.parse(child, rules)
return child.tokens
@staticmethod
def parse_options(m: Match[str]) -> List[Tuple[str, str]]:
text = m.group("options")
if not text.strip():
return []
options = []
for line in re.split(r"\n+", text):
line = line.strip()[1:]
if not line:
continue
i = line.find(":")
k = line[:i]
v = line[i + 1 :].strip()
options.append((k, v))
return options
| DirectiveParser |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 30118,
"end": 30978
} | class ____(Response):
"""
Response of projects.create endpoint.
:param id: Project id
:type id: str
"""
_service = "projects"
_action = "create"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"id": {"description": "Project id", "type": ["string", "null"]}},
"type": "object",
}
def __init__(self, id: Optional[str] = None, **kwargs: Any) -> None:
super(CreateResponse, self).__init__(**kwargs)
self.id = id
@schema_property("id")
def id(self) -> Optional[str]:
return self._property_id
@id.setter
def id(self, value: Optional[str]) -> None:
if value is None:
self._property_id = None
return
self.assert_isinstance(value, "id", six.string_types)
self._property_id = value
| CreateResponse |
python | spack__spack | lib/spack/spack/oci/opener.py | {
"start": 5913,
"end": 5999
} | class ____(NamedTuple):
realm: str
service: str
scope: str
| RealmServiceScope |
python | Lightning-AI__lightning | examples/pytorch/domain_templates/computer_vision_fine_tuning.py | {
"start": 2901,
"end": 3851
} | class ____(BaseFinetuning):
def __init__(self, milestones: tuple = (5, 10), train_bn: bool = False):
super().__init__()
self.milestones = milestones
self.train_bn = train_bn
def freeze_before_training(self, pl_module: LightningModule):
self.freeze(modules=pl_module.feature_extractor, train_bn=self.train_bn)
def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer):
if epoch == self.milestones[0]:
# unfreeze 5 last layers
self.unfreeze_and_add_param_group(
modules=pl_module.feature_extractor[-5:], optimizer=optimizer, train_bn=self.train_bn
)
elif epoch == self.milestones[1]:
# unfreeze remaining layers
self.unfreeze_and_add_param_group(
modules=pl_module.feature_extractor[:-5], optimizer=optimizer, train_bn=self.train_bn
)
| MilestonesFinetuning |
python | great-expectations__great_expectations | tests/expectations/metrics/query_metrics/test_query_metrics.py | {
"start": 2734,
"end": 6011
} | class ____(QueryTable):
metric_name = "my_query.table"
value_keys = ("my_query",)
query_param_name: ClassVar[str] = "my_query"
@pytest.mark.unit
@mock.patch.object(sa, "text")
@mock.patch.object(
QueryMetricProvider, "_get_substituted_batch_subquery_from_query_and_batch_selectable"
)
@mock.patch.object(QueryMetricProvider, "_get_sqlalchemy_records_from_substituted_batch_subquery")
@pytest.mark.parametrize(
"metric_class, class_metric_value_kwargs, query_parameters",
[
(
MyQueryColumn,
{"column": "my_column"},
QueryParameters(column="my_column"),
),
(
MyQueryColumnPair,
{"column_A": "my_column_A", "column_B": "my_column_B"},
QueryParameters(column_A="my_column_A", column_B="my_column_B"),
),
(
MyQueryMultipleColumns,
{"columns": ["my_column_1", "my_column_2", "my_column_3"]},
QueryParameters(columns=["my_column_1", "my_column_2", "my_column_3"]),
),
(
MyQueryTable,
{},
None,
),
],
)
def test_sqlalchemy_query_metrics_that_return_records(
mock_get_sqlalchemy_records_from_substituted_batch_subquery,
mock_get_substituted_batch_subquery_from_query_and_batch_selectable,
mock_sqlalchemy_text,
mock_sqlalchemy_execution_engine: MockSqlAlchemyExecutionEngine,
metric_class: QueryMetricProvider,
class_metric_value_kwargs: dict,
query_parameters: Optional[QueryParameters],
batch_selectable: sa.Table,
):
metric_value_kwargs = {
"query_param": "my_query",
"my_query": "SELECT * FROM {batch} WHERE passenger_count > 7",
}
metric_value_kwargs.update(class_metric_value_kwargs)
mock_substituted_batch_subquery = "SELECT * FROM (my_table) WHERE passenger_count > 7"
mock_get_substituted_batch_subquery_from_query_and_batch_selectable.return_value = (
mock_substituted_batch_subquery
)
mock_sqlalchemy_text.return_value = "*"
with mock.patch.object(mock_sqlalchemy_execution_engine, "execute_query"):
metric_class._sqlalchemy(
cls=metric_class,
execution_engine=mock_sqlalchemy_execution_engine,
metric_domain_kwargs={},
metric_value_kwargs=metric_value_kwargs,
metrics={},
runtime_configuration={},
)
if query_parameters:
mock_get_substituted_batch_subquery_from_query_and_batch_selectable.assert_called_once_with(
query=metric_value_kwargs["my_query"],
batch_selectable=batch_selectable,
execution_engine=mock_sqlalchemy_execution_engine,
query_parameters=query_parameters,
)
else:
mock_get_substituted_batch_subquery_from_query_and_batch_selectable.assert_called_once_with(
query=metric_value_kwargs["my_query"],
batch_selectable=batch_selectable,
execution_engine=mock_sqlalchemy_execution_engine,
)
mock_get_sqlalchemy_records_from_substituted_batch_subquery.assert_called_once_with(
substituted_batch_subquery=mock_substituted_batch_subquery,
execution_engine=mock_sqlalchemy_execution_engine,
)
| MyQueryTable |
python | python__mypy | mypy/typeanal.py | {
"start": 101273,
"end": 104136
} | class ____(TrivialSyntheticTypeTranslator):
"""See docstring of detect_diverging_alias() for details."""
# TODO: this doesn't really need to be a translator, but we don't have a trivial visitor.
def __init__(
self,
seen_nodes: set[TypeAlias],
lookup: Callable[[str, Context], SymbolTableNode | None],
scope: TypeVarLikeScope,
) -> None:
super().__init__()
self.seen_nodes = seen_nodes
self.lookup = lookup
self.scope = scope
self.diverging = False
def visit_type_alias_type(self, t: TypeAliasType) -> Type:
assert t.alias is not None, f"Unfixed type alias {t.type_ref}"
if t.alias in self.seen_nodes:
for arg in t.args:
if not (
isinstance(arg, TypeVarLikeType)
or isinstance(arg, UnpackType)
and isinstance(arg.type, TypeVarLikeType)
) and has_type_vars(arg):
self.diverging = True
return t
# All clear for this expansion chain.
return t
new_nodes = self.seen_nodes | {t.alias}
visitor = DivergingAliasDetector(new_nodes, self.lookup, self.scope)
_ = get_proper_type(t).accept(visitor)
if visitor.diverging:
self.diverging = True
return t
def detect_diverging_alias(
node: TypeAlias,
target: Type,
lookup: Callable[[str, Context], SymbolTableNode | None],
scope: TypeVarLikeScope,
) -> bool:
"""This detects type aliases that will diverge during type checking.
For example F = Something[..., F[List[T]]]. At each expansion step this will produce
*new* type aliases: e.g. F[List[int]], F[List[List[int]]], etc. So we can't detect
recursion. It is a known problem in the literature, recursive aliases and generic types
don't always go well together. It looks like there is no known systematic solution yet.
# TODO: should we handle such aliases using type_recursion counter and some large limit?
They may be handy in rare cases, e.g. to express a union of non-mixed nested lists:
Nested = Union[T, Nested[List[T]]] ~> Union[T, List[T], List[List[T]], ...]
"""
visitor = DivergingAliasDetector({node}, lookup, scope)
_ = target.accept(visitor)
return visitor.diverging
def check_for_explicit_any(
typ: Type | None,
options: Options,
is_typeshed_stub: bool,
msg: MessageBuilder,
context: Context,
) -> None:
if options.disallow_any_explicit and not is_typeshed_stub and typ and has_explicit_any(typ):
msg.explicit_any(context)
def has_explicit_any(t: Type) -> bool:
"""
Whether this type is or type it contains is an Any coming from explicit type annotation
"""
return t.accept(HasExplicitAny())
| DivergingAliasDetector |
python | imageio__imageio | imageio/plugins/_tifffile.py | {
"start": 123046,
"end": 162319
} | class ____(object):
"""TIFF image file directory (IFD).
Attributes
----------
index : int
Index of page in file.
dtype : numpy.dtype or None
Data type (native byte order) of the image in IFD.
shape : tuple
Dimensions of the image in IFD.
axes : str
Axes label codes:
'X' width, 'Y' height, 'S' sample, 'I' image series|page|plane,
'Z' depth, 'C' color|em-wavelength|channel, 'E' ex-wavelength|lambda,
'T' time, 'R' region|tile, 'A' angle, 'P' phase, 'H' lifetime,
'L' exposure, 'V' event, 'Q' unknown, '_' missing
tags : dict
Dictionary of tags in IFD. {tag.name: TiffTag}
colormap : numpy.ndarray
Color look up table, if exists.
All attributes are read-only.
Notes
-----
The internal, normalized '_shape' attribute is 6 dimensional:
0 : number planes/images (stk, ij).
1 : planar samplesperpixel.
2 : imagedepth Z (sgi).
3 : imagelength Y.
4 : imagewidth X.
5 : contig samplesperpixel.
"""
# default properties; will be updated from tags
imagewidth = 0
imagelength = 0
imagedepth = 1
tilewidth = 0
tilelength = 0
tiledepth = 1
bitspersample = 1
samplesperpixel = 1
sampleformat = 1
rowsperstrip = 2**32 - 1
compression = 1
planarconfig = 1
fillorder = 1
photometric = 0
predictor = 1
extrasamples = 1
colormap = None
software = ""
description = ""
description1 = ""
def __init__(self, parent, index, keyframe=None):
"""Initialize instance from file.
The file handle position must be at offset to a valid IFD.
"""
self.parent = parent
self.index = index
self.shape = ()
self._shape = ()
self.dtype = None
self._dtype = None
self.axes = ""
self.tags = {}
self.dataoffsets = ()
self.databytecounts = ()
# read TIFF IFD structure and its tags from file
fh = parent.filehandle
self.offset = fh.tell() # offset to this IFD
try:
tagno = struct.unpack(parent.tagnoformat, fh.read(parent.tagnosize))[0]
if tagno > 4096:
raise ValueError("suspicious number of tags")
except Exception:
raise ValueError("corrupted tag list at offset %i" % self.offset)
tagsize = parent.tagsize
data = fh.read(tagsize * tagno)
tags = self.tags
index = -tagsize
for _ in range(tagno):
index += tagsize
try:
tag = TiffTag(self.parent, data[index : index + tagsize])
except TiffTag.Error as e:
warnings.warn(str(e))
continue
tagname = tag.name
if tagname not in tags:
name = tagname
tags[name] = tag
else:
# some files contain multiple tags with same code
# e.g. MicroManager files contain two ImageDescription tags
i = 1
while True:
name = "%s%i" % (tagname, i)
if name not in tags:
tags[name] = tag
break
name = TIFF.TAG_ATTRIBUTES.get(name, "")
if name:
if name[:3] in "sof des" and not isinstance(tag.value, str):
pass # wrong string type for software, description
else:
setattr(self, name, tag.value)
if not tags:
return # found in FIBICS
# consolidate private tags; remove them from self.tags
if self.is_andor:
self.andor_tags
elif self.is_epics:
self.epics_tags
if self.is_lsm or (self.index and self.parent.is_lsm):
# correct non standard LSM bitspersample tags
self.tags["BitsPerSample"]._fix_lsm_bitspersample(self)
if self.is_vista or (self.index and self.parent.is_vista):
# ISS Vista writes wrong ImageDepth tag
self.imagedepth = 1
if self.is_stk and "UIC1tag" in tags and not tags["UIC1tag"].value:
# read UIC1tag now that plane count is known
uic1tag = tags["UIC1tag"]
fh.seek(uic1tag.valueoffset)
tags["UIC1tag"].value = read_uic1tag(
fh,
self.parent.byteorder,
uic1tag.dtype,
uic1tag.count,
None,
tags["UIC2tag"].count,
)
if "IJMetadata" in tags:
# decode IJMetadata tag
try:
tags["IJMetadata"].value = imagej_metadata(
tags["IJMetadata"].value,
tags["IJMetadataByteCounts"].value,
self.parent.byteorder,
)
except Exception as e:
warnings.warn(str(e))
if "BitsPerSample" in tags:
tag = tags["BitsPerSample"]
if tag.count == 1:
self.bitspersample = tag.value
else:
# LSM might list more items than samplesperpixel
value = tag.value[: self.samplesperpixel]
if any((v - value[0] for v in value)):
self.bitspersample = value
else:
self.bitspersample = value[0]
if "SampleFormat" in tags:
tag = tags["SampleFormat"]
if tag.count == 1:
self.sampleformat = tag.value
else:
value = tag.value[: self.samplesperpixel]
if any((v - value[0] for v in value)):
self.sampleformat = value
else:
self.sampleformat = value[0]
if "ImageLength" in tags:
if "RowsPerStrip" not in tags or tags["RowsPerStrip"].count > 1:
self.rowsperstrip = self.imagelength
# self.stripsperimage = int(math.floor(
# float(self.imagelength + self.rowsperstrip - 1) /
# self.rowsperstrip))
# determine dtype
dtype = self.sampleformat, self.bitspersample
dtype = TIFF.SAMPLE_DTYPES.get(dtype, None)
if dtype is not None:
dtype = numpy.dtype(dtype)
self.dtype = self._dtype = dtype
# determine shape of data
imagelength = self.imagelength
imagewidth = self.imagewidth
imagedepth = self.imagedepth
samplesperpixel = self.samplesperpixel
if self.is_stk:
assert self.imagedepth == 1
uictag = tags["UIC2tag"].value
planes = tags["UIC2tag"].count
if self.planarconfig == 1:
self._shape = (planes, 1, 1, imagelength, imagewidth, samplesperpixel)
if samplesperpixel == 1:
self.shape = (planes, imagelength, imagewidth)
self.axes = "YX"
else:
self.shape = (planes, imagelength, imagewidth, samplesperpixel)
self.axes = "YXS"
else:
self._shape = (planes, samplesperpixel, 1, imagelength, imagewidth, 1)
if samplesperpixel == 1:
self.shape = (planes, imagelength, imagewidth)
self.axes = "YX"
else:
self.shape = (planes, samplesperpixel, imagelength, imagewidth)
self.axes = "SYX"
# detect type of series
if planes == 1:
self.shape = self.shape[1:]
elif numpy.all(uictag["ZDistance"] != 0):
self.axes = "Z" + self.axes
elif numpy.all(numpy.diff(uictag["TimeCreated"]) != 0):
self.axes = "T" + self.axes
else:
self.axes = "I" + self.axes
elif self.photometric == 2 or samplesperpixel > 1: # PHOTOMETRIC.RGB
if self.planarconfig == 1:
self._shape = (
1,
1,
imagedepth,
imagelength,
imagewidth,
samplesperpixel,
)
if imagedepth == 1:
self.shape = (imagelength, imagewidth, samplesperpixel)
self.axes = "YXS"
else:
self.shape = (imagedepth, imagelength, imagewidth, samplesperpixel)
self.axes = "ZYXS"
else:
self._shape = (
1,
samplesperpixel,
imagedepth,
imagelength,
imagewidth,
1,
)
if imagedepth == 1:
self.shape = (samplesperpixel, imagelength, imagewidth)
self.axes = "SYX"
else:
self.shape = (samplesperpixel, imagedepth, imagelength, imagewidth)
self.axes = "SZYX"
else:
self._shape = (1, 1, imagedepth, imagelength, imagewidth, 1)
if imagedepth == 1:
self.shape = (imagelength, imagewidth)
self.axes = "YX"
else:
self.shape = (imagedepth, imagelength, imagewidth)
self.axes = "ZYX"
# dataoffsets and databytecounts
if "TileOffsets" in tags:
self.dataoffsets = tags["TileOffsets"].value
elif "StripOffsets" in tags:
self.dataoffsets = tags["StripOffsets"].value
else:
self.dataoffsets = (0,)
if "TileByteCounts" in tags:
self.databytecounts = tags["TileByteCounts"].value
elif "StripByteCounts" in tags:
self.databytecounts = tags["StripByteCounts"].value
else:
self.databytecounts = (product(self.shape) * (self.bitspersample // 8),)
if self.compression != 1:
warnings.warn("required ByteCounts tag is missing")
assert len(self.shape) == len(self.axes)
def asarray(
self,
out=None,
squeeze=True,
lock=None,
reopen=True,
maxsize=2**44,
validate=True,
):
"""Read image data from file and return as numpy array.
Raise ValueError if format is unsupported.
Parameters
----------
out : numpy.ndarray, str, or file-like object; optional
Buffer where image data will be saved.
If None (default), a new array will be created.
If numpy.ndarray, a writable array of compatible dtype and shape.
If 'memmap', directly memory-map the image data in the TIFF file
if possible; else create a memory-mapped array in a temporary file.
If str or open file, the file name or file object used to
create a memory-map to an array stored in a binary file on disk.
squeeze : bool
If True, all length-1 dimensions (except X and Y) are
squeezed out from the array.
If False, the shape of the returned array might be different from
the page.shape.
lock : {RLock, NullContext}
A reentrant lock used to synchronize reads from file.
If None (default), the lock of the parent's filehandle is used.
reopen : bool
If True (default) and the parent file handle is closed, the file
is temporarily re-opened and closed if no exception occurs.
maxsize: int or None
Maximum size of data before a ValueError is raised.
Can be used to catch DOS. Default: 16 TB.
validate : bool
If True (default), validate various parameters.
If None, only validate parameters and return None.
"""
self_ = self
self = self.keyframe # self or keyframe
if not self._shape or product(self._shape) == 0:
return
tags = self.tags
if validate or validate is None:
if maxsize and product(self._shape) > maxsize:
raise ValueError("data are too large %s" % str(self._shape))
if self.dtype is None:
raise ValueError(
"data type not supported: %s%i"
% (self.sampleformat, self.bitspersample)
)
if self.compression not in TIFF.DECOMPESSORS:
raise ValueError("cannot decompress %s" % self.compression.name)
if "SampleFormat" in tags:
tag = tags["SampleFormat"]
if tag.count != 1 and any((i - tag.value[0] for i in tag.value)):
raise ValueError("sample formats do not match %s" % tag.value)
if self.is_chroma_subsampled and (
self.compression != 7 or self.planarconfig == 2
):
raise NotImplementedError("chroma subsampling not supported")
if validate is None:
return
fh = self_.parent.filehandle
lock = fh.lock if lock is None else lock
with lock:
closed = fh.closed
if closed:
if reopen:
fh.open()
else:
raise IOError("file handle is closed")
dtype = self._dtype
shape = self._shape
imagewidth = self.imagewidth
imagelength = self.imagelength
imagedepth = self.imagedepth
bitspersample = self.bitspersample
typecode = self.parent.byteorder + dtype.char
lsb2msb = self.fillorder == 2
offsets, bytecounts = self_.offsets_bytecounts
istiled = self.is_tiled
if istiled:
tilewidth = self.tilewidth
tilelength = self.tilelength
tiledepth = self.tiledepth
tw = (imagewidth + tilewidth - 1) // tilewidth
tl = (imagelength + tilelength - 1) // tilelength
td = (imagedepth + tiledepth - 1) // tiledepth
shape = (
shape[0],
shape[1],
td * tiledepth,
tl * tilelength,
tw * tilewidth,
shape[-1],
)
tileshape = (tiledepth, tilelength, tilewidth, shape[-1])
runlen = tilewidth
else:
runlen = imagewidth
if self.planarconfig == 1:
runlen *= self.samplesperpixel
if out == "memmap" and self.is_memmappable:
with lock:
result = fh.memmap_array(typecode, shape, offset=offsets[0])
elif self.is_contiguous:
if out is not None:
out = create_output(out, shape, dtype)
with lock:
fh.seek(offsets[0])
result = fh.read_array(typecode, product(shape), out=out)
if out is None and not result.dtype.isnative:
# swap byte order and dtype without copy
result.byteswap(True)
result = result.view(result.dtype.newbyteorder())
if lsb2msb:
reverse_bitorder(result)
else:
result = create_output(out, shape, dtype)
decompress = TIFF.DECOMPESSORS[self.compression]
if self.compression == 7: # COMPRESSION.JPEG
if bitspersample not in (8, 12):
raise ValueError("unsupported JPEG precision %i" % bitspersample)
if "JPEGTables" in tags:
table = tags["JPEGTables"].value
else:
table = b""
unpack = identityfunc
colorspace = TIFF.PHOTOMETRIC(self.photometric).name
def decompress(
x,
func=decompress,
table=table,
bitspersample=bitspersample,
colorspace=colorspace,
):
return func(x, table, bitspersample, colorspace).reshape(-1)
elif bitspersample in (8, 16, 32, 64, 128):
if (bitspersample * runlen) % 8:
raise ValueError("data and sample size mismatch")
def unpack(x, typecode=typecode):
if self.predictor == 3: # PREDICTOR.FLOATINGPOINT
# the floating point horizontal differencing decoder
# needs the raw byte order
typecode = dtype.char
try:
# read only numpy array
return numpy.frombuffer(x, typecode)
except ValueError:
# strips may be missing EOI
# warnings.warn('unpack: %s' % e)
xlen = (len(x) // (bitspersample // 8)) * (bitspersample // 8)
return numpy.frombuffer(x[:xlen], typecode)
elif isinstance(bitspersample, tuple):
def unpack(x, typecode=typecode, bitspersample=bitspersample):
return unpack_rgb(x, typecode, bitspersample)
else:
def unpack(
x, typecode=typecode, bitspersample=bitspersample, runlen=runlen
):
return unpack_ints(x, typecode, bitspersample, runlen)
if istiled:
writable = None
tw, tl, td, pl = 0, 0, 0, 0
for tile in buffered_read(fh, lock, offsets, bytecounts):
if lsb2msb:
tile = reverse_bitorder(tile)
tile = decompress(tile)
tile = unpack(tile)
try:
tile.shape = tileshape
except ValueError:
# incomplete tiles; see gdal issue #1179
warnings.warn("invalid tile data")
t = numpy.zeros(tileshape, dtype).reshape(-1)
s = min(tile.size, t.size)
t[:s] = tile[:s]
tile = t.reshape(tileshape)
if self.predictor == 2: # PREDICTOR.HORIZONTAL
if writable is None:
writable = tile.flags["WRITEABLE"]
if writable:
numpy.cumsum(tile, axis=-2, dtype=dtype, out=tile)
else:
tile = numpy.cumsum(tile, axis=-2, dtype=dtype)
elif self.predictor == 3: # PREDICTOR.FLOATINGPOINT
raise NotImplementedError()
result[
0,
pl,
td : td + tiledepth,
tl : tl + tilelength,
tw : tw + tilewidth,
:,
] = tile
del tile
tw += tilewidth
if tw >= shape[4]:
tw, tl = 0, tl + tilelength
if tl >= shape[3]:
tl, td = 0, td + tiledepth
if td >= shape[2]:
td, pl = 0, pl + 1
result = result[..., :imagedepth, :imagelength, :imagewidth, :]
else:
strip_size = self.rowsperstrip * self.imagewidth
if self.planarconfig == 1:
strip_size *= self.samplesperpixel
result = result.reshape(-1)
index = 0
for strip in buffered_read(fh, lock, offsets, bytecounts):
if lsb2msb:
strip = reverse_bitorder(strip)
strip = decompress(strip)
strip = unpack(strip)
size = min(result.size, strip.size, strip_size, result.size - index)
result[index : index + size] = strip[:size]
del strip
index += size
result.shape = self._shape
if self.predictor != 1 and not (istiled and not self.is_contiguous):
if self.parent.is_lsm and self.compression == 1:
pass # work around bug in LSM510 software
elif self.predictor == 2: # PREDICTOR.HORIZONTAL
numpy.cumsum(result, axis=-2, dtype=dtype, out=result)
elif self.predictor == 3: # PREDICTOR.FLOATINGPOINT
result = decode_floats(result)
if squeeze:
try:
result.shape = self.shape
except ValueError:
warnings.warn(
"failed to reshape from %s to %s"
% (str(result.shape), str(self.shape))
)
if closed:
# TODO: file should remain open if an exception occurred above
fh.close()
return result
def asrgb(
self,
uint8=False,
alpha=None,
colormap=None,
dmin=None,
dmax=None,
*args,
**kwargs,
):
"""Return image data as RGB(A).
Work in progress.
"""
data = self.asarray(*args, **kwargs)
self = self.keyframe # self or keyframe
photometric = self.photometric
PHOTOMETRIC = TIFF.PHOTOMETRIC
if photometric == PHOTOMETRIC.PALETTE:
colormap = self.colormap
if colormap.shape[1] < 2**self.bitspersample or self.dtype.char not in "BH":
raise ValueError("cannot apply colormap")
if uint8:
if colormap.max() > 255:
colormap >>= 8
colormap = colormap.astype("uint8")
if "S" in self.axes:
data = data[..., 0] if self.planarconfig == 1 else data[0]
data = apply_colormap(data, colormap)
elif photometric == PHOTOMETRIC.RGB:
if "ExtraSamples" in self.tags:
if alpha is None:
alpha = TIFF.EXTRASAMPLE
extrasamples = self.extrasamples
if self.tags["ExtraSamples"].count == 1:
extrasamples = (extrasamples,)
for i, exs in enumerate(extrasamples):
if exs in alpha:
if self.planarconfig == 1:
data = data[..., [0, 1, 2, 3 + i]]
else:
data = data[:, [0, 1, 2, 3 + i]]
break
else:
if self.planarconfig == 1:
data = data[..., :3]
else:
data = data[:, :3]
# TODO: convert to uint8?
elif photometric == PHOTOMETRIC.MINISBLACK:
raise NotImplementedError()
elif photometric == PHOTOMETRIC.MINISWHITE:
raise NotImplementedError()
elif photometric == PHOTOMETRIC.SEPARATED:
raise NotImplementedError()
else:
raise NotImplementedError()
return data
def aspage(self):
return self
@property
def keyframe(self):
return self
@keyframe.setter
def keyframe(self, index):
return
@lazyattr
def offsets_bytecounts(self):
"""Return simplified offsets and bytecounts."""
if self.is_contiguous:
offset, byte_count = self.is_contiguous
return [offset], [byte_count]
return clean_offsets_counts(self.dataoffsets, self.databytecounts)
@lazyattr
def is_contiguous(self):
"""Return offset and size of contiguous data, else None.
Excludes prediction and fill_order.
"""
if self.compression != 1 or self.bitspersample not in (8, 16, 32, 64):
return
if "TileWidth" in self.tags:
if (
self.imagewidth != self.tilewidth
or self.imagelength % self.tilelength
or self.tilewidth % 16
or self.tilelength % 16
):
return
if (
"ImageDepth" in self.tags
and "TileDepth" in self.tags
and (
self.imagelength != self.tilelength
or self.imagedepth % self.tiledepth
)
):
return
offsets = self.dataoffsets
bytecounts = self.databytecounts
if len(offsets) == 1:
return offsets[0], bytecounts[0]
if self.is_stk or all(
(
offsets[i] + bytecounts[i] == offsets[i + 1] or bytecounts[i + 1] == 0
) # no data/ignore offset
for i in range(len(offsets) - 1)
):
return offsets[0], sum(bytecounts)
@lazyattr
def is_final(self):
"""Return if page's image data are stored in final form.
Excludes byte-swapping.
"""
return (
self.is_contiguous
and self.fillorder == 1
and self.predictor == 1
and not self.is_chroma_subsampled
)
@lazyattr
def is_memmappable(self):
"""Return if page's image data in file can be memory-mapped."""
return (
self.parent.filehandle.is_file
and self.is_final
and
# (self.bitspersample == 8 or self.parent.isnative) and
self.is_contiguous[0] % self.dtype.itemsize == 0
) # aligned?
def __str__(self, detail=0, width=79):
"""Return string containing information about page."""
if self.keyframe != self:
return TiffFrame.__str__(self, detail)
attr = ""
for name in ("memmappable", "final", "contiguous"):
attr = getattr(self, "is_" + name)
if attr:
attr = name.upper()
break
info = " ".join(
s
for s in (
"x".join(str(i) for i in self.shape),
"%s%s"
% (TIFF.SAMPLEFORMAT(self.sampleformat).name, self.bitspersample),
"|".join(
i
for i in (
TIFF.PHOTOMETRIC(self.photometric).name,
"TILED" if self.is_tiled else "",
self.compression.name if self.compression != 1 else "",
self.planarconfig.name if self.planarconfig != 1 else "",
self.predictor.name if self.predictor != 1 else "",
self.fillorder.name if self.fillorder != 1 else "",
)
if i
),
attr,
"|".join((f.upper() for f in self.flags)),
)
if s
)
info = "TiffPage %i @%i %s" % (self.index, self.offset, info)
if detail <= 0:
return info
info = [info]
tags = self.tags
tlines = []
vlines = []
for tag in sorted(tags.values(), key=lambda x: x.code):
value = tag.__str__(width=width + 1)
tlines.append(value[:width].strip())
if detail > 1 and len(value) > width:
name = tag.name.upper()
if detail <= 2 and ("COUNTS" in name or "OFFSETS" in name):
value = pformat(tag.value, width=width, height=detail * 4)
else:
value = pformat(tag.value, width=width, height=detail * 12)
vlines.append("%s\n%s" % (tag.name, value))
info.append("\n".join(tlines))
if detail > 1:
info.append("\n\n".join(vlines))
if detail > 3:
try:
info.append(
"DATA\n%s" % pformat(self.asarray(), width=width, height=detail * 8)
)
except Exception:
pass
return "\n\n".join(info)
@lazyattr
def flags(self):
"""Return set of flags."""
return set(
(
name.lower()
for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, "is_" + name)
)
)
@property
def ndim(self):
"""Return number of array dimensions."""
return len(self.shape)
@property
def size(self):
"""Return number of elements in array."""
return product(self.shape)
@lazyattr
def andor_tags(self):
"""Return consolidated metadata from Andor tags as dict.
Remove Andor tags from self.tags.
"""
if not self.is_andor:
return
tags = self.tags
result = {"Id": tags["AndorId"].value}
for tag in list(self.tags.values()):
code = tag.code
if not 4864 < code < 5031:
continue
value = tag.value
name = tag.name[5:] if len(tag.name) > 5 else tag.name
result[name] = value
del tags[tag.name]
return result
@lazyattr
def epics_tags(self):
"""Return consolidated metadata from EPICS areaDetector tags as dict.
Remove areaDetector tags from self.tags.
"""
if not self.is_epics:
return
result = {}
tags = self.tags
for tag in list(self.tags.values()):
code = tag.code
if not 65000 <= code < 65500:
continue
value = tag.value
if code == 65000:
result["timeStamp"] = datetime.datetime.fromtimestamp(float(value))
elif code == 65001:
result["uniqueID"] = int(value)
elif code == 65002:
result["epicsTSSec"] = int(value)
elif code == 65003:
result["epicsTSNsec"] = int(value)
else:
key, value = value.split(":", 1)
result[key] = astype(value)
del tags[tag.name]
return result
@lazyattr
def geotiff_tags(self):
"""Return consolidated metadata from GeoTIFF tags as dict."""
if not self.is_geotiff:
return
tags = self.tags
gkd = tags["GeoKeyDirectoryTag"].value
if gkd[0] != 1:
warnings.warn("invalid GeoKeyDirectoryTag")
return {}
result = {
"KeyDirectoryVersion": gkd[0],
"KeyRevision": gkd[1],
"KeyRevisionMinor": gkd[2],
# 'NumberOfKeys': gkd[3],
}
# deltags = ['GeoKeyDirectoryTag']
geokeys = TIFF.GEO_KEYS
geocodes = TIFF.GEO_CODES
for index in range(gkd[3]):
keyid, tagid, count, offset = gkd[4 + index * 4 : index * 4 + 8]
keyid = geokeys.get(keyid, keyid)
if tagid == 0:
value = offset
else:
tagname = TIFF.TAGS[tagid]
# deltags.append(tagname)
value = tags[tagname].value[offset : offset + count]
if tagid == 34737 and count > 1 and value[-1] == "|":
value = value[:-1]
value = value if count > 1 else value[0]
if keyid in geocodes:
try:
value = geocodes[keyid](value)
except Exception:
pass
result[keyid] = value
if "IntergraphMatrixTag" in tags:
value = tags["IntergraphMatrixTag"].value
value = numpy.array(value)
if len(value) == 16:
value = value.reshape((4, 4)).tolist()
result["IntergraphMatrix"] = value
if "ModelPixelScaleTag" in tags:
value = numpy.array(tags["ModelPixelScaleTag"].value).tolist()
result["ModelPixelScale"] = value
if "ModelTiepointTag" in tags:
value = tags["ModelTiepointTag"].value
value = numpy.array(value).reshape((-1, 6)).squeeze().tolist()
result["ModelTiepoint"] = value
if "ModelTransformationTag" in tags:
value = tags["ModelTransformationTag"].value
value = numpy.array(value).reshape((4, 4)).tolist()
result["ModelTransformation"] = value
elif False:
# if 'ModelPixelScaleTag' in tags and 'ModelTiepointTag' in tags:
sx, sy, sz = tags["ModelPixelScaleTag"].value
tiepoints = tags["ModelTiepointTag"].value
transforms = []
for tp in range(0, len(tiepoints), 6):
i, j, k, x, y, z = tiepoints[tp : tp + 6]
transforms.append(
[
[sx, 0.0, 0.0, x - i * sx],
[0.0, -sy, 0.0, y + j * sy],
[0.0, 0.0, sz, z - k * sz],
[0.0, 0.0, 0.0, 1.0],
]
)
if len(tiepoints) == 6:
transforms = transforms[0]
result["ModelTransformation"] = transforms
if "RPCCoefficientTag" in tags:
rpcc = tags["RPCCoefficientTag"].value
result["RPCCoefficient"] = {
"ERR_BIAS": rpcc[0],
"ERR_RAND": rpcc[1],
"LINE_OFF": rpcc[2],
"SAMP_OFF": rpcc[3],
"LAT_OFF": rpcc[4],
"LONG_OFF": rpcc[5],
"HEIGHT_OFF": rpcc[6],
"LINE_SCALE": rpcc[7],
"SAMP_SCALE": rpcc[8],
"LAT_SCALE": rpcc[9],
"LONG_SCALE": rpcc[10],
"HEIGHT_SCALE": rpcc[11],
"LINE_NUM_COEFF": rpcc[12:33],
"LINE_DEN_COEFF ": rpcc[33:53],
"SAMP_NUM_COEFF": rpcc[53:73],
"SAMP_DEN_COEFF": rpcc[73:],
}
return result
@property
def is_tiled(self):
"""Page contains tiled image."""
return "TileWidth" in self.tags
@property
def is_reduced(self):
"""Page is reduced image of another image."""
return "NewSubfileType" in self.tags and self.tags["NewSubfileType"].value & 1
@property
def is_chroma_subsampled(self):
"""Page contains chroma subsampled image."""
return "YCbCrSubSampling" in self.tags and self.tags[
"YCbCrSubSampling"
].value != (1, 1)
@lazyattr
def is_imagej(self):
"""Return ImageJ description if exists, else None."""
for description in (self.description, self.description1):
if not description:
return
if description[:7] == "ImageJ=":
return description
@lazyattr
def is_shaped(self):
"""Return description containing array shape if exists, else None."""
for description in (self.description, self.description1):
if not description:
return
if description[:1] == "{" and '"shape":' in description:
return description
if description[:6] == "shape=":
return description
@property
def is_mdgel(self):
"""Page contains MDFileTag tag."""
return "MDFileTag" in self.tags
@property
def is_mediacy(self):
"""Page contains Media Cybernetics Id tag."""
return "MC_Id" in self.tags and self.tags["MC_Id"].value[:7] == b"MC TIFF"
@property
def is_stk(self):
"""Page contains UIC2Tag tag."""
return "UIC2tag" in self.tags
@property
def is_lsm(self):
"""Page contains CZ_LSMINFO tag."""
return "CZ_LSMINFO" in self.tags
@property
def is_fluoview(self):
"""Page contains FluoView MM_STAMP tag."""
return "MM_Stamp" in self.tags
@property
def is_nih(self):
"""Page contains NIH image header."""
return "NIHImageHeader" in self.tags
@property
def is_sgi(self):
"""Page contains SGI image and tile depth tags."""
return "ImageDepth" in self.tags and "TileDepth" in self.tags
@property
def is_vista(self):
"""Software tag is 'ISS Vista'."""
return self.software == "ISS Vista"
@property
def is_metaseries(self):
"""Page contains MDS MetaSeries metadata in ImageDescription tag."""
if self.index > 1 or self.software != "MetaSeries":
return False
d = self.description
return d.startswith("<MetaData>") and d.endswith("</MetaData>")
@property
def is_ome(self):
"""Page contains OME-XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == "<?xml version=" and d[-6:] == "</OME>"
@property
def is_scn(self):
"""Page contains Leica SCN XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == "<?xml version=" and d[-6:] == "</scn>"
@property
def is_micromanager(self):
"""Page contains Micro-Manager metadata."""
return "MicroManagerMetadata" in self.tags
@property
def is_andor(self):
"""Page contains Andor Technology tags."""
return "AndorId" in self.tags
@property
def is_pilatus(self):
"""Page contains Pilatus tags."""
return self.software[:8] == "TVX TIFF" and self.description[:2] == "# "
@property
def is_epics(self):
"""Page contains EPICS areaDetector tags."""
return (
self.description == "EPICS areaDetector"
or self.software == "EPICS areaDetector"
)
@property
def is_tvips(self):
"""Page contains TVIPS metadata."""
return "TVIPS" in self.tags
@property
def is_fei(self):
"""Page contains SFEG or HELIOS metadata."""
return "FEI_SFEG" in self.tags or "FEI_HELIOS" in self.tags
@property
def is_sem(self):
"""Page contains Zeiss SEM metadata."""
return "CZ_SEM" in self.tags
@property
def is_svs(self):
"""Page contains Aperio metadata."""
return self.description[:20] == "Aperio Image Library"
@property
def is_scanimage(self):
"""Page contains ScanImage metadata."""
return (
self.description[:12] == "state.config"
or self.software[:22] == "SI.LINE_FORMAT_VERSION"
or "scanimage.SI." in self.description[-256:]
)
@property
def is_qptiff(self):
"""Page contains PerkinElmer tissue images metadata."""
# The ImageDescription tag contains XML with a top-level
# <PerkinElmer-QPI-ImageDescription> element
return self.software[:15] == "PerkinElmer-QPI"
@property
def is_geotiff(self):
"""Page contains GeoTIFF metadata."""
return "GeoKeyDirectoryTag" in self.tags
| TiffPage |
python | tornadoweb__tornado | tornado/test/concurrent_test.py | {
"start": 3364,
"end": 3875
} | class ____(BaseCapClient):
@gen.coroutine
def capitalize(self, request_data):
logging.debug("capitalize")
stream = IOStream(socket.socket())
logging.debug("connecting")
yield stream.connect(("127.0.0.1", self.port))
stream.write(utf8(request_data + "\n"))
logging.debug("reading")
data = yield stream.read_until(b"\n")
logging.debug("returning")
stream.close()
raise gen.Return(self.process_response(data))
| GeneratorCapClient |
python | instagram__MonkeyType | monkeytype/typing.py | {
"start": 13925,
"end": 15132
} | class ____(TypeRewriter):
"""Rewrite Union[T1, ..., TN] as Any for large N."""
def __init__(self, max_union_len: int = 5):
super().__init__()
self.max_union_len = max_union_len
def _rewrite_to_tuple(self, union):
"""Union[Tuple[V, ..., V], Tuple[V, ..., V], ...] -> Tuple[V, ...]"""
value_type = None
for t in union.__args__:
if not is_generic_of(t, Tuple):
return None
value_type = value_type or t.__args__[0]
if not all(vt is value_type for vt in t.__args__):
return None
return Tuple[value_type, ...]
def rewrite_Union(self, union):
if len(union.__args__) <= self.max_union_len:
return union
rw_union = self._rewrite_to_tuple(union)
if rw_union is not None:
return rw_union
try:
for ancestor in inspect.getmro(union.__args__[0]):
if ancestor is not object and all(
issubclass(t, ancestor) for t in union.__args__
):
return ancestor
except (TypeError, AttributeError):
pass
return Any
| RewriteLargeUnion |
python | getsentry__sentry | src/sentry/middleware/integrations/parsers/vercel.py | {
"start": 297,
"end": 527
} | class ____(BaseRequestParser):
provider = "vercel"
webhook_identifier = WebhookProviderIdentifier.VERCEL
def get_response(self) -> HttpResponseBase:
return self.get_response_from_control_silo()
| VercelRequestParser |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-jira/llama_index/tools/jira/base.py | {
"start": 123,
"end": 9783
} | class ____(BaseToolSpec):
"""Atlassian Jira Tool Spec."""
spec_functions = [
"jira_issues_query",
"jira_issue_query",
"jira_comments_query",
"jira_all_projects",
]
def __init__(
self,
email: Optional[str] = None,
api_token: Optional[str] = None,
server_url: Optional[str] = None,
) -> None:
"""Initialize the Atlassian Jira tool spec."""
from jira import JIRA
if email and api_token and server_url:
self.jira = JIRA(
basic_auth=(email, api_token),
server=server_url,
)
else:
raise Exception("Error: Please provide Jira api credentials to continue")
def jira_all_projects(self) -> dict:
"""
Retrieve all projects from the Atlassian Jira account.
This method fetches a list of projects from Jira and returns them in a structured
format, including the project ID, key, and name. If an error occurs during
retrieval, an error message is returned.
Returns:
dict: A dictionary containing:
- 'error' (bool): Indicates whether the request was successful.
- 'message' (str): A description of the result.
- 'projects' (list, optional): A list of projects with their details
(ID, key, name) if retrieval is successful.
"""
try:
projects = self.jira.projects()
if projects:
return {
"error": False,
"message": "All Projects from the account",
"projects": [
{"id": project.id, "key": project.key, "name": project.name}
for project in projects
],
}
except Exception:
pass
return {"error": True, "message": "Unable to fetch projects"}
def jira_comments_query(
self, issue_key: str, author_email: Optional[str] = None
) -> dict:
"""
Retrieve all comments for a given Jira issue, optionally filtering by the author's email.
This function fetches comments from a specified Jira issue and returns them as a structured
JSON response. If an `author_email` is provided, only comments from that specific author
will be included.
Args:
issue_key (str): The Jira issue key for which to retrieve comments.
author_email (str, Optional): filters comments by the author's email.
Returns:
dict: A dictionary containing:
- 'error' (bool): Indicates whether the request was successful.
- 'message' (str): A descriptive message about the result.
- 'comments' (list, optional): A list of comments, where each comment includes:
- 'id' (str): The unique identifier of the comment.
- 'author' (str): The display name of the comment's author.
- 'author_email' (str): The author's email address.
- 'body' (str): The content of the comment.
- 'created_at' (str): The timestamp when the comment was created.
- 'updated_at' (str): The timestamp when the comment was last updated.
"""
error = False
try:
issue = self.jira.issue(issue_key)
all_comments = list(issue.fields.comment.comments)
filtered_results = []
for comment in all_comments:
if (
author_email is not None
and author_email not in comment.author.emailAddress
):
continue
filtered_results.append(
{
"id": comment.id,
"author": comment.author.displayName,
"author_email": comment.author.emailAddress,
"body": comment.body,
"created_at": comment.created,
"updated_at": comment.updated,
}
)
message = f'All the comments in the issue key "{issue_key}"'
except Exception:
error = True
message = "Unable to fetch comments due to some error"
response = {"error": error, "message": message}
if error is False:
response["comments"] = filtered_results
return response
def jira_issue_query(
self, issue_key: str, just_payload: bool = False
) -> Union[None, dict]:
"""
Retrieves detailed information about a specific Jira issue.
This method fetches issue details such as summary, description, type, project, priority, status,
reporter, assignee, labels, and timestamps. The response structure can be adjusted using the
`just_payload` flag.
Args:
issue_key (str): The unique key or ticket number of the Jira issue.
just_payload (bool, optional): If True, returns only the issue payload without the response
metadata. Defaults to False.
Returns:
Union[None, dict]: A dictionary containing issue details if found, or an error response if the issue
cannot be retrieved.
Example:
> jira_client.load_issue("JIRA-123", just_payload=True)
{
'key': 'JIRA-123',
'summary': 'Fix login bug',
'description': 'Users unable to log in under certain conditions...',
'type': 'Bug',
'project_name': 'Web App',
'priority': 'High',
'status': 'In Progress',
'reporter': 'John Doe',
'reporter_email': 'john.doe@example.com',
'labels': ['authentication', 'urgent'],
'created_at': '2024-02-01T10:15:30.000Z',
'updated_at': '2024-02-02T12:20:45.000Z',
'assignee': 'Jane Smith',
'assignee_email': 'jane.smith@example.com'
}
"""
error = False
try:
issue = self.jira.issue(issue_key)
payload = {
"key": issue.key,
"summary": issue.fields.summary,
"description": issue.fields.description,
"type": issue.fields.issuetype.name,
"project_name": issue.fields.project.name,
"priority": issue.fields.priority.name,
"status": issue.fields.status.name,
"reporter": issue.fields.reporter.displayName
if issue.fields.reporter
else None,
"reporter_email": issue.fields.reporter.emailAddress
if issue.fields.reporter
else None,
"labels": issue.fields.labels,
"created_at": issue.fields.created,
"updated_at": issue.fields.updated,
"assignee": issue.fields.assignee.displayName
if issue.fields.assignee
else None,
"assignee_email": issue.fields.assignee.emailAddress
if issue.fields.assignee
else None,
}
message = f"Details of the issue: {issue.key}"
except Exception:
error = True
message = "Unable to fetch issue due to some error"
if error is False and just_payload:
return payload
response = {"error": error, "message": message}
if error is False:
response["result"] = payload
return response
def jira_issues_query(self, keyword: str, max_results: int = 10) -> dict:
"""
Search for Jira issues containing a specific keyword.
This function searches for Jira issues where the specified `keyword` appears in the summary, description, or comments.
The results are sorted by creation date in descending order.
Args:
keyword (str): The keyword to search for within issue summaries, descriptions, or comments.
max_results (int, optional): The maximum number of issues to return. Defaults to 10. If set higher than 100, it will be limited to 100.
Returns:
dict: A dictionary with the following structure:
- 'error' (bool): Indicates if an error occurred during the fetch operation.
- 'message' (str): Describes the outcome of the operation.
- 'results' (list, optional): A list of issues matching the search criteria, present only if no error occurred.
"""
error = False
max_results = min(max_results, 100)
# if custom_query is not None:
# jql = custom_query
# else:
jql = f'summary ~ "{keyword}" or description ~ "{keyword}" or text ~ "{keyword}" order by created desc'
try:
issues = [
self.jira_issue_query(issue.key, just_payload=True)
for issue in self.jira.search_issues(jql, maxResults=max_results)
]
message = "All the issues with specific matching conditions"
except Exception:
error = True
message = "Unable to fetch issue due to some error"
response = {"error": error, "message": message}
if error is False:
response["results"] = issues
return response
| JiraToolSpec |
python | pypa__setuptools | pkg_resources/__init__.py | {
"start": 9827,
"end": 10502
} | class ____(ResolutionError):
"""A requested distribution was not found"""
_template = (
"The '{self.req}' distribution was not found "
"and is required by {self.requirers_str}"
)
@property
def req(self) -> Requirement:
return self.args[0]
@property
def requirers(self) -> set[str] | None:
return self.args[1]
@property
def requirers_str(self):
if not self.requirers:
return 'the application'
return ', '.join(self.requirers)
def report(self):
return self._template.format(**locals())
def __str__(self) -> str:
return self.report()
| DistributionNotFound |
python | kamyu104__LeetCode-Solutions | Python/design-in-memory-file-system.py | {
"start": 439,
"end": 1884
} | class ____(object):
def __init__(self):
self.__root = TrieNode()
def ls(self, path):
"""
:type path: str
:rtype: List[str]
"""
curr = self.__getNode(path)
if curr.is_file:
return [self.__split(path, '/')[-1]]
return sorted(curr.children.keys())
def mkdir(self, path):
"""
:type path: str
:rtype: void
"""
curr = self.__putNode(path)
curr.is_file = False
def addContentToFile(self, filePath, content):
"""
:type filePath: str
:type content: str
:rtype: void
"""
curr = self.__putNode(filePath)
curr.is_file = True
curr.content += content
def readContentFromFile(self, filePath):
"""
:type filePath: str
:rtype: str
"""
return self.__getNode(filePath).content
def __getNode(self, path):
curr = self.__root
for s in self.__split(path, '/'):
curr = curr.children[s]
return curr
def __putNode(self, path):
curr = self.__root
for s in self.__split(path, '/'):
if s not in curr.children:
curr.children[s] = TrieNode()
curr = curr.children[s]
return curr
def __split(self, path, delim):
if path == '/':
return []
return path.split('/')[1:]
| FileSystem |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 26912,
"end": 27311
} | class ____(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the requested resource is no longer available
at the server and no forwarding address is known.
code: 410, title: Gone
"""
code = 410
title = 'Gone'
explanation = (
'This resource is no longer available. No forwarding '
'address is given.'
)
| HTTPGone |
python | kamyu104__LeetCode-Solutions | Python/split-array-with-minimum-difference.py | {
"start": 44,
"end": 625
} | class ____(object):
def splitArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, i = 0, 0
while i+1 < len(nums) and nums[i] < nums[i+1]:
left += nums[i]
i += 1
right, j = 0, len(nums)-1
while j-1 >= 0 and nums[j] < nums[j-1]:
right += nums[j]
j -= 1
if j-i+1 >= 3:
return -1
if j-i+1 == 2:
return abs((right+nums[j])-(left+nums[i]))
return min(abs(right-(left+nums[i])), abs((right+nums[j])-left))
| Solution |
python | astropy__astropy | astropy/time/formats.py | {
"start": 78732,
"end": 78945
} | class ____(TimeEpochDateString):
"""Julian Epoch year as string value(s) like 'J2000.0'."""
name = "jyear_str"
epoch_to_jd = "epj2jd"
jd_to_epoch = "epj"
epoch_prefix = "J"
| TimeJulianEpochString |
python | django__django | tests/queries/models.py | {
"start": 12919,
"end": 13002
} | class ____(models.Model):
f1 = models.TextField()
f2 = models.TextField()
| FK1 |
python | doocs__leetcode | solution/1500-1599/1556.Thousand Separator/Solution.py | {
"start": 0,
"end": 359
} | class ____:
def thousandSeparator(self, n: int) -> str:
cnt = 0
ans = []
while 1:
n, v = divmod(n, 10)
ans.append(str(v))
cnt += 1
if n == 0:
break
if cnt == 3:
ans.append('.')
cnt = 0
return ''.join(ans[::-1])
| Solution |
python | astropy__astropy | astropy/units/tests/test_structured.py | {
"start": 1228,
"end": 1512
} | class ____(StructuredTestBase):
@classmethod
def setup_class(cls):
super().setup_class()
cls.pv_unit = StructuredUnit((cls.p_unit, cls.v_unit), ("p", "v"))
cls.pv_t_unit = StructuredUnit((cls.pv_unit, cls.t_unit), ("pv", "t"))
| StructuredTestBaseWithUnits |
python | pandas-dev__pandas | pandas/io/formats/info.py | {
"start": 21958,
"end": 23390
} | class ____(_TableBuilderAbstract):
"""
Abstract builder for dataframe info table.
Parameters
----------
info : DataFrameInfo.
Instance of DataFrameInfo.
"""
def __init__(self, *, info: DataFrameInfo) -> None:
self.info: DataFrameInfo = info
def get_lines(self) -> list[str]:
self._lines = []
if self.col_count == 0:
self._fill_empty_info()
else:
self._fill_non_empty_info()
return self._lines
def _fill_empty_info(self) -> None:
"""Add lines to the info table, pertaining to empty dataframe."""
self.add_object_type_line()
self.add_index_range_line()
self._lines.append(f"Empty {type(self.data).__name__}\n")
@abstractmethod
def _fill_non_empty_info(self) -> None:
"""Add lines to the info table, pertaining to non-empty dataframe."""
@property
def data(self) -> DataFrame:
"""DataFrame."""
return self.info.data
@property
def ids(self) -> Index:
"""Dataframe columns."""
return self.info.ids
@property
def col_count(self) -> int:
"""Number of dataframe columns to be summarized."""
return self.info.col_count
def add_memory_usage_line(self) -> None:
"""Add line containing memory usage."""
self._lines.append(f"memory usage: {self.memory_usage_string}")
| _DataFrameTableBuilder |
python | Textualize__textual | src/textual/scrollbar.py | {
"start": 870,
"end": 986
} | class ____(ScrollMessage, verbose=True):
"""Message sent when clicking below handle."""
@rich.repr.auto
| ScrollDown |
python | getsentry__sentry | src/sentry/auth/provider.py | {
"start": 1492,
"end": 5436
} | class ____(PipelineProvider["AuthHelper"], abc.ABC):
"""
A provider indicates how authenticate should happen for a given service,
including its configuration and basic identity management.
"""
is_partner = False
requires_refresh = True
is_saml = False
# All auth providers by default require the sso-basic feature
required_feature = "organizations:sso-basic"
def __init__(self, **config: Any) -> None:
super().__init__()
self.config = config
self.logger = logging.getLogger(f"sentry.auth.{self.key}")
def get_configure_view(
self,
) -> Callable[[HttpRequest, RpcOrganization, RpcAuthProvider], DeferredResponse | str]:
"""Return the view which handles configuration (post-setup)."""
return lambda request, organization, auth_provider: ""
def get_auth_pipeline(self) -> Sequence[AuthView]:
"""
Return a list of AuthView instances representing the authentication
pipeline for this provider.
"""
raise NotImplementedError
def get_setup_pipeline(self) -> Sequence[AuthView]:
"""
Return a list of AuthView instances representing the initial setup
pipeline for this provider.
Defaults to the defined authentication pipeline.
"""
return self.get_auth_pipeline()
def get_pipeline_views(self) -> Sequence[AuthView]:
return self.get_auth_pipeline()
# TODO: state should be Mapping[str, Any]?
# Must be reconciled with sentry.pipeline.base.Pipeline.fetch_state
def build_config(self, state: Any) -> dict[str, Any]:
"""
Return a mapping containing provider configuration.
- ``state`` is the resulting data captured by the pipeline
"""
raise NotImplementedError
def build_identity(self, state: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Return a mapping containing the identity information.
- ``state`` is the resulting data captured by the pipeline
>>> {
>>> "id": "foo@example.com",
>>> "email": "foo@example.com",
>>> "name": "Foo Bar",
>>> "email_verified": True,
>>> }
The ``email`` and ``id`` keys are required, ``name`` is optional.
The ``id`` may be passed in as a ``MigratingIdentityId`` should the
the id key be migrating from one value to another and have multiple
lookup values.
The provider is trustable and the email address is verified by the provider,
the ``email_verified`` attribute should be set to ``True``.
If the identity can not be constructed an ``IdentityNotValid`` error
should be raised.
"""
raise NotImplementedError
def update_identity(
self, new_data: dict[str, Any], current_data: Mapping[str, Any]
) -> Mapping[str, Any]:
"""
When re-authenticating with a provider, the identity data may need to
be mutated based on the previous state. An example of this is Google,
which will not return a `refresh_token` unless the user explicitly
goes through an approval process.
Return the new state which should be used for an identity.
"""
return new_data
def refresh_identity(self, auth_identity: AuthIdentity) -> None:
"""
Updates the AuthIdentity with any changes from upstream. The primary
example of a change would be signalling this identity is no longer
valid.
If the identity is no longer valid an ``IdentityNotValid`` error should
be raised.
"""
raise NotImplementedError
def can_use_scim(self, organization_id: int, user: User) -> bool:
"""
Controls whether or not a provider can have SCIM enabled to manage users.
By default we have this on for all providers.
"""
return True
| Provider |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.