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
|
run-llama__llama_index
|
llama-index-core/llama_index/core/llms/mock.py
|
{
"start": 2945,
"end": 3151
}
|
class ____(MockLLM):
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
yield from []
|
MockLLMWithNonyieldingChatStream
|
python
|
Lightning-AI__lightning
|
src/lightning/pytorch/utilities/model_summary/model_summary.py
|
{
"start": 1460,
"end": 4957
}
|
class ____:
"""Summary class for a single layer in a :class:`~lightning.pytorch.core.LightningModule`. It collects the
following information:
- Type of the layer (e.g. Linear, BatchNorm1d, ...)
- Input shape
- Output shape
- Number of parameters
The input and output shapes are only known after the example input array was
passed through the model.
Example::
>>> model = torch.nn.Conv2d(3, 8, 3)
>>> summary = LayerSummary(model)
>>> summary.num_parameters
224
>>> summary.layer_type
'Conv2d'
>>> output = model(torch.rand(1, 3, 5, 5))
>>> summary.in_size
[1, 3, 5, 5]
>>> summary.out_size
[1, 8, 3, 3]
Args:
module: A module to summarize
"""
def __init__(self, module: nn.Module) -> None:
super().__init__()
self._module = module
self._hook_handle = self._register_hook()
self._in_size: Optional[Union[str, list]] = None
self._out_size: Optional[Union[str, list]] = None
def __del__(self) -> None:
self.detach_hook()
def _register_hook(self) -> Optional[RemovableHandle]:
"""Registers a hook on the module that computes the input- and output size(s) on the first forward pass. If the
hook is called, it will remove itself from the from the module, meaning that recursive models will only record
their input- and output shapes once. Registering hooks on :class:`~torch.jit.ScriptModule` is not supported.
Return:
A handle for the installed hook, or ``None`` if registering the hook is not possible.
"""
def hook(_: nn.Module, inp: Any, out: Any) -> None:
if len(inp) == 1:
inp = inp[0]
self._in_size = parse_batch_shape(inp)
self._out_size = parse_batch_shape(out)
assert self._hook_handle is not None
self._hook_handle.remove()
def hook_with_kwargs(_: nn.Module, args: Any, kwargs: Any, out: Any) -> None:
# We can't write them in the same function, since the forward hook
# uses positional arguments.
inp = (*args, *kwargs.values()) if kwargs is not None else args
hook(_, inp, out)
handle = None
if not isinstance(self._module, torch.jit.ScriptModule):
handle = self._module.register_forward_hook(hook_with_kwargs, with_kwargs=True)
return handle
def detach_hook(self) -> None:
"""Removes the forward hook if it was not already removed in the forward pass.
Will be called after the summary is created.
"""
if self._hook_handle is not None:
self._hook_handle.remove()
@property
def in_size(self) -> Union[str, list]:
return self._in_size or UNKNOWN_SIZE
@property
def out_size(self) -> Union[str, list]:
return self._out_size or UNKNOWN_SIZE
@property
def layer_type(self) -> str:
"""Returns the class name of the module."""
return str(self._module.__class__.__name__)
@property
def num_parameters(self) -> int:
"""Returns the number of parameters in this module."""
return sum(p.numel() if not _tensor_has_shape(p) else 0 for p in self._module.parameters())
@property
def training(self) -> bool:
"""Returns whether the module is in training mode."""
return self._module.training
|
LayerSummary
|
python
|
numba__numba
|
numba/tests/test_gdb_bindings.py
|
{
"start": 3918,
"end": 6897
}
|
class ____(TestCase):
"""
This test class is used to generate tests which will run the test cases
defined in TestGdbBindImpls in isolated subprocesses, this is for safety
in case something goes awry.
"""
# test mutates env
_numba_parallel_test_ = False
_DEBUG = True
def run_cmd(self, cmdline, env, kill_is_ok=False):
popen = subprocess.Popen(cmdline,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
shell=True)
# finish in 20s or kill it, there's no work being done
def kill():
popen.stdout.flush()
popen.stderr.flush()
popen.kill()
timeout = threading.Timer(20., kill)
try:
timeout.start()
out, err = popen.communicate()
retcode = popen.returncode
if retcode != 0:
raise AssertionError(
"process failed with code %s: "
"stderr follows\n%s\n"
"stdout :%s" % (retcode, err.decode(), out.decode()))
return out.decode(), err.decode()
finally:
timeout.cancel()
return None, None
def run_test_in_separate_process(self, test, **kwargs):
env_copy = os.environ.copy()
env_copy['NUMBA_OPT'] = '1'
# Set GDB_TEST to permit the execution of tests decorated with
# @needs_gdb_harness
env_copy['GDB_TEST'] = '1'
cmdline = [sys.executable, "-m", "numba.runtests", test]
return self.run_cmd(' '.join(cmdline), env_copy, **kwargs)
@classmethod
def _inject(cls, name):
themod = TestGdbBindImpls.__module__
thecls = TestGdbBindImpls.__name__
# strip impl
assert name.endswith('_impl')
methname = name.replace('_impl', '')
injected_method = '%s.%s.%s' % (themod, thecls, name)
def test_template(self):
o, e = self.run_test_in_separate_process(injected_method)
dbgmsg = f'\nSTDOUT={o}\nSTDERR={e}\n'
# If the test was skipped in the subprocess, then mark this as a
# skipped test.
m = re.search(r"\.\.\. skipped '(.*?)'", e)
if m is not None:
self.skipTest(m.group(1))
self.assertIn('GNU gdb', o, msg=dbgmsg)
self.assertIn('OK', e, msg=dbgmsg)
self.assertNotIn('FAIL', e, msg=dbgmsg)
self.assertNotIn('ERROR', e, msg=dbgmsg)
if 'quick' in name:
setattr(cls, methname, test_template)
else:
setattr(cls, methname, long_running(test_template))
@classmethod
def generate(cls):
for name in dir(TestGdbBindImpls):
if name.startswith('test_gdb'):
cls._inject(name)
TestGdbBinding.generate()
@not_arm
@unix_only
@needs_gdb
|
TestGdbBinding
|
python
|
huggingface__transformers
|
src/transformers/models/rwkv/modeling_rwkv.py
|
{
"start": 18145,
"end": 18826
}
|
class ____(ModelOutput):
r"""
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
avoid providing the old `input_ids`.
"""
last_hidden_state: Optional[torch.FloatTensor] = None
state: Optional[list[torch.FloatTensor]] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for causal language model (or autoregressive) outputs.
"""
)
|
RwkvOutput
|
python
|
spyder-ide__spyder
|
spyder/utils/syntaxhighlighters.py
|
{
"start": 72178,
"end": 73899
}
|
class ____(BaseWebSH):
"""HTML Syntax Highlighter"""
PROG = re.compile(make_html_patterns(), re.S)
# =============================================================================
# Markdown highlighter
# =============================================================================
def make_md_patterns():
h1 = '^#[^#]+'
h2 = '^##[^#]+'
h3 = '^###[^#]+'
h4 = '^####[^#]+'
h5 = '^#####[^#]+'
h6 = '^######[^#]+'
titles = any('title', [h1, h2, h3, h4, h5, h6])
html_tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
html_symbols = '&[^; ].+;'
html_comment = '<!--.+-->'
strikethrough = any('strikethrough', [r'(~~)(.*?)~~'])
strong = any('strong', [r'(\*\*)(.*?)\*\*'])
italic = r'(__)(.*?)__'
emphasis = r'(//)(.*?)//'
italic = any('italic', [italic, emphasis])
# links - (links) after [] or links after []:
link_html = (r'(?<=(\]\())[^\(\)]*(?=\))|'
'(<https?://[^>]+>)|'
'(<[^ >]+@[^ >]+>)')
# link/image references - [] or ![]
link = r'!?\[[^\[\]]*\]'
links = any('link', [link_html, link])
# blockquotes and lists - > or - or * or 0.
blockquotes = (r'(^>+.*)'
r'|(^(?: |\t)*[0-9]+\. )'
r'|(^(?: |\t)*- )'
r'|(^(?: |\t)*\* )')
# code
code = any('code', ['^`{3,}.*$'])
inline_code = any('inline_code', ['`[^`]*`'])
# math - $$
math = any('number', [r'^(?:\${2}).*$', html_symbols])
comment = any('comment', [blockquotes, html_comment])
return '|'.join([titles, comment, html_tags, math, links, italic, strong,
strikethrough, code, inline_code])
|
HtmlSH
|
python
|
pandas-dev__pandas
|
pandas/errors/__init__.py
|
{
"start": 9100,
"end": 10949
}
|
class ____(Warning):
"""
Warning raised when reading different dtypes in a column from a file.
Raised for a dtype incompatibility. This can happen whenever `read_csv`
or `read_table` encounter non-uniform dtypes in a column(s) of a given
CSV file.
See Also
--------
read_csv : Read CSV (comma-separated) file into a DataFrame.
read_table : Read general delimited file into a DataFrame.
Notes
-----
This warning is issued when dealing with larger files because the dtype
checking happens per chunk read.
Despite the warning, the CSV file is read with mixed types in a single
column which will be an object type. See the examples below to better
understand this issue.
Examples
--------
This example creates and reads a large CSV file with a column that contains
`int` and `str`.
>>> df = pd.DataFrame(
... {
... "a": (["1"] * 100000 + ["X"] * 100000 + ["1"] * 100000),
... "b": ["b"] * 300000,
... }
... ) # doctest: +SKIP
>>> df.to_csv("test.csv", index=False) # doctest: +SKIP
>>> df2 = pd.read_csv("test.csv") # doctest: +SKIP
... # DtypeWarning: Columns (0: a) have mixed types
Important to notice that ``df2`` will contain both `str` and `int` for the
same input, '1'.
>>> df2.iloc[262140, 0] # doctest: +SKIP
'1'
>>> type(df2.iloc[262140, 0]) # doctest: +SKIP
<class 'str'>
>>> df2.iloc[262150, 0] # doctest: +SKIP
1
>>> type(df2.iloc[262150, 0]) # doctest: +SKIP
<class 'int'>
One way to solve this issue is using the `dtype` parameter in the
`read_csv` and `read_table` functions to explicit the conversion:
>>> df2 = pd.read_csv("test.csv", sep=",", dtype={"a": str}) # doctest: +SKIP
No warning was issued.
"""
|
DtypeWarning
|
python
|
python-excel__xlwt
|
xlwt/antlr.py
|
{
"start": 76725,
"end": 77763
}
|
class ____(object):
def __init__(self):
self.root = None ### current root of tree
self.child = None ### current child to which siblings are added
### Make sure that child is the last sibling */
def advanceChildToEnd(self):
if self.child:
while self.child.getNextSibling():
self.child = self.child.getNextSibling()
### Copy an ASTPair. Don't call it clone() because we want type-safety */
def copy(self):
tmp = ASTPair()
tmp.root = self.root
tmp.child = self.child
return tmp
def toString(self):
r = ifelse(not root,"null",self.root.getText())
c = ifelse(not child,"null",self.child.getText())
return "[%s,%s]" % (r,c)
__str__ = toString
__repr__ = toString
###xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx###
### ASTFactory ###
###xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx###
|
ASTPair
|
python
|
django__django
|
tests/one_to_one/models.py
|
{
"start": 378,
"end": 674
}
|
class ____(models.Model):
place = models.OneToOneField(Place, models.CASCADE, primary_key=True)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
def __str__(self):
return "%s the restaurant" % self.place.name
|
Restaurant
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/tests/ghostwriter/test_ghostwriter.py
|
{
"start": 2828,
"end": 3546
}
|
class ____(enum.Enum):
a = "value of AnEnum.a"
b = "value of AnEnum.b"
def takes_enum(foo=AnEnum.a):
# This can only fail if we use the default argument to guess
# that any instance of that enum type should be allowed.
assert foo != AnEnum.b
def test_ghostwriter_exploits_arguments_with_enum_defaults():
source_code = ghostwriter.fuzz(takes_enum)
test = get_test_function(source_code)
with pytest.raises(AssertionError):
test()
def timsort(seq: Sequence[int]) -> list[int]:
return sorted(seq)
def non_type_annotation(x: 3): # type: ignore
pass
def annotated_any(x: Any):
pass
space_in_name = type("a name", (type,), {"__init__": lambda self: None})
|
AnEnum
|
python
|
apache__airflow
|
providers/google/tests/unit/google/cloud/hooks/test_cloud_sql.py
|
{
"start": 79975,
"end": 82880
}
|
class ____:
@pytest.mark.asyncio
@mock.patch(HOOK_STR.format("CloudSQLAsyncHook._get_conn"))
async def test_async_get_operation_name_should_execute_successfully(self, mocked_conn, hook_async):
await hook_async.get_operation_name(
operation_name=OPERATION_NAME,
project_id=PROJECT_ID,
session=session,
)
mocked_conn.assert_awaited_once_with(url=OPERATION_URL, session=session)
@pytest.mark.asyncio
@mock.patch(HOOK_STR.format("CloudSQLAsyncHook.get_operation_name"))
async def test_async_get_operation_completed_should_execute_successfully(self, mocked_get, hook_async):
response = aiohttp.ClientResponse(
"get",
URL(OPERATION_URL),
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
traces=[],
loop=mock.Mock(),
session=None,
)
response.status = 200
mocked_get.return_value = response
mocked_get.return_value._headers = {"Authorization": "test-token"}
mocked_get.return_value._body = b'{"status": "DONE"}'
operation = await hook_async.get_operation(operation_name=OPERATION_NAME, project_id=PROJECT_ID)
mocked_get.assert_awaited_once()
assert operation["status"] == "DONE"
@pytest.mark.asyncio
@mock.patch(HOOK_STR.format("CloudSQLAsyncHook.get_operation_name"))
async def test_async_get_operation_running_should_execute_successfully(self, mocked_get, hook_async):
response = aiohttp.ClientResponse(
"get",
URL(OPERATION_URL),
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
traces=[],
loop=mock.Mock(),
session=None,
)
response.status = 200
mocked_get.return_value = response
mocked_get.return_value._headers = {"Authorization": "test-token"}
mocked_get.return_value._body = b'{"status": "RUNNING"}'
operation = await hook_async.get_operation(operation_name=OPERATION_NAME, project_id=PROJECT_ID)
mocked_get.assert_awaited_once()
assert operation["status"] == "RUNNING"
@pytest.mark.asyncio
@mock.patch(HOOK_STR.format("CloudSQLAsyncHook._get_conn"))
async def test_async_get_operation_exception_should_execute_successfully(
self, mocked_get_conn, hook_async
):
"""Assets that the logging is done correctly when CloudSQLAsyncHook raises HttpError"""
mocked_get_conn.side_effect = HttpError(
resp=mock.MagicMock(status=409), content=b"Operation already exists"
)
with pytest.raises(HttpError):
await hook_async.get_operation(operation_name=OPERATION_NAME, project_id=PROJECT_ID)
|
TestCloudSQLAsyncHook
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/typeParams1.py
|
{
"start": 101,
"end": 158
}
|
class ____[T1]: ...
def func1[T1](): ...
T2: str
|
ClassA
|
python
|
run-llama__llama_index
|
llama-index-integrations/llms/llama-index-llms-opea/llama_index/llms/opea/base.py
|
{
"start": 176,
"end": 730
}
|
class ____(OpenAILike):
"""
Adapter for a OPEA LLM.
Examples:
`pip install llama-index-llms-opea`
```python
from llama_index.llms.opea import OPEA
llm = OPEA(
model="meta-llama/Meta-Llama-3.1-8B-Instruct",
api_base="http://localhost:8080/v1",
)
```
"""
is_chat_model: bool = Field(
default=True,
description=LLMMetadata.model_fields["is_chat_model"].description,
)
@classmethod
def class_name(cls) -> str:
return "OPEA"
|
OPEA
|
python
|
huggingface__transformers
|
src/transformers/models/fnet/modeling_fnet.py
|
{
"start": 8135,
"end": 8783
}
|
class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->FNet
|
FNetIntermediate
|
python
|
doocs__leetcode
|
solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/Solution2.py
|
{
"start": 0,
"end": 237
}
|
class ____:
def countKDifference(self, nums: List[int], k: int) -> int:
ans = 0
cnt = Counter()
for num in nums:
ans += cnt[num - k] + cnt[num + k]
cnt[num] += 1
return ans
|
Solution
|
python
|
PrefectHQ__prefect
|
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
|
{
"start": 140226,
"end": 140811
}
|
class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("user_id", "limit", "expiry", "client_mutation_id")
user_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="userId")
limit = sgqlc.types.Field(
sgqlc.types.non_null(RepositoryInteractionLimit), graphql_name="limit"
)
expiry = sgqlc.types.Field(RepositoryInteractionLimitExpiry, graphql_name="expiry")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
|
SetUserInteractionLimitInput
|
python
|
huggingface__transformers
|
tests/models/git/test_processing_git.py
|
{
"start": 876,
"end": 1269
}
|
class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = GitProcessor
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
return tokenizer_class.from_pretrained(
"hf-internal-testing/tiny-random-BertModel", model_input_names=["input_ids", "attention_mask"]
)
|
GitProcessorTest
|
python
|
getsentry__sentry
|
tests/sentry/api/endpoints/test_project_artifact_lookup.py
|
{
"start": 2254,
"end": 26737
}
|
class ____(APITestCase):
def assert_download_matches_file(self, url: str, file_contents: bytes) -> None:
response = self.client.get(url)
file = BytesIO(file_contents)
for chunk in response:
assert file.read(len(chunk)) == chunk
def create_archive(self, fields, files, dist=None):
manifest = dict(
fields, files={filename: {"url": f"fake://{filename}"} for filename in files}
)
buffer = BytesIO()
with zipfile.ZipFile(buffer, mode="w") as zf:
zf.writestr("manifest.json", orjson.dumps(manifest).decode())
for filename, content in files.items():
zf.writestr(filename, content)
buffer.seek(0)
name = f"release-artifacts-{uuid.uuid4().hex}.zip"
file_ = File.objects.create(name=name, type="release.bundle")
file_.putfile(buffer)
file_.update(timestamp=datetime(2021, 6, 11, 9, 13, 1, 317902, tzinfo=timezone.utc))
return (update_artifact_index(self.release, dist, file_), buffer.getvalue())
def test_query_by_debug_ids(self) -> None:
debug_id_a = "aaaaaaaa-0000-0000-0000-000000000000"
debug_id_b = "bbbbbbbb-0000-0000-0000-000000000000"
file_ab = make_compressed_zip_file(
{
"path/in/zip/a": {
"url": "~/path/to/app.js",
"type": "source_map",
"content": b"foo_id",
"headers": {
"debug-id": debug_id_a,
},
},
"path/in/zip/b": {
"url": "~/path/to/app.js",
"type": "source_map",
"content": b"bar_id",
"headers": {
"debug-id": debug_id_b,
},
},
},
)
upload_bundle(file_ab, self.project)
debug_id_c = "cccccccc-0000-0000-0000-000000000000"
file_c = make_compressed_zip_file(
{
"path/in/zip/c": {
"url": "~/path/to/app.js",
"type": "source_map",
"content": b"baz_id",
"headers": {
"debug-id": debug_id_c,
},
},
},
)
upload_bundle(file_c, self.project)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
# query by one debug-id
response = self.client.get(f"{url}?debug_id={debug_id_a}").json()
assert len(response) == 1
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], file_ab)
# query by another debug-id pointing to the same bundle
response = self.client.get(f"{url}?debug_id={debug_id_b}").json()
assert len(response) == 1
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], file_ab)
# query by another debug-id pointing to different bundles
response = self.client.get(f"{url}?debug_id={debug_id_c}").json()
assert len(response) == 1
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], file_c)
def test_query_by_url(self) -> None:
debug_id_a = "aaaaaaaa-0000-0000-0000-000000000000"
dist = self.release.add_dist("whatever")
file_a = make_compressed_zip_file(
{
"path/in/zip": {
"url": "~/path/to/app.js",
"type": "source_map",
"content": b"foo_url",
"headers": {
"debug-id": debug_id_a,
},
},
},
)
upload_bundle(file_a, self.project, self.release.version, dist.name)
file_b = make_compressed_zip_file(
{
"path/in/zip_a": {
"url": "~/path/to/app.js",
"type": "source_map",
"content": b"foo_url",
},
"path/in/zip_b": {
"url": "~/path/to/other/app.js",
"type": "source_map",
"content": b"bar_url",
},
},
)
upload_bundle(file_b, self.project, self.release.version, dist.name)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
# query by url that is in both files, so we get both files
response = self.client.get(
f"{url}?release={self.release.version}&dist={dist.name}&url=path/to/app"
).json()
assert len(response) == 2
assert response[0]["type"] == "bundle"
assert response[1]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], file_a)
self.assert_download_matches_file(response[1]["url"], file_b)
# query by both debug-id and url with overlapping bundles
response = self.client.get(
f"{url}?release={self.release.version}&dist={dist.name}&debug_id={debug_id_a}&url=path/to/app"
).json()
assert len(response) == 1
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], file_a)
def test_query_by_url_from_releasefiles(self) -> None:
file_headers = {"Sourcemap": "application.js.map"}
file = make_file("application.js", b"wat", "release.file", file_headers)
ReleaseFile.objects.create(
organization_id=self.project.organization_id,
release_id=self.release.id,
file=file,
name="http://example.com/application.js",
)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
response = self.client.get(
f"{url}?release={self.release.version}&url=application.js"
).json()
assert len(response) == 1
assert response[0]["type"] == "file"
assert response[0]["abs_path"] == "http://example.com/application.js"
assert response[0]["headers"] == file_headers
self.assert_download_matches_file(response[0]["url"], b"wat")
def test_query_by_url_from_legacy_bundle(self) -> None:
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
assert read_artifact_index(self.release, None) is None
archive1, archive1_file = self.create_archive(
fields={},
files={
"foo": "foo1",
"bar": "bar1",
},
)
assert read_artifact_index(self.release, None) == {
"files": {
"fake://foo": {
"archive_ident": archive1.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "foo",
"sha1": "18a16d4530763ef43321d306c9f6c59ffed33072",
"size": 4,
},
"fake://bar": {
"archive_ident": archive1.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "bar",
"sha1": "763675d6a1d8d0a3a28deca62bb68abd8baf86f3",
"size": 4,
},
},
}
# Should download 1 archives as both files are within a single archive
response = self.client.get(f"{url}?release={self.release.version}&url=foo&url=bar").json()
assert len(response) == 1
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], archive1_file)
# Override `bar` file inside the index. It will now have different `sha1`` and different `archive_ident` as it comes from other archive.
archive2, archive2_file = self.create_archive(
fields={},
files={
"bar": "BAR1",
},
)
assert read_artifact_index(self.release, None) == {
"files": {
"fake://foo": {
"archive_ident": archive1.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "foo",
"sha1": "18a16d4530763ef43321d306c9f6c59ffed33072",
"size": 4,
},
"fake://bar": {
"archive_ident": archive2.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "bar",
"sha1": "7f9353c7b307875542883ba558a1692706fcad33",
"size": 4,
},
},
}
response = self.client.get(f"{url}?release={self.release.version}&url=foo").json()
assert len(response) == 2
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], archive1_file)
assert response[1]["type"] == "bundle"
self.assert_download_matches_file(response[1]["url"], archive2_file)
response = self.client.get(f"{url}?release={self.release.version}&url=bar").json()
assert len(response) == 2
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], archive1_file)
assert response[1]["type"] == "bundle"
self.assert_download_matches_file(response[1]["url"], archive2_file)
def test_query_by_url_and_dist_from_legacy_bundle(self) -> None:
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
dist = self.release.add_dist("foo")
archive1, archive1_file = self.create_archive(
fields={},
files={
"foo": "foo2",
"bar": "bar2",
},
dist=dist,
)
# No index for dist-less requests.
assert read_artifact_index(self.release, None) is None
assert read_artifact_index(self.release, dist) == {
"files": {
"fake://foo": {
"archive_ident": archive1.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "foo",
"sha1": "aaadd94977b8fbf3f6fb09fc3bbbc9edbdfa8427",
"size": 4,
},
"fake://bar": {
"archive_ident": archive1.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "bar",
"sha1": "033c4846b506a4a48e32cdf54515c91d3499adb3",
"size": 4,
},
},
}
# Should download 1 archives as both files are within a single archive
response = self.client.get(
f"{url}?release={self.release.version}&url=foo&url=bar&dist=foo"
).json()
assert len(response) == 1
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], archive1_file)
# Override `bar` file inside the index. It will now have different `sha1`` and different `archive_ident` as it comes from other archive.
archive2, archive2_file = self.create_archive(
fields={},
files={
"bar": "BAR2",
},
dist=dist,
)
assert read_artifact_index(self.release, dist) == {
"files": {
"fake://foo": {
"archive_ident": archive1.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "foo",
"sha1": "aaadd94977b8fbf3f6fb09fc3bbbc9edbdfa8427",
"size": 4,
},
"fake://bar": {
"archive_ident": archive2.ident,
"date_created": "2021-06-11T09:13:01.317902Z",
"filename": "bar",
"sha1": "528c5563f06a1e98954d17d365a219b68dd93baf",
"size": 4,
},
},
}
response = self.client.get(
f"{url}?release={self.release.version}&dist={dist.name}&url=foo"
).json()
assert len(response) == 2
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], archive1_file)
assert response[1]["type"] == "bundle"
self.assert_download_matches_file(response[1]["url"], archive2_file)
# Should download 2 archives as they have different `archive_ident`
response = self.client.get(
f"{url}?release={self.release.version}&dist={dist.name}&url=bar"
).json()
assert len(response) == 2
assert response[0]["type"] == "bundle"
self.assert_download_matches_file(response[0]["url"], archive1_file)
assert response[1]["type"] == "bundle"
self.assert_download_matches_file(response[1]["url"], archive2_file)
@freeze_time("2023-05-23 10:00:00")
def test_renewal_with_debug_id(self) -> None:
for days_before, expected_date_added, debug_id in (
(
2,
datetime.now(tz=timezone.utc) - timedelta(days=2),
"2432d9ad-fe87-4f77-938d-50cc9b2b2e2a",
),
(35, datetime.now(tz=timezone.utc), "ef88bc3e-d334-4809-9723-5c5dbc8bd4e9"),
):
file_zip = make_compressed_zip_file(
{
"path/in/zip/c": {
"url": "~/path/to/app.js",
"type": "source_map",
"content": b"baz_renew",
"headers": {
"debug-id": debug_id,
},
},
},
)
file = make_file("bundle_c.zip", file_zip)
bundle_id = uuid4()
date_added = datetime.now(tz=timezone.utc) - timedelta(days=days_before)
artifact_bundle = ArtifactBundle.objects.create(
organization_id=self.organization.id,
bundle_id=bundle_id,
file=file,
artifact_count=1,
date_added=date_added,
)
ProjectArtifactBundle.objects.create(
organization_id=self.organization.id,
project_id=self.project.id,
artifact_bundle=artifact_bundle,
date_added=date_added,
)
DebugIdArtifactBundle.objects.create(
organization_id=self.organization.id,
debug_id=debug_id,
artifact_bundle=artifact_bundle,
source_file_type=SourceFileType.SOURCE_MAP.value,
date_added=date_added,
)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
with self.tasks():
self.client.get(f"{url}?debug_id={debug_id}")
assert (
ArtifactBundle.objects.get(id=artifact_bundle.id).date_added == expected_date_added
)
assert (
ProjectArtifactBundle.objects.get(artifact_bundle_id=artifact_bundle.id).date_added
== expected_date_added
)
assert (
DebugIdArtifactBundle.objects.get(artifact_bundle_id=artifact_bundle.id).date_added
== expected_date_added
)
@freeze_time("2023-05-23 10:00:00")
def test_renewal_with_url(self) -> None:
file_zip = make_compressed_zip_file(
{
"path/in/zip/c": {
"url": "~/path/to/app.js",
"type": "source_map",
"content": b"baz_renew",
},
},
)
file = make_file("bundle_c.zip", file_zip)
for days_before, expected_date_added, release in (
(
2,
datetime.now(tz=timezone.utc) - timedelta(days=2),
self.create_release(version="1.0"),
),
(35, datetime.now(tz=timezone.utc), self.create_release(version="2.0")),
):
dist = release.add_dist("android")
bundle_id = uuid4()
date_added = datetime.now(tz=timezone.utc) - timedelta(days=days_before)
artifact_bundle = ArtifactBundle.objects.create(
organization_id=self.organization.id,
bundle_id=bundle_id,
file=file,
artifact_count=1,
date_added=date_added,
)
ProjectArtifactBundle.objects.create(
organization_id=self.organization.id,
project_id=self.project.id,
artifact_bundle=artifact_bundle,
date_added=date_added,
)
ReleaseArtifactBundle.objects.create(
organization_id=self.organization.id,
release_name=release.version,
dist_name=dist.name,
artifact_bundle=artifact_bundle,
date_added=date_added,
)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
with self.tasks():
self.client.get(f"{url}?release={release.version}&dist={dist.name}&url=path/to/app")
assert (
ArtifactBundle.objects.get(id=artifact_bundle.id).date_added == expected_date_added
)
assert (
ProjectArtifactBundle.objects.get(artifact_bundle_id=artifact_bundle.id).date_added
== expected_date_added
)
assert (
ReleaseArtifactBundle.objects.get(artifact_bundle_id=artifact_bundle.id).date_added
== expected_date_added
)
def test_renewal_of_releasefiles(self) -> None:
old_timestamp = datetime.now(tz=timezone.utc) - timedelta(days=45)
file_headers = {"Sourcemap": "application.js.map"}
file = make_file("application.js", b"wat", "release.file", file_headers)
releasefile = ReleaseFile.objects.create(
organization_id=self.project.organization_id,
release_id=self.release.id,
file=file,
name="http://example.com/application.js",
date_accessed=old_timestamp,
)
archive1, archive1_file = self.create_archive(
fields={},
files={
"foo": "foo1",
"bar": "bar1",
},
)
archive1.date_accessed = old_timestamp
archive1.save()
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
response = self.client.get(
f"{url}?release={self.release.version}&url=application.js"
).json()
# the lookup finds both, as the bundle is resolved only by the release
assert len(response) == 2
assert response[0]["type"] == "file"
assert response[1]["type"] == "bundle"
assert ReleaseFile.objects.get(id=releasefile.id).date_accessed > old_timestamp
assert ReleaseFile.objects.get(id=archive1.id).date_accessed > old_timestamp
def test_access_control(self) -> None:
# release file
file_a = make_file("application.js", b"wat", "release.file", {})
release_file = ReleaseFile.objects.create(
organization_id=self.project.organization_id,
release_id=self.release.id,
file=file_a,
name="http://example.com/application.js",
)
# artifact bundle
file_b_zip = make_compressed_zip_file(
{
"path/in/zip/c": {
"url": "~/path/to/app.js",
"type": "minified_source",
"content": b"accezzzz",
"headers": {},
},
},
)
file_b = make_file("bundle_b.zip", file_b_zip)
bundle_id = uuid4()
artifact_bundle = ArtifactBundle.objects.create(
organization_id=self.organization.id,
bundle_id=bundle_id,
file=file_b,
artifact_count=1,
)
ProjectArtifactBundle.objects.create(
organization_id=self.organization.id,
project_id=self.project.id,
artifact_bundle=artifact_bundle,
)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
# `self.user` has access to these files
self.assert_download_matches_file(f"{url}?download=release_file/{release_file.id}", b"wat")
self.assert_download_matches_file(
f"{url}?download=artifact_bundle/{artifact_bundle.id}", file_b_zip
)
# legacy `File`-based download does not work
response = self.client.get(f"{url}?download={file_a.id}")
assert response.status_code == 400
# with another user on a different org
other_user = self.create_user()
other_org = self.create_organization(name="other-org", owner=other_user)
other_project = self.create_project(organization=other_org)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": other_org.slug,
"project_id_or_slug": other_project.slug,
},
)
self.login_as(user=other_user)
# accessing foreign files should not work
response = self.client.get(f"{url}?download=release_file/{release_file.id}")
assert response.status_code == 404
response = self.client.get(f"{url}?download=artifact_bundle/{artifact_bundle.id}")
assert response.status_code == 404
def test_download_invalid_id(self) -> None:
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-artifact-lookup",
kwargs={
"organization_id_or_slug": self.project.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
# Try to download a file with a non-integer ID
response = self.client.get(f"{url}?download=release_file/abcde")
assert response.status_code == 400
|
ArtifactLookupTest
|
python
|
joke2k__faker
|
tests/providers/test_address.py
|
{
"start": 18024,
"end": 20125
}
|
class ____:
"""Test en_BD address provider methods"""
def test_administrative_unit(self, faker, num_samples):
for _ in range(num_samples):
administrative_unit = faker.administrative_unit()
assert isinstance(administrative_unit, str)
assert administrative_unit in EnBdAddressProvider.cities
def test_area_name(self, faker, num_samples):
for _ in range(num_samples):
area_name = faker.area_name()
assert isinstance(area_name, str)
assert area_name in EnBdAddressProvider.area_names
def test_building_name(self, faker, num_samples):
for _ in range(num_samples):
building_name = faker.building_name()
assert isinstance(building_name, str)
assert building_name in EnBdAddressProvider.building_names
def test_building_number(self, faker, num_samples):
for _ in range(num_samples):
building_number = faker.building_number()
assert isinstance(building_number, str)
def test_city_prefix(self, faker, num_samples):
for _ in range(num_samples):
city_prefix = faker.city_prefix()
assert isinstance(city_prefix, str)
assert city_prefix in EnBdAddressProvider.city_prefixes
def test_city(self, faker, num_samples):
for _ in range(num_samples):
city = faker.city()
assert isinstance(city, str)
assert city in EnBdAddressProvider.cities
def test_postcode(self, faker, num_samples):
for _ in range(num_samples):
postcode = faker.postcode()
assert isinstance(postcode, str)
assert re.fullmatch(r"\d{4}", postcode)
def test_secondary_address(self, faker, num_samples):
for _ in range(num_samples):
secondary_address = faker.secondary_address()
assert isinstance(secondary_address, str)
def test_town(self, faker, num_samples):
for _ in range(num_samples):
town = faker.town()
assert isinstance(town, str)
|
TestEnBd
|
python
|
huggingface__transformers
|
src/transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py
|
{
"start": 2214,
"end": 2955
}
|
class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
HunYuanDenseV1RMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
HunYuanDenseV1RMSNorm
|
python
|
walkccc__LeetCode
|
solutions/256. Paint House/256.py
|
{
"start": 0,
"end": 319
}
|
class ____:
def minCost(self, costs: list[list[int]]) -> list[list[int]]:
for i in range(1, len(costs)):
costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])
costs[i][1] += min(costs[i - 1][0], costs[i - 1][2])
costs[i][2] += min(costs[i - 1][0], costs[i - 1][1])
return min(costs[-1])
|
Solution
|
python
|
pytorch__pytorch
|
test/distributed/checkpoint/test_planner.py
|
{
"start": 26129,
"end": 27934
}
|
class ____(TestCase):
@with_temp_dir
def test_strict(self):
original_module = nn.Linear(2, 2)
dcp.save(state_dict={"module": original_module}, checkpoint_id=self.temp_dir)
new_module = nn.Linear(2, 2)
new_module.extra_param = nn.Parameter(torch.randn(2, 2))
dcp.load(
state_dict={"module": new_module},
checkpoint_id=self.temp_dir,
planner=DefaultLoadPlanner(allow_partial_load=True),
)
with self.assertRaisesRegex(CheckpointException, "Missing key in checkpoint"):
dcp.load(
state_dict={"module": new_module},
checkpoint_id=self.temp_dir,
planner=DefaultLoadPlanner(allow_partial_load=False),
)
@with_temp_dir
def test_load_different_sizes_throws(self):
original_module = nn.Linear(2, 2)
dcp.save(state_dict={"module": original_module}, checkpoint_id=self.temp_dir)
new_module = nn.Linear(3, 2)
with self.assertRaisesRegex(CheckpointException, "Size mismatch"):
dcp.load(
state_dict={"module": new_module},
checkpoint_id=self.temp_dir,
planner=DefaultLoadPlanner(),
)
@with_temp_dir
def test_version_key_in_planner_data(self):
original_module = nn.Linear(2, 2)
dcp.save(state_dict={"module": original_module}, checkpoint_id=self.temp_dir)
new_module = nn.Linear(2, 2)
planner = DefaultLoadPlanner()
dcp.load(
state_dict={"module": new_module},
checkpoint_id=self.temp_dir,
planner=planner,
)
self.assertEqual(planner.metadata.version, CURRENT_DCP_VERSION)
if __name__ == "__main__":
run_tests()
|
TestLoadPlanner
|
python
|
charliermarsh__ruff
|
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
|
{
"start": 1144,
"end": 1192
}
|
class ____:
# comment
"""Docstring"""
|
Test
|
python
|
ansible__ansible
|
test/lib/ansible_test/_internal/completion.py
|
{
"start": 4472,
"end": 4966
}
|
class ____(PythonCompletionConfig):
"""Configuration for a POSIX host reachable over SSH."""
def __init__(self, user: str, host: str) -> None:
super().__init__(
name=f'{user}@{host}',
python=','.join(SUPPORTED_PYTHON_VERSIONS),
)
@property
def is_default(self) -> bool:
"""True if the completion entry is only used for defaults, otherwise False."""
return False
@dataclasses.dataclass(frozen=True)
|
PosixSshCompletionConfig
|
python
|
huggingface__transformers
|
src/transformers/models/vit/modeling_vit.py
|
{
"start": 10575,
"end": 11212
}
|
class ____(nn.Module):
"""
The residual connection is defined in ViTLayer instead of here (as is the case with other models), due to the
layernorm applied before each block.
"""
def __init__(self, config: ViTConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
return hidden_states
|
ViTSelfOutput
|
python
|
joblib__joblib
|
benchmarks/bench_compression.py
|
{
"start": 2359,
"end": 8935
}
|
class ____:
"""Protect the underlying fileobj against numerous calls to write
This is achieved by internally keeping a list of small chunks and
only flushing to the backing fileobj if passed a large chunk or
after a threshold on the number of small chunks.
"""
def __init__(self, fileobj, max_buffer_size=10 * 1024**2):
self._fileobj = fileobj
self._buffer = bytearray(max_buffer_size)
self.max_buffer_size = max_buffer_size
self._position = 0
def read(self, n=None):
data = b""
if n is None:
data = self._fileobj.read()
else:
while len(data) < n:
if self._position == 0:
self._buffer = self._fileobj.read(self.max_buffer_size)
elif self._position == self.max_buffer_size:
self._position = 0
continue
next_position = min(
self.max_buffer_size, self._position + n - len(data)
)
data += self._buffer[self._position : next_position]
self._position = next_position
return data
def readline(self):
line = []
while True:
c = self.read(1)
line.append(c)
if c == b"\n":
break
return b"".join(line)
def close(self):
self._fileobj.close()
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
return False
def run_bench():
print(
"% 20s | %10s | % 12s | % 8s | % 9s | % 9s | % 5s"
% (
"Object",
"Compression",
"Buffer",
"Pickler/Unpickler",
"dump time (s)",
"load time (s)",
"Disk used (MB)",
)
)
print("--- | --- | --- | --- | --- | --- | ---")
for oname, obj in objects.items():
# Looping over the objects (array, dict, etc)
if isinstance(obj, np.ndarray):
osize = obj.nbytes / 1e6
else:
osize = sys.getsizeof(obj) / 1e6
for cname, f in compressors.items():
fobj = f[0]
fname = f[1]
fmode = f[2]
fopts = f[3]
# Looping other defined compressors
for bname, buf in bufs.items():
writebuf = buf[0]
readbuf = buf[1]
# Looping other picklers
for pname, p in picklers.items():
pickler = p[0]
unpickler = p[1]
t0 = time.time()
# Now pickling the object in the file
if (
writebuf is not None
and writebuf.__name__ == io.BytesIO.__name__
):
b = writebuf()
p = pickler(b)
p.dump(obj)
with fileobj(fobj, fname, fmode, fopts) as f:
f.write(b.getvalue())
else:
with bufferize(
fileobj(fobj, fname, fmode, fopts), writebuf
) as f:
p = pickler(f)
p.dump(obj)
dtime = time.time() - t0
t0 = time.time()
# Now loading the object from the file
obj_r = None
if readbuf is not None and readbuf.__name__ == io.BytesIO.__name__:
b = readbuf()
with fileobj(fobj, fname, "rb", {}) as f:
b.write(f.read())
b.seek(0)
obj_r = _load(unpickler, fname, b)
else:
with bufferize(fileobj(fobj, fname, "rb", {}), readbuf) as f:
obj_r = _load(unpickler, fname, f)
ltime = time.time() - t0
if isinstance(obj, np.ndarray):
assert (obj == obj_r).all()
else:
assert obj == obj_r
print_line(
"{} ({:.1f}MB)".format(oname, osize),
cname,
bname,
pname,
dtime,
ltime,
"{:.2f}".format(os.path.getsize(fname) / 1e6),
)
# Defining objects used in this bench
DICT_SIZE = int(1e6)
ARRAY_SIZE = int(1e7)
arr = np.random.normal(size=(ARRAY_SIZE))
arr[::2] = 1
# Objects used for testing
objects = OrderedDict(
[
("dict", dict((i, str(i)) for i in range(DICT_SIZE))),
("list", [i for i in range(DICT_SIZE)]),
("array semi-random", arr),
("array random", np.random.normal(size=(ARRAY_SIZE))),
("array ones", np.ones((ARRAY_SIZE))),
]
)
# We test 3 different picklers
picklers = OrderedDict(
[
# Python implementation of Pickler/Unpickler
("Pickle", (_Pickler, _Unpickler)),
# C implementation of Pickler/Unpickler
("cPickle", (Pickler, Unpickler)),
# Joblib Pickler/Unpickler designed for numpy arrays.
("Joblib", (NumpyPickler, NumpyUnpickler)),
]
)
# The list of supported compressors used for testing
compressors = OrderedDict(
[
("No", (open, "/tmp/test_raw", "wb", {})),
("Zlib", (BinaryZlibFile, "/tmp/test_zlib", "wb", {"compresslevel": 3})),
("Gzip", (BinaryGzipFile, "/tmp/test_gzip", "wb", {"compresslevel": 3})),
("Bz2", (bz2.BZ2File, "/tmp/test_bz2", "wb", {"compresslevel": 3})),
(
"Xz",
(
lzma.LZMAFile,
"/tmp/test_xz",
"wb",
{"preset": 3, "check": lzma.CHECK_NONE},
),
),
(
"Lzma",
(
lzma.LZMAFile,
"/tmp/test_lzma",
"wb",
{"preset": 3, "format": lzma.FORMAT_ALONE},
),
),
]
)
# Test 3 buffering strategies
bufs = OrderedDict(
[
("None", (None, None)),
("io.BytesIO", (io.BytesIO, io.BytesIO)),
("io.Buffered", (io.BufferedWriter, io.BufferedReader)),
("PickleBuffered", (PickleBufferedWriter, PickleBufferedReader)),
]
)
if __name__ == "__main__":
run_bench()
|
PickleBufferedReader
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/fastapi/FAST003.py
|
{
"start": 4390,
"end": 4440
}
|
class ____(BaseModel):
my_id: int
|
PydanticParams
|
python
|
lxml__lxml
|
src/lxml/html/soupparser.py
|
{
"start": 3094,
"end": 10197
}
|
class ____:
# Minimal imitation of BeautifulSoup.Tag
def __init__(self, contents):
self.name = 'html'
self.attrs = []
self.contents = contents
def __iter__(self):
return self.contents.__iter__()
def _convert_tree(beautiful_soup_tree, makeelement):
if makeelement is None:
makeelement = html.html_parser.makeelement
# Split the tree into three parts:
# i) everything before the root element: document type
# declaration, comments, processing instructions, whitespace
# ii) the root(s),
# iii) everything after the root: comments, processing
# instructions, whitespace
first_element_idx = last_element_idx = None
html_root = declaration = None
for i, e in enumerate(beautiful_soup_tree):
if isinstance(e, Tag):
if first_element_idx is None:
first_element_idx = i
last_element_idx = i
if html_root is None and e.name and e.name.lower() == 'html':
html_root = e
elif declaration is None and isinstance(e, _DECLARATION_OR_DOCTYPE):
declaration = e
# For a nice, well-formatted document, the variable roots below is
# a list consisting of a single <html> element. However, the document
# may be a soup like '<meta><head><title>Hello</head><body>Hi
# all<\p>'. In this example roots is a list containing meta, head
# and body elements.
if first_element_idx is None:
pre_root = post_root = []
roots = beautiful_soup_tree.contents
else:
pre_root = beautiful_soup_tree.contents[:first_element_idx]
roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1]
post_root = beautiful_soup_tree.contents[last_element_idx+1:]
# Reorganize so that there is one <html> root...
if html_root is not None:
# ... use existing one if possible, ...
i = roots.index(html_root)
html_root.contents = roots[:i] + html_root.contents + roots[i+1:]
else:
# ... otherwise create a new one.
html_root = _PseudoTag(roots)
convert_node = _init_node_converters(makeelement)
# Process pre_root
res_root = convert_node(html_root)
prev = res_root
for e in reversed(pre_root):
converted = convert_node(e)
if converted is not None:
prev.addprevious(converted)
prev = converted
# ditto for post_root
prev = res_root
for e in post_root:
converted = convert_node(e)
if converted is not None:
prev.addnext(converted)
prev = converted
if declaration is not None:
try:
# bs4 provides full Doctype string
doctype_string = declaration.output_ready()
except AttributeError:
doctype_string = declaration.string
match = _parse_doctype_declaration(doctype_string)
if not match:
# Something is wrong if we end up in here. Since soupparser should
# tolerate errors, do not raise Exception, just let it pass.
pass
else:
external_id, sys_uri = match.groups()
docinfo = res_root.getroottree().docinfo
# strip quotes and update DOCTYPE values (any of None, '', '...')
docinfo.public_id = external_id and external_id[1:-1]
docinfo.system_url = sys_uri and sys_uri[1:-1]
return res_root
def _init_node_converters(makeelement):
converters = {}
ordered_node_types = []
def converter(*types):
def add(handler):
for t in types:
converters[t] = handler
ordered_node_types.append(t)
return handler
return add
def find_best_converter(node):
for t in ordered_node_types:
if isinstance(node, t):
return converters[t]
return None
def convert_node(bs_node, parent=None):
# duplicated in convert_tag() below
try:
handler = converters[type(bs_node)]
except KeyError:
handler = converters[type(bs_node)] = find_best_converter(bs_node)
if handler is None:
return None
return handler(bs_node, parent)
def map_attrs(bs_attrs):
if isinstance(bs_attrs, dict): # bs4
attribs = {}
for k, v in bs_attrs.items():
if isinstance(v, list):
v = " ".join(v)
attribs[k] = unescape(v)
else:
attribs = {k: unescape(v) for k, v in bs_attrs}
return attribs
def append_text(parent, text):
if len(parent) == 0:
parent.text = (parent.text or '') + text
else:
parent[-1].tail = (parent[-1].tail or '') + text
# converters are tried in order of their definition
@converter(Tag, _PseudoTag)
def convert_tag(bs_node, parent):
attrs = bs_node.attrs
if parent is not None:
attribs = map_attrs(attrs) if attrs else None
res = etree.SubElement(parent, bs_node.name, attrib=attribs)
else:
attribs = map_attrs(attrs) if attrs else {}
res = makeelement(bs_node.name, attrib=attribs)
for child in bs_node:
# avoid double recursion by inlining convert_node(), see above
try:
handler = converters[type(child)]
except KeyError:
pass
else:
if handler is not None:
handler(child, res)
continue
convert_node(child, res)
return res
@converter(Comment)
def convert_comment(bs_node, parent):
res = html.HtmlComment(bs_node)
if parent is not None:
parent.append(res)
return res
@converter(ProcessingInstruction)
def convert_pi(bs_node, parent):
if bs_node.endswith('?'):
# The PI is of XML style (<?as df?>) but BeautifulSoup
# interpreted it as being SGML style (<?as df>). Fix.
bs_node = bs_node[:-1]
res = etree.ProcessingInstruction(*bs_node.split(' ', 1))
if parent is not None:
parent.append(res)
return res
@converter(NavigableString)
def convert_text(bs_node, parent):
if parent is not None:
append_text(parent, unescape(bs_node))
return None
return convert_node
# copied from ET's ElementSoup
try:
from html.entities import name2codepoint # Python 3
except ImportError:
from htmlentitydefs import name2codepoint
handle_entities = re.compile(r"&(\w+);").sub
try:
unichr
except NameError:
# Python 3
unichr = chr
def unescape(string):
if not string:
return ''
# work around oddities in BeautifulSoup's entity handling
def unescape_entity(m):
try:
return unichr(name2codepoint[m.group(1)])
except KeyError:
return m.group(0) # use as is
return handle_entities(unescape_entity, string)
|
_PseudoTag
|
python
|
getsentry__sentry
|
src/sentry/sentry_apps/utils/webhooks.py
|
{
"start": 52,
"end": 99
}
|
class ____(StrEnum):
pass
|
SentryAppActionType
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_set_column09.py
|
{
"start": 315,
"end": 1011
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("set_column09.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_column("A:A", 100)
worksheet.set_column("F:H", 8)
worksheet.set_column("C:D", 12)
worksheet.set_column("A:A", 10)
worksheet.set_column("XFD:XFD", 5)
worksheet.set_column("ZZ:ZZ", 3)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
huggingface__transformers
|
src/transformers/models/pop2piano/modeling_pop2piano.py
|
{
"start": 17100,
"end": 18506
}
|
class ____(nn.Module):
def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
super().__init__()
self.SelfAttention = Pop2PianoAttention(
config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
)
self.layer_norm = Pop2PianoLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(
self,
hidden_states,
attention_mask=None,
position_bias=None,
past_key_values=None,
use_cache=False,
output_attentions=False,
cache_position=None,
):
normed_hidden_states = self.layer_norm(hidden_states)
attention_output = self.SelfAttention(
normed_hidden_states,
mask=attention_mask,
position_bias=position_bias,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
cache_position=cache_position,
)
hidden_states = hidden_states + self.dropout(attention_output[0])
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
return outputs
# Copied from transformers.models.t5.modeling_t5.T5LayerCrossAttention with T5->Pop2Piano,t5->pop2piano
|
Pop2PianoLayerSelfAttention
|
python
|
scipy__scipy
|
scipy/stats/tests/test_distributions.py
|
{
"start": 63178,
"end": 66196
}
|
class ____:
# survival function reference values were computed with mpmath
# from mpmath import mp
# mp.dps = 50
# def sf_mpmath(x):
# x = mp.mpf(x)
# return float(mp.mpf(2.)/(mp.exp(x) + mp.one))
@pytest.mark.parametrize('x, ref', [(100, 7.440151952041672e-44),
(200, 2.767793053473475e-87)])
def test_sf(self, x, ref):
assert_allclose(stats.halflogistic.sf(x), ref, rtol=1e-15)
# inverse survival function reference values were computed with mpmath
# from mpmath import mp
# mp.dps = 200
# def isf_mpmath(x):
# halfx = mp.mpf(x)/2
# return float(-mp.log(halfx/(mp.one - halfx)))
@pytest.mark.parametrize('q, ref', [(7.440151952041672e-44, 100),
(2.767793053473475e-87, 200),
(1-1e-9, 1.999999943436137e-09),
(1-1e-15, 1.9984014443252818e-15)])
def test_isf(self, q, ref):
assert_allclose(stats.halflogistic.isf(q), ref, rtol=1e-15)
def test_logcdf(self):
x = 30.0
# Reference value computed with mpmath.
ref = -1.871524593768035e-13
logcdf = stats.halflogistic.logcdf(x)
assert_allclose(logcdf, ref, rtol=5e-15)
def test_logsf(self):
x = 2e-14
# Reference value computed with mpmath.
ref = -1.000000000000005e-14
logsf = stats.halflogistic.logsf(x)
assert_allclose(logsf, ref, rtol=5e-15)
@pytest.mark.parametrize("rvs_loc", [1e-5, 1e10])
@pytest.mark.parametrize("rvs_scale", [1e-2, 100, 1e8])
@pytest.mark.parametrize('fix_loc', [True, False])
@pytest.mark.parametrize('fix_scale', [True, False])
def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale,
fix_loc, fix_scale):
rng = np.random.default_rng(6762668991392531563)
data = stats.halflogistic.rvs(loc=rvs_loc, scale=rvs_scale, size=1000,
random_state=rng)
kwds = {}
if fix_loc and fix_scale:
error_msg = ("All parameters fixed. There is nothing to "
"optimize.")
with pytest.raises(RuntimeError, match=error_msg):
stats.halflogistic.fit(data, floc=rvs_loc, fscale=rvs_scale)
return
if fix_loc:
kwds['floc'] = rvs_loc
if fix_scale:
kwds['fscale'] = rvs_scale
# Numerical result may equal analytical result if the initial guess
# computed from moment condition is already optimal.
_assert_less_or_close_loglike(stats.halflogistic, data, **kwds,
maybe_identical=True)
def test_fit_bad_floc(self):
msg = r" Maximum likelihood estimation with 'halflogistic' requires"
with assert_raises(FitDataError, match=msg):
stats.halflogistic.fit([0, 2, 4], floc=1)
|
TestHalfLogistic
|
python
|
google__pytype
|
pytype/rewrite/operators_test.py
|
{
"start": 176,
"end": 503
}
|
class ____(test_utils.ContextfulTestBase):
def test_call_binary(self):
a = self.ctx.consts[1].to_variable()
b = self.ctx.consts[2].to_variable()
ret = operators.call_binary(self.ctx, '__add__', a, b)
self.assertIsInstance(ret, variables.Variable)
if __name__ == '__main__':
unittest.main()
|
BinaryOperatorTest
|
python
|
walkccc__LeetCode
|
solutions/2946. Matrix Similarity After Cyclic Shifts/2946.py
|
{
"start": 0,
"end": 221
}
|
class ____:
def areSimilar(self, mat: list[list[int]], k: int) -> bool:
n = len(mat[0])
for row in mat:
for j in range(n):
if row[j] != row[(j + k) % n]:
return False
return True
|
Solution
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-github/source_github/github_schema.py
|
{
"start": 267194,
"end": 268831
}
|
class ____(sgqlc.types.Input):
"""Require all commits be made to a non-target branch and submitted
via a pull request before they can be merged.
"""
__schema__ = github_schema
__field_names__ = (
"dismiss_stale_reviews_on_push",
"require_code_owner_review",
"require_last_push_approval",
"required_approving_review_count",
"required_review_thread_resolution",
)
dismiss_stale_reviews_on_push = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="dismissStaleReviewsOnPush")
"""New, reviewable commits pushed will dismiss previous pull request
review approvals.
"""
require_code_owner_review = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="requireCodeOwnerReview")
"""Require an approving review in pull requests that modify files
that have a designated code owner.
"""
require_last_push_approval = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="requireLastPushApproval")
"""Whether the most recent reviewable push must be approved by
someone other than the person who pushed it.
"""
required_approving_review_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="requiredApprovingReviewCount")
"""The number of approving reviews that are required before a pull
request can be merged.
"""
required_review_thread_resolution = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="requiredReviewThreadResolution")
"""All conversations on code must be resolved before a pull request
can be merged.
"""
|
PullRequestParametersInput
|
python
|
astropy__astropy
|
astropy/io/ascii/core.py
|
{
"start": 5417,
"end": 6239
}
|
class ____(np.ma.core.MaskedConstant):
"""A trivial extension of numpy.ma.masked.
We want to be able to put the generic term ``masked`` into a dictionary.
The constant ``numpy.ma.masked`` is not hashable (see
https://github.com/numpy/numpy/issues/4660), so we need to extend it
here with a hash value.
See https://github.com/numpy/numpy/issues/11021 for rationale for
__copy__ and __deepcopy__ methods.
"""
def __hash__(self):
"""All instances of this class shall have the same hash."""
# Any large number will do.
return 1234567890
def __copy__(self) -> Self:
"""This is a singleton so just return self."""
return self
def __deepcopy__(self, memo):
return self
masked: Final[MaskedConstant] = MaskedConstant()
|
MaskedConstant
|
python
|
keras-team__keras
|
keras/src/backend/tensorflow/trainer.py
|
{
"start": 705,
"end": 27517
}
|
class ____(base_trainer.Trainer):
def __init__(self):
super().__init__()
self.train_function = None
self.test_function = None
self.predict_function = None
# Specifies how many steps of the step_per_execution loop to unroll.
# Increasing this value can reduce kernel launch overhead,
# but will increase memory usage and compilation time.
self.unrolled_steps_per_execution = 1
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribute_strategy = tf.distribute.get_strategy()
else:
self._distribute_strategy = None
@property
def distribute_strategy(self):
return self._distribute_strategy or tf.distribute.get_strategy()
@property
def distribute_reduction_method(self):
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def train_step(self, data):
x, y, sample_weight = data_adapter_utils.unpack_x_y_sample_weight(data)
# Forward pass
with tf.GradientTape() as tape:
if self._call_has_training_arg:
y_pred = self(x, training=True)
else:
y_pred = self(x)
loss = self._compute_loss(
x=x,
y=y,
y_pred=y_pred,
sample_weight=sample_weight,
training=True,
)
self._loss_tracker.update_state(
loss_module.unscale_loss_for_distribution(loss),
sample_weight=tf.shape(
next(i for i in tree.flatten(x) if i is not None)
)[0],
)
if self.optimizer is not None:
loss = self.optimizer.scale_loss(loss)
# Compute gradients
if self.trainable_weights:
trainable_weights = self.trainable_weights
gradients = tape.gradient(loss, trainable_weights)
# Update weights
self.optimizer.apply_gradients(zip(gradients, trainable_weights))
else:
warnings.warn("The model does not have any trainable weights.")
return self.compute_metrics(x, y, y_pred, sample_weight=sample_weight)
def test_step(self, data):
x, y, sample_weight = data_adapter_utils.unpack_x_y_sample_weight(data)
if self._call_has_training_arg:
y_pred = self(x, training=False)
else:
y_pred = self(x)
loss = self._compute_loss(
x=x, y=y, y_pred=y_pred, sample_weight=sample_weight, training=False
)
self._loss_tracker.update_state(
loss_module.unscale_loss_for_distribution(loss),
sample_weight=tf.shape(
next(i for i in tree.flatten(x) if i is not None)
)[0],
)
return self.compute_metrics(x, y, y_pred, sample_weight=sample_weight)
def predict_step(self, data):
x, _, _ = data_adapter_utils.unpack_x_y_sample_weight(data)
if self._call_has_training_arg:
y_pred = self(x, training=False)
else:
y_pred = self(x)
return y_pred
def _autoconvert_optionals(self, step_func):
# Wrapper converting (nested) TF Optional in input data to None
@functools.wraps(step_func)
def wrapper(data):
converted_data = tree.map_structure(
lambda i: (
None if isinstance(i, tf.experimental.Optional) else i
),
data,
)
result = step_func(converted_data)
return result
return wrapper
def _make_function(self, step_function):
@tf.autograph.experimental.do_not_convert
def one_step_on_data(data):
"""Runs a single training step on a batch of data."""
outputs = self.distribute_strategy.run(step_function, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction="auto",
)
return outputs
if not self.run_eagerly:
one_step_on_data = tf.function(
one_step_on_data,
reduce_retracing=True,
jit_compile=self.jit_compile,
)
one_step_on_data = self._autoconvert_optionals(one_step_on_data)
@tf.autograph.experimental.do_not_convert
def multi_step_on_iterator(iterator):
if self.steps_per_execution == 1:
return tf.experimental.Optional.from_value(
one_step_on_data(iterator.get_next())
)
# the spec is set lazily during the tracing of `tf.while_loop`
empty_outputs = tf.experimental.Optional.empty(None)
def cond(execution_step, optional_outputs, next_optional_inputs):
return tf.logical_and(
tf.less(execution_step, self.steps_per_execution),
next_optional_inputs.has_value(),
)
def inner_body(
execution_step, optional_outputs, next_optional_inputs
):
def has_next():
next_optional_outputs = tf.experimental.Optional.from_value(
one_step_on_data(next_optional_inputs.get_value())
)
empty_outputs._element_spec = (
next_optional_outputs.element_spec
)
return next_optional_outputs
def no_has_next():
optional_outputs._element_spec = empty_outputs._element_spec
return optional_outputs
next_optional_outputs = tf.cond(
tf.logical_and(
tf.less(execution_step, self.steps_per_execution),
next_optional_inputs.has_value(),
),
has_next,
no_has_next,
)
return (
execution_step + 1,
next_optional_outputs,
# We don't want to iterate if we have reached
# `steps_per_execution` steps
tf.cond(
tf.less(execution_step + 1, self.steps_per_execution),
lambda: iterator.get_next_as_optional(),
lambda: next_optional_inputs,
),
)
def body(execution_step, optional_outputs, next_optional_inputs):
for _ in range(
min(
self.unrolled_steps_per_execution,
self.steps_per_execution,
)
):
execution_step, optional_outputs, next_optional_inputs = (
inner_body(
execution_step,
optional_outputs,
next_optional_inputs,
)
)
return (execution_step, optional_outputs, next_optional_inputs)
execution_step = tf.constant(0)
next_optional_inputs = iterator.get_next_as_optional()
# Run the while loop
_, final_optional_outputs, _ = tf.while_loop(
cond,
body,
loop_vars=[execution_step, empty_outputs, next_optional_inputs],
)
final_optional_outputs._element_spec = empty_outputs.element_spec
return final_optional_outputs
if not self.run_eagerly:
multi_step_on_iterator = tf.function(
multi_step_on_iterator, reduce_retracing=True
)
def function(iterator):
if isinstance(
iterator, (tf.data.Iterator, tf.distribute.DistributedIterator)
):
opt_outputs = multi_step_on_iterator(iterator)
if not opt_outputs.has_value():
raise StopIteration
return opt_outputs.get_value()
else:
for step, data in zip(
range(self.steps_per_execution), iterator
):
outputs = one_step_on_data(data)
return outputs
return function
def make_train_function(self, force=False):
if self.train_function is not None and not force:
return self.train_function
self.train_function = self._make_function(self.train_step)
def make_test_function(self, force=False):
if self.test_function is not None and not force:
return self.test_function
self.test_function = self._make_function(self.test_step)
def make_predict_function(self, force=False):
if self.predict_function is not None and not force:
return self.predict_function
@tf.autograph.experimental.do_not_convert
def one_step_on_data(data):
"""Runs a predict test step on a batch of data."""
return self.predict_step(data)
if not self.run_eagerly and self.jit_compile:
one_step_on_data = tf.function(
one_step_on_data, reduce_retracing=True, jit_compile=True
)
one_step_on_data = self._autoconvert_optionals(one_step_on_data)
@tf.autograph.experimental.do_not_convert
def one_step_on_data_distributed(data):
data = data[0]
outputs = self.distribute_strategy.run(
one_step_on_data, args=(data,)
)
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction="concat",
)
return outputs
@tf.autograph.experimental.do_not_convert
def multi_step_on_data(data):
outputs = one_step_on_data_distributed(data[:1])
for single_step_data in data[1:]:
step_outputs = one_step_on_data_distributed([single_step_data])
outputs = tree.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if self.steps_per_execution > 1:
predict_function = multi_step_on_data
else:
predict_function = one_step_on_data_distributed
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
callbacks=None,
validation_split=0.0,
validation_data=None,
shuffle=True,
class_weight=None,
sample_weight=None,
initial_epoch=0,
steps_per_epoch=None,
validation_steps=None,
validation_batch_size=None,
validation_freq=1,
):
self._assert_compile_called("fit")
# Possibly cap epochs for debugging runs.
max_epochs = config.max_epochs()
if max_epochs and max_epochs < epochs:
warnings.warn("Limiting epochs to %d" % max_epochs)
epochs = max_epochs
# TODO: respect compiled trainable state
self._eval_epoch_iterator = None
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for TF/numpy/jax arrays.
(
(x, y, sample_weight),
validation_data,
) = array_slicing.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data is not None:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter_utils.unpack_x_y_sample_weight(validation_data)
# Create an iterator that yields batches for one epoch.
epoch_iterator = TFEpochIterator(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
shuffle=shuffle,
class_weight=class_weight,
distribute_strategy=self.distribute_strategy,
steps_per_execution=self.steps_per_execution,
)
self._maybe_symbolic_build(iterator=epoch_iterator)
epoch_iterator.reset()
# Container that configures and calls callbacks.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
verbose=verbose,
epochs=epochs,
steps=epoch_iterator.num_batches,
model=self,
)
self.stop_training = False
self.make_train_function()
callbacks.on_train_begin()
training_logs = None
logs = {}
initial_epoch = self._initial_epoch or initial_epoch
for epoch in range(initial_epoch, epochs):
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with epoch_iterator.catch_stop_iteration():
for begin_step, end_step, iterator in epoch_iterator:
callbacks.on_train_batch_begin(begin_step)
logs = self.train_function(iterator)
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
# Override with model metrics instead of last step logs if needed.
epoch_logs = dict(self._get_metrics_result_or_logs(logs))
# Run validation.
if validation_data is not None and self._should_eval(
epoch, validation_freq
):
# Create EpochIterator for evaluation and cache it.
if getattr(self, "_eval_epoch_iterator", None) is None:
self._eval_epoch_iterator = TFEpochIterator(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
distribute_strategy=self.distribute_strategy,
steps_per_execution=self.steps_per_execution,
steps_per_epoch=validation_steps,
shuffle=False,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
f"val_{name}": val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if (
isinstance(self.optimizer, optimizers_module.Optimizer)
and epochs > 0
):
self.optimizer.finalize_variable_values(self.trainable_weights)
# If _eval_epoch_iterator exists, delete it after all epochs are done.
if getattr(self, "_eval_epoch_iterator", None) is not None:
del self._eval_epoch_iterator
callbacks.on_train_end(logs=training_logs)
return self.history
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
return_dict=False,
**kwargs,
):
self._assert_compile_called("evaluate")
# TODO: respect compiled trainable state
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise ValueError(f"Arguments not recognized: {kwargs}")
if use_cached_eval_dataset:
epoch_iterator = self._eval_epoch_iterator
else:
# Create an iterator that yields batches of input/target data.
epoch_iterator = TFEpochIterator(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
shuffle=False,
distribute_strategy=self.distribute_strategy,
steps_per_execution=self.steps_per_execution,
)
self._maybe_symbolic_build(iterator=epoch_iterator)
epoch_iterator.reset()
# Container that configures and calls callbacks.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_progbar=verbose != 0,
verbose=verbose,
epochs=1,
steps=epoch_iterator.num_batches,
model=self,
)
self.make_test_function()
self.stop_evaluating = False
callbacks.on_test_begin()
logs = {}
self.reset_metrics()
with epoch_iterator.catch_stop_iteration():
for begin_step, end_step, iterator in epoch_iterator:
callbacks.on_test_batch_begin(begin_step)
logs = self.test_function(iterator)
callbacks.on_test_batch_end(end_step, logs)
if self.stop_evaluating:
break
logs = self._get_metrics_result_or_logs(logs)
callbacks.on_test_end(logs)
if return_dict:
return logs
return self._flatten_metrics_in_order(logs)
@traceback_utils.filter_traceback
def predict(
self, x, batch_size=None, verbose="auto", steps=None, callbacks=None
):
# Create an iterator that yields batches of input data.
epoch_iterator = TFEpochIterator(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
shuffle=False,
distribute_strategy=self.distribute_strategy,
steps_per_execution=self.steps_per_execution,
)
# Container that configures and calls callbacks.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_progbar=verbose != 0,
verbose=verbose,
epochs=1,
steps=epoch_iterator.num_batches,
model=self,
)
def append_to_outputs(batch_outputs, outputs):
if outputs is None:
outputs = tree.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tree.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(batch_output),
outputs,
batch_outputs,
)
return outputs
def get_data(iterator):
"""Returns data for the next execution."""
data = []
for _ in range(self.steps_per_execution):
try:
single_step_data = next(iterator)
except (StopIteration, tf.errors.OutOfRangeError) as e:
if hasattr(data, "__len__") and len(data) > 0:
# Suppress the error when still have remaining data.
return data
else:
# Re-raise the error for
# EpochIterator.catch_stop_iteration() to catch when
# no data left.
raise e
data.append(single_step_data)
return data
self.make_predict_function()
self.stop_predicting = False
callbacks.on_predict_begin()
outputs = None
with epoch_iterator.catch_stop_iteration():
for begin_step, end_step, iterator in epoch_iterator:
callbacks.on_predict_batch_begin(begin_step)
data = get_data(iterator)
batch_outputs = self.predict_function(data)
outputs = append_to_outputs(batch_outputs, outputs)
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if self.stop_predicting:
break
callbacks.on_predict_end()
outputs = tree.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
return tree.map_structure(convert_to_np_if_not_ragged, outputs)
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
return_dict=False,
):
self._assert_compile_called("train_on_batch")
if class_weight is not None:
if sample_weight is not None:
raise ValueError(
"Arguments `sample_weight` and `class_weight` "
"cannot be specified at the same time. "
f"Received: sample_weight={sample_weight}, "
f"class_weight={class_weight}"
)
sample_weight = data_adapter_utils.class_weight_to_sample_weights(
y, class_weight
)
# Maybe build model
self._maybe_symbolic_build(data_batch=(x, y, sample_weight))
self.make_train_function()
def data():
yield (x, y, sample_weight)
logs = self.train_function(data())
logs = tree.map_structure(lambda x: np.array(x), logs)
if return_dict:
return logs
return self._flatten_metrics_in_order(logs)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
return_dict=False,
):
self._assert_compile_called("test_on_batch")
def data():
yield (x, y, sample_weight)
# Maybe build model
self._maybe_symbolic_build(data_batch=(x, y, sample_weight))
self.make_test_function()
logs = self.test_function(data())
logs = tree.map_structure(lambda x: np.array(x), logs)
if return_dict:
return logs
return self._flatten_metrics_in_order(logs)
def predict_on_batch(self, x):
self.make_predict_function()
batch_outputs = self.predict_function([(x,)])
batch_outputs = tree.map_structure(
convert_to_np_if_not_ragged, batch_outputs
)
return batch_outputs
# Backwards compatibility shims.
@property
def compiled_metrics(self):
class DeprecatedCompiledMetric:
def update_state(_, y, y_pred, sample_weight=None):
return self._compiled_metrics_update_state(
y, y_pred, sample_weight=sample_weight
)
return DeprecatedCompiledMetric()
def _compiled_metrics_update_state(self, y, y_pred, sample_weight=None):
warnings.warn(
"`model.compiled_metrics()` is deprecated. "
"Instead, use e.g.:\n"
"```\n"
"for metric in self.metrics:\n"
" metric.update_state(y, y_pred)\n"
"```\n",
stacklevel=2,
)
for metric in self.metrics:
if isinstance(metric, metrics_module.Mean):
metric.update_state(y_pred, sample_weight=sample_weight)
else:
metric.update_state(y, y_pred, sample_weight=sample_weight)
def compiled_loss(
self, y, y_pred, sample_weight=None, regularization_losses=None
):
warnings.warn(
"`model.compiled_loss()` is deprecated. Instead, use "
"`model.compute_loss(x, y, y_pred, sample_weight, training)`.",
)
return self.compute_loss(
x=None, y=y, y_pred=y_pred, sample_weight=sample_weight
)
def loss(self, y, y_pred, sample_weight=None):
warnings.warn(
"`model.loss()` is deprecated. Instead, use "
"`model.compute_loss(x, y, y_pred, sample_weight, training)`.",
)
return self.compute_loss(
x=None, y=y, y_pred=y_pred, sample_weight=sample_weight
)
def _maybe_symbolic_build(self, iterator=None, data_batch=None):
# Only symbolic build when distribute strategy is created in tf trainer
if self._distribute_strategy is None:
# When no distribution strategy is set, defer building
# to when the train/test/predict function gets traced.
# This maximizes backwards compatibility.
return
# Unlike jax/torch iterator, tf iterator returns an iterator instead
# of data batch in `iterator`.
if iterator is not None:
for _, _, it in iterator:
maybe_distributed_data_batch = next(it)
has_distributed_values = tree.map_structure(
lambda x: isinstance(x, tf.distribute.DistributedValues),
maybe_distributed_data_batch,
)
if all(tree.flatten(has_distributed_values)):
data_batch = self.distribute_strategy.reduce(
"MEAN",
maybe_distributed_data_batch,
axis=None,
)
else:
data_batch = maybe_distributed_data_batch
break
with self.distribute_strategy.scope():
self._symbolic_build(data_batch=data_batch)
def _aggregate_additional_loss(self, loss):
loss = super()._aggregate_additional_loss(loss)
return loss_module.scale_loss_for_distribution(loss)
|
TensorFlowTrainer
|
python
|
apache__airflow
|
providers/tableau/src/airflow/providers/tableau/hooks/tableau.py
|
{
"start": 1968,
"end": 7623
}
|
class ____(BaseHook):
"""
Connects to the Tableau Server Instance and allows to communicate with it.
Can be used as a context manager: automatically authenticates the connection
when opened and signs out when closed.
.. seealso:: https://tableau.github.io/server-client-python/docs/
:param site_id: The id of the site where the workbook belongs to.
It will connect to the default site if you don't provide an id.
:param tableau_conn_id: The :ref:`Tableau Connection id <howto/connection:tableau>`
containing the credentials to authenticate to the Tableau Server.
"""
conn_name_attr = "tableau_conn_id"
default_conn_name = "tableau_default"
conn_type = "tableau"
hook_name = "Tableau"
def __init__(self, site_id: str | None = None, tableau_conn_id: str = default_conn_name) -> None:
super().__init__()
self.tableau_conn_id = tableau_conn_id
self.conn = self.get_connection(self.tableau_conn_id)
self.site_id = site_id or self.conn.extra_dejson.get("site_id", "")
self.server = Server(self.conn.host)
verify: Any = self.conn.extra_dejson.get("verify", True)
if isinstance(verify, str):
verify = parse_boolean(verify)
self.server.add_http_options(
options_dict={"verify": verify, "cert": self.conn.extra_dejson.get("cert", None)}
)
self.server.use_server_version()
self.tableau_conn = None
def __enter__(self):
if not self.tableau_conn:
self.tableau_conn = self.get_conn()
return self
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.server.auth.sign_out()
def get_conn(self) -> Auth.contextmgr:
"""
Sign in to the Tableau Server.
:return: an authorized Tableau Server Context Manager object.
"""
extra = self.conn.extra_dejson
password_auth_set = self.conn.login and self.conn.password
jwt_auth_set = extra.get("auth") == "jwt"
if password_auth_set and jwt_auth_set:
raise AirflowException(
"Username/password authentication and JWT authentication cannot be used simultaneously. Please specify only one authentication method."
)
if password_auth_set:
return self._auth_via_password()
if jwt_auth_set:
if not exactly_one(jwt_file := "jwt_file" in extra, jwt_token := "jwt_token" in extra):
msg = (
"When auth set to 'jwt' then expected exactly one parameter 'jwt_file' or 'jwt_token'"
" in connection extra, but "
)
if jwt_file and jwt_token:
msg += "provided both."
else:
msg += "none of them provided."
raise ValueError(msg)
if jwt_file:
self.jwt_token = Path(extra["jwt_file"]).read_text()
else:
self.jwt_token = extra["jwt_token"]
return self._auth_via_jwt()
raise NotImplementedError("No Authentication method found for given Credentials!")
def _auth_via_password(self) -> Auth.contextmgr:
tableau_auth = TableauAuth(
username=cast("str", self.conn.login),
password=cast("str", self.conn.password),
site_id=self.site_id,
)
return self.server.auth.sign_in(tableau_auth)
def _auth_via_jwt(self) -> Auth.contextmgr:
jwt_auth = JWTAuth(jwt=self.jwt_token, site_id=self.site_id)
return self.server.auth.sign_in(jwt_auth)
def get_all(self, resource_name: str) -> Pager:
"""
Get all items of the given resource.
.. see also:: https://tableau.github.io/server-client-python/docs/page-through-results
:param resource_name: The name of the resource to paginate.
For example: jobs or workbooks.
:return: all items by returning a Pager.
"""
try:
resource = getattr(self.server, resource_name)
except AttributeError:
raise ValueError(f"Resource name {resource_name} is not found.")
return Pager(resource.get)
def get_job_status(self, job_id: str) -> TableauJobFinishCode:
"""
Get the current state of a defined Tableau Job.
.. see also:: https://tableau.github.io/server-client-python/docs/api-ref#jobs
:param job_id: The id of the job to check.
:return: An Enum that describe the Tableau job's return code
"""
return TableauJobFinishCode(int(self.server.jobs.get_by_id(job_id).finish_code))
def wait_for_state(self, job_id: str, target_state: TableauJobFinishCode, check_interval: float) -> bool:
"""
Wait until the current state of a defined Tableau Job is target_state or different from PENDING.
:param job_id: The id of the job to check.
:param target_state: Enum that describe the Tableau job's target state
:param check_interval: time in seconds that the job should wait in
between each instance state checks until operation is completed
:return: return True if the job is equal to the target_status, False otherwise.
"""
finish_code = self.get_job_status(job_id=job_id)
while finish_code == TableauJobFinishCode.PENDING and finish_code != target_state:
self.log.info("job state: %s", finish_code)
time.sleep(check_interval)
finish_code = self.get_job_status(job_id=job_id)
return finish_code == target_state
|
TableauHook
|
python
|
huggingface__transformers
|
src/transformers/models/speecht5/modeling_speecht5.py
|
{
"start": 59317,
"end": 60336
}
|
class ____(SpeechT5PreTrainedModel):
"""
This wrapper class is a helper class to correctly load pretrained checkpoints when used in combination with
[`SpeechT5Model`].
"""
def __init__(self, config: SpeechT5Config):
super().__init__(config)
self.wrapped_encoder = SpeechT5Encoder(config)
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_values: torch.FloatTensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, BaseModelOutput]:
return self.wrapped_encoder(
hidden_states=input_values,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
|
SpeechT5EncoderWithoutPrenet
|
python
|
zarr-developers__zarr-python
|
src/zarr/core/dtype/npy/string.py
|
{
"start": 12241,
"end": 13279
}
|
class ____(DTypeConfig_V2[Literal["|O"], Literal["vlen-utf8"]]):
"""
A wrapper around the JSON representation of the ``VariableLengthUTF8`` data type in Zarr V2.
The ``name`` field of this class contains the value that would appear under the
``dtype`` field in Zarr V2 array metadata. The ``object_codec_id`` field is always ``"vlen-utf8"``.
References
----------
The structure of the ``name`` field is defined in the Zarr V2
[specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding).
Examples
--------
```python
{
"name": "|O",
"object_codec_id": "vlen-utf8"
}
```
"""
# VariableLengthUTF8 is defined in two places, conditioned on the version of NumPy.
# If NumPy 2 is installed, then VariableLengthUTF8 is defined with the NumPy variable length
# string dtype as the native dtype. Otherwise, VariableLengthUTF8 is defined with the NumPy object
# dtype as the native dtype.
|
VariableLengthUTF8JSON_V2
|
python
|
Farama-Foundation__Gymnasium
|
tests/test_core.py
|
{
"start": 7391,
"end": 8883
}
|
class ____:
@staticmethod
def test_nonempty_seed_retrieved_when_not_set(example_env):
assert example_env.np_random_seed is not None
assert isinstance(example_env.np_random_seed, int)
@staticmethod
def test_seed_set_at_reset_and_retrieved(example_env):
seed = 42
example_env.reset(seed=seed)
assert example_env.np_random_seed == seed
# resetting with seed=None means seed remains the same
example_env.reset(seed=None)
assert example_env.np_random_seed == seed
@staticmethod
def test_seed_cannot_be_set_directly(example_env):
with pytest.raises(AttributeError):
example_env.np_random_seed = 42
@staticmethod
def test_negative_seed_retrieved_when_seed_unknown(example_env):
rng, _ = np_random()
example_env.np_random = rng
# seed is unknown
assert example_env.np_random_seed == -1
@staticmethod
def test_seeding_works_in_wrapped_envs(example_env):
seed = 42
wrapper_env = ExampleWrapper(example_env)
wrapper_env.reset(seed=seed)
assert wrapper_env.np_random_seed == seed
# resetting with seed=None means seed remains the same
wrapper_env.reset(seed=None)
assert wrapper_env.np_random_seed == seed
# setting np_random directly makes seed unknown
rng, _ = np_random()
wrapper_env.np_random = rng
assert wrapper_env.np_random_seed == -1
|
TestRandomSeeding
|
python
|
tensorflow__tensorflow
|
tensorflow/python/data/experimental/kernel_tests/wrap_unwrap_test.py
|
{
"start": 1131,
"end": 3157
}
|
class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
# TODO(b/182414964): After making options persistent across tf.function is
# enabled, the ModelDatasetOp and MaxIntraParallelismOp are no longer present
# in Python. As a result, the FinalizeDataset is placed on GPU because of
# colocation constraint on the iterator. It then requires a registered copy
# operation from CPU to GPU for RangeDataset that does not exist and the test
# fails. Fix this test and re-enable it.
def DISABLED_testBasic(self):
ds = dataset_ops.Dataset.range(100)
ds_variant = ds._variant_tensor # pylint: disable=protected-access
wrapped_variant = gen_dataset_ops.wrap_dataset_variant(ds_variant)
unwrapped_variant = gen_dataset_ops.unwrap_dataset_variant(wrapped_variant)
variant_ds = dataset_ops._VariantDataset(unwrapped_variant,
ds.element_spec)
get_next = self.getNext(variant_ds, requires_initialization=True)
for i in range(100):
self.assertEqual(i, self.evaluate(get_next()))
@combinations.generate(test_base.graph_only_combinations())
def testGPU(self):
ds = dataset_ops.Dataset.range(100)
ds_variant = ds._variant_tensor # pylint: disable=protected-access
wrapped_variant = gen_dataset_ops.wrap_dataset_variant(ds_variant)
with ops.device("/gpu:0"):
gpu_wrapped_variant = array_ops.identity(wrapped_variant)
unwrapped_variant = gen_dataset_ops.unwrap_dataset_variant(
gpu_wrapped_variant)
variant_ds = dataset_ops._VariantDataset(unwrapped_variant,
ds.element_spec)
iterator = dataset_ops.make_initializable_iterator(variant_ds)
get_next = iterator.get_next()
with self.cached_session():
self.evaluate(iterator.initializer)
for i in range(100):
self.assertEqual(i, self.evaluate(get_next))
if __name__ == "__main__":
test.main()
|
WrapUnwrapTest
|
python
|
run-llama__llama_index
|
llama-index-integrations/tools/llama-index-tools-jina/llama_index/tools/jina/base.py
|
{
"start": 226,
"end": 1678
}
|
class ____(BaseToolSpec):
"""
Jina tool spec.
"""
spec_functions = ["jina_search"]
def _make_request(self, params: Dict) -> requests.Response:
"""
Make a request to the Jina Search API.
Args:
params (dict): The parameters to be passed to the API.
Returns:
requests.Response: The response from the API.
"""
headers = {
"Accept": "application/json",
}
url = str(URL(JINA_SEARCH_URL_ENDPOINT + params.get("query")))
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()
def jina_search(self, query: str) -> List[Document]:
"""
Make a query to the Jina Search engine to receive a list of results.
Args:
query (str): The query to be passed to Jina Search.
Returns:
[Document]: A list of documents containing search results.
"""
search_params = {
"query": query,
}
response = self._make_request(search_params)
return [
Document(
text=result["content"],
extra_info={
"url": result["url"],
"title": result["title"],
"description": result["description"],
},
)
for result in response["data"]
]
|
JinaToolSpec
|
python
|
rapidsai__cudf
|
python/cudf/cudf/pandas/fast_slow_proxy.py
|
{
"start": 33643,
"end": 33754
}
|
class ____(FallbackError):
"""Raises when cuDF produces an AttributeError"""
pass
|
AttributeFallbackError
|
python
|
tensorflow__tensorflow
|
tensorflow/python/keras/legacy_tf_layers/pooling.py
|
{
"start": 12473,
"end": 15652
}
|
class ____(keras_layers.AveragePooling3D, base.Layer):
"""Average pooling layer for 3D inputs (e.g. volumes).
Args:
pool_size: An integer or tuple/list of 3 integers:
(pool_depth, pool_height, pool_width)
specifying the size of the pooling window.
Can be a single integer to specify the same value for
all spatial dimensions.
strides: An integer or tuple/list of 3 integers,
specifying the strides of the pooling operation.
Can be a single integer to specify the same value for
all spatial dimensions.
padding: A string. The padding method, either 'valid' or 'same'.
Case-insensitive.
data_format: A string. The ordering of the dimensions in the inputs.
`channels_last` (default) and `channels_first` are supported.
`channels_last` corresponds to inputs with shape
`(batch, depth, height, width, channels)` while `channels_first`
corresponds to inputs with shape
`(batch, channels, depth, height, width)`.
name: A string, the name of the layer.
"""
def __init__(self, pool_size, strides,
padding='valid', data_format='channels_last',
name=None, **kwargs):
if strides is None:
raise ValueError('Argument `strides` must not be None.')
super(AveragePooling3D, self).__init__(
pool_size=pool_size, strides=strides,
padding=padding, data_format=data_format, name=name, **kwargs)
def average_pooling3d(inputs,
pool_size, strides,
padding='valid', data_format='channels_last',
name=None):
"""Average pooling layer for 3D inputs (e.g. volumes).
Args:
inputs: The tensor over which to pool. Must have rank 5.
pool_size: An integer or tuple/list of 3 integers:
(pool_depth, pool_height, pool_width)
specifying the size of the pooling window.
Can be a single integer to specify the same value for
all spatial dimensions.
strides: An integer or tuple/list of 3 integers,
specifying the strides of the pooling operation.
Can be a single integer to specify the same value for
all spatial dimensions.
padding: A string. The padding method, either 'valid' or 'same'.
Case-insensitive.
data_format: A string. The ordering of the dimensions in the inputs.
`channels_last` (default) and `channels_first` are supported.
`channels_last` corresponds to inputs with shape
`(batch, depth, height, width, channels)` while `channels_first`
corresponds to inputs with shape
`(batch, channels, depth, height, width)`.
name: A string, the name of the layer.
Returns:
Output tensor.
Raises:
ValueError: if eager execution is enabled.
"""
warnings.warn('`tf.layers.average_pooling3d` is deprecated and '
'will be removed in a future version. '
'Please use `tf.keras.layers.AveragePooling3D` instead.')
layer = AveragePooling3D(pool_size=pool_size, strides=strides,
padding=padding, data_format=data_format,
name=name)
return layer.apply(inputs)
|
AveragePooling3D
|
python
|
pennersr__django-allauth
|
allauth/account/forms.py
|
{
"start": 29146,
"end": 29723
}
|
class ____(forms.Form):
code = forms.CharField(
label=_("Code"),
widget=forms.TextInput(
attrs={"placeholder": _("Code"), "autocomplete": "one-time-code"},
),
)
def __init__(self, *args, **kwargs):
self.code = kwargs.pop("code", None)
super().__init__(*args, **kwargs)
def clean_code(self):
code = self.cleaned_data.get("code")
if not compare_user_code(actual=code, expected=self.code):
raise get_adapter().validation_error("incorrect_code")
return code
|
BaseConfirmCodeForm
|
python
|
django__django
|
tests/migrations/test_executor.py
|
{
"start": 35183,
"end": 39380
}
|
class ____(SimpleTestCase):
"""(More) isolated unit tests for executor methods."""
def test_minimize_rollbacks(self):
"""
Minimize unnecessary rollbacks in connected apps.
When you say "./manage.py migrate appA 0001", rather than migrating to
just after appA-0001 in the linearized migration plan (which could roll
back migrations in other apps that depend on appA 0001, but don't need
to be rolled back since we're not rolling back appA 0001), we migrate
to just before appA-0002.
"""
a1_impl = FakeMigration("a1")
a1 = ("a", "1")
a2_impl = FakeMigration("a2")
a2 = ("a", "2")
b1_impl = FakeMigration("b1")
b1 = ("b", "1")
graph = MigrationGraph()
graph.add_node(a1, a1_impl)
graph.add_node(a2, a2_impl)
graph.add_node(b1, b1_impl)
graph.add_dependency(None, b1, a1)
graph.add_dependency(None, a2, a1)
executor = MigrationExecutor(None)
executor.loader = FakeLoader(
graph,
{
a1: a1_impl,
b1: b1_impl,
a2: a2_impl,
},
)
plan = executor.migration_plan({a1})
self.assertEqual(plan, [(a2_impl, True)])
def test_minimize_rollbacks_branchy(self):
r"""
Minimize rollbacks when target has multiple in-app children.
a: 1 <---- 3 <--\
\ \- 2 <--- 4
\ \
b: \- 1 <--- 2
"""
a1_impl = FakeMigration("a1")
a1 = ("a", "1")
a2_impl = FakeMigration("a2")
a2 = ("a", "2")
a3_impl = FakeMigration("a3")
a3 = ("a", "3")
a4_impl = FakeMigration("a4")
a4 = ("a", "4")
b1_impl = FakeMigration("b1")
b1 = ("b", "1")
b2_impl = FakeMigration("b2")
b2 = ("b", "2")
graph = MigrationGraph()
graph.add_node(a1, a1_impl)
graph.add_node(a2, a2_impl)
graph.add_node(a3, a3_impl)
graph.add_node(a4, a4_impl)
graph.add_node(b1, b1_impl)
graph.add_node(b2, b2_impl)
graph.add_dependency(None, a2, a1)
graph.add_dependency(None, a3, a1)
graph.add_dependency(None, a4, a2)
graph.add_dependency(None, a4, a3)
graph.add_dependency(None, b2, b1)
graph.add_dependency(None, b1, a1)
graph.add_dependency(None, b2, a2)
executor = MigrationExecutor(None)
executor.loader = FakeLoader(
graph,
{
a1: a1_impl,
b1: b1_impl,
a2: a2_impl,
b2: b2_impl,
a3: a3_impl,
a4: a4_impl,
},
)
plan = executor.migration_plan({a1})
should_be_rolled_back = [b2_impl, a4_impl, a2_impl, a3_impl]
exp = [(m, True) for m in should_be_rolled_back]
self.assertEqual(plan, exp)
def test_backwards_nothing_to_do(self):
r"""
If the current state satisfies the given target, do nothing.
a: 1 <--- 2
b: \- 1
c: \- 1
If a1 is applied already and a2 is not, and we're asked to migrate to
a1, don't apply or unapply b1 or c1, regardless of their current state.
"""
a1_impl = FakeMigration("a1")
a1 = ("a", "1")
a2_impl = FakeMigration("a2")
a2 = ("a", "2")
b1_impl = FakeMigration("b1")
b1 = ("b", "1")
c1_impl = FakeMigration("c1")
c1 = ("c", "1")
graph = MigrationGraph()
graph.add_node(a1, a1_impl)
graph.add_node(a2, a2_impl)
graph.add_node(b1, b1_impl)
graph.add_node(c1, c1_impl)
graph.add_dependency(None, a2, a1)
graph.add_dependency(None, b1, a1)
graph.add_dependency(None, c1, a1)
executor = MigrationExecutor(None)
executor.loader = FakeLoader(
graph,
{
a1: a1_impl,
b1: b1_impl,
},
)
plan = executor.migration_plan({a1})
self.assertEqual(plan, [])
|
ExecutorUnitTests
|
python
|
getsentry__sentry
|
src/sentry/search/events/builder/base.py
|
{
"start": 2314,
"end": 70048
}
|
class ____:
requires_organization_condition: bool = False
organization_column: str = "organization.id"
function_alias_prefix: str | None = None
spans_metrics_builder = False
entity: Entity | None = None
config_class: type[DatasetConfig] | None = None
duration_fields: set[str] = set()
size_fields: dict[str, str] = {}
uuid_fields: set[str] = set()
span_id_fields: set[str] = set()
def get_middle(self):
"""Get the middle for comparison functions"""
if self.start is None or self.end is None:
raise InvalidSearchQuery("Need both start & end to use percent_change")
return self.start + (self.end - self.start) / 2
def first_half_condition(self):
"""Create the first half condition for percent_change functions"""
return Function(
"less",
[
self.column("timestamp"),
Function("toDateTime", [self.get_middle()]),
],
)
def second_half_condition(self):
"""Create the second half condition for percent_change functions"""
return Function(
"greaterOrEquals",
[
self.column("timestamp"),
Function("toDateTime", [self.get_middle()]),
],
)
def _dataclass_params(
self, snuba_params: SnubaParams | None, params: ParamsType
) -> SnubaParams:
"""Shim so the query builder can start using the dataclass
need a lot of type: ignore since the params being passed can't be trusted from files that are probably still in the type ignorelist
"""
if snuba_params is not None:
return snuba_params
if "project_objects" in params:
projects = params["project_objects"]
elif "project_id" in params and isinstance(params["project_id"], (list, tuple)):
projects = list(Project.objects.filter(id__in=params["project_id"]))
else:
projects = []
if "organization_id" in params and isinstance(params["organization_id"], int):
organization = Organization.objects.filter(id=params["organization_id"]).first()
else:
organization = projects[0].organization if projects else None
# Yes this is a little janky, but its temporary until we can have everyone passing the dataclass directly
environments: Sequence[Environment | None] = []
if "environment_objects" in params:
environments = cast(Sequence[Union[Environment, None]], params["environment_objects"])
if "environment" in params and organization is not None:
if isinstance(params["environment"], list):
environments = list(
Environment.objects.filter(
organization_id=organization.id, name__in=params["environment"]
)
)
if "" in params["environment"]:
environments.append(None)
elif isinstance(params["environment"], str):
environments = list(
Environment.objects.filter(
organization_id=organization.id, name=params["environment"]
)
)
else:
environments = [] # type: ignore[unreachable]
user_id = params.get("user_id")
user = user_service.get_user(user_id=user_id) if user_id is not None else None # type: ignore[arg-type]
teams = (
Team.objects.filter(id__in=params["team_id"])
if "team_id" in params and isinstance(params["team_id"], list)
else []
)
return SnubaParams(
start=cast(datetime, params.get("start")),
end=cast(datetime, params.get("end")),
environments=environments,
projects=projects,
user=user,
teams=teams,
organization=organization,
)
def __init__(
self,
dataset: Dataset,
params: ParamsType,
config: QueryBuilderConfig | None = None,
snuba_params: SnubaParams | None = None,
query: str | None = None,
selected_columns: list[str] | None = None,
groupby_columns: list[str] | None = None,
equations: list[str] | None = None,
orderby: list[str] | str | None = None,
limit: int | None = 50,
offset: int | None = 0,
limitby: tuple[str, int] | None = None,
turbo: bool = False,
sample_rate: float | None = None,
array_join: str | None = None,
entity: Entity | None = None,
):
sentry_sdk.set_tag("querybuilder.name", type(self).__name__)
if config is None:
self.builder_config = QueryBuilderConfig()
else:
self.builder_config = config
self.dataset = dataset
# filter params is the older style params, shouldn't be used anymore
self.filter_params = params
if snuba_params is not None:
self.filter_params = snuba_params.filter_params
self.params = self._dataclass_params(snuba_params, params)
org_id = self.params.organization_id
self.organization_id: int | None = (
org_id if org_id is not None and isinstance(org_id, int) else None
)
self.raw_equations = equations
self.raw_orderby = orderby
self.query = query
self.selected_columns = selected_columns or []
self.groupby_columns = groupby_columns
self.tips: dict[str, set[str]] = {
"query": set(),
"columns": set(),
}
# Base Tenant IDs for any Snuba Request built/executed using a QueryBuilder
org_id = self.organization_id or (
self.params.organization.id if self.params.organization else None
)
self.tenant_ids: dict[str, str | None | int] | None = dict()
if org_id is not None:
self.tenant_ids["organization_id"] = org_id
if "use_case_id" in params and params.get("use_case_id") is not None:
self.tenant_ids["use_case_id"] = params.get("use_case_id")
if not self.tenant_ids:
self.tenant_ids = None
# Function is a subclass of CurriedFunction
self.where: list[WhereType] = []
self.having: list[WhereType] = []
# The list of aggregates to be selected
self.aggregates: list[CurriedFunction] = []
self.columns: list[SelectType] = []
self.orderby: list[OrderBy] = []
self.groupby: list[SelectType] = []
self.projects_to_filter: set[int] = set()
self.function_alias_map: dict[str, fields.FunctionDetails] = {}
self.equation_alias_map: dict[str, SelectType] = {}
# field: function map for post-processing values
self.value_resolver_map: dict[str, Callable[[Any], Any]] = {}
# value_resolver_map may change type
self.meta_resolver_map: dict[str, str] = {}
# These maps let us convert from prefixed to original tag keys
# and vice versa to avoid collisions where tags and functions have
# similar aliases
self.prefixed_to_tag_map: dict[str, str] = {}
self.tag_to_prefixed_map: dict[str, str] = {}
# Tags with their type in them can't be passed to clickhouse because of the space
# This map is so we can convert those back before the user sees the internal alias
self.typed_tag_to_alias_map: dict[str, str] = {}
self.alias_to_typed_tag_map: dict[str, str] = {}
self.requires_other_aggregates = False
self.limit = self.resolve_limit(limit)
self.offset = None if offset is None else Offset(offset)
self.turbo = turbo
self.sample_rate = sample_rate
self.config = self.load_config()
self.parse_config()
self.start: datetime | None = None
self.end: datetime | None = None
self.resolve_query(
query=query,
selected_columns=selected_columns,
groupby_columns=groupby_columns,
equations=equations,
orderby=orderby,
)
self.entity = entity
self.limitby = self.resolve_limitby(limitby)
self.array_join = None if array_join is None else [self.resolve_column(array_join)]
def are_columns_resolved(self) -> bool:
return len(self.columns) > 0 and isinstance(self.columns[0], Function)
def resolve_time_conditions(self) -> None:
if self.builder_config.skip_time_conditions:
return
# start/end are required so that we can run a query in a reasonable amount of time
if self.params.start is None or self.params.end is None:
raise InvalidSearchQuery("Cannot query without a valid date range")
self.start = self.params.start
self.end = self.params.end
def resolve_column_name(self, col: str) -> str:
# TODO: when utils/snuba.py becomes typed don't need this extra annotation
column_resolver: Callable[[str], str] = resolve_column(self.dataset)
column_name = column_resolver(col)
# If the original column was passed in as tag[X], then there won't be a conflict
# and there's no need to prefix the tag
if not col.startswith("tags[") and column_name.startswith("tags["):
self.prefixed_to_tag_map[f"tags_{col}"] = col
self.tag_to_prefixed_map[col] = f"tags_{col}"
elif not col.startswith("flags[") and column_name.startswith("flags["):
self.prefixed_to_tag_map[f"flags_{col}"] = col
self.tag_to_prefixed_map[col] = f"flags_{col}"
return column_name
def resolve_query(
self,
query: str | None = None,
selected_columns: list[str] | None = None,
groupby_columns: list[str] | None = None,
equations: list[str] | None = None,
orderby: list[str] | str | None = None,
) -> None:
with sentry_sdk.start_span(op="QueryBuilder", name="resolve_query"):
with sentry_sdk.start_span(op="QueryBuilder", name="resolve_time_conditions"):
# Has to be done early, since other conditions depend on start and end
self.resolve_time_conditions()
with sentry_sdk.start_span(op="QueryBuilder", name="resolve_conditions"):
self.where, self.having = self.resolve_conditions(query)
with sentry_sdk.start_span(op="QueryBuilder", name="resolve_params"):
# params depends on parse_query, and conditions being resolved first since there may be projects in conditions
self.where += self.resolve_params()
with sentry_sdk.start_span(op="QueryBuilder", name="resolve_columns"):
self.columns = self.resolve_select(selected_columns, equations)
with sentry_sdk.start_span(op="QueryBuilder", name="resolve_orderby"):
self.orderby = self.resolve_orderby(orderby)
with sentry_sdk.start_span(op="QueryBuilder", name="resolve_groupby"):
self.groupby = self.resolve_groupby(groupby_columns)
def parse_config(self) -> None:
if not hasattr(self, "config") or self.config is None:
raise Exception("Setup failed, dataset config was not loaded")
self.field_alias_converter = self.config.field_alias_converter
self.function_converter = self.config.function_converter
self.search_filter_converter = self.config.search_filter_converter
self.orderby_converter = self.config.orderby_converter
def load_config(self) -> DatasetConfig:
if self.config_class is None:
raise NotImplementedError("config_class was not set on this QueryBuilder")
return self.config_class(self)
def resolve_limit(self, limit: int | None) -> Limit | None:
return None if limit is None else Limit(limit)
def resolve_limitby(self, limitby: tuple[str, int] | None) -> LimitBy | None:
if limitby is None:
return None
column, count = limitby
resolved = self.resolve_column(column)
if isinstance(resolved, Column):
return LimitBy([resolved], count)
# Special case to allow limit bys on array joined columns.
# Simply allowing any function to be used in a limit by
# result in hard to debug issues so be careful.
if isinstance(resolved, Function) and resolved.function == "arrayJoin":
return LimitBy([Column(resolved.alias)], count)
# TODO: Limit By can only operate on a `Column`. This has the implication
# that non aggregate transforms are not allowed in the order by clause.
raise InvalidSearchQuery(f"{column} used in a limit by but is not a column.")
def resolve_where(self, parsed_terms: event_filter.ParsedTerms) -> list[WhereType]:
"""Given a list of parsed terms, construct their equivalent snql where
conditions. filtering out any aggregates"""
where_conditions: list[WhereType] = []
for term in parsed_terms:
if isinstance(term, event_search.SearchFilter):
condition = self.format_search_filter(term)
if condition:
where_conditions.append(condition)
return where_conditions
def resolve_having(self, parsed_terms: event_filter.ParsedTerms) -> list[WhereType]:
"""Given a list of parsed terms, construct their equivalent snql having
conditions, filtering only for aggregate conditions"""
if not self.builder_config.use_aggregate_conditions:
return []
having_conditions: list[WhereType] = []
for term in parsed_terms:
if isinstance(term, event_search.AggregateFilter):
condition = self.convert_aggregate_filter_to_condition(term)
if condition:
having_conditions.append(condition)
return having_conditions
def resolve_conditions(
self,
query: str | None,
) -> tuple[list[WhereType], list[WhereType]]:
sentry_sdk.set_tag("query.query_string", query if query else "<No Query>")
sentry_sdk.set_tag(
"query.use_aggregate_conditions",
self.builder_config.use_aggregate_conditions,
)
parsed_terms = self.parse_query(query)
self.has_or_condition = any(
event_search.SearchBoolean.is_or_operator(term) for term in parsed_terms
)
sentry_sdk.set_tag("query.has_or_condition", self.has_or_condition)
if any(
isinstance(term, event_search.ParenExpression)
or event_search.SearchBoolean.is_operator(term)
for term in parsed_terms
):
where, having = self.resolve_boolean_conditions(parsed_terms)
else:
where = self.resolve_where(parsed_terms)
having = self.resolve_having(parsed_terms)
sentry_sdk.set_tag("query.has_having_conditions", len(having) > 0)
sentry_sdk.set_tag("query.has_where_conditions", len(where) > 0)
return where, having
def resolve_boolean_conditions(
self, terms: event_filter.ParsedTerms
) -> tuple[list[WhereType], list[WhereType]]:
if len(terms) == 1:
return self.resolve_boolean_condition(terms[0])
# Filter out any ANDs since we can assume anything without an OR is an AND. Also do some
# basic sanitization of the query: can't have two operators next to each other, and can't
# start or end a query with an operator.
previous_term: event_filter.ParsedTerm | None = None
new_terms = []
term: event_filter.ParsedTerm | None = None
for term in terms:
if previous_term:
if event_search.SearchBoolean.is_operator(
previous_term
) and event_search.SearchBoolean.is_operator(term):
raise InvalidSearchQuery(
f"Missing condition in between two condition operators: '{previous_term} {term}'"
)
else:
if event_search.SearchBoolean.is_operator(term):
raise InvalidSearchQuery(
f"Condition is missing on the left side of '{term}' operator"
)
if term != event_search.SearchBoolean.BOOLEAN_AND:
new_terms.append(term)
previous_term = term
if term is not None and event_search.SearchBoolean.is_operator(term):
raise InvalidSearchQuery(f"Condition is missing on the right side of '{term}' operator")
terms = new_terms
# We put precedence on AND, which sort of counter-intuitively means we have to split the query
# on ORs first, so the ANDs are grouped together. Search through the query for ORs and split the
# query on each OR.
# We want to maintain a binary tree, so split the terms on the first OR we can find and recurse on
# the two sides. If there is no OR, split the first element out to AND
index = None
lhs, rhs = None, None
operator = None
try:
index = terms.index(event_search.SearchBoolean.BOOLEAN_OR)
lhs, rhs = terms[:index], terms[index + 1 :]
operator = Or
except Exception:
lhs, rhs = terms[:1], terms[1:]
operator = And
lhs_where, lhs_having = self.resolve_boolean_conditions(lhs)
rhs_where, rhs_having = self.resolve_boolean_conditions(rhs)
is_where_condition: Callable[[list[WhereType]], bool] = lambda x: bool(
x and len(x) == 1 and isinstance(x[0], Condition)
)
if (
# A direct field:a OR field:b
operator == Or
and is_where_condition(lhs_where)
and is_where_condition(rhs_where)
and lhs_where[0].lhs == rhs_where[0].lhs
) or (
# Chained or statements become field:a OR (field:b OR (...))
operator == Or
and is_where_condition(lhs_where)
and rhs_where
and isinstance(rhs_where[0], Or)
# Even in a long chain the first condition would be the next field
and isinstance(rhs_where[0].conditions[0], Condition)
and lhs_where[0].lhs == rhs_where[0].conditions[0].lhs
):
self.tips["query"].add(constants.QUERY_TIPS["CHAINED_OR"])
if operator == Or and (lhs_where or rhs_where) and (lhs_having or rhs_having):
raise InvalidSearchQuery(
"Having an OR between aggregate filters and normal filters is invalid."
)
where = self._combine_conditions(lhs_where, rhs_where, operator)
having = self._combine_conditions(lhs_having, rhs_having, operator)
return where, having
def resolve_boolean_condition(
self, term: event_filter.ParsedTerm
) -> tuple[list[WhereType], list[WhereType]]:
if isinstance(term, event_search.ParenExpression):
return self.resolve_boolean_conditions(term.children)
where, having = [], []
if isinstance(term, event_search.SearchFilter):
where = self.resolve_where([term])
elif isinstance(term, event_search.AggregateFilter):
having = self.resolve_having([term])
return where, having
def resolve_projects(self) -> list[int]:
return self.params.project_ids
def resolve_params(self) -> list[WhereType]:
"""Keys included as url params take precedent if same key is included in search
They are also considered safe and to have had access rules applied unlike conditions
from the query string.
"""
conditions = []
# Update start to be within retention
expired = False
if self.start and self.end:
expired, self.start = outside_retention_with_modified_start(
self.start, self.end, self.params.organization
)
if expired:
raise QueryOutsideRetentionError(
"Invalid date range. Please try a more recent date range."
)
if self.start:
conditions.append(Condition(self.column("timestamp"), Op.GTE, self.start))
if self.end:
conditions.append(Condition(self.column("timestamp"), Op.LT, self.end))
# project_ids is a required column for most datasets, however, Snuba does not
# complain on an empty list which results on no data being returned.
# This change will prevent calling Snuba when no projects are selected.
# Snuba will complain with UnqualifiedQueryError: validation failed for entity...
project_ids = self.resolve_projects()
if not project_ids:
# TODO: Fix the tests and always raise the error
# In development, we will let Snuba complain about the lack of projects
# so the developer can write their tests with a non-empty project list
# In production, we will raise an error
if not in_test_environment():
raise UnqualifiedQueryError("You need to specify at least one project with data.")
else:
conditions.append(
Condition(
self.column("project_id"),
Op.IN,
project_ids,
)
)
if len(self.params.environments) > 0:
term = event_search.SearchFilter(
event_search.SearchKey("environment"),
"=",
event_search.SearchValue(self.params.environment_names),
)
condition = self._environment_filter_converter(term)
if condition:
conditions.append(condition)
if self.requires_organization_condition:
if self.params.organization is None:
raise InvalidSearchQuery("Organization is a required parameter")
conditions.append(
Condition(
self.column(self.organization_column),
Op.EQ,
self.params.organization.id,
)
)
return conditions
def resolve_select(
self, selected_columns: list[str] | None, equations: list[str] | None
) -> list[SelectType]:
"""Given a public list of discover fields, construct the corresponding
list of Snql Columns or Functions. Duplicate columns are ignored
"""
if selected_columns is None:
return []
resolved_columns = []
stripped_columns = [column.strip() for column in set(selected_columns)]
sentry_sdk.set_tag("query.has_equations", equations is not None and len(equations) > 0)
if equations:
stripped_columns, parsed_equations = resolve_equation_list(
equations,
stripped_columns,
**(
self.builder_config.equation_config
if self.builder_config.equation_config
else {}
),
custom_measurements=self.get_custom_measurement_names_set(),
)
for index, parsed_equation in enumerate(parsed_equations):
resolved_equation = self.resolve_equation(
parsed_equation.equation, f"equation[{index}]"
)
self.equation_alias_map[equations[index]] = resolved_equation
resolved_columns.append(resolved_equation)
if parsed_equation.contains_functions:
self.aggregates.append(resolved_equation)
# Add threshold config alias if there's a function that depends on it
# TODO: this should be replaced with an explicit request for the project_threshold_config as a column
for column in self.config.custom_threshold_columns:
if (
column in stripped_columns
and constants.PROJECT_THRESHOLD_CONFIG_ALIAS not in stripped_columns
):
stripped_columns.append(constants.PROJECT_THRESHOLD_CONFIG_ALIAS)
break
for column in stripped_columns:
if column == "":
continue
# need to make sure the column is resolved with the appropriate alias
# because the resolved snuba name may be different
resolved_column = self.resolve_column(column, alias=True)
if resolved_column not in self.columns:
resolved_columns.append(resolved_column)
if self.builder_config.auto_fields:
# Ensure fields we require to build a functioning interface
# are present.
if not self.aggregates and "id" not in stripped_columns:
resolved_columns.append(self.resolve_column("id", alias=True))
stripped_columns.append("id")
if "id" in stripped_columns and "project.id" not in stripped_columns:
resolved_columns.append(self.resolve_column("project.name", alias=True))
return resolved_columns
def resolve_field(self, raw_field: str, alias: bool = False) -> Column:
"""Given a public field, resolve the alias based on the Query's
dataset and return the Snql Column
"""
tag_match = constants.TAG_KEY_RE.search(raw_field)
flag_match = constants.FLAG_KEY_RE.search(raw_field)
if tag_match:
field = tag_match.group("tag")
elif flag_match:
field = flag_match.group("flag")
else:
field = raw_field
if constants.VALID_FIELD_PATTERN.match(field):
return self.aliased_column(raw_field) if alias else self.column(raw_field)
else:
raise InvalidSearchQuery(f"Invalid characters in field {field}")
def resolve_field_alias(self, alias: str) -> SelectType:
"""Given a field alias, convert it to its corresponding snql"""
converter = self.field_alias_converter.get(alias)
if not converter:
raise NotImplementedError(f"{alias} not implemented in snql field parsing yet")
return converter(alias)
def resolve_function(
self,
function: str,
match: Match[str] | None = None,
resolve_only: bool = False,
overwrite_alias: str | None = None,
) -> SelectType:
"""Given a public function, resolve to the corresponding Snql function
:param function: the public alias for a function eg. "p50(transaction.duration)"
:param match: the Match so we don't have to run the regex twice
:param resolve_only: whether we should add the aggregate to self.aggregates
:param overwrite_alias: ignore the alias in the parsed_function and use this string instead
"""
if match is None:
match = fields.is_function(function)
if not match:
raise InvalidSearchQuery(f"Invalid characters in field {function}")
name, combinator_name, parsed_arguments, alias = self.parse_function(match)
if overwrite_alias is not None:
alias = overwrite_alias
snql_function = self.function_converter[name]
combinator = snql_function.find_combinator(combinator_name)
if combinator_name is not None and combinator is None:
raise InvalidSearchQuery(
f"{snql_function.name}: no support for the -{combinator_name} combinator"
)
if not snql_function.is_accessible(self.builder_config.functions_acl, combinator):
raise InvalidSearchQuery(f"{snql_function.name}: no access to private function")
combinator_applied = False
arguments = snql_function.format_as_arguments(
name, parsed_arguments, self.filter_params, combinator
)
self.function_alias_map[alias] = fields.FunctionDetails(
function, snql_function, arguments.copy()
)
for arg in snql_function.args:
if isinstance(arg, fields.ColumnArg):
if (
arguments[arg.name] in fields.NumericColumn.numeric_array_columns
and isinstance(arg, fields.NumericColumn)
and not isinstance(combinator, fields.SnQLArrayCombinator)
):
arguments[arg.name] = Function(
"arrayJoin", [self.resolve_column(arguments[arg.name])]
)
else:
column = self.resolve_column(arguments[arg.name])
# Can't keep aliased expressions
if isinstance(column, AliasedExpression):
column = column.exp
arguments[arg.name] = column
if combinator is not None and combinator.is_applicable(arg.name):
arguments[arg.name] = combinator.apply(arguments[arg.name])
combinator_applied = True
if combinator and not combinator_applied:
raise InvalidSearchQuery("Invalid combinator: Arguments passed were incompatible")
resolved_function = self.resolve_snql_function(
snql_function, arguments, alias, resolve_only
)
if resolved_function is not None:
return resolved_function
if snql_function.requires_other_aggregates:
self.requires_other_aggregates = True
return snql_function.snql_column(arguments, alias)
def get_function_result_type(
self,
function: str,
) -> str | None:
"""Given a function, resolve it and then get the result_type
params to this function should match that of resolve_function
"""
resolved_function = self.resolve_function(function, resolve_only=True)
if not isinstance(resolved_function, Function) or resolved_function.alias is None:
return None
function_details = self.function_alias_map.get(resolved_function.alias)
if function_details is None:
return None
result_type: str | None = function_details.instance.get_result_type(
function_details.field, function_details.arguments
)
return result_type
def resolve_snql_function(
self,
snql_function: fields.SnQLFunction,
arguments: Mapping[str, NormalizedArg],
alias: str,
resolve_only: bool,
) -> SelectType | None:
if snql_function.snql_aggregate is not None:
if not resolve_only:
self.aggregates.append(snql_function.snql_aggregate(arguments, alias))
return snql_function.snql_aggregate(arguments, alias)
return None
def resolve_equation(self, equation: Operation, alias: str | None = None) -> SelectType:
"""Convert this tree of Operations to the equivalent snql functions"""
lhs = self._resolve_equation_operand(equation.lhs)
rhs = self._resolve_equation_operand(equation.rhs)
if equation.operator == "divide":
rhs = Function("nullIf", [rhs, 0])
return Function(equation.operator, [lhs, rhs], alias)
def resolve_orderby(self, orderby: list[str] | str | None) -> list[OrderBy]:
"""Given a list of public aliases, optionally prefixed by a `-` to
represent direction, construct a list of Snql Orderbys
"""
validated: list[OrderBy] = []
if orderby is None:
return validated
if isinstance(orderby, str):
if not orderby:
return validated
orderby = [orderby]
orderby_columns: list[str] = orderby if orderby else []
resolved_orderby: str | SelectType | None
for orderby in orderby_columns:
bare_orderby = orderby.lstrip("-")
bare_orderby = self.tag_to_prefixed_map.get(bare_orderby, bare_orderby)
try:
# Allow ordering equations with the calculated alias (ie. equation[0])
if is_equation_alias(bare_orderby):
resolved_orderby = bare_orderby
# Allow ordering equations directly with the raw alias (ie. equation|a + b)
elif is_equation(bare_orderby):
if not strip_equation(bare_orderby):
raise InvalidSearchQuery("Cannot sort by an empty equation")
resolved_orderby = self.equation_alias_map[strip_equation(bare_orderby)]
bare_orderby = resolved_orderby.alias
else:
resolved_orderby = self.resolve_column(bare_orderby)
except (NotImplementedError, IncompatibleMetricsQuery):
resolved_orderby = None
direction = Direction.DESC if orderby.startswith("-") else Direction.ASC
if fields.is_function(bare_orderby) and (
isinstance(resolved_orderby, Function)
or isinstance(resolved_orderby, CurriedFunction)
or isinstance(resolved_orderby, AliasedExpression)
):
bare_orderby = resolved_orderby.alias
# tags that are typed have a different alias because we can't pass commas down
elif bare_orderby in self.typed_tag_to_alias_map:
bare_orderby = self.typed_tag_to_alias_map[bare_orderby]
for selected_column in self.columns:
if isinstance(selected_column, Column) and selected_column == resolved_orderby:
validated.append(OrderBy(selected_column, direction))
break
elif (
isinstance(selected_column, AliasedExpression)
and selected_column.alias == bare_orderby
):
if bare_orderby in self.orderby_converter:
validated.append(self.orderby_converter[bare_orderby](direction))
break
# We cannot directly order by an `AliasedExpression`.
# Instead, we order by the column inside.
validated.append(OrderBy(selected_column.exp, direction))
break
elif (
isinstance(selected_column, CurriedFunction)
and selected_column.alias == bare_orderby
):
if bare_orderby in self.orderby_converter:
validated.append(self.orderby_converter[bare_orderby](direction))
validated.append(OrderBy(selected_column, direction))
break
if len(validated) == len(orderby_columns):
return validated
# TODO: This is no longer true, can order by fields that aren't selected, keeping
# for now so we're consistent with the existing functionality
raise InvalidSearchQuery("Cannot sort by a field that is not selected.")
def resolve_column(self, field: NormalizedArg, alias: bool = False) -> SelectType:
"""Given a public field, construct the corresponding Snql, this
function will determine the type of the field alias, whether its a
column, field alias or function and call the corresponding resolver
:param field: The public field string to resolve into Snql. This may
be a column, field alias, or even a function.
:param alias: Whether or not the resolved column is aliased to the
original name. If false, it may still have an alias
but is not guaranteed.
"""
if not isinstance(field, str):
raise InvalidSearchQuery(f"{field} cannot be used as a column")
match = fields.is_function(field)
if match:
return self.resolve_function(field, match)
elif self.is_field_alias(field):
return self.resolve_field_alias(field)
else:
return self.resolve_field(field, alias=alias)
def resolve_groupby(self, groupby_columns: list[str] | None = None) -> list[SelectType]:
self.validate_aggregate_arguments()
if self.aggregates:
groupby_columns = (
[self.resolve_column(column) for column in groupby_columns]
if groupby_columns
else []
)
return [
column
for column in self.columns
if column not in self.aggregates and not self.is_equation_column(column)
] + [
column
for column in groupby_columns
if column not in self.aggregates
and not self.is_equation_column(column)
and column not in self.columns
]
else:
return []
@property
def flattened_having(self) -> list[Condition]:
"""Return self.having as a flattened list ignoring boolean operators
This is because self.having can have a mix of BooleanConditions and Conditions. And each BooleanCondition can in
turn be a mix of either type.
"""
flattened: list[Condition] = []
boolean_conditions: list[BooleanCondition] = []
for condition in self.having:
if isinstance(condition, Condition):
flattened.append(condition)
elif isinstance(condition, BooleanCondition):
boolean_conditions.append(condition)
while len(boolean_conditions) > 0:
boolean_condition = boolean_conditions.pop()
for condition in boolean_condition.conditions:
if isinstance(condition, Condition):
flattened.append(condition)
elif isinstance(condition, BooleanCondition):
boolean_conditions.append(condition)
return flattened
@cached_property
def custom_measurement_map(self) -> Sequence[MetricMeta]:
# Both projects & org are required, but might be missing for the search parser
if self.organization_id is None or not self.builder_config.has_metrics:
return []
from sentry.snuba.metrics.datasource import get_custom_measurements
should_use_user_time_range = self.params.organization is not None and features.has(
"organizations:performance-discover-get-custom-measurements-reduced-range",
self.params.organization,
actor=None,
)
start = (
self.params.start
if should_use_user_time_range
else datetime.today() - timedelta(days=90)
)
end = self.params.end if should_use_user_time_range else datetime.today()
try:
result = get_custom_measurements(
project_ids=self.params.project_ids,
organization_id=self.organization_id,
start=start,
end=end,
)
# Don't fully fail if we can't get the CM, but still capture the exception
except Exception as error:
sentry_sdk.capture_exception(error)
return []
return result
def get_custom_measurement_names_set(self) -> set[str]:
return {measurement["name"] for measurement in self.custom_measurement_map}
def get_measurement_by_name(self, name: str) -> MetricMeta | None:
# Skip the iteration if its not a measurement, which can save a custom measurement query entirely
if not is_measurement(name):
return None
for measurement in self.custom_measurement_map:
if measurement["name"] == name:
return measurement
return None
def get_field_type(self, field: str) -> str | None:
if field in self.meta_resolver_map:
return self.meta_resolver_map[field]
if is_percentage_measurement(field):
return "percentage"
if is_numeric_measurement(field):
return "number"
if (
field in self.duration_fields
or is_duration_measurement(field)
or is_span_op_breakdown(field)
):
return "duration"
if unit := self.size_fields.get(field):
return unit
measurement = self.get_measurement_by_name(field)
# let the caller decide what to do
if measurement is None:
return None
unit = measurement["unit"]
if unit in constants.SIZE_UNITS or unit in constants.DURATION_UNITS:
return unit
elif unit == "none":
return "integer"
elif unit in constants.PERCENT_UNITS:
return "percentage"
else:
return "number"
def validate_having_clause(self) -> None:
"""Validate that the functions in having are selected columns
Skipped if auto_aggregations are enabled, and at least one other aggregate is selected
This is so we don't change grouping suddenly
"""
conditions = self.flattened_having
if self.builder_config.auto_aggregations and self.aggregates:
for condition in conditions:
lhs = condition.lhs
if isinstance(lhs, CurriedFunction) and lhs not in self.columns:
self.columns.append(lhs)
self.aggregates.append(lhs)
return
# If auto aggregations is disabled or aggregations aren't present in the first place we throw an error
else:
error_extra = (
", and could not be automatically added"
if self.builder_config.auto_aggregations
else ""
)
for condition in conditions:
lhs = condition.lhs
if isinstance(lhs, CurriedFunction) and lhs not in self.columns:
raise InvalidSearchQuery(
"Aggregate {} used in a condition but is not a selected column{}.".format(
lhs.alias,
error_extra,
)
)
def validate_aggregate_arguments(self) -> None:
# There might not be any columns during the resolve_groupby step
if self.columns and self.requires_other_aggregates and len(self.aggregates) == 0:
raise InvalidSearchQuery(
"Another aggregate function needs to be selected in order to use the total.count field"
)
for column in self.columns:
if column in self.aggregates:
continue
conflicting_functions: list[CurriedFunction] = []
for aggregate in self.aggregates:
if column in aggregate.parameters:
conflicting_functions.append(aggregate)
if conflicting_functions:
# The first two functions and then a trailing count of remaining functions
function_msg = ", ".join(
[self.get_public_alias(function) for function in conflicting_functions[:2]]
) + (
f" and {len(conflicting_functions) - 2} more."
if len(conflicting_functions) > 2
else ""
)
alias = column.name if isinstance(column, Column) else column.alias
raise InvalidSearchQuery(
f"A single field cannot be used both inside and outside a function in the same query. To use {alias} you must first remove the function(s): {function_msg}"
)
# General helper methods
def aliased_column(self, name: str) -> SelectType:
"""Given an unresolved sentry name and an expected alias, return a snql
column that will be aliased to the expected alias.
:param name: The unresolved sentry name.
:param alias: The expected alias in the result.
"""
# TODO: This method should use an aliased column from the SDK once
# that is available to skip these hacks that we currently have to
# do aliasing.
resolved = self.resolve_column_name(name)
column = Column(resolved)
# If the expected alias is identical to the resolved snuba column,
# no need to do this aliasing trick.
#
# Additionally, tags of the form `tags[...]` can't be aliased again
# because it confuses the sdk.
if name == resolved:
return column
# If the expected aliases differs from the resolved snuba column,
# make sure to alias the expression appropriately so we get back
# the column with the correct names.
return AliasedExpression(column, self.tag_to_prefixed_map.get(name, name))
def column(self, name: str) -> Column:
"""Given an unresolved sentry column name and return a snql column.
:param name: The unresolved sentry name.
"""
resolved_column = self.resolve_column_name(name)
if self.entity:
return Column(resolved_column, entity=self.entity)
return Column(resolved_column)
# Query filter helper methods
def add_conditions(self, conditions: list[Condition]) -> None:
self.where += conditions
def parse_query(self, query: str | None) -> event_filter.ParsedTerms:
"""Given a user's query, string construct a list of filters that can be
then used to construct the conditions of the Query"""
if query is None:
return []
try:
parsed_terms = event_search.parse_search_query(
query,
params=self.filter_params,
config=event_search.SearchConfig.create_from(
event_search.default_config,
**self.builder_config.parser_config_overrides,
),
get_field_type=self.get_field_type,
get_function_result_type=self.get_function_result_type,
)
except ParseError as e:
if e.expr is not None:
raise InvalidSearchQuery(f"Parse error: {e.expr.name} (column {e.column():d})")
else:
raise InvalidSearchQuery(f"Parse error for: {query}")
if not parsed_terms:
return []
return parsed_terms
def format_search_filter(self, term: event_search.SearchFilter) -> WhereType | None:
converted_filter = self.convert_search_filter_to_condition(term)
return converted_filter if converted_filter else None
def _combine_conditions(
self, lhs: list[WhereType], rhs: list[WhereType], operator: And | Or
) -> list[WhereType]:
combined_conditions = [
conditions[0] if len(conditions) == 1 else And(conditions=conditions)
for conditions in [lhs, rhs]
if len(conditions) > 0
]
length = len(combined_conditions)
if length == 0:
return []
elif len(combined_conditions) == 1:
return combined_conditions
else:
return [operator(conditions=combined_conditions)]
def resolve_measurement_value(self, unit: str, value: float) -> float:
if unit in constants.SIZE_UNITS:
return constants.SIZE_UNITS[cast(constants.SizeUnit, unit)] * value
elif unit in constants.DURATION_UNITS:
return constants.DURATION_UNITS[cast(constants.DurationUnit, unit)] * value
return value
def convert_aggregate_filter_to_condition(
self, aggregate_filter: event_search.AggregateFilter
) -> WhereType | None:
name = aggregate_filter.key.name
value = aggregate_filter.value.value
unit = self.get_function_result_type(aggregate_filter.key.name)
if unit:
value = self.resolve_measurement_value(unit, value)
value = (
int(value.timestamp()) if isinstance(value, datetime) and name != "timestamp" else value
)
if aggregate_filter.operator in {"=", "!="} and value == "":
operator = Op.IS_NULL if aggregate_filter.operator == "=" else Op.IS_NOT_NULL
return Condition(name, operator)
# When resolving functions in conditions we don't want to add them to the list of aggregates
function = self.resolve_function(name, resolve_only=True)
return Condition(function, Op(aggregate_filter.operator), value)
def convert_search_filter_to_condition(
self,
search_filter: event_search.SearchFilter,
) -> WhereType | None:
name = search_filter.key.name
value = search_filter.value.value
if value and (unit := self.get_field_type(name)):
if unit in constants.SIZE_UNITS or unit in constants.DURATION_UNITS:
value = self.resolve_measurement_value(unit, value)
search_filter = event_search.SearchFilter(
search_filter.key,
search_filter.operator,
event_search.SearchValue(value),
)
if name in constants.NO_CONVERSION_FIELDS:
return None
converter = self.search_filter_converter.get(name, self.default_filter_converter)
return converter(search_filter)
def validate_uuid_like_filters(self, search_filter: event_search.SearchFilter):
name = search_filter.key.name
value = search_filter.value
if name in self.uuid_fields:
if value.is_wildcard():
raise InvalidSearchQuery(WILDCARD_NOT_ALLOWED.format(name))
if not value.is_event_id():
raise InvalidSearchQuery(INVALID_ID_DETAILS.format(name))
def validate_span_id_like_filters(self, search_filter: event_search.SearchFilter):
name = search_filter.key.name
value = search_filter.value
if name in self.span_id_fields:
if value.is_wildcard():
raise InvalidSearchQuery(WILDCARD_NOT_ALLOWED.format(name))
if not value.is_span_id():
raise InvalidSearchQuery(INVALID_SPAN_ID.format(name))
def default_filter_converter(
self, search_filter: event_search.SearchFilter
) -> WhereType | None:
self.validate_uuid_like_filters(search_filter)
self.validate_span_id_like_filters(search_filter)
name = search_filter.key.name
operator = search_filter.operator
value = search_filter.value.value
strs = search_filter.value.split_wildcards()
if strs is not None:
# If we have a mixture of wildcards and non-wildcards in a [] set, we must
# group them into their own sets to apply the appropriate operators, and
# then 'OR' them together.
# It's also the case that queries can look like 'foo:[A*]', meaning a single
# wildcard in a set. Handle that case as well.
(non_wildcards, wildcards) = strs
if len(wildcards) > 0:
operator = "="
if search_filter.operator == "NOT IN":
operator = "!="
filters = [
self.default_filter_converter(
event_search.SearchFilter(
search_filter.key, operator, event_search.SearchValue(wc)
)
)
for wc in wildcards
]
if len(non_wildcards) > 0:
lhs = self.default_filter_converter(
event_search.SearchFilter(
search_filter.key,
search_filter.operator,
event_search.SearchValue(non_wildcards),
)
)
filters.append(lhs)
if len(filters) > 1:
return Or(filters)
else:
return filters[0]
# Some fields aren't valid queries
if name in constants.SKIP_FILTER_RESOLUTION:
name = f"tags[{name}]"
lhs = self.resolve_column(name)
if name in constants.ARRAY_FIELDS:
if search_filter.value.is_wildcard():
# TODO: There are rare cases where this chaining don't
# work. For example, a wildcard like '\**' will incorrectly
# be replaced with '\%%'.
return Condition(
lhs,
Op.LIKE if operator == "=" else Op.NOT_LIKE,
# Slashes have to be double escaped so they are
# interpreted as a string literal.
str(search_filter.value.raw_value)
.replace("\\", "\\\\")
.replace("%", "\\%")
.replace("_", "\\_")
.replace("*", "%"),
)
elif search_filter.is_in_filter:
return Condition(
Function("hasAny", [self.column(name), value]),
Op.EQ if operator == "IN" else Op.NEQ,
1,
)
elif search_filter.value.raw_value == "":
return Condition(
Function("notEmpty", [self.column(name)]),
Op.EQ if operator == "!=" else Op.NEQ,
1,
)
# timestamp{,.to_{hour,day}} need a datetime string
# last_seen needs an integer
if isinstance(value, datetime) and name not in constants.TIMESTAMP_FIELDS:
value = int(value.timestamp()) * 1000
# Tags are never null, but promoted tags are columns and so can be null.
# To handle both cases, use `ifNull` to convert to an empty string and
# compare so we need to check for empty values.
is_tag = isinstance(lhs, Column) and (
lhs.subscriptable == "tags" or lhs.subscriptable == "sentry_tags"
)
is_attr = isinstance(lhs, Column) and (
lhs.subscriptable == "attr_str" or lhs.subscriptable == "attr_num"
)
is_context = isinstance(lhs, Column) and lhs.subscriptable == "contexts"
if is_tag or is_attr:
subscriptable = lhs.subscriptable
if operator not in ["IN", "NOT IN"] and not isinstance(value, str):
sentry_sdk.set_tag("query.lhs", lhs)
sentry_sdk.set_tag("query.rhs", value)
sentry_sdk.capture_message("Tag value was not a string", level="error")
value = str(value)
lhs = Function("ifNull", [lhs, ""])
else:
subscriptable = None
# Handle checks for existence
if search_filter.operator in ("=", "!=") and search_filter.value.value == "":
if is_context and name in self.config.nullable_context_keys:
return Condition(
Function("has", [Column("contexts.key"), lhs.key]),
Op(search_filter.operator),
0,
)
elif is_tag or is_attr or is_context or name in self.config.non_nullable_keys:
return Condition(lhs, Op(search_filter.operator), value)
elif is_measurement(name):
# Measurements can be a `Column` (e.g., `"lcp"`) or a `Function` (e.g., `"frames_frozen_rate"`). In either cause, since they are nullable, return a simple null check
return Condition(
Function("isNull", [lhs]),
Op.EQ,
1 if search_filter.operator == "=" else 0,
)
elif isinstance(lhs, Column):
# If not a tag, we can just check that the column is null.
return Condition(Function("isNull", [lhs]), Op(search_filter.operator), 1)
is_null_condition = None
# TODO(wmak): Skip this for all non-nullable keys not just event.type
if (
search_filter.operator in ("!=", "NOT IN")
and not search_filter.key.is_tag
and not is_attr
and not is_tag
and name not in self.config.non_nullable_keys
):
# Handle null columns on inequality comparisons. Any comparison
# between a value and a null will result to null, so we need to
# explicitly check for whether the condition is null, and OR it
# together with the inequality check.
# We don't need to apply this for tags, since if they don't exist
# they'll always be an empty string.
is_null_condition = Condition(Function("isNull", [lhs]), Op.EQ, 1)
if search_filter.value.is_wildcard():
if self.config.optimize_wildcard_searches:
kind, value_o = search_filter.value.classify_and_format_wildcard()
else:
kind, value_o = "other", search_filter.value.value
if kind == "prefix":
condition = Condition(
Function("startsWith", [Function("lower", [lhs]), value_o]),
Op.EQ if search_filter.operator in constants.EQUALITY_OPERATORS else Op.NEQ,
1,
)
elif kind == "suffix":
condition = Condition(
Function("endsWith", [Function("lower", [lhs]), value_o]),
Op.EQ if search_filter.operator in constants.EQUALITY_OPERATORS else Op.NEQ,
1,
)
elif kind == "infix":
condition = Condition(
Function("positionCaseInsensitive", [lhs, value_o]),
Op.NEQ if search_filter.operator in constants.EQUALITY_OPERATORS else Op.EQ,
0,
)
else:
condition = Condition(
Function("match", [lhs, f"(?i){value}"]),
Op(search_filter.operator),
1,
)
if (
self.config.optimize_wildcard_searches
and subscriptable is not None
and subscriptable in self.config.subscriptables_with_index
):
# Some tables have a bloom filter index on the tags.key
# column that can be used
condition = And(
conditions=[
condition,
Condition(
Function(
"has",
[
# Each dataset is responsible for making sure
# the `{subscriptable}.key` is an available column
self.resolve_column(f"{subscriptable}.key"),
name,
],
),
Op.EQ,
1,
),
]
)
else:
# pull out the aliased expression if it exists
if isinstance(lhs, AliasedExpression):
lhs = lhs.exp
condition = Condition(lhs, Op(search_filter.operator), value)
if is_null_condition:
return Or(conditions=[is_null_condition, condition])
else:
return condition
def _environment_filter_converter(
self, search_filter: event_search.SearchFilter
) -> WhereType | None:
# conditions added to env_conditions can be OR'ed
env_conditions = []
value = search_filter.value.value
values_set = set(value if isinstance(value, (list, tuple)) else [value])
# sorted for consistency
values = sorted(f"{value}" for value in values_set)
environment = self.column("environment")
# the "no environment" environment is null in snuba
if "" in values:
values.remove("")
operator = Op.IS_NULL if search_filter.operator == "=" else Op.IS_NOT_NULL
env_conditions.append(Condition(environment, operator))
if len(values) == 1:
operator = Op.EQ if search_filter.operator in constants.EQUALITY_OPERATORS else Op.NEQ
env_conditions.append(Condition(environment, operator, values.pop()))
elif values:
operator = (
Op.IN if search_filter.operator in constants.EQUALITY_OPERATORS else Op.NOT_IN
)
env_conditions.append(Condition(environment, operator, values))
if len(env_conditions) > 1:
return Or(conditions=env_conditions)
else:
return env_conditions[0]
# Query Fields helper methods
def _resolve_equation_operand(self, operand: OperandType | None) -> SelectType | float:
if isinstance(operand, Operation):
return self.resolve_equation(operand)
elif isinstance(operand, float):
return operand
else:
return self.resolve_column(operand)
def is_equation_column(self, column: SelectType) -> bool:
"""Equations are only ever functions, and shouldn't be literals so we
need to check that the column is a Function
"""
return isinstance(column, CurriedFunction) and is_equation_alias(column.alias)
def is_column_function(self, column: SelectType) -> bool:
return isinstance(column, CurriedFunction) and column not in self.aggregates
def is_field_alias(self, field: str) -> bool:
"""Given a public field, check if it's a field alias"""
return field in self.field_alias_converter
def is_function(self, function: str) -> bool:
""" "Given a public field, check if it's a supported function"""
return function in self.function_converter
def parse_function(self, match: Match[str]) -> tuple[str, str | None, list[str], str]:
"""Given a FUNCTION_PATTERN match, separate the function name, arguments
and alias out
"""
raw_function = match.group("function")
function, combinator = fields.parse_combinator(raw_function)
if not self.is_function(function):
raise self.config.missing_function_error(f"{function} is not a valid function")
arguments = fields.parse_arguments(function, match.group("columns"))
alias: str | Any | None = match.group("alias")
if alias is None:
alias = fields.get_function_alias_with_columns(
raw_function, arguments, self.function_alias_prefix
)
return (function, combinator, arguments, alias)
def get_public_alias(self, function: CurriedFunction) -> str:
"""Given a function resolved by QueryBuilder, get the public alias of that function
ie. any_user_display -> any(user_display)
"""
return self.function_alias_map[function.alias].field
def _get_entity_name(self) -> str:
if self.dataset in DATASET_TO_ENTITY_MAP:
return DATASET_TO_ENTITY_MAP[self.dataset].value
return self.dataset.value
def get_snql_query(self) -> Request:
self.validate_having_clause()
return Request(
dataset=self.dataset.value,
app_id="default",
query=Query(
match=Entity(self._get_entity_name(), sample=self.sample_rate),
select=self.columns,
array_join=self.array_join,
where=self.where,
having=self.having,
groupby=self.groupby,
orderby=self.orderby,
limit=self.limit,
offset=self.offset,
limitby=self.limitby,
),
flags=Flags(turbo=self.turbo),
tenant_ids=self.tenant_ids,
)
def run_query(
self,
referrer: str,
use_cache: bool = False,
query_source: QuerySource | None = None,
) -> Any:
if not referrer:
InvalidSearchQuery("Query missing referrer.")
return raw_snql_query(self.get_snql_query(), referrer, use_cache, query_source)
def process_results(self, results: Any) -> EventsResponse:
with sentry_sdk.start_span(op="QueryBuilder", name="process_results") as span:
span.set_data("result_count", len(results.get("data", [])))
translated_columns = self.alias_to_typed_tag_map
if self.builder_config.transform_alias_to_input_format:
translated_columns.update(
{
column: function_details.field
for column, function_details in self.function_alias_map.items()
}
)
for column in list(self.function_alias_map):
translated_column = translated_columns.get(column, column)
if translated_column in self.function_alias_map:
continue
function_alias = self.function_alias_map.get(column)
if function_alias is not None:
self.function_alias_map[translated_column] = function_alias
if self.raw_equations:
for index, equation in enumerate(self.raw_equations):
translated_columns[f"equation[{index}]"] = f"equation|{equation}"
# process the field meta
field_meta: dict[str, str] = {}
if "meta" in results:
for value in results["meta"]:
name = value["name"]
key = translated_columns.get(name, name)
key = self.prefixed_to_tag_map.get(key, key)
field_type = fields.get_json_meta_type(key, value.get("type"), self)
field_meta[key] = field_type
# Ensure all columns in the result have types.
if results["data"]:
for key in results["data"][0]:
field_key = translated_columns.get(key, key)
field_key = self.prefixed_to_tag_map.get(field_key, field_key)
if field_key not in field_meta:
field_meta[field_key] = "string"
# process the field results
def get_row(row: dict[str, Any]) -> dict[str, Any]:
transformed = {}
for key, value in row.items():
value = process_value(value)
if key in self.value_resolver_map:
new_value = self.value_resolver_map[key](value)
else:
new_value = value
resolved_key = translated_columns.get(key, key)
if not self.builder_config.skip_tag_resolution:
resolved_key = self.prefixed_to_tag_map.get(resolved_key, resolved_key)
transformed[resolved_key] = new_value
return transformed
return {
"data": [get_row(row) for row in results["data"]],
"meta": {
"fields": field_meta,
"tips": {},
},
}
|
BaseQueryBuilder
|
python
|
google__flatbuffers
|
python/flatbuffers/flexbuffers.py
|
{
"start": 1097,
"end": 4770
}
|
class ____(enum.IntEnum):
"""Supported bit widths of value types.
These are used in the lower 2 bits of a type field to determine the size of
the elements (and or size field) of the item pointed to (e.g. vector).
"""
W8 = 0 # 2^0 = 1 byte
W16 = 1 # 2^1 = 2 bytes
W32 = 2 # 2^2 = 4 bytes
W64 = 3 # 2^3 = 8 bytes
@staticmethod
def U(value):
"""Returns the minimum `BitWidth` to encode unsigned integer value."""
assert value >= 0
if value < (1 << 8):
return BitWidth.W8
elif value < (1 << 16):
return BitWidth.W16
elif value < (1 << 32):
return BitWidth.W32
elif value < (1 << 64):
return BitWidth.W64
else:
raise ValueError('value is too big to encode: %s' % value)
@staticmethod
def I(value):
"""Returns the minimum `BitWidth` to encode signed integer value."""
# -2^(n-1) <= value < 2^(n-1)
# -2^n <= 2 * value < 2^n
# 2 * value < 2^n, when value >= 0 or 2 * (-value) <= 2^n, when value < 0
# 2 * value < 2^n, when value >= 0 or 2 * (-value) - 1 < 2^n, when value < 0
#
# if value >= 0:
# return BitWidth.U(2 * value)
# else:
# return BitWidth.U(2 * (-value) - 1) # ~x = -x - 1
value *= 2
return BitWidth.U(value if value >= 0 else ~value)
@staticmethod
def F(value):
"""Returns the `BitWidth` to encode floating point value."""
if struct.unpack('<f', struct.pack('<f', value))[0] == value:
return BitWidth.W32
return BitWidth.W64
@staticmethod
def B(byte_width):
return {1: BitWidth.W8, 2: BitWidth.W16, 4: BitWidth.W32, 8: BitWidth.W64}[
byte_width
]
I = {1: 'b', 2: 'h', 4: 'i', 8: 'q'} # Integer formats
U = {1: 'B', 2: 'H', 4: 'I', 8: 'Q'} # Unsigned integer formats
F = {4: 'f', 8: 'd'} # Floating point formats
def _Unpack(fmt, buf):
return struct.unpack('<%s' % fmt[len(buf)], buf)[0]
def _UnpackVector(fmt, buf, length):
byte_width = len(buf) // length
return struct.unpack('<%d%s' % (length, fmt[byte_width]), buf)
def _Pack(fmt, value, byte_width):
return struct.pack('<%s' % fmt[byte_width], value)
def _PackVector(fmt, values, byte_width):
return struct.pack('<%d%s' % (len(values), fmt[byte_width]), *values)
def _Mutate(fmt, buf, value, byte_width, value_bit_width):
if (1 << value_bit_width) <= byte_width:
buf[:byte_width] = _Pack(fmt, value, byte_width)
return True
return False
# Computes how many bytes you'd have to pad to be able to write an
# "scalar_size" scalar if the buffer had grown to "buf_size",
# "scalar_size" is a power of two.
def _PaddingBytes(buf_size, scalar_size):
# ((buf_size + (scalar_size - 1)) // scalar_size) * scalar_size - buf_size
return -buf_size & (scalar_size - 1)
def _ShiftSlice(s, offset, length):
start = offset + (0 if s.start is None else s.start)
stop = offset + (length if s.stop is None else s.stop)
return slice(start, stop, s.step)
# https://en.cppreference.com/w/cpp/algorithm/lower_bound
def _LowerBound(values, value, pred):
"""Implementation of C++ std::lower_bound() algorithm."""
first, last = 0, len(values)
count = last - first
while count > 0:
i = first
step = count // 2
i += step
if pred(values[i], value):
i += 1
first = i
count -= step + 1
else:
count = step
return first
# https://en.cppreference.com/w/cpp/algorithm/binary_search
def _BinarySearch(values, value, pred=lambda x, y: x < y):
"""Implementation of C++ std::binary_search() algorithm."""
index = _LowerBound(values, value, pred)
if index != len(values) and not pred(value, values[index]):
return index
return -1
|
BitWidth
|
python
|
numpy__numpy
|
numpy/matrixlib/defmatrix.py
|
{
"start": 1626,
"end": 30875
}
|
class ____(N.ndarray):
"""
matrix(data, dtype=None, copy=True)
Returns a matrix from an array-like object, or from a string of data.
A matrix is a specialized 2-D array that retains its 2-D nature
through operations. It has certain special operators, such as ``*``
(matrix multiplication) and ``**`` (matrix power).
.. note:: It is no longer recommended to use this class, even for linear
algebra. Instead use regular arrays. The class may be removed
in the future.
Parameters
----------
data : array_like or string
If `data` is a string, it is interpreted as a matrix with commas
or spaces separating columns, and semicolons separating rows.
dtype : data-type
Data-type of the output matrix.
copy : bool
If `data` is already an `ndarray`, then this flag determines
whether the data is copied (the default), or whether a view is
constructed.
See Also
--------
array
Examples
--------
>>> import numpy as np
>>> a = np.matrix('1 2; 3 4')
>>> a
matrix([[1, 2],
[3, 4]])
>>> np.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
"""
__array_priority__ = 10.0
def __new__(subtype, data, dtype=None, copy=True):
warnings.warn('the matrix subclass is not the recommended way to '
'represent matrices or deal with linear algebra (see '
'https://docs.scipy.org/doc/numpy/user/'
'numpy-for-matlab-users.html). '
'Please adjust your code to use regular ndarray.',
PendingDeprecationWarning, stacklevel=2)
if isinstance(data, matrix):
dtype2 = data.dtype
if (dtype is None):
dtype = dtype2
if (dtype2 == dtype) and (not copy):
return data
return data.astype(dtype)
if isinstance(data, N.ndarray):
if dtype is None:
intype = data.dtype
else:
intype = N.dtype(dtype)
new = data.view(subtype)
if intype != data.dtype:
return new.astype(intype)
if copy:
return new.copy()
else:
return new
if isinstance(data, str):
data = _convert_from_string(data)
# now convert data to an array
copy = None if not copy else True
arr = N.array(data, dtype=dtype, copy=copy)
ndim = arr.ndim
shape = arr.shape
if (ndim > 2):
raise ValueError("matrix must be 2-dimensional")
elif ndim == 0:
shape = (1, 1)
elif ndim == 1:
shape = (1, shape[0])
order = 'C'
if (ndim == 2) and arr.flags.fortran:
order = 'F'
if not (order or arr.flags.contiguous):
arr = arr.copy()
ret = N.ndarray.__new__(subtype, shape, arr.dtype,
buffer=arr,
order=order)
return ret
def __array_finalize__(self, obj):
self._getitem = False
if (isinstance(obj, matrix) and obj._getitem):
return
ndim = self.ndim
if (ndim == 2):
return
if (ndim > 2):
newshape = tuple(x for x in self.shape if x > 1)
ndim = len(newshape)
if ndim == 2:
self.shape = newshape
return
elif (ndim > 2):
raise ValueError("shape too large to be a matrix.")
else:
newshape = self.shape
if ndim == 0:
self.shape = (1, 1)
elif ndim == 1:
self.shape = (1, newshape[0])
return
def __getitem__(self, index):
self._getitem = True
try:
out = N.ndarray.__getitem__(self, index)
finally:
self._getitem = False
if not isinstance(out, N.ndarray):
return out
if out.ndim == 0:
return out[()]
if out.ndim == 1:
sh = out.shape[0]
# Determine when we should have a column array
try:
n = len(index)
except Exception:
n = 0
if n > 1 and isscalar(index[1]):
out.shape = (sh, 1)
else:
out.shape = (1, sh)
return out
def __mul__(self, other):
if isinstance(other, (N.ndarray, list, tuple)):
# This promotes 1-D vectors to row vectors
return N.dot(self, asmatrix(other))
if isscalar(other) or not hasattr(other, '__rmul__'):
return N.dot(self, other)
return NotImplemented
def __rmul__(self, other):
return N.dot(other, self)
def __imul__(self, other):
self[:] = self * other
return self
def __pow__(self, other):
return matrix_power(self, other)
def __ipow__(self, other):
self[:] = self ** other
return self
def __rpow__(self, other):
return NotImplemented
def _align(self, axis):
"""A convenience function for operations that need to preserve axis
orientation.
"""
if axis is None:
return self[0, 0]
elif axis == 0:
return self
elif axis == 1:
return self.transpose()
else:
raise ValueError("unsupported axis")
def _collapse(self, axis):
"""A convenience function for operations that want to collapse
to a scalar like _align, but are using keepdims=True
"""
if axis is None:
return self[0, 0]
else:
return self
# Necessary because base-class tolist expects dimension
# reduction by x[0]
def tolist(self):
"""
Return the matrix as a (possibly nested) list.
See `ndarray.tolist` for full documentation.
See Also
--------
ndarray.tolist
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.tolist()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
"""
return self.__array__().tolist()
# To preserve orientation of result...
def sum(self, axis=None, dtype=None, out=None):
"""
Returns the sum of the matrix elements, along the given axis.
Refer to `numpy.sum` for full documentation.
See Also
--------
numpy.sum
Notes
-----
This is the same as `ndarray.sum`, except that where an `ndarray` would
be returned, a `matrix` object is returned instead.
Examples
--------
>>> x = np.matrix([[1, 2], [4, 3]])
>>> x.sum()
10
>>> x.sum(axis=1)
matrix([[3],
[7]])
>>> x.sum(axis=1, dtype='float')
matrix([[3.],
[7.]])
>>> out = np.zeros((2, 1), dtype='float')
>>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
matrix([[3.],
[7.]])
"""
return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)
# To update docstring from array to matrix...
def squeeze(self, axis=None):
"""
Return a possibly reshaped matrix.
Refer to `numpy.squeeze` for more documentation.
Parameters
----------
axis : None or int or tuple of ints, optional
Selects a subset of the axes of length one in the shape.
If an axis is selected with shape entry greater than one,
an error is raised.
Returns
-------
squeezed : matrix
The matrix, but as a (1, N) matrix if it had shape (N, 1).
See Also
--------
numpy.squeeze : related function
Notes
-----
If `m` has a single column then that column is returned
as the single row of a matrix. Otherwise `m` is returned.
The returned matrix is always either `m` itself or a view into `m`.
Supplying an axis keyword argument will not affect the returned matrix
but it may cause an error to be raised.
Examples
--------
>>> c = np.matrix([[1], [2]])
>>> c
matrix([[1],
[2]])
>>> c.squeeze()
matrix([[1, 2]])
>>> r = c.T
>>> r
matrix([[1, 2]])
>>> r.squeeze()
matrix([[1, 2]])
>>> m = np.matrix([[1, 2], [3, 4]])
>>> m.squeeze()
matrix([[1, 2],
[3, 4]])
"""
return N.ndarray.squeeze(self, axis=axis)
# To update docstring from array to matrix...
def flatten(self, order='C'):
"""
Return a flattened copy of the matrix.
All `N` elements of the matrix are placed into a single row.
Parameters
----------
order : {'C', 'F', 'A', 'K'}, optional
'C' means to flatten in row-major (C-style) order. 'F' means to
flatten in column-major (Fortran-style) order. 'A' means to
flatten in column-major order if `m` is Fortran *contiguous* in
memory, row-major order otherwise. 'K' means to flatten `m` in
the order the elements occur in memory. The default is 'C'.
Returns
-------
y : matrix
A copy of the matrix, flattened to a `(1, N)` matrix where `N`
is the number of elements in the original matrix.
See Also
--------
ravel : Return a flattened array.
flat : A 1-D flat iterator over the matrix.
Examples
--------
>>> m = np.matrix([[1,2], [3,4]])
>>> m.flatten()
matrix([[1, 2, 3, 4]])
>>> m.flatten('F')
matrix([[1, 3, 2, 4]])
"""
return N.ndarray.flatten(self, order=order)
def mean(self, axis=None, dtype=None, out=None):
"""
Returns the average of the matrix elements along the given axis.
Refer to `numpy.mean` for full documentation.
See Also
--------
numpy.mean
Notes
-----
Same as `ndarray.mean` except that, where that returns an `ndarray`,
this returns a `matrix` object.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3, 4)))
>>> x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.mean()
5.5
>>> x.mean(0)
matrix([[4., 5., 6., 7.]])
>>> x.mean(1)
matrix([[ 1.5],
[ 5.5],
[ 9.5]])
"""
return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)
def std(self, axis=None, dtype=None, out=None, ddof=0):
"""
Return the standard deviation of the array elements along the given axis.
Refer to `numpy.std` for full documentation.
See Also
--------
numpy.std
Notes
-----
This is the same as `ndarray.std`, except that where an `ndarray` would
be returned, a `matrix` object is returned instead.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3, 4)))
>>> x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.std()
3.4520525295346629 # may vary
>>> x.std(0)
matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
>>> x.std(1)
matrix([[ 1.11803399],
[ 1.11803399],
[ 1.11803399]])
"""
return N.ndarray.std(self, axis, dtype, out, ddof,
keepdims=True)._collapse(axis)
def var(self, axis=None, dtype=None, out=None, ddof=0):
"""
Returns the variance of the matrix elements, along the given axis.
Refer to `numpy.var` for full documentation.
See Also
--------
numpy.var
Notes
-----
This is the same as `ndarray.var`, except that where an `ndarray` would
be returned, a `matrix` object is returned instead.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3, 4)))
>>> x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.var()
11.916666666666666
>>> x.var(0)
matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
>>> x.var(1)
matrix([[1.25],
[1.25],
[1.25]])
"""
return N.ndarray.var(self, axis, dtype, out, ddof,
keepdims=True)._collapse(axis)
def prod(self, axis=None, dtype=None, out=None):
"""
Return the product of the array elements over the given axis.
Refer to `prod` for full documentation.
See Also
--------
prod, ndarray.prod
Notes
-----
Same as `ndarray.prod`, except, where that returns an `ndarray`, this
returns a `matrix` object instead.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.prod()
0
>>> x.prod(0)
matrix([[ 0, 45, 120, 231]])
>>> x.prod(1)
matrix([[ 0],
[ 840],
[7920]])
"""
return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis)
def any(self, axis=None, out=None):
"""
Test whether any array element along a given axis evaluates to True.
Refer to `numpy.any` for full documentation.
Parameters
----------
axis : int, optional
Axis along which logical OR is performed
out : ndarray, optional
Output to existing array instead of creating new one, must have
same shape as expected output
Returns
-------
any : bool, ndarray
Returns a single bool if `axis` is ``None``; otherwise,
returns `ndarray`
"""
return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis)
def all(self, axis=None, out=None):
"""
Test whether all matrix elements along a given axis evaluate to True.
Parameters
----------
See `numpy.all` for complete descriptions
See Also
--------
numpy.all
Notes
-----
This is the same as `ndarray.all`, but it returns a `matrix` object.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> y = x[0]; y
matrix([[0, 1, 2, 3]])
>>> (x == y)
matrix([[ True, True, True, True],
[False, False, False, False],
[False, False, False, False]])
>>> (x == y).all()
False
>>> (x == y).all(0)
matrix([[False, False, False, False]])
>>> (x == y).all(1)
matrix([[ True],
[False],
[False]])
"""
return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis)
def max(self, axis=None, out=None):
"""
Return the maximum value along an axis.
Parameters
----------
See `amax` for complete descriptions
See Also
--------
amax, ndarray.max
Notes
-----
This is the same as `ndarray.max`, but returns a `matrix` object
where `ndarray.max` would return an ndarray.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.max()
11
>>> x.max(0)
matrix([[ 8, 9, 10, 11]])
>>> x.max(1)
matrix([[ 3],
[ 7],
[11]])
"""
return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis)
def argmax(self, axis=None, out=None):
"""
Indexes of the maximum values along an axis.
Return the indexes of the first occurrences of the maximum values
along the specified axis. If axis is None, the index is for the
flattened matrix.
Parameters
----------
See `numpy.argmax` for complete descriptions
See Also
--------
numpy.argmax
Notes
-----
This is the same as `ndarray.argmax`, but returns a `matrix` object
where `ndarray.argmax` would return an `ndarray`.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.argmax()
11
>>> x.argmax(0)
matrix([[2, 2, 2, 2]])
>>> x.argmax(1)
matrix([[3],
[3],
[3]])
"""
return N.ndarray.argmax(self, axis, out)._align(axis)
def min(self, axis=None, out=None):
"""
Return the minimum value along an axis.
Parameters
----------
See `amin` for complete descriptions.
See Also
--------
amin, ndarray.min
Notes
-----
This is the same as `ndarray.min`, but returns a `matrix` object
where `ndarray.min` would return an ndarray.
Examples
--------
>>> x = -np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, -1, -2, -3],
[ -4, -5, -6, -7],
[ -8, -9, -10, -11]])
>>> x.min()
-11
>>> x.min(0)
matrix([[ -8, -9, -10, -11]])
>>> x.min(1)
matrix([[ -3],
[ -7],
[-11]])
"""
return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis)
def argmin(self, axis=None, out=None):
"""
Indexes of the minimum values along an axis.
Return the indexes of the first occurrences of the minimum values
along the specified axis. If axis is None, the index is for the
flattened matrix.
Parameters
----------
See `numpy.argmin` for complete descriptions.
See Also
--------
numpy.argmin
Notes
-----
This is the same as `ndarray.argmin`, but returns a `matrix` object
where `ndarray.argmin` would return an `ndarray`.
Examples
--------
>>> x = -np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, -1, -2, -3],
[ -4, -5, -6, -7],
[ -8, -9, -10, -11]])
>>> x.argmin()
11
>>> x.argmin(0)
matrix([[2, 2, 2, 2]])
>>> x.argmin(1)
matrix([[3],
[3],
[3]])
"""
return N.ndarray.argmin(self, axis, out)._align(axis)
def ptp(self, axis=None, out=None):
"""
Peak-to-peak (maximum - minimum) value along the given axis.
Refer to `numpy.ptp` for full documentation.
See Also
--------
numpy.ptp
Notes
-----
Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
this returns a `matrix` object.
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.ptp()
11
>>> x.ptp(0)
matrix([[8, 8, 8, 8]])
>>> x.ptp(1)
matrix([[3],
[3],
[3]])
"""
return N.ptp(self, axis, out)._align(axis)
@property
def I(self): # noqa: E743
"""
Returns the (multiplicative) inverse of invertible `self`.
Parameters
----------
None
Returns
-------
ret : matrix object
If `self` is non-singular, `ret` is such that ``ret * self`` ==
``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
``True``.
Raises
------
numpy.linalg.LinAlgError: Singular matrix
If `self` is singular.
See Also
--------
linalg.inv
Examples
--------
>>> m = np.matrix('[1, 2; 3, 4]'); m
matrix([[1, 2],
[3, 4]])
>>> m.getI()
matrix([[-2. , 1. ],
[ 1.5, -0.5]])
>>> m.getI() * m
matrix([[ 1., 0.], # may vary
[ 0., 1.]])
"""
M, N = self.shape
if M == N:
from numpy.linalg import inv as func
else:
from numpy.linalg import pinv as func
return asmatrix(func(self))
@property
def A(self):
"""
Return `self` as an `ndarray` object.
Equivalent to ``np.asarray(self)``.
Parameters
----------
None
Returns
-------
ret : ndarray
`self` as an `ndarray`
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.getA()
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
"""
return self.__array__()
@property
def A1(self):
"""
Return `self` as a flattened `ndarray`.
Equivalent to ``np.asarray(x).ravel()``
Parameters
----------
None
Returns
-------
ret : ndarray
`self`, 1-D, as an `ndarray`
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.getA1()
array([ 0, 1, 2, ..., 9, 10, 11])
"""
return self.__array__().ravel()
def ravel(self, order='C'):
"""
Return a flattened matrix.
Refer to `numpy.ravel` for more documentation.
Parameters
----------
order : {'C', 'F', 'A', 'K'}, optional
The elements of `m` are read using this index order. 'C' means to
index the elements in C-like order, with the last axis index
changing fastest, back to the first axis index changing slowest.
'F' means to index the elements in Fortran-like index order, with
the first index changing fastest, and the last index changing
slowest. Note that the 'C' and 'F' options take no account of the
memory layout of the underlying array, and only refer to the order
of axis indexing. 'A' means to read the elements in Fortran-like
index order if `m` is Fortran *contiguous* in memory, C-like order
otherwise. 'K' means to read the elements in the order they occur
in memory, except for reversing the data when strides are negative.
By default, 'C' index order is used.
Returns
-------
ret : matrix
Return the matrix flattened to shape `(1, N)` where `N`
is the number of elements in the original matrix.
A copy is made only if necessary.
See Also
--------
matrix.flatten : returns a similar output matrix but always a copy
matrix.flat : a flat iterator on the array.
numpy.ravel : related function which returns an ndarray
"""
return N.ndarray.ravel(self, order=order)
@property
def T(self):
"""
Returns the transpose of the matrix.
Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
Parameters
----------
None
Returns
-------
ret : matrix object
The (non-conjugated) transpose of the matrix.
See Also
--------
transpose, getH
Examples
--------
>>> m = np.matrix('[1, 2; 3, 4]')
>>> m
matrix([[1, 2],
[3, 4]])
>>> m.getT()
matrix([[1, 3],
[2, 4]])
"""
return self.transpose()
@property
def H(self):
"""
Returns the (complex) conjugate transpose of `self`.
Equivalent to ``np.transpose(self)`` if `self` is real-valued.
Parameters
----------
None
Returns
-------
ret : matrix object
complex conjugate transpose of `self`
Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4)))
>>> z = x - 1j*x; z
matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
[ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
[ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
>>> z.getH()
matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
[ 1. +1.j, 5. +5.j, 9. +9.j],
[ 2. +2.j, 6. +6.j, 10.+10.j],
[ 3. +3.j, 7. +7.j, 11.+11.j]])
"""
if issubclass(self.dtype.type, N.complexfloating):
return self.transpose().conjugate()
else:
return self.transpose()
# kept for compatibility
getT = T.fget
getA = A.fget
getA1 = A1.fget
getH = H.fget
getI = I.fget
def _from_string(str, gdict, ldict):
rows = str.split(';')
rowtup = []
for row in rows:
trow = row.split(',')
newrow = []
for x in trow:
newrow.extend(x.split())
trow = newrow
coltup = []
for col in trow:
col = col.strip()
try:
thismat = ldict[col]
except KeyError:
try:
thismat = gdict[col]
except KeyError as e:
raise NameError(f"name {col!r} is not defined") from None
coltup.append(thismat)
rowtup.append(concatenate(coltup, axis=-1))
return concatenate(rowtup, axis=0)
@set_module('numpy')
def bmat(obj, ldict=None, gdict=None):
"""
Build a matrix object from a string, nested sequence, or array.
Parameters
----------
obj : str or array_like
Input data. If a string, variables in the current scope may be
referenced by name.
ldict : dict, optional
A dictionary that replaces local operands in current frame.
Ignored if `obj` is not a string or `gdict` is None.
gdict : dict, optional
A dictionary that replaces global operands in current frame.
Ignored if `obj` is not a string.
Returns
-------
out : matrix
Returns a matrix object, which is a specialized 2-D array.
See Also
--------
block :
A generalization of this function for N-d arrays, that returns normal
ndarrays.
Examples
--------
>>> import numpy as np
>>> A = np.asmatrix('1 1; 1 1')
>>> B = np.asmatrix('2 2; 2 2')
>>> C = np.asmatrix('3 4; 5 6')
>>> D = np.asmatrix('7 8; 9 0')
All the following expressions construct the same block matrix:
>>> np.bmat([[A, B], [C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat('A,B; C,D')
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
"""
if isinstance(obj, str):
if gdict is None:
# get previous frame
frame = sys._getframe().f_back
glob_dict = frame.f_globals
loc_dict = frame.f_locals
else:
glob_dict = gdict
loc_dict = ldict
return matrix(_from_string(obj, glob_dict, loc_dict))
if isinstance(obj, (tuple, list)):
# [[A,B],[C,D]]
arr_rows = []
for row in obj:
if isinstance(row, N.ndarray): # not 2-d
return matrix(concatenate(obj, axis=-1))
else:
arr_rows.append(concatenate(row, axis=-1))
return matrix(concatenate(arr_rows, axis=0))
if isinstance(obj, N.ndarray):
return matrix(obj)
|
matrix
|
python
|
ansible__ansible
|
lib/ansible/utils/collection_loader/_collection_config.py
|
{
"start": 378,
"end": 1178
}
|
class ____:
def __init__(self):
self._handlers = set()
def __iadd__(self, handler):
if not callable(handler):
raise ValueError('handler must be callable')
self._handlers.add(handler)
return self
def __isub__(self, handler):
try:
self._handlers.remove(handler)
except KeyError:
pass
return self
def _on_exception(self, handler, exc, *args, **kwargs):
# if we return True, we want the caller to re-raise
return True
def fire(self, *args, **kwargs):
for h in self._handlers:
try:
h(*args, **kwargs)
except Exception as ex:
if self._on_exception(h, ex, *args, **kwargs):
raise
|
_EventSource
|
python
|
prompt-toolkit__python-prompt-toolkit
|
src/prompt_toolkit/output/win32.py
|
{
"start": 17362,
"end": 17597
}
|
class ____:
BLACK = 0x0000
BLUE = 0x0001
GREEN = 0x0002
CYAN = 0x0003
RED = 0x0004
MAGENTA = 0x0005
YELLOW = 0x0006
GRAY = 0x0007
INTENSITY = 0x0008 # Foreground color is intensified.
|
FOREGROUND_COLOR
|
python
|
django__django
|
tests/model_indexes/tests.py
|
{
"start": 11649,
"end": 14735
}
|
class ____(TestCase):
@skipUnlessDBFeature("supports_tablespaces")
def test_db_tablespace(self):
editor = connection.schema_editor()
# Index with db_tablespace attribute.
for fields in [
# Field with db_tablespace specified on model.
["shortcut"],
# Field without db_tablespace specified on model.
["author"],
# Multi-column with db_tablespaces specified on model.
["shortcut", "isbn"],
# Multi-column without db_tablespace specified on model.
["title", "author"],
]:
with self.subTest(fields=fields):
index = models.Index(fields=fields, db_tablespace="idx_tbls2")
self.assertIn(
'"idx_tbls2"', str(index.create_sql(Book, editor)).lower()
)
# Indexes without db_tablespace attribute.
for fields in [["author"], ["shortcut", "isbn"], ["title", "author"]]:
with self.subTest(fields=fields):
index = models.Index(fields=fields)
# The DEFAULT_INDEX_TABLESPACE setting can't be tested because
# it's evaluated when the model class is defined. As a
# consequence, @override_settings doesn't work.
if settings.DEFAULT_INDEX_TABLESPACE:
self.assertIn(
'"%s"' % settings.DEFAULT_INDEX_TABLESPACE,
str(index.create_sql(Book, editor)).lower(),
)
else:
self.assertNotIn("TABLESPACE", str(index.create_sql(Book, editor)))
# Field with db_tablespace specified on the model and an index without
# db_tablespace.
index = models.Index(fields=["shortcut"])
self.assertIn('"idx_tbls"', str(index.create_sql(Book, editor)).lower())
@skipUnlessDBFeature("supports_tablespaces")
def test_func_with_tablespace(self):
# Functional index with db_tablespace attribute.
index = models.Index(
Lower("shortcut").desc(),
name="functional_tbls",
db_tablespace="idx_tbls2",
)
with connection.schema_editor() as editor:
sql = str(index.create_sql(Book, editor))
self.assertIn(editor.quote_name("idx_tbls2"), sql)
# Functional index without db_tablespace attribute.
index = models.Index(Lower("shortcut").desc(), name="functional_no_tbls")
with connection.schema_editor() as editor:
sql = str(index.create_sql(Book, editor))
# The DEFAULT_INDEX_TABLESPACE setting can't be tested because it's
# evaluated when the model class is defined. As a consequence,
# @override_settings doesn't work.
if settings.DEFAULT_INDEX_TABLESPACE:
self.assertIn(
editor.quote_name(settings.DEFAULT_INDEX_TABLESPACE),
sql,
)
else:
self.assertNotIn("TABLESPACE", sql)
|
IndexesTests
|
python
|
scrapy__scrapy
|
scrapy/resolver.py
|
{
"start": 764,
"end": 2380
}
|
class ____(ThreadedResolver):
"""
Default caching resolver. IPv4 only, supports setting a timeout value for DNS requests.
"""
def __init__(self, reactor: ReactorBase, cache_size: int, timeout: float):
super().__init__(reactor)
dnscache.limit = cache_size
self.timeout = timeout
@classmethod
def from_crawler(cls, crawler: Crawler, reactor: ReactorBase) -> Self:
if crawler.settings.getbool("DNSCACHE_ENABLED"):
cache_size = crawler.settings.getint("DNSCACHE_SIZE")
else:
cache_size = 0
return cls(reactor, cache_size, crawler.settings.getfloat("DNS_TIMEOUT"))
def install_on_reactor(self) -> None:
self.reactor.installResolver(self)
def getHostByName(self, name: str, timeout: Sequence[int] = ()) -> Deferred[str]:
if name in dnscache:
return defer.succeed(dnscache[name])
# in Twisted<=16.6, getHostByName() is always called with
# a default timeout of 60s (actually passed as (1, 3, 11, 45) tuple),
# so the input argument above is simply overridden
# to enforce Scrapy's DNS_TIMEOUT setting's value
# The timeout arg is typed as Sequence[int] but supports floats.
timeout = (self.timeout,) # type: ignore[assignment]
d = super().getHostByName(name, timeout)
if dnscache.limit:
d.addCallback(self._cache_result, name)
return d
def _cache_result(self, result: Any, name: str) -> Any:
dnscache[name] = result
return result
@implementer(IHostResolution)
|
CachingThreadedResolver
|
python
|
astropy__astropy
|
astropy/samp/tests/test_standard_profile.py
|
{
"start": 468,
"end": 8894
}
|
class ____:
@property
def hub_init_kwargs(self):
return {}
@property
def client_init_kwargs(self):
return {}
@property
def client_connect_kwargs(self):
return {}
@pytest.fixture(autouse=True)
def setup_method(self, tmp_path):
self.tmpdir = str(tmp_path)
self.hub = SAMPHubServer(
web_profile=False, mode="multiple", pool_size=1, **self.hub_init_kwargs
)
self.hub.start()
self.client1 = SAMPIntegratedClient(**self.client_init_kwargs)
self.client1.connect(hub=self.hub, pool_size=1, **self.client_connect_kwargs)
self.client2 = SAMPIntegratedClient(**self.client_init_kwargs)
self.client2.connect(hub=self.hub, pool_size=1, **self.client_connect_kwargs)
def teardown_method(self):
if self.client1.is_connected:
self.client1.disconnect()
if self.client2.is_connected:
self.client2.disconnect()
self.hub.stop()
def test_main(self):
self.client1_id = self.client1.get_public_id()
self.client2_id = self.client2.get_public_id()
self.metadata1 = {
"samp.name": "Client 1",
"samp.description.text": "Client 1 Description",
"client.version": "1.1",
}
self.metadata2 = {
"samp.name": "Client 2",
"samp.description.text": "Client 2 Description",
"client.version": "1.2",
}
# Check that the clients are connected
assert self.client1.is_connected
assert self.client2.is_connected
# Check that ping works
self.client1.ping()
self.client2.ping()
# Check that get_registered_clients works as expected.
assert self.client1_id not in self.client1.get_registered_clients()
assert self.client2_id in self.client1.get_registered_clients()
assert self.client1_id in self.client2.get_registered_clients()
assert self.client2_id not in self.client2.get_registered_clients()
# Check that get_metadata works as expected
assert self.client1.get_metadata(self.client1_id) == {}
assert self.client1.get_metadata(self.client2_id) == {}
assert self.client2.get_metadata(self.client1_id) == {}
assert self.client2.get_metadata(self.client2_id) == {}
self.client1.declare_metadata(self.metadata1)
assert self.client1.get_metadata(self.client1_id) == self.metadata1
assert self.client2.get_metadata(self.client1_id) == self.metadata1
assert self.client1.get_metadata(self.client2_id) == {}
assert self.client2.get_metadata(self.client2_id) == {}
self.client2.declare_metadata(self.metadata2)
assert self.client1.get_metadata(self.client1_id) == self.metadata1
assert self.client2.get_metadata(self.client1_id) == self.metadata1
assert self.client1.get_metadata(self.client2_id) == self.metadata2
assert self.client2.get_metadata(self.client2_id) == self.metadata2
# Check that, without subscriptions, sending a notification from one
# client to another raises an error.
message = {}
message["samp.mtype"] = "table.load.votable"
message["samp.params"] = {}
with pytest.raises(SAMPProxyError):
self.client1.notify(self.client2_id, message)
# Check that there are no currently active subscriptions
assert self.client1.get_subscribed_clients("table.load.votable") == {}
assert self.client2.get_subscribed_clients("table.load.votable") == {}
# We now test notifications and calls
rec1 = Receiver(self.client1)
rec2 = Receiver(self.client2)
self.client2.bind_receive_notification(
"table.load.votable", rec2.receive_notification
)
self.client2.bind_receive_call("table.load.votable", rec2.receive_call)
self.client1.bind_receive_response("test-tag", rec1.receive_response)
# Check resulting subscriptions
assert self.client1.get_subscribed_clients("table.load.votable") == {
self.client2_id: {}
}
assert self.client2.get_subscribed_clients("table.load.votable") == {}
assert "table.load.votable" in self.client1.get_subscriptions(self.client2_id)
assert "table.load.votable" in self.client2.get_subscriptions(self.client2_id)
# Once we have finished with the calls and notifications, we will
# check the data got across correctly.
# Test notify
params = random_params(self.tmpdir)
self.client1.notify(
self.client2.get_public_id(),
{"samp.mtype": "table.load.votable", "samp.params": params},
)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
params = random_params(self.tmpdir)
self.client1.enotify(
self.client2.get_public_id(), "table.load.votable", **params
)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
# Test notify_all
params = random_params(self.tmpdir)
self.client1.notify_all(
{"samp.mtype": "table.load.votable", "samp.params": params}
)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
params = random_params(self.tmpdir)
self.client1.enotify_all("table.load.votable", **params)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
# Test call
params = random_params(self.tmpdir)
self.client1.call(
self.client2.get_public_id(),
"test-tag",
{"samp.mtype": "table.load.votable", "samp.params": params},
)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
params = random_params(self.tmpdir)
self.client1.ecall(
self.client2.get_public_id(), "test-tag", "table.load.votable", **params
)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
# Test call_all
params = random_params(self.tmpdir)
self.client1.call_all(
"tag1", {"samp.mtype": "table.load.votable", "samp.params": params}
)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
params = random_params(self.tmpdir)
self.client1.ecall_all("tag2", "table.load.votable", **params)
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
# Test call_and_wait
params = random_params(self.tmpdir)
result = self.client1.call_and_wait(
self.client2.get_public_id(),
{"samp.mtype": "table.load.votable", "samp.params": params},
timeout=5,
)
assert result == TEST_REPLY
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
params = random_params(self.tmpdir)
result = self.client1.ecall_and_wait(
self.client2.get_public_id(), "table.load.votable", timeout=5, **params
)
assert result == TEST_REPLY
assert_output(
"table.load.votable",
self.client2.get_private_key(),
self.client1_id,
params,
timeout=60,
)
# TODO: check that receive_response received the right data
|
TestStandardProfile
|
python
|
huggingface__transformers
|
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
|
{
"start": 92752,
"end": 93066
}
|
class ____(Qwen2VLRotaryEmbedding):
def __init__(self, config: Qwen2_5OmniThinkerConfig, device=None):
super().__init__(config, device)
# It's same as `Qwen2_5_VLAttention`, but talker model's hidden_size isn't divisible by num_heads.
# Removes the value error as a workaround.
|
Qwen2_5OmniRotaryEmbedding
|
python
|
google__jax
|
jax/_src/interpreters/batching.py
|
{
"start": 4560,
"end": 15182
}
|
class ____:
stacked_axis: int
# For each axis, we store its index and the corresponding segment lengths.
# For example, the jumble i:(Fin 3) => f32[lens1.i, 7, lens2.i]
# would be represented with ragged_axes = [(1, lens1), (3, lens2)]
ragged_axes: tuple[tuple[int, Any], ...]
@property
def size(self):
# TODO(mattjj, axch): All the segment lengths arrays better be the
# same length!
return len(self.ragged_axes[0][1])
def move_stacked_axis(self: RaggedAxis, dst: int) -> RaggedAxis:
# Assumes that all stored and incoming axes are already canonicalized
def move_axis(ax):
if self.stacked_axis > ax and ax >= dst:
return ax + 1
if self.stacked_axis < ax and ax <= dst:
return ax - 1
return ax
new_axes = tuple((move_axis(ax), sizes) for ax, sizes in self.ragged_axes)
return RaggedAxis(dst, new_axes)
def transpose_ragged_axes(dim: RaggedAxis, perm: tuple[int, ...]) -> RaggedAxis:
new_ragged_axes = []
for idx, old_idx in enumerate(perm):
for ax, size in dim.ragged_axes:
if old_idx == ax:
new_ragged_axes.append((idx, size))
break
return _sorted_ragged_axis(dim.stacked_axis, new_ragged_axes)
def _sorted_ragged_axis(stacked_axis, ragged_axes):
return RaggedAxis(stacked_axis, tuple(sorted(ragged_axes, key=lambda p: p[0])))
def make_batch_axis(
ndim: int,
stacked_axis: int,
ragged_axes: list[tuple[int, Array | core.Var]],
) -> int | RaggedAxis:
if ragged_axes:
canonical = [(canonicalize_axis(ax, ndim), sz) for ax, sz in ragged_axes]
return _sorted_ragged_axis(canonicalize_axis(stacked_axis, ndim), canonical)
else:
return canonicalize_axis(stacked_axis, ndim)
def bdim_as_shape(
bdim: int | RaggedAxis, data_shape: core.Shape) -> core.Shape:
if isinstance(bdim, RaggedAxis):
result = list(data_shape)
binder = core.Var(core.ShapedArray((), np.dtype('int32')))
for ragged_axis, segment_lens in bdim.ragged_axes:
result[ragged_axis] = IndexedAxisSize(binder, segment_lens)
return tuple(result)
else:
return data_shape
def shape_as_bdim(
stacked_axis: int, data_shape: core.Shape) -> int | RaggedAxis:
# This assumes that there is only one binder in the data_shape.
ragged_axes = [(i, size.lengths) for i, size in enumerate(data_shape)
if isinstance(size, IndexedAxisSize)]
return make_batch_axis(len(data_shape), stacked_axis, ragged_axes)
def _update_annotation(
f: lu.WrappedFun, orig_type: core.InputType | None,
axis_size: core.AxisSize, axis_name: AxisName,
explicit_in_dims: Sequence[int | RaggedAxis | None],
segment_lens: Sequence[Array],
) -> lu.WrappedFun:
if orig_type is None: return f
# By convention, `explicit_in_dims` only accounts for explicit arguments.
assert len(explicit_in_dims) == sum(explicit for _, explicit in orig_type)
# We need to:
# * if `axis_size` is dynamic, add a new implicit binder (type) for it;
# * for each element of `segment_lengths`, add a new explicit binder for it;
# * drop other implicit binders, replacing DBIdx which refer to them with
# Name objects;
# * for each (aval, in_dim) pair: if int-valued in_dim, add batch axis (int
# size if `axis_size` is int, otherwise Name); if RaggedAxis-valued in_dim,
# add batch axis (int if corresponding segment_lengths is concrete, Name if
# not);
# * generate full in_type with implicit args too.
class Name:
def __init__(self, a): self.a = a
names = [Name(a) for a, _ in orig_type]
avals = [a.update(shape=tuple(names[d.val] if type(d) is pe.DBIdx else d
for d in a.shape))
if type(a) is core.DShapedArray else a for a, e in orig_type if e]
new_avals = [core.get_aval(s) for s in segment_lens]
sz = Name(axis_size.aval) if isinstance(axis_size, Tracer) else axis_size
for a, d in zip(avals, explicit_in_dims):
if isinstance(d, RaggedAxis):
raise NotImplementedError
else:
new_avals.append(core.unmapped_aval(sz, d, a)) # type: ignore
mentioned = {d for a in new_avals if type(a) is core.DShapedArray
for d in a.shape if type(d) is Name}
expl_names = set(map(Name, new_avals))
impl_names = mentioned - expl_names # type: ignore
impl_part = [(n.a, False) for n in impl_names] # type: ignore
name_map = {n: pe.DBIdx(i) for i, n in enumerate((*impl_names, *expl_names))}
expl_part = [(a.update(shape=tuple(name_map.get(d, d) for d in a.shape))
if type(a) is core.DShapedArray else a, True) for a in new_avals]
return lu.annotate(f, (*impl_part, *expl_part))
### vmappable typeclass
Vmappable = Any
Elt = Any
MapSpec = Any
AxisSize = Any
MeshAxis = Any
GetIdx = Callable[[], Tracer] # TODO(mattjj): revise this laziness
ToEltHandler = Callable[[Callable, GetIdx, Vmappable, MapSpec], Elt]
FromEltHandler = Callable[[Callable, AxisSize, Elt, MapSpec], Vmappable]
MakeIotaHandler = Callable[[AxisSize], Array]
def to_elt(trace: Trace, get_idx: GetIdx, x: Vmappable, spec: MapSpec) -> Elt:
handler = to_elt_handlers.get(type(x))
if handler:
return handler(partial(to_elt, trace, get_idx), get_idx, x, spec)
elif type(x) is Jumble:
if spec is not jumble_axis:
raise TypeError("jumble input without using jumble_axis in_axes spec")
ias: IndexedAxisSize # Not present in the AxisSize union in core.py
(d, ias), = ((i, sz) # type: ignore
for i, sz in enumerate(x.aval.elt_ty.shape)
if type(sz) is IndexedAxisSize)
batch_axis = make_batch_axis(x.data.ndim, 0, [(d+1, ias.lengths)])
return BatchTracer(trace, x.data, batch_axis)
elif isinstance(spec, int) or spec is None:
spec = spec and canonicalize_axis(spec, len(np.shape(x)))
return (BatchTracer(trace, x, spec, source_info_util.current())
if spec is not None else x)
else:
if isinstance(trace, BatchTrace) and isinstance(spec, JumbleAxis):
# TODO(mvoz): A vaguely questionable assumption that it is always
# sound to have a 0 axis here. This is true for the current use cases
# and comes from how we handle intermediary products of jumbles in
# vmap.
return BatchTracer(trace, x, 0, source_info_util.current())
# TODO(mvoz): This is a terrible place to fall into if you pass
# a non jumble type in, make it clearer what went wrong.
assert False, f'Unexpected type in ELT? {type(x)}'
to_elt_handlers: dict[type, ToEltHandler] = {}
def from_elt(trace: BatchTrace, axis_size: AxisSize, mesh_axis: MeshAxis,
i: int, x: Elt, spec: MapSpec) -> Vmappable:
handler = from_elt_handlers.get(type(x))
if handler:
def _cont(axis_size, elt, axis):
return from_elt(trace, axis_size, mesh_axis, i, elt, axis)
return handler(_cont, axis_size, x, spec)
val, bdim = trace.to_batch_info(x)
if type(bdim) is RaggedAxis:
if spec is not jumble_axis:
# TODO(mattjj): improve this error message
raise TypeError("ragged output without using jumble_axis out_axes spec")
return _jumble_result(axis_size, bdim.stacked_axis, bdim.ragged_axes, val)
else:
try:
return matchaxis(trace.axis_data.name, axis_size, mesh_axis,
bdim, spec, val)
except SpecMatchError:
raise SpecMatchError(i, x.batch_dim, spec) from None
from_elt_handlers: dict[type, FromEltHandler] = {}
def make_iota(axis_size: AxisSize) -> Array:
# Callers of this utility, via batch() or vtile(), must be in a context
# where lax is importable.
from jax import lax # pytype: disable=import-error
handler = make_iota_handlers.get(type(axis_size))
if handler:
return handler(axis_size)
else:
return lax.iota('int32', int(axis_size))
make_iota_handlers: dict[type, MakeIotaHandler] = {}
def register_vmappable(data_type: type, spec_type: type, axis_size_type: type,
to_elt: Callable, from_elt: Callable,
make_iota: Callable | None):
vmappables[data_type] = (spec_type, axis_size_type)
spec_types.add(spec_type)
to_elt_handlers[data_type] = to_elt
from_elt_handlers[data_type] = from_elt
if make_iota: make_iota_handlers[axis_size_type] = make_iota
vmappables: dict[type, tuple[type, type]] = {}
spec_types: set[type] = {JumbleAxis}
def unregister_vmappable(data_type: type) -> None:
_, axis_size_type = vmappables.pop(data_type)
del to_elt_handlers[data_type]
del from_elt_handlers[data_type]
if axis_size_type in make_iota_handlers:
del make_iota_handlers[axis_size_type]
global spec_types
spec_types = (
{JumbleAxis} | {spec_type for spec_type, _ in vmappables.values()}
)
def is_vmappable(x: Any) -> bool:
return type(x) is Jumble or type(x) in vmappables
@lu.transformation_with_aux2
def flatten_fun_for_vmap(f: Callable,
store: lu.Store, in_tree: PyTreeDef, *args_flat):
py_args, py_kwargs = tree_unflatten(in_tree, args_flat)
ans = f(*py_args, **py_kwargs)
ans, out_tree = tree_flatten(ans, is_leaf=is_vmappable)
store.store(out_tree)
return ans
# Propagate ragged masking rules from invars to outvars
# rule([params], [raggedness_per_invar], outvars) ->
# [raggedness_per_invar, raggedness_per_outvar]
RaggedMaskingRule = Callable[
[list[Any], list[Any], list[Any]], tuple[list[Any], list[Any]]
]
ragged_prop_rules: dict[core.Primitive, RaggedMaskingRule] = {}
def ragged_mask_elementwise_rule(eqn_params, invar_raggedness, outvars):
# TODO(mvoz): A util for getting the ragged representations
first_invar_raggedness = invar_raggedness[0]
for other_invar_raggedness in invar_raggedness[1:]:
if other_invar_raggedness != first_invar_raggedness:
raise ValueError(f'{other_invar_raggedness} != {first_invar_raggedness}')
outvar_raggedness = [first_invar_raggedness] * len(outvars)
return invar_raggedness, outvar_raggedness
def ragged_mask_assert_no_op_rule(eqn_params, invar_raggedness, outvars):
if any(invar_raggedness):
raise ValueError(f'unexpected invar_raggedness: {invar_raggedness}')
return invar_raggedness, [None] * len(outvars)
def ragged_mask_no_op_rule(eqn_params, invar_raggedness, outvars):
return invar_raggedness, [None] * len(outvars)
def ragged_mask_transfer_identity(
eqn_params, invar_raggedness, outvar_raggedness
):
assert len(invar_raggedness) == 1, invar_raggedness
outvar_raggedness = invar_raggedness
return invar_raggedness, outvar_raggedness
### tracer
# TODO(mattjj): use a special sentinel type rather than None
NotMapped = type(None)
not_mapped = None
|
RaggedAxis
|
python
|
kamyu104__LeetCode-Solutions
|
Python/minimum-number-of-valid-strings-to-form-target-i.py
|
{
"start": 1139,
"end": 1362
}
|
class ____(object):
def __init__(self):
self.children = collections.defaultdict(AhoNode)
# self.indices = []
self.suffix = None
# self.output = None
self.length = 0 # added
|
AhoNode
|
python
|
pandas-dev__pandas
|
pandas/errors/__init__.py
|
{
"start": 5821,
"end": 6671
}
|
class ____(PandasPendingDeprecationWarning):
"""
Warning raised for an upcoming change that will be enforced in pandas 5.0.
See Also
--------
errors.PandasChangeWarning: Class for deprecations that will raise any warning.
errors.PandasPendingDeprecationWarning : Class for deprecations that will raise a
PendingDeprecationWarning.
errors.PandasDeprecationWarning : Class for deprecations that will raise a
DeprecationWarning.
errors.PandasFutureWarning : Class for deprecations that will raise a FutureWarning.
Examples
--------
>>> pd.errors.Pandas5Warning
<class 'pandas.errors.Pandas5Warning'>
"""
@classmethod
def version(cls) -> str:
"""Version where change will be enforced."""
return "5.0"
_CurrentDeprecationWarning = Pandas4Warning
|
Pandas5Warning
|
python
|
sqlalchemy__sqlalchemy
|
test/orm/test_rel_fn.py
|
{
"start": 987,
"end": 25440
}
|
class ____:
@classmethod
def setup_test_class(cls):
m = MetaData()
cls.left = Table(
"lft",
m,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
cls.right = Table(
"rgt",
m,
Column("id", Integer, primary_key=True),
Column("lid", Integer, ForeignKey("lft.id")),
Column("x", Integer),
Column("y", Integer),
)
from sqlalchemy.orm import registry
reg = registry()
cls.relationship = relationship("Otherwise")
@reg.mapped
class Whatever:
__table__ = cls.left
foo = cls.relationship
@reg.mapped
class Otherwise:
__table__ = cls.right
reg.configure()
cls.right_multi_fk = Table(
"rgt_multi_fk",
m,
Column("id", Integer, primary_key=True),
Column("lid1", Integer, ForeignKey("lft.id")),
Column("lid2", Integer, ForeignKey("lft.id")),
)
cls.selfref = Table(
"selfref",
m,
Column("id", Integer, primary_key=True),
Column("sid", Integer, ForeignKey("selfref.id")),
)
cls.composite_selfref = Table(
"composite_selfref",
m,
Column("id", Integer, primary_key=True),
Column("group_id", Integer, primary_key=True),
Column("parent_id", Integer),
ForeignKeyConstraint(
["parent_id", "group_id"],
["composite_selfref.id", "composite_selfref.group_id"],
),
)
cls.m2mleft = Table(
"m2mlft", m, Column("id", Integer, primary_key=True)
)
cls.m2mright = Table(
"m2mrgt", m, Column("id", Integer, primary_key=True)
)
cls.m2msecondary = Table(
"m2msecondary",
m,
Column("lid", Integer, ForeignKey("m2mlft.id"), primary_key=True),
Column("rid", Integer, ForeignKey("m2mrgt.id"), primary_key=True),
)
cls.m2msecondary_no_fks = Table(
"m2msecondary_no_fks",
m,
Column("lid", Integer, primary_key=True),
Column("rid", Integer, primary_key=True),
)
cls.m2msecondary_ambig_fks = Table(
"m2msecondary_ambig_fks",
m,
Column("lid1", Integer, ForeignKey("m2mlft.id"), primary_key=True),
Column("rid1", Integer, ForeignKey("m2mrgt.id"), primary_key=True),
Column("lid2", Integer, ForeignKey("m2mlft.id"), primary_key=True),
Column("rid2", Integer, ForeignKey("m2mrgt.id"), primary_key=True),
)
cls.base_w_sub_rel = Table(
"base_w_sub_rel",
m,
Column("id", Integer, primary_key=True),
Column("sub_id", Integer, ForeignKey("rel_sub.id")),
)
cls.rel_sub = Table(
"rel_sub",
m,
Column(
"id",
Integer,
ForeignKey("base_w_sub_rel.id"),
primary_key=True,
),
)
cls.base = Table(
"base",
m,
Column("id", Integer, primary_key=True),
Column("flag", Boolean),
)
cls.sub = Table(
"sub",
m,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
)
cls.sub_w_base_rel = Table(
"sub_w_base_rel",
m,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("base_id", Integer, ForeignKey("base.id")),
)
cls.sub_w_sub_rel = Table(
"sub_w_sub_rel",
m,
Column("id", Integer, ForeignKey("base.id"), primary_key=True),
Column("sub_id", Integer, ForeignKey("sub.id")),
)
cls.right_w_base_rel = Table(
"right_w_base_rel",
m,
Column("id", Integer, primary_key=True),
Column("base_id", Integer, ForeignKey("base.id")),
)
cls.three_tab_a = Table(
"three_tab_a", m, Column("id", Integer, primary_key=True)
)
cls.three_tab_b = Table(
"three_tab_b",
m,
Column("id", Integer, primary_key=True),
Column("aid", Integer, ForeignKey("three_tab_a.id")),
)
cls.three_tab_c = Table(
"three_tab_c",
m,
Column("id", Integer, primary_key=True),
Column("aid", Integer, ForeignKey("three_tab_a.id")),
Column("bid", Integer, ForeignKey("three_tab_b.id")),
)
cls.composite_target = Table(
"composite_target",
m,
Column("uid", Integer, primary_key=True),
Column("oid", Integer, primary_key=True),
)
cls.composite_multi_ref = Table(
"composite_multi_ref",
m,
Column("uid1", Integer),
Column("uid2", Integer),
Column("oid", Integer),
ForeignKeyConstraint(
("uid1", "oid"),
("composite_target.uid", "composite_target.oid"),
),
ForeignKeyConstraint(
("uid2", "oid"),
("composite_target.uid", "composite_target.oid"),
),
)
cls.purely_single_col = Table(
"purely_single_col", m, Column("path", String)
)
def _join_fixture_overlapping_three_tables(self, **kw):
def _can_sync(*cols):
for c in cols:
if self.three_tab_c.c.contains_column(c):
return False
else:
return True
return relationships._JoinCondition(
self.three_tab_a,
self.three_tab_b,
self.three_tab_a,
self.three_tab_b,
prop=self.relationship,
support_sync=False,
can_be_synced_fn=_can_sync,
primaryjoin=and_(
self.three_tab_a.c.id == self.three_tab_b.c.aid,
self.three_tab_c.c.bid == self.three_tab_b.c.id,
self.three_tab_c.c.aid == self.three_tab_a.c.id,
),
)
def _join_fixture_m2m(self, **kw):
return relationships._JoinCondition(
self.m2mleft,
self.m2mright,
self.m2mleft,
self.m2mright,
prop=self.relationship,
secondary=self.m2msecondary,
**kw,
)
def _join_fixture_m2m_backref(self, **kw):
"""return JoinCondition in the same way RelationshipProperty
calls it for a backref on an m2m.
"""
j1 = self._join_fixture_m2m()
return (
j1,
relationships._JoinCondition(
self.m2mright,
self.m2mleft,
self.m2mright,
self.m2mleft,
prop=self.relationship,
secondary=self.m2msecondary,
primaryjoin=j1.secondaryjoin_minus_local,
secondaryjoin=j1.primaryjoin_minus_local,
),
)
def _join_fixture_o2m(self, **kw):
return relationships._JoinCondition(
self.left,
self.right,
self.left,
self.right,
prop=self.relationship,
**kw,
)
def _join_fixture_m2o(self, **kw):
return relationships._JoinCondition(
self.right,
self.left,
self.right,
self.left,
prop=self.relationship,
**kw,
)
def _join_fixture_o2m_selfref(self, **kw):
return relationships._JoinCondition(
self.selfref,
self.selfref,
self.selfref,
self.selfref,
prop=self.relationship,
**kw,
)
def _join_fixture_m2o_selfref(self, **kw):
return relationships._JoinCondition(
self.selfref,
self.selfref,
self.selfref,
self.selfref,
prop=self.relationship,
remote_side={self.selfref.c.id},
**kw,
)
def _join_fixture_o2m_composite_selfref(self, **kw):
return relationships._JoinCondition(
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
prop=self.relationship,
**kw,
)
def _join_fixture_m2o_composite_selfref(self, **kw):
return relationships._JoinCondition(
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
prop=self.relationship,
remote_side={
self.composite_selfref.c.id,
self.composite_selfref.c.group_id,
},
**kw,
)
def _join_fixture_o2m_composite_selfref_func(self, **kw):
return relationships._JoinCondition(
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
prop=self.relationship,
primaryjoin=and_(
self.composite_selfref.c.group_id
== func.foo(self.composite_selfref.c.group_id),
self.composite_selfref.c.parent_id
== self.composite_selfref.c.id,
),
**kw,
)
def _join_fixture_o2m_composite_selfref_func_remote_side(self, **kw):
return relationships._JoinCondition(
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
prop=self.relationship,
primaryjoin=and_(
self.composite_selfref.c.group_id
== func.foo(self.composite_selfref.c.group_id),
self.composite_selfref.c.parent_id
== self.composite_selfref.c.id,
),
remote_side={self.composite_selfref.c.parent_id},
**kw,
)
def _join_fixture_o2m_composite_selfref_func_annotated(self, **kw):
return relationships._JoinCondition(
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
self.composite_selfref,
prop=self.relationship,
primaryjoin=and_(
remote(self.composite_selfref.c.group_id)
== func.foo(self.composite_selfref.c.group_id),
remote(self.composite_selfref.c.parent_id)
== self.composite_selfref.c.id,
),
**kw,
)
def _join_fixture_compound_expression_1(self, **kw):
return relationships._JoinCondition(
self.left,
self.right,
self.left,
self.right,
prop=self.relationship,
primaryjoin=(self.left.c.x + self.left.c.y)
== relationships.remote(
relationships.foreign(self.right.c.x * self.right.c.y)
),
**kw,
)
def _join_fixture_compound_expression_2(self, **kw):
return relationships._JoinCondition(
self.left,
self.right,
self.left,
self.right,
prop=self.relationship,
primaryjoin=(self.left.c.x + self.left.c.y)
== relationships.foreign(self.right.c.x * self.right.c.y),
**kw,
)
def _join_fixture_compound_expression_1_non_annotated(self, **kw):
return relationships._JoinCondition(
self.left,
self.right,
self.left,
self.right,
prop=self.relationship,
primaryjoin=(self.left.c.x + self.left.c.y)
== (self.right.c.x * self.right.c.y),
**kw,
)
def _join_fixture_base_to_joined_sub(self, **kw):
# see test/orm/inheritance/test_abc_inheritance:TestaTobM2O
# and others there
right = self.base_w_sub_rel.join(
self.rel_sub, self.base_w_sub_rel.c.id == self.rel_sub.c.id
)
return relationships._JoinCondition(
self.base_w_sub_rel,
right,
self.base_w_sub_rel,
self.rel_sub,
prop=self.relationship,
primaryjoin=self.base_w_sub_rel.c.sub_id == self.rel_sub.c.id,
**kw,
)
def _join_fixture_o2m_joined_sub_to_base(self, **kw):
left = self.base.join(
self.sub_w_base_rel, self.base.c.id == self.sub_w_base_rel.c.id
)
return relationships._JoinCondition(
left,
self.base,
self.sub_w_base_rel,
self.base,
prop=self.relationship,
primaryjoin=self.sub_w_base_rel.c.base_id == self.base.c.id,
)
def _join_fixture_m2o_joined_sub_to_sub_on_base(self, **kw):
# this is a late add - a variant of the test case
# in #2491 where we join on the base cols instead. only
# m2o has a problem at the time of this test.
left = self.base.join(self.sub, self.base.c.id == self.sub.c.id)
right = self.base.join(
self.sub_w_base_rel, self.base.c.id == self.sub_w_base_rel.c.id
)
return relationships._JoinCondition(
left,
right,
self.sub,
self.sub_w_base_rel,
prop=self.relationship,
primaryjoin=self.sub_w_base_rel.c.base_id == self.base.c.id,
)
def _join_fixture_o2m_joined_sub_to_sub(self, **kw):
left = self.base.join(self.sub, self.base.c.id == self.sub.c.id)
right = self.base.join(
self.sub_w_sub_rel, self.base.c.id == self.sub_w_sub_rel.c.id
)
return relationships._JoinCondition(
left,
right,
self.sub,
self.sub_w_sub_rel,
prop=self.relationship,
primaryjoin=self.sub.c.id == self.sub_w_sub_rel.c.sub_id,
)
def _join_fixture_m2o_sub_to_joined_sub(self, **kw):
# see test.orm.test_mapper:MapperTest.test_add_column_prop_deannotate,
right = self.base.join(
self.right_w_base_rel, self.base.c.id == self.right_w_base_rel.c.id
)
return relationships._JoinCondition(
self.right_w_base_rel,
right,
self.right_w_base_rel,
self.right_w_base_rel,
prop=self.relationship,
)
def _join_fixture_m2o_sub_to_joined_sub_func(self, **kw):
# see test.orm.test_mapper:MapperTest.test_add_column_prop_deannotate,
right = self.base.join(
self.right_w_base_rel, self.base.c.id == self.right_w_base_rel.c.id
)
return relationships._JoinCondition(
self.right_w_base_rel,
right,
self.right_w_base_rel,
self.right_w_base_rel,
prop=self.relationship,
primaryjoin=self.right_w_base_rel.c.base_id
== func.foo(self.base.c.id),
)
def _join_fixture_o2o_joined_sub_to_base(self, **kw):
left = self.base.join(self.sub, self.base.c.id == self.sub.c.id)
# see test_relationships->AmbiguousJoinInterpretedAsSelfRef
return relationships._JoinCondition(
left,
self.sub,
left,
self.sub,
prop=self.relationship,
)
def _join_fixture_o2m_to_annotated_func(self, **kw):
return relationships._JoinCondition(
self.left,
self.right,
self.left,
self.right,
prop=self.relationship,
primaryjoin=self.left.c.id == foreign(func.foo(self.right.c.lid)),
**kw,
)
def _join_fixture_o2m_to_oldstyle_func(self, **kw):
return relationships._JoinCondition(
self.left,
self.right,
self.left,
self.right,
prop=self.relationship,
primaryjoin=self.left.c.id == func.foo(self.right.c.lid),
consider_as_foreign_keys={self.right.c.lid},
**kw,
)
def _join_fixture_overlapping_composite_fks(self, **kw):
return relationships._JoinCondition(
self.composite_target,
self.composite_multi_ref,
self.composite_target,
self.composite_multi_ref,
prop=self.relationship,
consider_as_foreign_keys={
self.composite_multi_ref.c.uid2,
self.composite_multi_ref.c.oid,
},
**kw,
)
def _join_fixture_o2m_o_side_none(self, **kw):
return relationships._JoinCondition(
self.left,
self.right,
self.left,
self.right,
prop=self.relationship,
primaryjoin=and_(
self.left.c.id == self.right.c.lid, self.left.c.x == 5
),
**kw,
)
def _join_fixture_purely_single_o2m(self, **kw):
return relationships._JoinCondition(
self.purely_single_col,
self.purely_single_col,
self.purely_single_col,
self.purely_single_col,
prop=self.relationship,
support_sync=False,
primaryjoin=self.purely_single_col.c.path.like(
remote(foreign(self.purely_single_col.c.path.concat("%")))
),
)
def _join_fixture_purely_single_m2o(self, **kw):
return relationships._JoinCondition(
self.purely_single_col,
self.purely_single_col,
self.purely_single_col,
self.purely_single_col,
prop=self.relationship,
support_sync=False,
primaryjoin=remote(self.purely_single_col.c.path).like(
foreign(self.purely_single_col.c.path.concat("%"))
),
)
def _join_fixture_remote_local_multiple_ref(self, **kw):
def fn(a, b):
return (a == b) | (b == a)
return relationships._JoinCondition(
self.selfref,
self.selfref,
self.selfref,
self.selfref,
prop=self.relationship,
support_sync=False,
primaryjoin=fn(
# we're putting a do-nothing annotation on
# "a" so that the left/right is preserved;
# annotation vs. non seems to affect __eq__ behavior
self.selfref.c.sid._annotate({"foo": "bar"}),
foreign(remote(self.selfref.c.sid)),
),
)
def _join_fixture_inh_selfref_w_entity(self, **kw):
fake_logger = mock.Mock(info=lambda *arg, **kw: None)
prop = mock.Mock(
parent=mock.Mock(), mapper=mock.Mock(), logger=fake_logger
)
local_selectable = self.base.join(self.sub)
remote_selectable = self.base.join(self.sub_w_sub_rel)
# note this test requires that "parentmapper" annotation is
# present in the columns ahead of time
sub_w_sub_rel__sub_id = self.sub_w_sub_rel.c.sub_id._annotate(
{"parentmapper": prop.mapper}
)
sub__id = self.sub.c.id._annotate({"parentmapper": prop.parent})
sub_w_sub_rel__flag = self.base.c.flag._annotate(
{"parentmapper": prop.mapper}
)
return relationships._JoinCondition(
local_selectable,
remote_selectable,
local_selectable,
remote_selectable,
primaryjoin=and_(
sub_w_sub_rel__sub_id == sub__id,
sub_w_sub_rel__flag == True, # noqa
),
prop=prop,
)
def _assert_non_simple_warning(self, fn):
assert_warns_message(
exc.SAWarning,
"Non-simple column elements in "
"primary join condition for property "
r"Whatever.foo - consider using remote\(\) "
"annotations to mark the remote side.",
fn,
)
def _assert_raises_no_relevant_fks(
self, fn, expr, relname, primary, *arg, **kw
):
assert_raises_message(
exc.ArgumentError,
r"Could not locate any relevant foreign key columns "
r"for %s join condition '%s' on relationship %s. "
r"Ensure that referencing columns are associated with "
r"a ForeignKey or ForeignKeyConstraint, or are annotated "
r"in the join condition with the foreign\(\) annotation."
% (primary, expr, relname),
fn,
*arg,
**kw,
)
def _assert_raises_no_equality(
self, fn, expr, relname, primary, *arg, **kw
):
assert_raises_message(
exc.ArgumentError,
"Could not locate any simple equality expressions "
"involving locally mapped foreign key columns for %s join "
"condition '%s' on relationship %s. "
"Ensure that referencing columns are associated with a "
"ForeignKey or ForeignKeyConstraint, or are annotated in "
r"the join condition with the foreign\(\) annotation. "
"To allow comparison operators other than '==', "
"the relationship can be marked as viewonly=True."
% (primary, expr, relname),
fn,
*arg,
**kw,
)
def _assert_raises_ambig_join(
self, fn, relname, secondary_arg, *arg, **kw
):
if secondary_arg is not None:
assert_raises_message(
exc.AmbiguousForeignKeysError,
"Could not determine join condition between "
"parent/child tables on relationship %s - "
"there are multiple foreign key paths linking the "
"tables via secondary table '%s'. "
"Specify the 'foreign_keys' argument, providing a list "
"of those columns which should be counted as "
"containing a foreign key reference from the "
"secondary table to each of the parent and child tables."
% (relname, secondary_arg),
fn,
*arg,
**kw,
)
else:
assert_raises_message(
exc.AmbiguousForeignKeysError,
"Could not determine join condition between "
"parent/child tables on relationship %s - "
"there are no foreign keys linking these tables. "
% (relname,),
fn,
*arg,
**kw,
)
def _assert_raises_no_join(self, fn, relname, secondary_arg, *arg, **kw):
if secondary_arg is not None:
assert_raises_message(
exc.NoForeignKeysError,
"Could not determine join condition between "
"parent/child tables on relationship %s - "
"there are no foreign keys linking these tables "
"via secondary table '%s'. "
"Ensure that referencing columns are associated "
"with a ForeignKey "
"or ForeignKeyConstraint, or specify 'primaryjoin' and "
"'secondaryjoin' expressions" % (relname, secondary_arg),
fn,
*arg,
**kw,
)
else:
assert_raises_message(
exc.NoForeignKeysError,
"Could not determine join condition between "
"parent/child tables on relationship %s - "
"there are no foreign keys linking these tables. "
"Ensure that referencing columns are associated "
"with a ForeignKey "
"or ForeignKeyConstraint, or specify a 'primaryjoin' "
"expression." % (relname,),
fn,
*arg,
**kw,
)
|
_JoinFixtures
|
python
|
pezy__LeetCode
|
001. Add Two Numbers/solution.py
|
{
"start": 49,
"end": 140
}
|
class ____:
def __init__(self, x):
self.val = x
self.next = None
|
ListNode
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/worksheet/test_write_sheet_views6.py
|
{
"start": 301,
"end": 3142
}
|
class ____(unittest.TestCase):
"""
Test the Worksheet _write_sheet_views() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_sheet_views1(self):
"""Test the _write_sheet_views() method with freeze panes + selection"""
self.worksheet.select()
self.worksheet.set_selection("A2")
self.worksheet.freeze_panes(1, 0)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/><selection pane="bottomLeft" activeCell="A2" sqref="A2"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views2(self):
"""Test the _write_sheet_views() method with freeze panes + selection"""
self.worksheet.select()
self.worksheet.set_selection("B1")
self.worksheet.freeze_panes(0, 1)
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="1" topLeftCell="B1" activePane="topRight" state="frozen"/><selection pane="topRight" activeCell="B1" sqref="B1"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views3(self):
"""Test the _write_sheet_views() method with freeze panes + selection"""
self.worksheet.select()
self.worksheet.set_selection("G4")
self.worksheet.freeze_panes("G4")
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="6" ySplit="3" topLeftCell="G4" activePane="bottomRight" state="frozen"/><selection pane="topRight" activeCell="G1" sqref="G1"/><selection pane="bottomLeft" activeCell="A4" sqref="A4"/><selection pane="bottomRight" activeCell="G4" sqref="G4"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
def test_write_sheet_views4(self):
"""Test the _write_sheet_views() method with freeze panes + selection"""
self.worksheet.select()
self.worksheet.set_selection("I5")
self.worksheet.freeze_panes("G4")
self.worksheet._write_sheet_views()
exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="6" ySplit="3" topLeftCell="G4" activePane="bottomRight" state="frozen"/><selection pane="topRight" activeCell="G1" sqref="G1"/><selection pane="bottomLeft" activeCell="A4" sqref="A4"/><selection pane="bottomRight" activeCell="I5" sqref="I5"/></sheetView></sheetViews>'
got = self.fh.getvalue()
self.assertEqual(exp, got)
|
TestWriteSheetViews
|
python
|
jazzband__django-waffle
|
waffle/admin.py
|
{
"start": 4190,
"end": 4416
}
|
class ____(BaseAdmin):
actions = [enable_switches, disable_switches, delete_individually]
list_display = ('name', 'active', 'note', 'created', 'modified')
list_filter = ('active',)
ordering = ('-id',)
|
SwitchAdmin
|
python
|
facebook__pyre-check
|
source/interprocedural_analyses/taint/test/integration/add_breadcrumb_to_state.py
|
{
"start": 1400,
"end": 1775
}
|
class ____:
def __init__(self):
pass
# Annotated with `@AddBreadcrumbToState(Via[add_breadcrumb_to_state])`
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return
def test_add_breadcrumb_context_manager():
x = _test_source()
with BreadcrumbOnEnter():
_test_sink(x)
|
BreadcrumbOnEnter
|
python
|
scrapy__scrapy
|
scrapy/spiderloader.py
|
{
"start": 4579,
"end": 5037
}
|
class ____:
"""A dummy spider loader that does not load any spiders."""
@classmethod
def from_settings(cls, settings: BaseSettings) -> Self:
return cls()
def load(self, spider_name: str) -> type[Spider]:
raise KeyError("DummySpiderLoader doesn't load any spiders")
def list(self) -> list[str]:
return []
def find_by_request(self, request: Request) -> __builtins__.list[str]:
return []
|
DummySpiderLoader
|
python
|
plotly__plotly.py
|
plotly/graph_objs/scatter/selected/_textfont.py
|
{
"start": 233,
"end": 2420
}
|
class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.selected"
_path_str = "scatter.selected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of selected points.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the text font color of selected points.
"""
def __init__(self, arg=None, color=None, **kwargs):
"""
Construct a new Textfont object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter.selected.Textfont`
color
Sets the text font color of selected points.
Returns
-------
Textfont
"""
super().__init__("textfont")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scatter.selected.Textfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter.selected.Textfont`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
Textfont
|
python
|
doocs__leetcode
|
solution/1600-1699/1653.Minimum Deletions to Make String Balanced/Solution.py
|
{
"start": 0,
"end": 321
}
|
class ____:
def minimumDeletions(self, s: str) -> int:
n = len(s)
f = [0] * (n + 1)
b = 0
for i, c in enumerate(s, 1):
if c == 'b':
f[i] = f[i - 1]
b += 1
else:
f[i] = min(f[i - 1] + 1, b)
return f[n]
|
Solution
|
python
|
dagster-io__dagster
|
python_modules/dagster-graphql/dagster_graphql/client/utils.py
|
{
"start": 214,
"end": 561
}
|
class ____(Enum):
"""This enum describes the status of a GraphQL mutation to reload a Dagster repository location.
Args:
Enum (str): can be either `ReloadRepositoryLocationStatus.SUCCESS`
or `ReloadRepositoryLocationStatus.FAILURE`.
"""
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
|
ReloadRepositoryLocationStatus
|
python
|
apache__airflow
|
providers/google/tests/unit/google/cloud/hooks/test_datastore.py
|
{
"start": 1137,
"end": 16478
}
|
class ____:
def setup_method(self):
with patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_init
):
self.datastore_hook = DatastoreHook()
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook._authorize")
@patch("airflow.providers.google.cloud.hooks.datastore.build")
def test_get_conn(self, mock_build, mock_authorize):
conn = self.datastore_hook.get_conn()
mock_build.assert_called_once_with(
"datastore", "v1", http=mock_authorize.return_value, cache_discovery=False
)
assert conn == mock_build.return_value
assert conn == self.datastore_hook.connection
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_allocate_ids(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
partial_keys = []
keys = self.datastore_hook.allocate_ids(partial_keys=partial_keys, project_id=GCP_PROJECT_ID)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
allocate_ids = projects.return_value.allocateIds
allocate_ids.assert_called_once_with(projectId=GCP_PROJECT_ID, body={"keys": partial_keys})
execute = allocate_ids.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert keys == execute.return_value["keys"]
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_allocate_ids_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.connection = mock_get_conn.return_value
partial_keys = []
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.allocate_ids(partial_keys=partial_keys)
assert "project_id" in str(ctx.value)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_begin_transaction(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
transaction = self.datastore_hook.begin_transaction(
project_id=GCP_PROJECT_ID,
transaction_options={},
)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
begin_transaction = projects.return_value.beginTransaction
begin_transaction.assert_called_once_with(projectId=GCP_PROJECT_ID, body={"transactionOptions": {}})
execute = begin_transaction.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert transaction == execute.return_value["transaction"]
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_begin_transaction_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.connection = mock_get_conn.return_value
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.begin_transaction()
assert "project_id" in str(ctx.value)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_commit(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
body = {"item": "a"}
resp = self.datastore_hook.commit(body=body, project_id=GCP_PROJECT_ID)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
commit = projects.return_value.commit
commit.assert_called_once_with(projectId=GCP_PROJECT_ID, body=body)
execute = commit.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert resp == execute.return_value
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_commit_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.connection = mock_get_conn.return_value
body = {"item": "a"}
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.commit(body=body)
assert "project_id" in str(ctx.value)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_lookup(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
keys = []
read_consistency = "ENUM"
transaction = "transaction"
resp = self.datastore_hook.lookup(
keys=keys, read_consistency=read_consistency, transaction=transaction, project_id=GCP_PROJECT_ID
)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
lookup = projects.return_value.lookup
lookup.assert_called_once_with(
projectId=GCP_PROJECT_ID,
body={"keys": keys, "readConsistency": read_consistency, "transaction": transaction},
)
execute = lookup.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert resp == execute.return_value
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_lookup_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.connection = mock_get_conn.return_value
keys = []
read_consistency = "ENUM"
transaction = "transaction"
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.lookup(
keys=keys,
read_consistency=read_consistency,
transaction=transaction,
)
assert "project_id" in str(ctx.value)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_rollback(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
transaction = "transaction"
self.datastore_hook.rollback(transaction=transaction, project_id=GCP_PROJECT_ID)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
rollback = projects.return_value.rollback
rollback.assert_called_once_with(projectId=GCP_PROJECT_ID, body={"transaction": transaction})
execute = rollback.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_rollback_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.connection = mock_get_conn.return_value
transaction = "transaction"
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.rollback(transaction=transaction)
assert "project_id" in str(ctx.value)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_run_query(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
body = {"item": "a"}
resp = self.datastore_hook.run_query(body=body, project_id=GCP_PROJECT_ID)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
run_query = projects.return_value.runQuery
run_query.assert_called_once_with(projectId=GCP_PROJECT_ID, body=body)
execute = run_query.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert resp == execute.return_value["batch"]
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_run_query_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.connection = mock_get_conn.return_value
body = {"item": "a"}
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.run_query(body=body)
assert "project_id" in str(ctx.value)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_get_operation(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
name = "name"
resp = self.datastore_hook.get_operation(name=name)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
operations = projects.return_value.operations
operations.assert_called_once_with()
get = operations.return_value.get
get.assert_called_once_with(name=name)
execute = get.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert resp == execute.return_value
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_delete_operation(self, mock_get_conn):
self.datastore_hook.connection = mock_get_conn.return_value
name = "name"
resp = self.datastore_hook.delete_operation(name=name)
projects = self.datastore_hook.connection.projects
projects.assert_called_once_with()
operations = projects.return_value.operations
operations.assert_called_once_with()
delete = operations.return_value.delete
delete.assert_called_once_with(name=name)
execute = delete.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert resp == execute.return_value
@patch("airflow.providers.google.cloud.hooks.datastore.time.sleep")
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_operation",
side_effect=[
{"metadata": {"common": {"state": "PROCESSING"}}},
{"metadata": {"common": {"state": "NOT PROCESSING"}}},
],
)
def test_poll_operation_until_done(self, mock_get_operation, mock_time_sleep):
name = "name"
polling_interval_in_seconds = 10
result = self.datastore_hook.poll_operation_until_done(name, polling_interval_in_seconds)
mock_get_operation.assert_has_calls([call(name), call(name)])
mock_time_sleep.assert_called_once_with(polling_interval_in_seconds)
assert result == {"metadata": {"common": {"state": "NOT PROCESSING"}}}
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_export_to_storage_bucket(self, mock_get_conn):
self.datastore_hook.admin_connection = mock_get_conn.return_value
bucket = "bucket"
namespace = None
entity_filter = {}
labels = {}
resp = self.datastore_hook.export_to_storage_bucket(
bucket=bucket,
namespace=namespace,
entity_filter=entity_filter,
labels=labels,
project_id=GCP_PROJECT_ID,
)
projects = self.datastore_hook.admin_connection.projects
projects.assert_called_once_with()
export = projects.return_value.export
export.assert_called_once_with(
projectId=GCP_PROJECT_ID,
body={
"outputUrlPrefix": "gs://" + "/".join(filter(None, [bucket, namespace])),
"entityFilter": entity_filter,
"labels": labels,
},
)
execute = export.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert resp == execute.return_value
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_export_to_storage_bucket_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.admin_connection = mock_get_conn.return_value
bucket = "bucket"
namespace = None
entity_filter = {}
labels = {}
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.export_to_storage_bucket(
bucket=bucket,
namespace=namespace,
entity_filter=entity_filter,
labels=labels,
)
assert "project_id" in str(ctx.value)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_import_from_storage_bucket(self, mock_get_conn):
self.datastore_hook.admin_connection = mock_get_conn.return_value
bucket = "bucket"
file = "file"
namespace = None
entity_filter = {}
labels = {}
resp = self.datastore_hook.import_from_storage_bucket(
bucket=bucket,
file=file,
namespace=namespace,
entity_filter=entity_filter,
labels=labels,
project_id=GCP_PROJECT_ID,
)
projects = self.datastore_hook.admin_connection.projects
projects.assert_called_once_with()
import_ = projects.return_value.import_
import_.assert_called_once_with(
projectId=GCP_PROJECT_ID,
body={
"inputUrl": "gs://" + "/".join(filter(None, [bucket, namespace, file])),
"entityFilter": entity_filter,
"labels": labels,
},
)
execute = import_.return_value.execute
execute.assert_called_once_with(num_retries=mock.ANY)
assert resp == execute.return_value
@patch(
"airflow.providers.google.cloud.hooks.datastore.DatastoreHook.project_id",
new_callable=mock.PropertyMock,
return_value=None,
)
@patch("airflow.providers.google.cloud.hooks.datastore.DatastoreHook.get_conn")
def test_import_from_storage_bucket_no_project_id(self, mock_get_conn, mock_project_id):
self.datastore_hook.admin_connection = mock_get_conn.return_value
bucket = "bucket"
file = "file"
namespace = None
entity_filter = {}
labels = {}
with pytest.raises(AirflowException) as ctx:
self.datastore_hook.import_from_storage_bucket(
bucket=bucket,
file=file,
namespace=namespace,
entity_filter=entity_filter,
labels=labels,
)
assert "project_id" in str(ctx.value)
|
TestDatastoreHook
|
python
|
pennersr__django-allauth
|
allauth/headless/base/response.py
|
{
"start": 705,
"end": 4267
}
|
class ____(APIResponse):
def __init__(self, request, user=None, status=None):
data = {}
if user and user.is_authenticated:
adapter = get_adapter()
data["user"] = adapter.serialize_user(user)
data["methods"] = get_authentication_records(request)
status = status or HTTPStatus.OK
else:
status = status or HTTPStatus.UNAUTHORIZED
if status != HTTPStatus.OK:
data["flows"] = self._get_flows(request, user)
meta = {
"is_authenticated": user and user.is_authenticated,
}
super().__init__(
request,
data=data,
meta=meta,
status=status,
)
def _get_flows(self, request, user):
auth_status = authkit.AuthenticationStatus(request)
ret = []
if user and user.is_authenticated:
ret.extend(flows.reauthentication.get_reauthentication_flows(user))
else:
if not allauth_settings.SOCIALACCOUNT_ONLY:
ret.append({"id": Flow.LOGIN})
if account_settings.LOGIN_BY_CODE_ENABLED:
ret.append({"id": Flow.LOGIN_BY_CODE})
if (
get_account_adapter().is_open_for_signup(request)
and not allauth_settings.SOCIALACCOUNT_ONLY
):
ret.append({"id": Flow.SIGNUP})
if allauth_settings.SOCIALACCOUNT_ENABLED:
from allauth.headless.socialaccount.response import provider_flows
ret.extend(provider_flows(request))
if allauth_settings.MFA_ENABLED:
if mfa_settings.PASSKEY_LOGIN_ENABLED:
ret.append({"id": Flow.MFA_LOGIN_WEBAUTHN})
stage_key = None
stage = auth_status.get_pending_stage()
if stage:
stage_key = stage.key
else:
lsk = request.session.get(LOGIN_SESSION_KEY)
if isinstance(lsk, str):
stage_key = lsk
if stage_key:
pending_flow = {"id": stage_key, "is_pending": True}
if stage and stage_key == Flow.MFA_AUTHENTICATE:
self._enrich_mfa_flow(stage, pending_flow)
self._upsert_pending_flow(ret, pending_flow)
if (
not allauth_settings.SOCIALACCOUNT_ONLY
and account_settings.PASSWORD_RESET_BY_CODE_ENABLED
):
from allauth.account.internal.flows import password_reset_by_code
ret.append(
{
"id": Flow.PASSWORD_RESET_BY_CODE,
"is_pending": bool(
password_reset_by_code.PasswordResetVerificationProcess.resume(
request
)
),
}
)
return ret
def _upsert_pending_flow(self, flows, pending_flow):
flow = next((flow for flow in flows if flow["id"] == pending_flow["id"]), None)
if flow:
flow.update(pending_flow)
else:
flows.append(pending_flow)
def _enrich_mfa_flow(self, stage, flow: dict) -> None:
from allauth.mfa.adapter import get_adapter as get_mfa_adapter
from allauth.mfa.models import Authenticator
adapter = get_mfa_adapter()
types = []
for typ in Authenticator.Type:
if adapter.is_mfa_enabled(stage.login.user, types=[typ]):
types.append(typ)
flow["types"] = types
|
BaseAuthenticationResponse
|
python
|
python__mypy
|
mypy/stubdoc.py
|
{
"start": 977,
"end": 2088
}
|
class ____:
"""Signature info for a single argument."""
def __init__(
self,
name: str,
type: str | None = None,
*,
default: bool = False,
default_value: str = "...",
) -> None:
self.name = name
self.type = type
# Does this argument have a default value?
self.default = default
self.default_value = default_value
def is_star_arg(self) -> bool:
return self.name.startswith("*") and not self.name.startswith("**")
def is_star_kwarg(self) -> bool:
return self.name.startswith("**")
def __repr__(self) -> str:
return "ArgSig(name={}, type={}, default={})".format(
repr(self.name), repr(self.type), repr(self.default)
)
def __eq__(self, other: Any) -> bool:
if isinstance(other, ArgSig):
return (
self.name == other.name
and self.type == other.type
and self.default == other.default
and self.default_value == other.default_value
)
return False
|
ArgSig
|
python
|
RaRe-Technologies__gensim
|
docs/src/auto_examples/core/run_corpora_and_vector_spaces.py
|
{
"start": 6097,
"end": 14275
}
|
class ____:
def __iter__(self):
for line in open('https://radimrehurek.com/mycorpus.txt'):
# assume there's one document per line, tokens separated by whitespace
yield dictionary.doc2bow(line.lower().split())
###############################################################################
# The full power of Gensim comes from the fact that a corpus doesn't have to be
# a ``list``, or a ``NumPy`` array, or a ``Pandas`` dataframe, or whatever.
# Gensim *accepts any object that, when iterated over, successively yields
# documents*.
# This flexibility allows you to create your own corpus classes that stream the
# documents directly from disk, network, database, dataframes... The models
# in Gensim are implemented such that they don't require all vectors to reside
# in RAM at once. You can even create the documents on the fly!
###############################################################################
# Download the sample `mycorpus.txt file here <https://radimrehurek.com/mycorpus.txt>`_. The assumption that
# each document occupies one line in a single file is not important; you can mold
# the `__iter__` function to fit your input format, whatever it is.
# Walking directories, parsing XML, accessing the network...
# Just parse your input to retrieve a clean list of tokens in each document,
# then convert the tokens via a dictionary to their ids and yield the resulting sparse vector inside `__iter__`.
corpus_memory_friendly = MyCorpus() # doesn't load the corpus into memory!
print(corpus_memory_friendly)
###############################################################################
# Corpus is now an object. We didn't define any way to print it, so `print` just outputs address
# of the object in memory. Not very useful. To see the constituent vectors, let's
# iterate over the corpus and print each document vector (one at a time):
for vector in corpus_memory_friendly: # load one vector into memory at a time
print(vector)
###############################################################################
# Although the output is the same as for the plain Python list, the corpus is now much
# more memory friendly, because at most one vector resides in RAM at a time. Your
# corpus can now be as large as you want.
#
# Similarly, to construct the dictionary without loading all texts into memory:
# collect statistics about all tokens
dictionary = corpora.Dictionary(line.lower().split() for line in open('https://radimrehurek.com/mycorpus.txt'))
# remove stop words and words that appear only once
stop_ids = [
dictionary.token2id[stopword]
for stopword in stoplist
if stopword in dictionary.token2id
]
once_ids = [tokenid for tokenid, docfreq in dictionary.dfs.items() if docfreq == 1]
dictionary.filter_tokens(stop_ids + once_ids) # remove stop words and words that appear only once
dictionary.compactify() # remove gaps in id sequence after words that were removed
print(dictionary)
###############################################################################
# And that is all there is to it! At least as far as bag-of-words representation is concerned.
# Of course, what we do with such a corpus is another question; it is not at all clear
# how counting the frequency of distinct words could be useful. As it turns out, it isn't, and
# we will need to apply a transformation on this simple representation first, before
# we can use it to compute any meaningful document vs. document similarities.
# Transformations are covered in the next tutorial
# (:ref:`sphx_glr_auto_examples_core_run_topics_and_transformations.py`),
# but before that, let's briefly turn our attention to *corpus persistency*.
#
# .. _corpus-formats:
#
# Corpus Formats
# ---------------
#
# There exist several file formats for serializing a Vector Space corpus (~sequence of vectors) to disk.
# `Gensim` implements them via the *streaming corpus interface* mentioned earlier:
# documents are read from (resp. stored to) disk in a lazy fashion, one document at
# a time, without the whole corpus being read into main memory at once.
#
# One of the more notable file formats is the `Market Matrix format <http://math.nist.gov/MatrixMarket/formats.html>`_.
# To save a corpus in the Matrix Market format:
#
# create a toy corpus of 2 documents, as a plain Python list
corpus = [[(1, 0.5)], []] # make one document empty, for the heck of it
corpora.MmCorpus.serialize('/tmp/corpus.mm', corpus)
###############################################################################
# Other formats include `Joachim's SVMlight format <http://svmlight.joachims.org/>`_,
# `Blei's LDA-C format <https://github.com/blei-lab/lda-c>`_ and
# `GibbsLDA++ format <https://gibbslda.sourceforge.net/>`_.
corpora.SvmLightCorpus.serialize('/tmp/corpus.svmlight', corpus)
corpora.BleiCorpus.serialize('/tmp/corpus.lda-c', corpus)
corpora.LowCorpus.serialize('/tmp/corpus.low', corpus)
###############################################################################
# Conversely, to load a corpus iterator from a Matrix Market file:
corpus = corpora.MmCorpus('/tmp/corpus.mm')
###############################################################################
# Corpus objects are streams, so typically you won't be able to print them directly:
print(corpus)
###############################################################################
# Instead, to view the contents of a corpus:
# one way of printing a corpus: load it entirely into memory
print(list(corpus)) # calling list() will convert any sequence to a plain Python list
###############################################################################
# or
# another way of doing it: print one document at a time, making use of the streaming interface
for doc in corpus:
print(doc)
###############################################################################
# The second way is obviously more memory-friendly, but for testing and development
# purposes, nothing beats the simplicity of calling ``list(corpus)``.
#
# To save the same Matrix Market document stream in Blei's LDA-C format,
corpora.BleiCorpus.serialize('/tmp/corpus.lda-c', corpus)
###############################################################################
# In this way, `gensim` can also be used as a memory-efficient **I/O format conversion tool**:
# just load a document stream using one format and immediately save it in another format.
# Adding new formats is dead easy, check out the `code for the SVMlight corpus
# <https://github.com/piskvorky/gensim/blob/develop/gensim/corpora/svmlightcorpus.py>`_ for an example.
#
# Compatibility with NumPy and SciPy
# ----------------------------------
#
# Gensim also contains `efficient utility functions <https://radimrehurek.com/gensim/matutils.html>`_
# to help converting from/to numpy matrices
import gensim
import numpy as np
numpy_matrix = np.random.randint(10, size=[5, 2]) # random matrix as an example
corpus = gensim.matutils.Dense2Corpus(numpy_matrix)
# numpy_matrix = gensim.matutils.corpus2dense(corpus, num_terms=number_of_corpus_features)
###############################################################################
# and from/to `scipy.sparse` matrices
import scipy.sparse
scipy_sparse_matrix = scipy.sparse.random(5, 2) # random sparse matrix as example
corpus = gensim.matutils.Sparse2Corpus(scipy_sparse_matrix)
scipy_csc_matrix = gensim.matutils.corpus2csc(corpus)
###############################################################################
# What Next
# ---------
#
# Read about :ref:`sphx_glr_auto_examples_core_run_topics_and_transformations.py`.
#
# References
# ----------
#
# For a complete reference (Want to prune the dictionary to a smaller size?
# Optimize converting between corpora and NumPy/SciPy arrays?), see the :ref:`apiref`.
#
# .. [1] This is the same corpus as used in
# `Deerwester et al. (1990): Indexing by Latent Semantic Analysis <http://www.cs.bham.ac.uk/~pxt/IDA/lsa_ind.pdf>`_, Table 2.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('run_corpora_and_vector_spaces.png')
imgplot = plt.imshow(img)
_ = plt.axis('off')
|
MyCorpus
|
python
|
tensorflow__tensorflow
|
tensorflow/core/function/trace_type/trace_type_builder.py
|
{
"start": 1134,
"end": 2198
}
|
class ____(trace.TracingContext):
"""Container for variables and flags shared across TraceType generation."""
def __init__(self, is_legacy_signature: bool = False):
self._global_to_local_id = {}
self._alias_id_to_placeholder = {}
self._is_legacy_signature = is_legacy_signature
def alias_global_id(self, global_id: Hashable) -> Hashable:
if global_id not in self._global_to_local_id:
self._global_to_local_id[global_id] = len(self._global_to_local_id)
return self._global_to_local_id[global_id]
def add_placeholder(self, alias_id: Hashable, variable) -> None:
self._alias_id_to_placeholder[alias_id] = variable
def get_placeholder_mapping(self) -> Dict[Hashable, Any]:
return self._alias_id_to_placeholder
@property
def is_legacy_signature(self) -> bool:
"""If the value is from a legacy signature representation.
Legacy signature representations include tf.function.input_signature and
ConcreteFunction.structured_input_signature.
"""
return self._is_legacy_signature
|
InternalTracingContext
|
python
|
has2k1__plotnine
|
plotnine/positions/position_nudge.py
|
{
"start": 169,
"end": 949
}
|
class ____(position):
"""
Nudge points
Useful to nudge labels away from the points
being labels.
Parameters
----------
x :
Horizontal nudge
y :
Vertical nudge
"""
def __init__(self, x: float = 0, y: float = 0):
self.params = {"x": x, "y": y}
@classmethod
def compute_layer(cls, data, params, layout):
trans_x = None # pyright: ignore
trans_y = None # pyright: ignore
if params["x"]:
def trans_x(x: FloatArrayLike) -> FloatArray:
return x + params["x"]
if params["y"]:
def trans_y(y: FloatArrayLike) -> FloatArray:
return y + params["y"]
return cls.transform_position(data, trans_x, trans_y)
|
position_nudge
|
python
|
pypa__pip
|
src/pip/_vendor/rich/styled.py
|
{
"start": 225,
"end": 1258
}
|
class ____:
"""Apply a style to a renderable.
Args:
renderable (RenderableType): Any renderable.
style (StyleType): A style to apply across the entire renderable.
"""
def __init__(self, renderable: "RenderableType", style: "StyleType") -> None:
self.renderable = renderable
self.style = style
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
style = console.get_style(self.style)
rendered_segments = console.render(self.renderable, options)
segments = Segment.apply_style(rendered_segments, style)
return segments
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
return Measurement.get(console, options, self.renderable)
if __name__ == "__main__": # pragma: no cover
from pip._vendor.rich import print
from pip._vendor.rich.panel import Panel
panel = Styled(Panel("hello"), "on blue")
print(panel)
|
Styled
|
python
|
PrefectHQ__prefect
|
src/prefect/filesystems.py
|
{
"start": 858,
"end": 1157
}
|
class ____(Block, abc.ABC):
_block_schema_capabilities = ["read-path", "write-path"]
@abc.abstractmethod
async def read_path(self, path: str) -> bytes:
pass
@abc.abstractmethod
async def write_path(self, path: str, content: bytes) -> None:
pass
|
WritableFileSystem
|
python
|
pallets__werkzeug
|
examples/plnt/database.py
|
{
"start": 1623,
"end": 1872
}
|
class ____:
query = session.query_property()
def __repr__(self):
return f"<{type(self).__name__} {self.guid!r}>"
mapper(Entry, entry_table)
mapper(Blog, blog_table, properties=dict(entries=dynamic_loader(Entry, backref="blog")))
|
Entry
|
python
|
weaviate__weaviate-python-client
|
weaviate/collections/classes/filters.py
|
{
"start": 4709,
"end": 5273
}
|
class ____:
_target: Optional[_TargetRefs] = None
_property: Union[str, _CountRef]
def _target_path(self) -> _FilterTargets:
if self._target is None:
return self._property
# get last element in chain
target = self._target
while target.target is not None:
assert isinstance(target.target, _MultiTargetRef) or isinstance(
target.target, _SingleTargetRef
)
target = target.target
target.target = self._property
return self._target
|
_FilterBase
|
python
|
pandas-dev__pandas
|
pandas/core/groupby/ops.py
|
{
"start": 39500,
"end": 40491
}
|
class ____(Generic[NDFrameT]):
def __init__(
self,
data: NDFrameT,
ngroups: int,
*,
sort_idx: npt.NDArray[np.intp],
sorted_ids: npt.NDArray[np.intp],
) -> None:
self.data = data
self.ngroups = ngroups
self._slabels = sorted_ids
self._sort_idx = sort_idx
def __iter__(self) -> Iterator:
if self.ngroups == 0:
# we are inside a generator, rather than raise StopIteration
# we merely return signal the end
return
starts, ends = lib.generate_slices(self._slabels, self.ngroups)
sdata = self._sorted_data
for start, end in zip(starts, ends, strict=True):
yield self._chop(sdata, slice(start, end))
@cache_readonly
def _sorted_data(self) -> NDFrameT:
return self.data.take(self._sort_idx, axis=0)
def _chop(self, sdata, slice_obj: slice) -> NDFrame:
raise AbstractMethodError(self)
|
DataSplitter
|
python
|
great-expectations__great_expectations
|
tests/integration/metrics/query/test_row_count.py
|
{
"start": 990,
"end": 2087
}
|
class ____:
@parameterize_batch_for_data_sources(
data_source_configs=SPARK_DATA_SOURCES,
data=DATA_FRAME,
)
def test_success_spark(self, batch_for_datasource) -> None:
batch = batch_for_datasource
metric = QueryRowCount(query="SELECT * FROM {batch} WHERE id > 0")
metric_result = batch.compute_metrics(metric)
assert isinstance(metric_result, QueryRowCountResult)
assert metric_result.value == 4
@parameterize_batch_for_data_sources(
data_source_configs=SQL_DATA_SOURCES,
data=DATA_FRAME,
)
@pytest.mark.parametrize(
["query", "result_value"],
[("SELECT * FROM {batch} WHERE id > 0", 4), ("SELECT * FROM {batch} WHERE id <= 2", 2)],
)
def test_success_sql(self, batch_for_datasource, query, result_value) -> None:
batch = batch_for_datasource
metric = QueryRowCount(query=query)
metric_result = batch.compute_metrics(metric)
assert isinstance(metric_result, QueryRowCountResult)
assert metric_result.value == result_value
|
TestQueryRowCount
|
python
|
apache__airflow
|
providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py
|
{
"start": 46467,
"end": 49902
}
|
class ____(GoogleCloudBaseOperator):
"""
Will update current set of Parameters to the set of specified nodes of the Memcached Instance.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudMemorystoreMemcachedApplyParametersOperator`
:param node_ids: Nodes to which we should apply the instance-level parameter group.
:param apply_all: Whether to apply instance-level parameter group to all nodes. If set to true,
will explicitly restrict users from specifying any nodes, and apply parameter group updates
to all nodes within the instance.
:param location: The location of the Cloud Memorystore instance (for example europe-west1)
:param instance_id: The logical name of the Memcached instance in the customer project.
:param project_id: Project ID of the project that contains the instance. If set
to None or missing, the default project_id from the Google Cloud connection is used.
:param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
``retry`` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
template_fields: Sequence[str] = (
"node_ids",
"apply_all",
"location",
"instance_id",
"project_id",
"retry",
"timeout",
"metadata",
"gcp_conn_id",
"impersonation_chain",
)
operator_extra_links = (MemcachedInstanceDetailsLink(),)
def __init__(
self,
*,
node_ids: Sequence[str],
apply_all: bool,
location: str,
instance_id: str,
project_id: str,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.node_ids = node_ids
self.apply_all = apply_all
self.location = location
self.instance_id = instance_id
self.project_id = project_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"instance_id": self.instance_id,
"location_id": self.location,
"project_id": self.project_id,
}
def execute(self, context: Context):
hook = CloudMemorystoreMemcachedHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
hook.apply_parameters(
node_ids=self.node_ids,
apply_all=self.apply_all,
location=self.location,
instance_id=self.instance_id,
project_id=self.project_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
MemcachedInstanceDetailsLink.persist(context=context)
|
CloudMemorystoreMemcachedApplyParametersOperator
|
python
|
python__mypy
|
mypyc/test-data/fixtures/ir.py
|
{
"start": 14000,
"end": 14048
}
|
class ____(Exception):
value: Any
|
StopIteration
|
python
|
redis__redis-py
|
redis/cluster.py
|
{
"start": 78953,
"end": 88599
}
|
class ____(PubSub):
"""
Wrapper for PubSub class.
IMPORTANT: before using ClusterPubSub, read about the known limitations
with pubsub in Cluster mode and learn how to workaround them:
https://redis-py-cluster.readthedocs.io/en/stable/pubsub.html
"""
def __init__(
self,
redis_cluster,
node=None,
host=None,
port=None,
push_handler_func=None,
event_dispatcher: Optional["EventDispatcher"] = None,
**kwargs,
):
"""
When a pubsub instance is created without specifying a node, a single
node will be transparently chosen for the pubsub connection on the
first command execution. The node will be determined by:
1. Hashing the channel name in the request to find its keyslot
2. Selecting a node that handles the keyslot: If read_from_replicas is
set to true or load_balancing_strategy is set, a replica can be selected.
:type redis_cluster: RedisCluster
:type node: ClusterNode
:type host: str
:type port: int
"""
self.node = None
self.set_pubsub_node(redis_cluster, node, host, port)
connection_pool = (
None
if self.node is None
else redis_cluster.get_redis_connection(self.node).connection_pool
)
self.cluster = redis_cluster
self.node_pubsub_mapping = {}
self._pubsubs_generator = self._pubsubs_generator()
if event_dispatcher is None:
self._event_dispatcher = EventDispatcher()
else:
self._event_dispatcher = event_dispatcher
super().__init__(
connection_pool=connection_pool,
encoder=redis_cluster.encoder,
push_handler_func=push_handler_func,
event_dispatcher=self._event_dispatcher,
**kwargs,
)
def set_pubsub_node(self, cluster, node=None, host=None, port=None):
"""
The pubsub node will be set according to the passed node, host and port
When none of the node, host, or port are specified - the node is set
to None and will be determined by the keyslot of the channel in the
first command to be executed.
RedisClusterException will be thrown if the passed node does not exist
in the cluster.
If host is passed without port, or vice versa, a DataError will be
thrown.
:type cluster: RedisCluster
:type node: ClusterNode
:type host: str
:type port: int
"""
if node is not None:
# node is passed by the user
self._raise_on_invalid_node(cluster, node, node.host, node.port)
pubsub_node = node
elif host is not None and port is not None:
# host and port passed by the user
node = cluster.get_node(host=host, port=port)
self._raise_on_invalid_node(cluster, node, host, port)
pubsub_node = node
elif any([host, port]) is True:
# only 'host' or 'port' passed
raise DataError("Passing a host requires passing a port, and vice versa")
else:
# nothing passed by the user. set node to None
pubsub_node = None
self.node = pubsub_node
def get_pubsub_node(self):
"""
Get the node that is being used as the pubsub connection
"""
return self.node
def _raise_on_invalid_node(self, redis_cluster, node, host, port):
"""
Raise a RedisClusterException if the node is None or doesn't exist in
the cluster.
"""
if node is None or redis_cluster.get_node(node_name=node.name) is None:
raise RedisClusterException(
f"Node {host}:{port} doesn't exist in the cluster"
)
def execute_command(self, *args):
"""
Execute a subscribe/unsubscribe command.
Taken code from redis-py and tweak to make it work within a cluster.
"""
# NOTE: don't parse the response in this function -- it could pull a
# legitimate message off the stack if the connection is already
# subscribed to one or more channels
if self.connection is None:
if self.connection_pool is None:
if len(args) > 1:
# Hash the first channel and get one of the nodes holding
# this slot
channel = args[1]
slot = self.cluster.keyslot(channel)
node = self.cluster.nodes_manager.get_node_from_slot(
slot,
self.cluster.read_from_replicas,
self.cluster.load_balancing_strategy,
)
else:
# Get a random node
node = self.cluster.get_random_node()
self.node = node
redis_connection = self.cluster.get_redis_connection(node)
self.connection_pool = redis_connection.connection_pool
self.connection = self.connection_pool.get_connection()
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
if self.push_handler_func is not None:
self.connection._parser.set_pubsub_push_handler(self.push_handler_func)
self._event_dispatcher.dispatch(
AfterPubSubConnectionInstantiationEvent(
self.connection, self.connection_pool, ClientType.SYNC, self._lock
)
)
connection = self.connection
self._execute(connection, connection.send_command, *args)
def _get_node_pubsub(self, node):
try:
return self.node_pubsub_mapping[node.name]
except KeyError:
pubsub = node.redis_connection.pubsub(
push_handler_func=self.push_handler_func
)
self.node_pubsub_mapping[node.name] = pubsub
return pubsub
def _sharded_message_generator(self):
for _ in range(len(self.node_pubsub_mapping)):
pubsub = next(self._pubsubs_generator)
message = pubsub.get_message()
if message is not None:
return message
return None
def _pubsubs_generator(self):
while True:
yield from self.node_pubsub_mapping.values()
def get_sharded_message(
self, ignore_subscribe_messages=False, timeout=0.0, target_node=None
):
if target_node:
message = self.node_pubsub_mapping[target_node.name].get_message(
ignore_subscribe_messages=ignore_subscribe_messages, timeout=timeout
)
else:
message = self._sharded_message_generator()
if message is None:
return None
elif str_if_bytes(message["type"]) == "sunsubscribe":
if message["channel"] in self.pending_unsubscribe_shard_channels:
self.pending_unsubscribe_shard_channels.remove(message["channel"])
self.shard_channels.pop(message["channel"], None)
node = self.cluster.get_node_from_key(message["channel"])
if self.node_pubsub_mapping[node.name].subscribed is False:
self.node_pubsub_mapping.pop(node.name)
if not self.channels and not self.patterns and not self.shard_channels:
# There are no subscriptions anymore, set subscribed_event flag
# to false
self.subscribed_event.clear()
if self.ignore_subscribe_messages or ignore_subscribe_messages:
return None
return message
def ssubscribe(self, *args, **kwargs):
if args:
args = list_or_args(args[0], args[1:])
s_channels = dict.fromkeys(args)
s_channels.update(kwargs)
for s_channel, handler in s_channels.items():
node = self.cluster.get_node_from_key(s_channel)
pubsub = self._get_node_pubsub(node)
if handler:
pubsub.ssubscribe(**{s_channel: handler})
else:
pubsub.ssubscribe(s_channel)
self.shard_channels.update(pubsub.shard_channels)
self.pending_unsubscribe_shard_channels.difference_update(
self._normalize_keys({s_channel: None})
)
if pubsub.subscribed and not self.subscribed:
self.subscribed_event.set()
self.health_check_response_counter = 0
def sunsubscribe(self, *args):
if args:
args = list_or_args(args[0], args[1:])
else:
args = self.shard_channels
for s_channel in args:
node = self.cluster.get_node_from_key(s_channel)
p = self._get_node_pubsub(node)
p.sunsubscribe(s_channel)
self.pending_unsubscribe_shard_channels.update(
p.pending_unsubscribe_shard_channels
)
def get_redis_connection(self):
"""
Get the Redis connection of the pubsub connected node.
"""
if self.node is not None:
return self.node.redis_connection
def disconnect(self):
"""
Disconnect the pubsub connection.
"""
if self.connection:
self.connection.disconnect()
for pubsub in self.node_pubsub_mapping.values():
pubsub.connection.disconnect()
|
ClusterPubSub
|
python
|
huggingface__transformers
|
src/transformers/models/big_bird/modeling_big_bird.py
|
{
"start": 67537,
"end": 67940
}
|
class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, pooled_output):
seq_relationship_score = self.seq_relationship(pooled_output)
return seq_relationship_score
# Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->BigBird
|
BigBirdOnlyNSPHead
|
python
|
pypa__setuptools
|
setuptools/_vendor/typeguard/_importhook.py
|
{
"start": 3061,
"end": 4575
}
|
class ____(MetaPathFinder):
"""
Wraps another path finder and instruments the module with
:func:`@typechecked <typeguard.typechecked>` if :meth:`should_instrument` returns
``True``.
Should not be used directly, but rather via :func:`~.install_import_hook`.
.. versionadded:: 2.6
"""
def __init__(self, packages: list[str] | None, original_pathfinder: MetaPathFinder):
self.packages = packages
self._original_pathfinder = original_pathfinder
def find_spec(
self,
fullname: str,
path: Sequence[str] | None,
target: types.ModuleType | None = None,
) -> ModuleSpec | None:
if self.should_instrument(fullname):
spec = self._original_pathfinder.find_spec(fullname, path, target)
if spec is not None and isinstance(spec.loader, SourceFileLoader):
spec.loader = TypeguardLoader(spec.loader.name, spec.loader.path)
return spec
return None
def should_instrument(self, module_name: str) -> bool:
"""
Determine whether the module with the given name should be instrumented.
:param module_name: full name of the module that is about to be imported (e.g.
``xyz.abc``)
"""
if self.packages is None:
return True
for package in self.packages:
if module_name == package or module_name.startswith(package + "."):
return True
return False
|
TypeguardFinder
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-shopify/unit_tests/integration/test_bulk_stream.py
|
{
"start": 9363,
"end": 30729
}
|
class ____(TestCase):
def setUp(self) -> None:
self._http_mocker = HttpMocker()
self._http_mocker.__enter__()
set_up_shop(self._http_mocker, _SHOP_NAME)
grant_all_scopes(self._http_mocker, _SHOP_NAME)
def tearDown(self) -> None:
self._http_mocker.__exit__(None, None, None)
def test_when_read_then_extract_records(self) -> None:
job_created_at = _INCREMENTAL_JOB_END_DATE - timedelta(minutes=5)
self._http_mocker.post(
create_job_creation_request(_SHOP_NAME, _INCREMENTAL_JOB_START_DATE, _INCREMENTAL_JOB_END_DATE),
JobCreationResponseBuilder(job_created_at=job_created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
.with_bulk_operation_id(_BULK_OPERATION_ID)
.build(),
)
self._http_mocker.post(
create_job_status_request(_SHOP_NAME, _BULK_OPERATION_ID),
JobStatusResponseBuilder().with_completed_status(_BULK_OPERATION_ID, _JOB_RESULT_URL).build(),
)
self._http_mocker.get(
HttpRequest(_JOB_RESULT_URL),
MetafieldOrdersJobResponseBuilder().with_record().with_record().build(),
)
# expectation is job start date should be the updated_at in orders
metafield_orders_orders_state = {
"orders": {"updated_at": _INCREMENTAL_JOB_START_DATE_ISO, "deleted": {"deleted_at": ""}},
"updated_at": _INCREMENTAL_JOB_START_DATE_ISO,
}
stream_state = StateBuilder().with_stream_state(_BULK_STREAM, metafield_orders_orders_state).build()
# we are passing to config a start date let's set something "old" as happen in many sources like 2 years ago
config_start_date = _INCREMENTAL_JOB_START_DATE - timedelta(weeks=104)
output = self._read(_get_config(config_start_date), sync_mode=SyncMode.incremental, state=stream_state)
assert output.errors == []
assert len(output.records) == 2
def test_when_read_with_updated_at_field_before_bulk_request_window_start_date(self) -> None:
""" "
The motivation of this test is https://github.com/airbytehq/oncall/issues/6874
In this scenario we end having stream_slices method to generate same slice N times.
Our checkpointing logic will trigger when job_checkpoint_interval is passed, but there may be the case that such checkpoint
has the same value as the current slice start date so we would end requesting same job.
In this test:
1. First job requires to checkpoint as we pass the 1500 limit, it cancels the bulk job and checkpoints from last cursor value.
2. Next job just goes "fine".
3. Now in the third and N job is where the behavior described above occurs, I just set it to happen a fixed N times as the
test depends on we keep feeding responses in the order of status running/canceled, but you can observe the repeated slices in the
logging.
e.g.
{"type":"LOG","log":{"level":"INFO","message":"Stream: `metafield_orders` requesting BULK Job for period: 2024-05-02T17:30:00+00:00 -- 2024-05-03T17:30:00+00:00. Slice size: `P1D`. The BULK checkpoint after `15000` lines."}}
...
{"type":"LOG","log":{"level":"INFO","message":"Stream metafield_orders, continue from checkpoint: `2024-05-02T17:30:00+00:00`."}}
{"type":"LOG","log":{"level":"INFO","message":"Stream: `metafield_orders` requesting BULK Job for period: 2024-05-02T17:30:00+00:00 -- 2024-05-03T17:30:00+00:00. Slice size: `P1D`. The BULK checkpoint after `15000` lines."}}
{"type":"LOG","log":{"level":"INFO","message":"Stream: `metafield_orders`, the BULK Job: `gid://shopify/BulkOperation/4472588009771` is CREATED"}}
...
"""
def add_n_records(builder, n, record_date: Optional[str] = None):
for _ in range(n):
builder = builder.with_record(updated_at=record_date)
return builder
# *************** 1st bulk job ***************************
job_created_at = _INCREMENTAL_JOB_END_DATE - timedelta(minutes=5)
# create a job request
self._http_mocker.post(
create_job_creation_request(_SHOP_NAME, _INCREMENTAL_JOB_START_DATE, _INCREMENTAL_JOB_END_DATE),
JobCreationResponseBuilder(job_created_at=job_created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
.with_bulk_operation_id(_BULK_OPERATION_ID)
.build(),
)
# get job status
self._http_mocker.post(
create_job_status_request(_SHOP_NAME, _BULK_OPERATION_ID),
[
JobStatusResponseBuilder().with_running_status(_BULK_OPERATION_ID, object_count="500").build(),
# this should make the job get canceled as it gets over 15000 rows
JobStatusResponseBuilder().with_running_status(_BULK_OPERATION_ID, object_count="16000").build(),
# this will complete the job
JobStatusResponseBuilder().with_canceled_status(_BULK_OPERATION_ID, _JOB_RESULT_URL, object_count="1700").build(),
],
)
# mock the cancel operation request as we passed the 15000 rows
self._http_mocker.post(create_job_cancel_request(_SHOP_NAME, _BULK_OPERATION_ID), [HttpResponse(json.dumps({}), status_code=200)])
# get results for the request that got cancelled
adjusted_checkpoint_start_date = _INCREMENTAL_JOB_START_DATE - timedelta(days=2, hours=6, minutes=30)
adjusted_record_date = adjusted_checkpoint_start_date.strftime("%Y-%m-%dT%H:%M:%SZ")
self._http_mocker.get(
HttpRequest(_JOB_RESULT_URL),
# MetafieldOrdersJobResponseBuilder().with_record().with_record().build(),
add_n_records(MetafieldOrdersJobResponseBuilder(), 80, adjusted_record_date).build(),
)
# *************** 2nd bulk job ***************************
# create a job request for a new job with checkpoint date
# that will be the adjusted_record_date + 1 day
next_bulk_operation_id = "gid://shopify/BulkOperation/4472588009771"
adjusted_checkpoint_end_date = adjusted_checkpoint_start_date + timedelta(days=1)
job_created_at = _INCREMENTAL_JOB_END_DATE - timedelta(minutes=4)
self._http_mocker.post(
# The start date is caused by record date in previous iteration
create_job_creation_request(_SHOP_NAME, adjusted_checkpoint_start_date, adjusted_checkpoint_end_date),
JobCreationResponseBuilder(job_created_at=job_created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
.with_bulk_operation_id(next_bulk_operation_id)
.build(),
)
# get job status
next_job_result_url = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/l6lersgk4i81iqc3n6iisywwtipb-final?GoogleAccessId=assets-us-prod%40shopify-tiers.iam.gserviceaccount.com&Expires=1715633149&Signature=oMjQelfAzUW%2FdulC3HbuBapbUriUJ%2Bc9%2FKpIIf954VTxBqKChJAdoTmWT9ymh%2FnCiHdM%2BeM%2FADz5siAC%2BXtHBWkJfvs%2F0cYpse0ueiQsw6R8gW5JpeSbizyGWcBBWkv5j8GncAnZOUVYDxRIgfxcPb8BlFxBfC3wsx%2F00v9D6EHbPpkIMTbCOAhheJdw9GmVa%2BOMqHGHlmiADM34RDeBPrvSo65f%2FakpV2LBQTEV%2BhDt0ndaREQ0MrpNwhKnc3vZPzA%2BliOGM0wyiYr9qVwByynHq8c%2FaJPPgI5eGEfQcyepgWZTRW5S0DbmBIFxZJLN6Nq6bJ2bIZWrVriUhNGx2g%3D%3D&response-content-disposition=attachment%3B+filename%3D%22bulk-4476008693950.jsonl%22%3B+filename%2A%3DUTF-8%27%27bulk-4476008693950.jsonl&response-content-type=application%2Fjsonl"
self._http_mocker.post(
create_job_status_request(_SHOP_NAME, next_bulk_operation_id),
[
# this will output the job is running
JobStatusResponseBuilder().with_completed_status(next_bulk_operation_id, next_job_result_url).build(),
],
)
# get results for the request that got cancelled
self._http_mocker.get(
HttpRequest(next_job_result_url),
# MetafieldOrdersJobResponseBuilder().with_record().with_record().build(),
add_n_records(MetafieldOrdersJobResponseBuilder(), 90, adjusted_record_date).build(),
)
# *************** 3rd and n+ bulk job ***************************
next_bulk_operation_id = "gid://shopify/BulkOperation/4472588009881"
adjusted_checkpoint_start_date = adjusted_checkpoint_end_date
adjusted_checkpoint_end_date = adjusted_checkpoint_start_date + timedelta(days=1)
job_created_at = _INCREMENTAL_JOB_END_DATE - timedelta(minutes=4)
create_job_request = create_job_creation_request(_SHOP_NAME, adjusted_checkpoint_start_date, adjusted_checkpoint_end_date)
self._http_mocker.post(
create_job_request,
JobCreationResponseBuilder(job_created_at=job_created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
.with_bulk_operation_id(next_bulk_operation_id)
.build(),
)
base_status_responses = [
JobStatusResponseBuilder().with_running_status(next_bulk_operation_id, object_count="500").build(),
# this should make the job get canceled as it gets over 15000 rows
JobStatusResponseBuilder().with_running_status(next_bulk_operation_id, object_count="16000").build(),
# this will complete the job
JobStatusResponseBuilder().with_canceled_status(next_bulk_operation_id, next_job_result_url, object_count="1700").build(),
]
n_times_to_loop = 4
responses_in_loop = base_status_responses * n_times_to_loop
# get job status
next_job_result_url = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/l6lersgk4i81iqc3n6iisywwtipb-final?GoogleAccessId=assets-us-prod%40shopify-tiers.iam.gserviceaccount.com&Expires=1715633149&Signature=oMjQelfAzUW%2FdulC3HbuBapbUriUJ%2Bc9%2FKpIIf954VTxBqKChJAdoTmWT9ymh%2FnCiHdM%2BeM%2FADz5siAC%2BXtHBWkJfvs%2F0cYpse0ueiQsw6R8gW5JpeSbizyGWcBBWkv5j8GncAnZOUVYDxRIgfxcPb8BlFxBfC3wsx%2F00v9D6EHbPpkIMTbCOAhheJdw9GmVa%2BOMqHGHlmiADM34RDeBPrvSo65f%2FakpV2LBQTEV%2BhDt0ndaREQ0MrpNwhKnc3vZPzA%2BliOGM0wyiYr9qVwByynHq8c%2FaJPPgI5eGEfQcyepgWZTRW5S0DbmBIFxZJLN6Nq6bJ2bIZWrVriUhNGx2g%3D%3D&response-content-disposition=attachment%3B+filename%3D%22bulk-4476008693960.jsonl%22%3B+filename%2A%3DUTF-8%27%27bulk-4476008693960.jsonl&response-content-type=application%2Fjsonl"
self._http_mocker.post(create_job_status_request(_SHOP_NAME, next_bulk_operation_id), responses_in_loop)
# mock the cancel operation request as we passed the 15000 rows
self._http_mocker.post(
create_job_cancel_request(_SHOP_NAME, next_bulk_operation_id), [HttpResponse(json.dumps({}), status_code=200)]
)
# get results
adjusted_record_date = adjusted_checkpoint_start_date.strftime("%Y-%m-%dT%H:%M:%SZ")
self._http_mocker.get(
HttpRequest(next_job_result_url),
add_n_records(MetafieldOrdersJobResponseBuilder(), 80, adjusted_record_date).build(),
)
# ********* end of request mocking *************
metafield_orders_orders_state = {
"orders": {"updated_at": _INCREMENTAL_JOB_START_DATE_ISO, "deleted": {"deleted_at": ""}},
"updated_at": _INCREMENTAL_JOB_START_DATE_ISO,
}
stream_state = StateBuilder().with_stream_state(_BULK_STREAM, metafield_orders_orders_state).build()
# we are passing to config a start date let's set something "old" as happen in many sources like 2 years ago
config_start_date = _INCREMENTAL_JOB_START_DATE - timedelta(weeks=104)
output = self._read(
_get_config(config_start_date, job_checkpoint_interval=15000), sync_mode=SyncMode.incremental, state=stream_state
)
expected_error_message = "The stream: `metafield_orders` checkpoint collision is detected."
result = output.errors[0].trace.error.internal_message
# The result of the test should be the `ShopifyBulkExceptions.BulkJobCheckpointCollisionError`
assert result is not None and expected_error_message in result
def _read(self, config, sync_mode=SyncMode.full_refresh, state: Optional[List[AirbyteStateMessage]] = None):
catalog = CatalogBuilder().with_stream(_BULK_STREAM, sync_mode).build()
output = read(SourceShopify(), config, catalog, state=state)
return output
def _read_customer_address(self, config, sync_mode=SyncMode.full_refresh, state: Optional[List[AirbyteStateMessage]] = None):
catalog = CatalogBuilder().with_stream(_CUSTOMER_ADDRESS_STREAM, sync_mode).build()
output = read(SourceShopify(), config, catalog, state=state)
return output
def test_when_read_with_updated_at_field_before_bulk_request_window_start_date_customer_address(self):
"""
The test logic is identical to the test above but with the another stream type, where cursor field is ID
and filter_checkpointed_cursor value should be used as the value to adjust slice end.
"""
def add_n_records(builder, n, record_date: Optional[str] = None):
for _ in range(n):
builder = builder.with_record(updated_at=record_date)
return builder
# *************** 1st bulk job ***************************
job_created_at = _INCREMENTAL_JOB_END_DATE - timedelta(minutes=5)
# create a job request
self._http_mocker.post(
create_job_creation_customer_address_request(_SHOP_NAME, _INCREMENTAL_JOB_START_DATE, _INCREMENTAL_JOB_END_DATE),
JobCreationResponseBuilder(job_created_at=job_created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
.with_bulk_operation_id(_BULK_OPERATION_ID)
.build(),
)
# get job status
self._http_mocker.post(
create_job_status_request(_SHOP_NAME, _BULK_OPERATION_ID),
[
JobStatusResponseBuilder().with_running_status(_BULK_OPERATION_ID, object_count="500").build(),
# this should make the job get canceled as it gets over 15000 rows
JobStatusResponseBuilder().with_running_status(_BULK_OPERATION_ID, object_count="16000").build(),
# this will complete the job
JobStatusResponseBuilder().with_canceled_status(_BULK_OPERATION_ID, _JOB_RESULT_URL, object_count="1700").build(),
],
)
# mock the cancel operation request as we passed the 15000 rows
self._http_mocker.post(create_job_cancel_request(_SHOP_NAME, _BULK_OPERATION_ID), [HttpResponse(json.dumps({}), status_code=200)])
# get results for the request that got cancelled
adjusted_checkpoint_start_date = _INCREMENTAL_JOB_START_DATE - timedelta(days=2, hours=6, minutes=30)
adjusted_record_date = adjusted_checkpoint_start_date.strftime("%Y-%m-%dT%H:%M:%SZ")
self._http_mocker.get(
HttpRequest(_JOB_RESULT_URL),
add_n_records(CustomerAddressResponseBuilder(), 80, adjusted_record_date).build(),
)
# *************** 2nd bulk job ***************************
# create a job request for a new job with checkpoint date
# that will be the adjusted_record_date + 1 day
next_bulk_operation_id = "gid://shopify/BulkOperation/4472588009771"
adjusted_checkpoint_end_date = adjusted_checkpoint_start_date + timedelta(days=1)
job_created_at = _INCREMENTAL_JOB_END_DATE - timedelta(minutes=4)
self._http_mocker.post(
# The start date is caused by record date in previous iteration
create_job_creation_customer_address_request(_SHOP_NAME, adjusted_checkpoint_start_date, adjusted_checkpoint_end_date),
JobCreationResponseBuilder(job_created_at=job_created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
.with_bulk_operation_id(next_bulk_operation_id)
.build(),
)
# get job status
next_job_result_url = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/l6lersgk4i81iqc3n6iisywwtipb-final?GoogleAccessId=assets-us-prod%40shopify-tiers.iam.gserviceaccount.com&Expires=1715633149&Signature=oMjQelfAzUW%2FdulC3HbuBapbUriUJ%2Bc9%2FKpIIf954VTxBqKChJAdoTmWT9ymh%2FnCiHdM%2BeM%2FADz5siAC%2BXtHBWkJfvs%2F0cYpse0ueiQsw6R8gW5JpeSbizyGWcBBWkv5j8GncAnZOUVYDxRIgfxcPb8BlFxBfC3wsx%2F00v9D6EHbPpkIMTbCOAhheJdw9GmVa%2BOMqHGHlmiADM34RDeBPrvSo65f%2FakpV2LBQTEV%2BhDt0ndaREQ0MrpNwhKnc3vZPzA%2BliOGM0wyiYr9qVwByynHq8c%2FaJPPgI5eGEfQcyepgWZTRW5S0DbmBIFxZJLN6Nq6bJ2bIZWrVriUhNGx2g%3D%3D&response-content-disposition=attachment%3B+filename%3D%22bulk-4476008693950.jsonl%22%3B+filename%2A%3DUTF-8%27%27bulk-4476008693950.jsonl&response-content-type=application%2Fjsonl"
self._http_mocker.post(
create_job_status_request(_SHOP_NAME, next_bulk_operation_id),
[
# this will output the job is running
JobStatusResponseBuilder().with_completed_status(next_bulk_operation_id, next_job_result_url).build(),
],
)
# get results for the request that got cancelled
self._http_mocker.get(
HttpRequest(next_job_result_url),
add_n_records(CustomerAddressResponseBuilder(), 90, adjusted_record_date).build(),
)
# *************** 3rd and n+ bulk job ***************************
next_bulk_operation_id = "gid://shopify/BulkOperation/4472588009881"
adjusted_checkpoint_start_date = adjusted_checkpoint_end_date
adjusted_checkpoint_end_date = adjusted_checkpoint_start_date + timedelta(days=1)
job_created_at = _INCREMENTAL_JOB_END_DATE - timedelta(minutes=4)
create_job_request = create_job_creation_customer_address_request(
_SHOP_NAME, adjusted_checkpoint_start_date, adjusted_checkpoint_end_date
)
self._http_mocker.post(
create_job_request,
JobCreationResponseBuilder(job_created_at=job_created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
.with_bulk_operation_id(next_bulk_operation_id)
.build(),
)
base_status_responses = [
JobStatusResponseBuilder().with_running_status(next_bulk_operation_id, object_count="500").build(),
# this should make the job get canceled as it gets over 15000 rows
JobStatusResponseBuilder().with_running_status(next_bulk_operation_id, object_count="16000").build(),
# this will complete the job
JobStatusResponseBuilder().with_canceled_status(next_bulk_operation_id, next_job_result_url, object_count="1700").build(),
]
n_times_to_loop = 4
responses_in_loop = base_status_responses * n_times_to_loop
# get job status
next_job_result_url = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/l6lersgk4i81iqc3n6iisywwtipb-final?GoogleAccessId=assets-us-prod%40shopify-tiers.iam.gserviceaccount.com&Expires=1715633149&Signature=oMjQelfAzUW%2FdulC3HbuBapbUriUJ%2Bc9%2FKpIIf954VTxBqKChJAdoTmWT9ymh%2FnCiHdM%2BeM%2FADz5siAC%2BXtHBWkJfvs%2F0cYpse0ueiQsw6R8gW5JpeSbizyGWcBBWkv5j8GncAnZOUVYDxRIgfxcPb8BlFxBfC3wsx%2F00v9D6EHbPpkIMTbCOAhheJdw9GmVa%2BOMqHGHlmiADM34RDeBPrvSo65f%2FakpV2LBQTEV%2BhDt0ndaREQ0MrpNwhKnc3vZPzA%2BliOGM0wyiYr9qVwByynHq8c%2FaJPPgI5eGEfQcyepgWZTRW5S0DbmBIFxZJLN6Nq6bJ2bIZWrVriUhNGx2g%3D%3D&response-content-disposition=attachment%3B+filename%3D%22bulk-4476008693960.jsonl%22%3B+filename%2A%3DUTF-8%27%27bulk-4476008693960.jsonl&response-content-type=application%2Fjsonl"
self._http_mocker.post(create_job_status_request(_SHOP_NAME, next_bulk_operation_id), responses_in_loop)
# mock the cancel operation request as we passed the 15000 rows
self._http_mocker.post(
create_job_cancel_request(_SHOP_NAME, next_bulk_operation_id), [HttpResponse(json.dumps({}), status_code=200)]
)
# get results
adjusted_record_date = adjusted_checkpoint_start_date.strftime("%Y-%m-%dT%H:%M:%SZ")
self._http_mocker.get(
HttpRequest(next_job_result_url),
add_n_records(CustomerAddressResponseBuilder(), 80, adjusted_record_date).build(),
)
# ********* end of request mocking *************
customer_address_stream_state = {"id": 11111111111111, "customers": {"updated_at": _INCREMENTAL_JOB_START_DATE_ISO}}
stream_state = StateBuilder().with_stream_state(_CUSTOMER_ADDRESS_STREAM, customer_address_stream_state).build()
# we are passing to config a start date let's set something "old" as happen in many sources like 2 years ago
config_start_date = _INCREMENTAL_JOB_START_DATE - timedelta(weeks=104)
output = self._read_customer_address(
_get_config(config_start_date, job_checkpoint_interval=15000), sync_mode=SyncMode.incremental, state=stream_state
)
expected_error_message = "The stream: `customer_address` checkpoint collision is detected."
result = output.errors[0].trace.error.internal_message
# The result of the test should be the `ShopifyBulkExceptions.BulkJobCheckpointCollisionError`
assert result is not None and expected_error_message in result
|
GraphQlBulkStreamIncrementalTest
|
python
|
pyqtgraph__pyqtgraph
|
pyqtgraph/graphicsItems/ViewBox/ViewBox.py
|
{
"start": 2230,
"end": 75813
}
|
class ____(GraphicsWidget):
"""
**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
Box that allows internal scaling/panning of children by mouse drag.
This class is usually created automatically as part of a :class:`PlotItem <pyqtgraph.PlotItem>` or with :func:`GraphicsLayout.addViewBox() <pyqtgraph.GraphicsLayout.addViewBox>`.
Features:
* Scaling contents by mouse or auto-scale when contents change
* View linking--multiple views display the same data ranges
* Configurable by context menu
* Item coordinate mapping methods
"""
sigYRangeChanged = QtCore.Signal(object, object)
sigXRangeChanged = QtCore.Signal(object, object)
sigRangeChangedManually = QtCore.Signal(object)
sigRangeChanged = QtCore.Signal(object, object, object)
sigStateChanged = QtCore.Signal(object)
sigTransformChanged = QtCore.Signal(object)
sigResized = QtCore.Signal(object)
## mouse modes
PanMode = 3
RectMode = 1
## axes
XAxis = 0
YAxis = 1
XYAxes = 2
## for linking views together
NamedViews = weakref.WeakValueDictionary() # name: ViewBox
AllViews = weakref.WeakKeyDictionary() # ViewBox: None
def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu=True, name=None, invertX=False, defaultPadding=0.02):
"""
================= =============================================================
**Arguments:**
*parent* (QGraphicsWidget) Optional parent widget
*border* (QPen) Do draw a border around the view, give any
single argument accepted by :func:`mkPen <pyqtgraph.mkPen>`
*lockAspect* (False or float) The aspect ratio to lock the view
coorinates to. (or False to allow the ratio to change)
*enableMouse* (bool) Whether mouse can be used to scale/pan the view
*invertY* (bool) See :func:`invertY <pyqtgraph.ViewBox.invertY>`
*invertX* (bool) See :func:`invertX <pyqtgraph.ViewBox.invertX>`
*enableMenu* (bool) Whether to display a context menu when
right-clicking on the ViewBox background.
*name* (str) Used to register this ViewBox so that it appears
in the "Link axis" dropdown inside other ViewBox
context menus. This allows the user to manually link
the axes of any other view to this one.
*defaultPadding* (float) fraction of the data range that will be added
as padding by default
================= =============================================================
"""
GraphicsWidget.__init__(self, parent)
self.name = None
self.linksBlocked = False
self.addedItems = []
self._matrixNeedsUpdate = True ## indicates that range has changed, but matrix update was deferred
self._autoRangeNeedsUpdate = True ## indicates auto-range needs to be recomputed.
self._lastScene = None ## stores reference to the last known scene this view was a part of.
self.state = {
## separating targetRange and viewRange allows the view to be resized
## while keeping all previously viewed contents visible
'targetRange': [[0,1], [0,1]], ## child coord. range visible [[xmin, xmax], [ymin, ymax]]
'viewRange': [[0,1], [0,1]], ## actual range viewed
'yInverted': invertY,
'xInverted': invertX,
'aspectLocked': False, ## False if aspect is unlocked, otherwise float specifies the locked ratio.
'autoRange': [True, True], ## False if auto range is disabled,
## otherwise float gives the fraction of data that is visible
'autoPan': [False, False], ## whether to only pan (do not change scaling) when auto-range is enabled
'autoVisibleOnly': [False, False], ## whether to auto-range only to the visible portion of a plot
'linkedViews': [None, None], ## may be None, "viewName", or weakref.ref(view)
## a name string indicates that the view *should* link to another, but no view with that name exists yet.
'defaultPadding': defaultPadding,
'mouseEnabled': [enableMouse, enableMouse],
'mouseMode': ViewBox.PanMode if getConfigOption('leftButtonPan') else ViewBox.RectMode,
'enableMenu': enableMenu,
'wheelScaleFactor': -1.0 / 8.0,
'background': None,
'logMode': [False, False],
# Limits
# maximum value of double float is 1.7E+308, but internal caluclations exceed this limit before the range reaches it.
'limits': {
'xLimits': [-1E307, +1E307], # Maximum and minimum visible X values
'yLimits': [-1E307, +1E307], # Maximum and minimum visible Y values
'xRange': [None, None], # Maximum and minimum X range
'yRange': [None, None], # Maximum and minimum Y range
}
}
self._updatingRange = False ## Used to break recursive loops. See updateAutoRange.
self._itemBoundsCache = weakref.WeakKeyDictionary()
self.locateGroup = None ## items displayed when using ViewBox.locate(item)
self.setFlag(self.GraphicsItemFlag.ItemClipsChildrenToShape)
self.setFlag(self.GraphicsItemFlag.ItemIsFocusable, True) ## so we can receive key presses
## childGroup is required so that ViewBox has local coordinates similar to device coordinates.
## this is a workaround for a Qt + OpenGL bug that causes improper clipping
## https://bugreports.qt.nokia.com/browse/QTBUG-23723
self.childGroup = ChildGroup(self)
self.childGroup.itemsChangedListeners.append(self)
self.background = QtWidgets.QGraphicsRectItem(self.rect())
self.background.setParentItem(self)
self.background.setZValue(-1e6)
self.background.setPen(fn.mkPen(None))
self.updateBackground()
self.border = fn.mkPen(border)
self.borderRect = QtWidgets.QGraphicsRectItem(self.rect())
self.borderRect.setParentItem(self)
self.borderRect.setZValue(1e3)
self.borderRect.setPen(self.border)
self._rbScaleBox = None
## show target rect for debugging
self.target = QtWidgets.QGraphicsRectItem(0, 0, 1, 1)
self.target.setPen(fn.mkPen('r'))
self.target.setParentItem(self)
self.target.hide()
self.axHistory = [] # maintain a history of zoom locations
self.axHistoryPointer = -1 # pointer into the history. Allows forward/backward movement, not just "undo"
self.setZValue(-100)
self.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding))
self.setAspectLocked(lockAspect)
if enableMenu:
self.menu = ViewBoxMenu(self)
else:
self.menu = None
self.register(name)
if name is None:
self.updateViewLists()
self._viewPixelSizeCache = None
@property
def rbScaleBox(self):
if self._rbScaleBox is None:
# call the setter with the default value
scaleBox = QtWidgets.QGraphicsRectItem(0, 0, 1, 1)
scaleBox.setPen(fn.mkPen((255, 255, 100), width=1))
scaleBox.setBrush(fn.mkBrush(255, 255, 0, 100))
scaleBox.setZValue(1e9)
scaleBox.hide()
self._rbScaleBox = scaleBox
self.addItem(scaleBox, ignoreBounds=True)
return self._rbScaleBox
@rbScaleBox.setter
def rbScaleBox(self, scaleBox):
if self._rbScaleBox is not None:
self.removeItem(self._rbScaleBox)
self._rbScaleBox = scaleBox
if scaleBox is None:
return None
scaleBox.setZValue(1e9)
scaleBox.hide()
self.addItem(scaleBox, ignoreBounds=True)
return None
def getAspectRatio(self):
"""return the current aspect ratio"""
rect = self.rect()
vr = self.viewRect()
if rect.height() == 0 or vr.width() == 0 or vr.height() == 0:
currentRatio = 1.0
else:
currentRatio = (rect.width()/float(rect.height())) / (
vr.width()/vr.height())
return currentRatio
def register(self, name):
"""
Add this ViewBox to the registered list of views.
This allows users to manually link the axes of any other ViewBox to
this one. The specified *name* will appear in the drop-down lists for
axis linking in the context menus of all other views.
The same can be accomplished by initializing the ViewBox with the *name* attribute.
"""
ViewBox.AllViews[self] = None
if self.name is not None:
del ViewBox.NamedViews[self.name]
self.name = name
if name is not None:
ViewBox.NamedViews[name] = self
ViewBox.updateAllViewLists()
sid = id(self)
self.destroyed.connect(lambda: ViewBox.forgetView(sid, name) if (ViewBox is not None and 'sid' in locals() and 'name' in locals()) else None)
def unregister(self):
"""
Remove this ViewBox from the list of linkable views. (see :func:`register() <pyqtgraph.ViewBox.register>`)
"""
del ViewBox.AllViews[self]
if self.name is not None:
del ViewBox.NamedViews[self.name]
def close(self):
self.clear()
self.unregister()
def implements(self, interface):
return interface == 'ViewBox'
def itemChange(self, change, value):
ret = super().itemChange(change, value)
if change == self.GraphicsItemChange.ItemSceneChange:
scene = self.scene()
if scene is not None and hasattr(scene, 'sigPrepareForPaint'):
scene.sigPrepareForPaint.disconnect(self.prepareForPaint)
elif change == self.GraphicsItemChange.ItemSceneHasChanged:
scene = self.scene()
if scene is not None and hasattr(scene, 'sigPrepareForPaint'):
scene.sigPrepareForPaint.connect(self.prepareForPaint)
return ret
@QtCore.Slot()
def prepareForPaint(self):
#autoRangeEnabled = (self.state['autoRange'][0] is not False) or (self.state['autoRange'][1] is not False)
# don't check whether auto range is enabled here--only check when setting dirty flag.
if self._autoRangeNeedsUpdate: # and autoRangeEnabled:
self.updateAutoRange()
self.updateMatrix()
def getState(self, copy=True):
"""Return the current state of the ViewBox.
Linked views are always converted to view names in the returned state."""
state = self.state.copy()
views = []
for v in state['linkedViews']:
if isinstance(v, weakref.ref):
v = v()
if v is None or isinstance(v, str):
views.append(v)
else:
views.append(v.name)
state['linkedViews'] = views
if copy:
return deepcopy(state)
else:
return state
def setState(self, state):
"""Restore the state of this ViewBox.
(see also getState)"""
state = state.copy()
self.setXLink(state['linkedViews'][0])
self.setYLink(state['linkedViews'][1])
del state['linkedViews']
self.state.update(state)
self._applyMenuEnabled()
self.updateViewRange()
self.sigStateChanged.emit(self)
def setBackgroundColor(self, color):
"""
Set the background color of the ViewBox.
If color is None, then no background will be drawn.
Added in version 0.9.9
"""
self.background.setVisible(color is not None)
self.state['background'] = color
self.updateBackground()
def setMouseMode(self, mode):
"""
Set the mouse interaction mode. *mode* must be either ViewBox.PanMode or ViewBox.RectMode.
In PanMode, the left mouse button pans the view and the right button scales.
In RectMode, the left button draws a rectangle which updates the visible region (this mode is more suitable for single-button mice)
"""
if mode not in [ViewBox.PanMode, ViewBox.RectMode]:
raise Exception("Mode must be ViewBox.PanMode or ViewBox.RectMode")
if mode == ViewBox.PanMode:
self._rbScaleBox = None
self.state['mouseMode'] = mode
self.sigStateChanged.emit(self)
def setLeftButtonAction(self, mode='rect'): ## for backward compatibility
if mode.lower() == 'rect':
self.setMouseMode(ViewBox.RectMode)
elif mode.lower() == 'pan':
self.setMouseMode(ViewBox.PanMode)
else:
raise Exception('graphicsItems:ViewBox:setLeftButtonAction: unknown mode = %s (Options are "pan" and "rect")' % mode)
def innerSceneItem(self):
return self.childGroup
def setMouseEnabled(self, x=None, y=None):
"""
Set whether each axis is enabled for mouse interaction. *x*, *y* arguments must be True or False.
This allows the user to pan/scale one axis of the view while leaving the other axis unchanged.
"""
if x is not None:
self.state['mouseEnabled'][0] = x
if y is not None:
self.state['mouseEnabled'][1] = y
self.sigStateChanged.emit(self)
def mouseEnabled(self):
return self.state['mouseEnabled'][:]
def setMenuEnabled(self, enableMenu=True):
self.state['enableMenu'] = enableMenu
self._applyMenuEnabled()
self.sigStateChanged.emit(self)
def menuEnabled(self):
return self.state.get('enableMenu', True)
def _applyMenuEnabled(self):
enableMenu = self.state.get("enableMenu", True)
if enableMenu and self.menu is None:
self.menu = ViewBoxMenu(self)
self.updateViewLists()
elif not enableMenu and self.menu is not None:
self.menu.setParent(None)
self.menu = None
def addItem(self, item, ignoreBounds=False):
"""
Add a QGraphicsItem to this view. The view will include this item when determining how to set its range
automatically unless *ignoreBounds* is True.
"""
if item.zValue() < self.zValue():
item.setZValue(self.zValue()+1)
scene = self.scene()
if scene is not None and scene is not item.scene():
scene.addItem(item) ## Necessary due to Qt bug: https://bugreports.qt-project.org/browse/QTBUG-18616
item.setParentItem(self.childGroup)
if not ignoreBounds:
self.addedItems.append(item)
self.queueUpdateAutoRange()
def removeItem(self, item):
"""Remove an item from this view."""
try:
self.addedItems.remove(item)
except:
pass
scene = self.scene()
if scene is not None:
scene.removeItem(item)
item.setParentItem(None)
self.queueUpdateAutoRange()
def clear(self):
for i in self.addedItems[:]:
self.removeItem(i)
for ch in self.childGroup.childItems():
ch.setParentItem(None)
def resizeEvent(self, ev):
if ev.oldSize() != ev.newSize():
self._viewPixelSizeCache = None
self._matrixNeedsUpdate = True
self.linkedXChanged()
self.linkedYChanged()
self.queueUpdateAutoRange()
self.updateViewRange()
# self._matrixNeedsUpdate = True
self.background.setRect(self.rect())
self.borderRect.setRect(self.rect())
self.sigStateChanged.emit(self)
self.sigResized.emit(self)
def boundingRect(self):
br = super().boundingRect()
return br.adjusted(0, 0, +0.5, +0.5)
def viewRange(self):
"""Return a the view's visible range as a list: [[xmin, xmax], [ymin, ymax]]"""
return [x[:] for x in self.state['viewRange']] ## return copy
def viewRect(self):
"""Return a QRectF bounding the region visible within the ViewBox"""
try:
vr0 = self.state['viewRange'][0]
vr1 = self.state['viewRange'][1]
return QtCore.QRectF(vr0[0], vr1[0], vr0[1]-vr0[0], vr1[1] - vr1[0])
except:
print("make qrectf failed:", self.state['viewRange'])
raise
def targetRange(self):
return [x[:] for x in self.state['targetRange']] ## return copy
def targetRect(self):
"""
Return the region which has been requested to be visible.
(this is not necessarily the same as the region that is *actually* visible--
resizing and aspect ratio constraints can cause targetRect() and viewRect() to differ)
"""
try:
tr0 = self.state['targetRange'][0]
tr1 = self.state['targetRange'][1]
return QtCore.QRectF(tr0[0], tr1[0], tr0[1]-tr0[0], tr1[1] - tr1[0])
except:
print("make qrectf failed:", self.state['targetRange'])
raise
def _resetTarget(self):
# Reset target range to exactly match current view range.
# This is used during mouse interaction to prevent unpredictable
# behavior (because the user is unaware of targetRange).
self.state['targetRange'] = [self.state['viewRange'][0][:], self.state['viewRange'][1][:]]
def _effectiveLimits(self):
# Determines restricted effective scaling range when in log mapping mode
if self.state['logMode'][0]:
xlimits = (# constrain to the +1.7E308 to 2.2E-308 range of double float values
max( self.state['limits']['xLimits'][0], -307.6 ),
min( self.state['limits']['xLimits'][1], +308.2 )
)
else:
xlimits = self.state['limits']['xLimits']
if self.state['logMode'][1]:
ylimits = (# constrain to the +1.7E308 to 2.2E-308 range of double float values
max( self.state['limits']['yLimits'][0], -307.6 ),
min( self.state['limits']['yLimits'][1], +308.2 )
)
else:
ylimits = self.state['limits']['yLimits']
# print('limits ', xlimits, ylimits) # diagnostic output should reflect additional limit in log mode
return (xlimits, ylimits)
def setRange(self, rect=None, xRange=None, yRange=None, padding=None, update=True, disableAutoRange=True):
"""
Set the visible range of the ViewBox.
Must specify at least one of *rect*, *xRange*, or *yRange*.
================== =====================================================================
**Arguments:**
*rect* (QRectF) The full range that should be visible in the view box.
*xRange* (min,max) The range that should be visible along the x-axis.
*yRange* (min,max) The range that should be visible along the y-axis.
*padding* (float) Expand the view by a fraction of the requested range.
By default, this value is set between the default padding value
and 0.1 depending on the size of the ViewBox.
*update* (bool) If True, update the range of the ViewBox immediately.
Otherwise, the update is deferred until before the next render.
*disableAutoRange* (bool) If True, auto-ranging is diabled. Otherwise, it is left
unchanged.
================== =====================================================================
"""
self._viewPixelSizeCache = None
changes = {} # axes
setRequested = [False, False]
if rect is not None:
changes = {0: [rect.left(), rect.right()], 1: [rect.top(), rect.bottom()]}
setRequested = [True, True]
if xRange is not None:
changes[0] = xRange
setRequested[0] = True
if yRange is not None:
changes[1] = yRange
setRequested[1] = True
if len(changes) == 0:
raise Exception("Must specify at least one of rect, xRange, or yRange. (gave rect=%s)" % str(type(rect)))
# Update axes one at a time
changed = [False, False]
# Disable auto-range for each axis that was requested to be set
if disableAutoRange:
xOff = False if setRequested[0] else None
yOff = False if setRequested[1] else None
self.enableAutoRange(x=xOff, y=yOff)
changed.append(True)
limits = self._effectiveLimits()
# print('rng:limits ', limits) # diagnostic output should reflect additional limit in log mode
# limits = (self.state['limits']['xLimits'], self.state['limits']['yLimits'])
minRng = [self.state['limits']['xRange'][0], self.state['limits']['yRange'][0]]
maxRng = [self.state['limits']['xRange'][1], self.state['limits']['yRange'][1]]
for ax, range in changes.items():
mn = min(range)
mx = max(range)
# If we requested 0 range, try to preserve previous scale.
# Otherwise just pick an arbitrary scale.
preserve = False
if mn == mx:
preserve = True
dy = self.state['viewRange'][ax][1] - self.state['viewRange'][ax][0]
if dy == 0:
dy = 1
mn -= dy*0.5
mx += dy*0.5
# Make sure that the range includes a usable number of quantization steps:
# approx. eps : 3e-16
# * min. steps : 10
# * mean value : (mn+mx)*0.5
quantization_limit = (mn+mx) * 1.5e-15 # +/-10 discrete steps of double resolution
if mx-mn < 2*quantization_limit:
mn -= quantization_limit
mx += quantization_limit
# Make sure no nan/inf get through
if not math.isfinite(mn) or not math.isfinite(mx):
raise Exception("Cannot set range [%s, %s]" % (str(mn), str(mx)))
# Apply padding
if not preserve:
if padding is None:
xpad = self.suggestPadding(ax)
else:
xpad = padding
p = (mx-mn) * xpad
mn -= p
mx += p
# max range cannot be larger than bounds, if they are given
if limits[ax][0] is not None and limits[ax][1] is not None:
if maxRng[ax] is not None:
maxRng[ax] = min(maxRng[ax], limits[ax][1] - limits[ax][0])
else:
maxRng[ax] = limits[ax][1] - limits[ax][0]
# If we have limits, we will have at least a max range as well
if maxRng[ax] is not None or minRng[ax] is not None:
diff = mx - mn
if maxRng[ax] is not None and diff > maxRng[ax]:
delta = maxRng[ax] - diff
elif minRng[ax] is not None and diff < minRng[ax]:
delta = minRng[ax] - diff
else:
delta = 0
mn -= delta / 2.
mx += delta / 2.
# Make sure our requested area is within limits, if any
if limits[ax][0] is not None or limits[ax][1] is not None:
lmn, lmx = limits[ax]
if lmn is not None and mn < lmn:
delta = lmn - mn # Shift the requested view to match our lower limit
mn = lmn
mx += delta
elif lmx is not None and mx > lmx:
delta = lmx - mx
mx = lmx
mn += delta
# Set target range
if self.state['targetRange'][ax] != [mn, mx]:
self.state['targetRange'][ax] = [mn, mx]
changed[ax] = True
# Update viewRange to match targetRange as closely as possible while
# accounting for aspect ratio constraint
lockX, lockY = setRequested
if lockX and lockY:
lockX = False
lockY = False
self.updateViewRange(lockX, lockY)
# If nothing has changed, we are done.
if any(changed):
# Update target rect for debugging
if self.target.isVisible():
self.target.setRect(self.mapRectFromItem(self.childGroup, self.targetRect()))
# If ortho axes have auto-visible-only, update them now
# Note that aspect ratio constraints and auto-visible probably do not work together..
if changed[0] and self.state['autoVisibleOnly'][1] and (self.state['autoRange'][0] is not False):
self._autoRangeNeedsUpdate = True
elif changed[1] and self.state['autoVisibleOnly'][0] and (self.state['autoRange'][1] is not False):
self._autoRangeNeedsUpdate = True
self.sigStateChanged.emit(self)
def setYRange(self, min, max, padding=None, update=True):
"""
Set the visible Y range of the view to [*min*, *max*].
The *padding* argument causes the range to be set larger by the fraction specified.
(by default, this value is between the default padding and 0.1 depending on the size of the ViewBox)
"""
self.setRange(yRange=[min, max], update=update, padding=padding)
def setXRange(self, min, max, padding=None, update=True):
"""
Set the visible X range of the view to [*min*, *max*].
The *padding* argument causes the range to be set larger by the fraction specified.
(by default, this value is between the default padding and 0.1 depending on the size of the ViewBox)
"""
self.setRange(xRange=[min, max], update=update, padding=padding)
def autoRange(self, padding=None, items=None, item=None):
"""
Set the range of the view box to make all children visible.
Note that this is not the same as enableAutoRange, which causes the view to
automatically auto-range whenever its contents are changed.
============== =============================================================
**Arguments:**
padding The fraction of the total data range to add on to the final
visible range. By default, this value is set between the
default padding and 0.1 depending on the size of the ViewBox.
items If specified, this is a list of items to consider when
determining the visible range.
============== =============================================================
"""
if item is None:
bounds = self.childrenBoundingRect(items=items)
else:
bounds = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
if bounds is not None:
self.setRange(bounds, padding=padding)
def suggestPadding(self, axis):
l = self.width() if axis==0 else self.height()
def_pad = self.state['defaultPadding']
if def_pad == 0.:
return def_pad # respect requested zero padding
max_pad = max(0.1, def_pad) # don't shrink a large default padding
if l > 0:
padding = fn.clip_scalar( 50*def_pad / (l**0.5), def_pad, max_pad)
else:
padding = def_pad
return padding
def setLimits(self, **kwds):
"""
Set limits that constrain the possible view ranges.
**Panning limits**. The following arguments define the region within the
viewbox coordinate system that may be accessed by panning the view.
=========== ============================================================
xMin Minimum allowed x-axis value
xMax Maximum allowed x-axis value
yMin Minimum allowed y-axis value
yMax Maximum allowed y-axis value
=========== ============================================================
**Scaling limits**. These arguments prevent the view being zoomed in or
out too far.
=========== ============================================================
minXRange Minimum allowed left-to-right span across the view.
maxXRange Maximum allowed left-to-right span across the view.
minYRange Minimum allowed top-to-bottom span across the view.
maxYRange Maximum allowed top-to-bottom span across the view.
=========== ============================================================
Added in version 0.9.9
"""
update = False
allowed = ['xMin', 'xMax', 'yMin', 'yMax', 'minXRange', 'maxXRange', 'minYRange', 'maxYRange']
for kwd in kwds:
if kwd not in allowed:
raise ValueError("Invalid keyword argument '%s'." % kwd)
for axis in [0,1]:
for mnmx in [0,1]:
kwd = [['xMin', 'xMax'], ['yMin', 'yMax']][axis][mnmx]
lname = ['xLimits', 'yLimits'][axis]
if kwd in kwds and self.state['limits'][lname][mnmx] != kwds[kwd]:
self.state['limits'][lname][mnmx] = kwds[kwd]
update = True
kwd = [['minXRange', 'maxXRange'], ['minYRange', 'maxYRange']][axis][mnmx]
lname = ['xRange', 'yRange'][axis]
if kwd in kwds and self.state['limits'][lname][mnmx] != kwds[kwd]:
self.state['limits'][lname][mnmx] = kwds[kwd]
update = True
if update:
self.updateViewRange()
def scaleBy(self, s=None, center=None, x=None, y=None):
"""
Scale by *s* around given center point (or center of view).
*s* may be a Point or tuple (x, y).
Optionally, x or y may be specified individually. This allows the other
axis to be left unaffected (note that using a scale factor of 1.0 may
cause slight changes due to floating-point error).
"""
if s is not None:
x, y = s[0], s[1]
affect = [x is not None, y is not None]
if not any(affect):
return
scale = Point([1.0 if x is None else x, 1.0 if y is None else y])
if self.state['aspectLocked'] is not False:
if x is None:
scale[0] = scale[1]
elif y is None:
scale[1] = scale[0]
else:
# scale to y if neither x nor y is None.
# this path is entered when dragging the mouse with right-button pressed.
scale[0] = scale[1]
vr = self.targetRect()
if center is None:
center = Point(vr.center())
else:
center = Point(center)
tl = center + (vr.topLeft()-center) * scale
br = center + (vr.bottomRight()-center) * scale
if not affect[0]:
self.setYRange(tl.y(), br.y(), padding=0)
elif not affect[1]:
self.setXRange(tl.x(), br.x(), padding=0)
else:
self.setRange(QtCore.QRectF(tl, br), padding=0)
def translateBy(self, t=None, x=None, y=None):
"""
Translate the view by *t*, which may be a Point or tuple (x, y).
Alternately, x or y may be specified independently, leaving the other
axis unchanged (note that using a translation of 0 may still cause
small changes due to floating-point error).
"""
vr = self.targetRect()
if t is not None:
t = Point(t)
self.setRange(vr.translated(t), padding=0)
else:
if x is not None:
x = vr.left()+x, vr.right()+x
if y is not None:
y = vr.top()+y, vr.bottom()+y
if x is not None or y is not None:
self.setRange(xRange=x, yRange=y, padding=0)
def enableAutoRange(self, axis=None, enable=True, x=None, y=None):
"""
Enable (or disable) auto-range for *axis*, which may be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes for both
(if *axis* is omitted, both axes will be changed).
When enabled, the axis will automatically rescale when items are added/removed or change their shape.
The argument *enable* may optionally be a float (0.0-1.0) which indicates the fraction of the data that should
be visible (this only works with items implementing a dataBounds method, such as PlotDataItem).
"""
# support simpler interface:
if x is not None or y is not None:
if x is not None:
self.enableAutoRange(ViewBox.XAxis, x)
if y is not None:
self.enableAutoRange(ViewBox.YAxis, y)
return
if enable is True:
enable = 1.0
if axis is None:
axis = ViewBox.XYAxes
if axis == ViewBox.XYAxes or axis == 'xy':
axes = [0, 1]
elif axis == ViewBox.XAxis or axis == 'x':
axes = [0]
elif axis == ViewBox.YAxis or axis == 'y':
axes = [1]
else:
raise Exception('axis argument must be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes.')
for ax in axes:
if self.state['autoRange'][ax] != enable:
# If we are disabling, do one last auto-range to make sure that
# previously scheduled auto-range changes are enacted
if enable is False and self._autoRangeNeedsUpdate:
self.updateAutoRange()
self.state['autoRange'][ax] = enable
self._autoRangeNeedsUpdate |= (enable is not False)
self.update()
self.sigStateChanged.emit(self)
def disableAutoRange(self, axis=None):
"""Disables auto-range. (See enableAutoRange)"""
self.enableAutoRange(axis, enable=False)
def autoRangeEnabled(self):
return self.state['autoRange'][:]
def setAutoPan(self, x=None, y=None):
"""Set whether automatic range will only pan (not scale) the view.
"""
if x is not None:
self.state['autoPan'][0] = x
if y is not None:
self.state['autoPan'][1] = y
if None not in [x,y]:
self.queueUpdateAutoRange()
def setAutoVisible(self, x=None, y=None):
"""Set whether automatic range uses only visible data when determining
the range to show.
"""
if x is not None:
self.state['autoVisibleOnly'][0] = x
if x is True:
self.state['autoVisibleOnly'][1] = False
if y is not None:
self.state['autoVisibleOnly'][1] = y
if y is True:
self.state['autoVisibleOnly'][0] = False
if x is not None or y is not None:
self.queueUpdateAutoRange()
def queueUpdateAutoRange(self):
self._autoRangeNeedsUpdate = True
self.update()
def updateAutoRange(self):
## Break recursive loops when auto-ranging.
## This is needed because some items change their size in response
## to a view change.
if self._updatingRange:
return
self._updatingRange = True
try:
if not any(self.state['autoRange']):
return
targetRect = self.viewRange()
fractionVisible = self.state['autoRange'][:]
for i in [0,1]:
if type(fractionVisible[i]) is bool:
fractionVisible[i] = 1.0
childRange = None
order = [0,1]
if self.state['autoVisibleOnly'][0] is True:
order = [1,0]
args = {}
for ax in order:
if self.state['autoRange'][ax] is False:
continue
if self.state['autoVisibleOnly'][ax]:
oRange = [None, None]
oRange[ax] = targetRect[1-ax]
childRange = self.childrenBounds(frac=fractionVisible, orthoRange=oRange)
else:
if childRange is None:
childRange = self.childrenBounds(frac=fractionVisible)
## Make corrections to range
xr = childRange[ax]
if xr is not None:
if self.state['autoPan'][ax]:
x = sum(xr) * 0.5
w2 = (targetRect[ax][1]-targetRect[ax][0]) / 2.
childRange[ax] = [x-w2, x+w2]
else:
padding = self.suggestPadding(ax)
wp = (xr[1] - xr[0]) * padding
childRange[ax][0] -= wp
childRange[ax][1] += wp
targetRect[ax] = childRange[ax]
args['xRange' if ax == 0 else 'yRange'] = targetRect[ax]
# check for and ignore bad ranges
for k in ['xRange', 'yRange']:
if k in args:
if not math.isfinite(args[k][0]) or not math.isfinite(args[k][1]):
_ = args.pop(k)
#print("Warning: %s is invalid: %s" % (k, str(r))
if len(args) == 0:
return
args['padding'] = 0.0
args['disableAutoRange'] = False
self.setRange(**args)
finally:
self._autoRangeNeedsUpdate = False
self._updatingRange = False
def setXLink(self, view):
"""Link this view's X axis to another view. (see LinkView)"""
self.linkView(self.XAxis, view)
def setYLink(self, view):
"""Link this view's Y axis to another view. (see LinkView)"""
self.linkView(self.YAxis, view)
def setLogMode(self, axis, logMode):
"""Informs ViewBox that log mode is active for the specified axis, so that the view range cen be restricted"""
if axis == 'x':
self.state['logMode'][0] = bool(logMode)
# print('x log mode', self.state['logMode'][0] )
elif axis == 'y':
self.state['logMode'][1] = bool(logMode)
# print('x log mode', self.state['logMode'][0] )
def linkView(self, axis, view):
"""
Link X or Y axes of two views and unlink any previously connected axes. *axis* must be ViewBox.XAxis or ViewBox.YAxis.
If view is None, the axis is left unlinked.
"""
if isinstance(view, str):
if view == '':
view = None
else:
view = ViewBox.NamedViews.get(view, view) ## convert view name to ViewBox if possible
if hasattr(view, 'implements') and view.implements('ViewBoxWrapper'):
view = view.getViewBox()
## used to connect/disconnect signals between a pair of views
if axis == ViewBox.XAxis:
signal = 'sigXRangeChanged'
slot = self.linkedXChanged
else:
signal = 'sigYRangeChanged'
slot = self.linkedYChanged
oldLink = self.linkedView(axis)
if oldLink is not None:
try:
getattr(oldLink, signal).disconnect(slot)
oldLink.sigResized.disconnect(slot)
except (TypeError, RuntimeError):
## This can occur if the view has been deleted already
pass
if view is None or isinstance(view, str):
self.state['linkedViews'][axis] = view
else:
self.state['linkedViews'][axis] = weakref.ref(view)
getattr(view, signal).connect(slot)
view.sigResized.connect(slot)
if view.autoRangeEnabled()[axis] is not False:
self.enableAutoRange(axis, False)
slot()
else:
if self.autoRangeEnabled()[axis] is False:
slot()
self.sigStateChanged.emit(self)
def blockLink(self, b):
self.linksBlocked = b ## prevents recursive plot-change propagation
@QtCore.Slot()
def linkedXChanged(self):
## called when x range of linked view has changed
view = self.linkedView(0)
self.linkedViewChanged(view, ViewBox.XAxis)
@QtCore.Slot()
def linkedYChanged(self):
## called when y range of linked view has changed
view = self.linkedView(1)
self.linkedViewChanged(view, ViewBox.YAxis)
def linkedView(self, ax):
## Return the linked view for axis *ax*.
## this method _always_ returns either a ViewBox or None.
v = self.state['linkedViews'][ax]
if v is None or isinstance(v, str):
return None
else:
return v() ## dereference weakref pointer. If the reference is dead, this returns None
def linkedViewChanged(self, view, axis):
if self.linksBlocked or view is None:
return
#print self.name, "ViewBox.linkedViewChanged", axis, view.viewRange()[axis]
vr = view.viewRect()
vg = view.screenGeometry()
sg = self.screenGeometry()
if vg is None or sg is None:
return
view.blockLink(True)
try:
if axis == ViewBox.XAxis:
overlap = min(sg.right(), vg.right()) - max(sg.left(), vg.left())
if overlap < min(vg.width()/3, sg.width()/3): ## if less than 1/3 of views overlap,
## then just replicate the view
x1 = vr.left()
x2 = vr.right()
else: ## views overlap; line them up
upp = float(vr.width()) / vg.width()
if self.xInverted():
x1 = vr.left() + (sg.right()-vg.right()) * upp
else:
x1 = vr.left() + (sg.x()-vg.x()) * upp
x2 = x1 + sg.width() * upp
self.enableAutoRange(ViewBox.XAxis, False)
self.setXRange(x1, x2, padding=0)
else:
overlap = min(sg.bottom(), vg.bottom()) - max(sg.top(), vg.top())
if overlap < min(vg.height()/3, sg.height()/3): ## if less than 1/3 of views overlap,
## then just replicate the view
y1 = vr.top()
y2 = vr.bottom()
else: ## views overlap; line them up
upp = float(vr.height()) / vg.height()
if self.yInverted():
y2 = vr.bottom() + (sg.bottom()-vg.bottom()) * upp
else:
y2 = vr.bottom() + (sg.top()-vg.top()) * upp
y1 = y2 - sg.height() * upp
self.enableAutoRange(ViewBox.YAxis, False)
self.setYRange(y1, y2, padding=0)
finally:
view.blockLink(False)
def screenGeometry(self):
"""return the screen geometry of the viewbox"""
v = self.getViewWidget()
if v is None:
return None
b = self.sceneBoundingRect()
wr = v.mapFromScene(b).boundingRect()
pos = v.mapToGlobal(v.pos())
wr.adjust(pos.x(), pos.y(), pos.x(), pos.y())
return wr
def itemsChanged(self):
## called when items are added/removed from self.childGroup
self.queueUpdateAutoRange()
def itemBoundsChanged(self, item):
self._itemBoundsCache.pop(item, None)
if (self.state['autoRange'][0] is not False) or (self.state['autoRange'][1] is not False):
self.queueUpdateAutoRange()
def _invertAxis(self, ax, inv):
key = 'xy'[ax] + 'Inverted'
if self.state[key] == inv:
return
self.state[key] = inv
self._matrixNeedsUpdate = True # updateViewRange won't detect this for us
self.updateViewRange()
self.update()
self.sigStateChanged.emit(self)
if ax:
self.sigYRangeChanged.emit(self, tuple(self.state['viewRange'][ax]))
else:
self.sigXRangeChanged.emit(self, tuple(self.state['viewRange'][ax]))
@QtCore.Slot()
@QtCore.Slot(QtWidgets.QWidget)
def invertY(self, b=True):
"""
By default, the positive y-axis points upward on the screen. Use invertY(True) to reverse the y-axis.
"""
self._invertAxis(1, b)
def yInverted(self):
return self.state['yInverted']
def invertX(self, b=True):
"""
By default, the positive x-axis points rightward on the screen. Use invertX(True) to reverse the x-axis.
"""
self._invertAxis(0, b)
def xInverted(self):
return self.state['xInverted']
def setBorder(self, *args, **kwds):
"""
Set the pen used to draw border around the view
If border is None, then no border will be drawn.
Added in version 0.9.10
See :func:`mkPen <pyqtgraph.mkPen>` for arguments.
"""
self.border = fn.mkPen(*args, **kwds)
self.borderRect.setPen(self.border)
def setDefaultPadding(self, padding=0.02):
"""
Sets the fraction of the data range that is used to pad the view range in when auto-ranging.
By default, this fraction is 0.02.
"""
self.state['defaultPadding'] = padding
def setAspectLocked(self, lock=True, ratio=1):
"""
If the aspect ratio is locked, view scaling must always preserve the aspect ratio.
By default, the ratio is set to 1; x and y both have the same scaling.
This ratio can be overridden (xScale/yScale), or use None to lock in the current ratio.
"""
if not lock:
if self.state['aspectLocked'] == False:
return
self.state['aspectLocked'] = False
else:
currentRatio = self.getAspectRatio()
if ratio is None:
ratio = currentRatio
if self.state['aspectLocked'] == ratio: # nothing to change
return
self.state['aspectLocked'] = ratio
if ratio != currentRatio: ## If this would change the current range, do that now
self.updateViewRange()
self.queueUpdateAutoRange()
self.updateViewRange()
self.sigStateChanged.emit(self)
def childTransform(self):
"""
Return the transform that maps from child(item in the childGroup) coordinates to local coordinates.
(This maps from inside the viewbox to outside)
"""
self.updateMatrix()
m = self.childGroup.transform()
return m
def mapToView(self, obj):
"""Maps from the local coordinates of the ViewBox to the coordinate system displayed inside the ViewBox"""
self.updateMatrix()
m = fn.invertQTransform(self.childTransform())
return m.map(obj)
def mapFromView(self, obj):
"""Maps from the coordinate system displayed inside the ViewBox to the local coordinates of the ViewBox"""
self.updateMatrix()
m = self.childTransform()
return m.map(obj)
def mapSceneToView(self, obj):
"""Maps from scene coordinates to the coordinate system displayed inside the ViewBox"""
self.updateMatrix()
return self.mapToView(self.mapFromScene(obj))
def mapViewToScene(self, obj):
"""Maps from the coordinate system displayed inside the ViewBox to scene coordinates"""
self.updateMatrix()
return self.mapToScene(self.mapFromView(obj))
def mapFromItemToView(self, item, obj):
"""Maps *obj* from the local coordinate system of *item* to the view coordinates"""
self.updateMatrix()
return self.childGroup.mapFromItem(item, obj)
def mapFromViewToItem(self, item, obj):
"""Maps *obj* from view coordinates to the local coordinate system of *item*."""
self.updateMatrix()
return self.childGroup.mapToItem(item, obj)
def mapViewToDevice(self, obj):
self.updateMatrix()
return self.mapToDevice(self.mapFromView(obj))
def mapDeviceToView(self, obj):
self.updateMatrix()
return self.mapToView(self.mapFromDevice(obj))
def viewPixelSize(self):
"""Return the (width, height) of a screen pixel in view coordinates."""
if self._viewPixelSizeCache is None:
o = self.mapToView(Point(0, 0))
px, py = [Point(self.mapToView(v) - o) for v in self.pixelVectors()]
self._viewPixelSizeCache = (px.length(), py.length())
return self._viewPixelSizeCache
def itemBoundingRect(self, item):
"""Return the bounding rect of the item in view coordinates"""
return self.mapSceneToView(item.sceneBoundingRect()).boundingRect()
def wheelEvent(self, ev, axis=None):
if axis in (0, 1):
mask = [False, False]
mask[axis] = self.state['mouseEnabled'][axis]
else:
mask = self.state['mouseEnabled'][:]
if not any(mask):
# if mouse zoom/pan is not enabled, ignore the event
ev.ignore()
return
s = 1.02 ** (ev.delta() * self.state['wheelScaleFactor']) # actual scaling factor
s = [(None if m is False else s) for m in mask]
center = Point(fn.invertQTransform(self.childGroup.transform()).map(ev.pos()))
self._resetTarget()
self.scaleBy(s, center)
ev.accept()
self.sigRangeChangedManually.emit(mask)
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.MouseButton.RightButton and self.menuEnabled():
ev.accept()
self.raiseContextMenu(ev)
def raiseContextMenu(self, ev):
menu = self.getMenu(ev)
if menu is not None:
self.scene().addParentContextMenus(self, menu, ev)
menu.popup(ev.screenPos().toPoint())
def getMenu(self, ev):
return self.menu
def getContextMenus(self, event):
return self.menu.actions() if self.menuEnabled() else []
def mouseDragEvent(self, ev, axis=None):
## if axis is specified, event will only affect that axis.
ev.accept() ## we accept all buttons
pos = ev.pos()
lastPos = ev.lastPos()
dif = pos - lastPos
dif = dif * -1
## Ignore axes if mouse is disabled
mouseEnabled = np.array(self.state['mouseEnabled'], dtype=np.float64)
mask = mouseEnabled.copy()
if axis is not None:
mask[1-axis] = 0.0
## Scale or translate based on mouse button
if ev.button() in [QtCore.Qt.MouseButton.LeftButton, QtCore.Qt.MouseButton.MiddleButton]:
if self.state['mouseMode'] == ViewBox.RectMode and axis is None:
if ev.isFinish(): ## This is the final move in the drag; change the view scale now
#print "finish"
self.rbScaleBox.hide()
ax = QtCore.QRectF(Point(ev.buttonDownPos(ev.button())), Point(pos))
ax = self.childGroup.mapRectFromParent(ax)
self.showAxRect(ax)
self.axHistoryPointer += 1
self.axHistory = self.axHistory[:self.axHistoryPointer] + [ax]
else:
## update shape of scale box
self.updateScaleBox(ev.buttonDownPos(), ev.pos())
else:
tr = self.childGroup.transform()
tr = fn.invertQTransform(tr)
tr = tr.map(dif*mask) - tr.map(Point(0,0))
x = tr.x() if mask[0] == 1 else None
y = tr.y() if mask[1] == 1 else None
self._resetTarget()
if x is not None or y is not None:
self.translateBy(x=x, y=y)
self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
elif ev.button() & QtCore.Qt.MouseButton.RightButton:
#print "vb.rightDrag"
if self.state['aspectLocked'] is not False:
mask[0] = 0
dif = ev.screenPos() - ev.lastScreenPos()
dif = np.array([dif.x(), dif.y()])
dif[0] *= -1
s = ((mask * 0.02) + 1) ** dif
tr = self.childGroup.transform()
tr = fn.invertQTransform(tr)
x = s[0] if mouseEnabled[0] == 1 else None
y = s[1] if mouseEnabled[1] == 1 else None
center = Point(tr.map(ev.buttonDownPos(QtCore.Qt.MouseButton.RightButton)))
self._resetTarget()
self.scaleBy(x=x, y=y, center=center)
self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
def keyPressEvent(self, ev):
"""
This routine should capture key presses in the current view box.
Key presses are used only when mouse mode is RectMode
The following events are implemented:
ctrl-A : zooms out to the default "full" view of the plot
ctrl-+ : moves forward in the zooming stack (if it exists)
ctrl-- : moves backward in the zooming stack (if it exists)
"""
ev.accept()
if ev.text() == '-':
self.scaleHistory(-1)
elif ev.text() in ['+', '=']:
self.scaleHistory(1)
elif ev.key() == QtCore.Qt.Key.Key_Backspace:
self.scaleHistory(len(self.axHistory))
else:
ev.ignore()
def scaleHistory(self, d):
if len(self.axHistory) == 0:
return
ptr = max(0, min(len(self.axHistory)-1, self.axHistoryPointer+d))
if ptr != self.axHistoryPointer:
self.axHistoryPointer = ptr
self.showAxRect(self.axHistory[ptr])
def updateScaleBox(self, p1, p2):
r = QtCore.QRectF(p1, p2)
r = self.childGroup.mapRectFromParent(r)
self.rbScaleBox.setPos(r.topLeft())
tr = QtGui.QTransform.fromScale(r.width(), r.height())
self.rbScaleBox.setTransform(tr)
self.rbScaleBox.show()
def showAxRect(self, ax, **kwargs):
"""Set the visible range to the given rectangle
Passes keyword arguments to setRange
"""
self.setRange(ax.normalized(), **kwargs) # be sure w, h are correct coordinates
self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
def allChildren(self, item=None):
"""Return a list of all children and grandchildren of this ViewBox"""
if item is None:
item = self.childGroup
children = [item]
for ch in item.childItems():
children.extend(self.allChildren(ch))
return children
def childrenBounds(self, frac=None, orthoRange=(None,None), items=None):
"""Return the bounding range of all children.
[[xmin, xmax], [ymin, ymax]]
Values may be None if there are no specific bounds for an axis.
"""
profiler = debug.Profiler()
if items is None:
items = self.addedItems
## First collect all boundary information
itemBounds = []
for item in items:
if not item.isVisible() or not item.scene() is self.scene():
continue
useX = True
useY = True
if hasattr(item, 'dataBounds') and item.dataBounds is not None:
if frac is None:
frac = (1.0, 1.0)
xr = item.dataBounds(0, frac=frac[0], orthoRange=orthoRange[0])
yr = item.dataBounds(1, frac=frac[1], orthoRange=orthoRange[1])
pxPad = 0 if not hasattr(item, 'pixelPadding') else item.pixelPadding()
if (
xr is None or
(xr[0] is None and xr[1] is None) or
not math.isfinite(xr[0]) or
not math.isfinite(xr[1])
):
useX = False
xr = (0,0)
if (
yr is None or
(yr[0] is None and yr[1] is None) or
not math.isfinite(yr[0]) or
not math.isfinite(yr[1])
):
useY = False
yr = (0,0)
bounds = QtCore.QRectF(xr[0], yr[0], xr[1]-xr[0], yr[1]-yr[0])
bounds = self.mapFromItemToView(item, bounds).boundingRect()
if not any([useX, useY]):
continue
## If we are ignoring only one axis, we need to check for rotations
if useX != useY: ## != means xor
ang = round(item.transformAngle())
if ang == 0 or ang == 180:
pass
elif ang == 90 or ang == 270:
useX, useY = useY, useX
else:
## Item is rotated at non-orthogonal angle, ignore bounds entirely.
## Not really sure what is the expected behavior in this case.
continue ## need to check for item rotations and decide how best to apply this boundary.
itemBounds.append((bounds, useX, useY, pxPad))
else:
if item.flags() & item.GraphicsItemFlag.ItemHasNoContents:
continue
bounds = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
itemBounds.append((bounds, True, True, 0))
## determine tentative new range
range = [None, None]
for bounds, useX, useY, px in itemBounds:
if useY:
if range[1] is not None:
range[1] = [min(bounds.top(), range[1][0]), max(bounds.bottom(), range[1][1])]
else:
range[1] = [bounds.top(), bounds.bottom()]
if useX:
if range[0] is not None:
range[0] = [min(bounds.left(), range[0][0]), max(bounds.right(), range[0][1])]
else:
range[0] = [bounds.left(), bounds.right()]
profiler()
## Now expand any bounds that have a pixel margin
## This must be done _after_ we have a good estimate of the new range
## to ensure that the pixel size is roughly accurate.
w = self.width()
h = self.height()
if w > 0 and range[0] is not None:
pxSize = (range[0][1] - range[0][0]) / w
for bounds, useX, useY, px in itemBounds:
if px == 0 or not useX:
continue
range[0][0] = min(range[0][0], bounds.left() - px*pxSize)
range[0][1] = max(range[0][1], bounds.right() + px*pxSize)
if h > 0 and range[1] is not None:
pxSize = (range[1][1] - range[1][0]) / h
for bounds, useX, useY, px in itemBounds:
if px == 0 or not useY:
continue
range[1][0] = min(range[1][0], bounds.top() - px*pxSize)
range[1][1] = max(range[1][1], bounds.bottom() + px*pxSize)
return range
def childrenBoundingRect(self, *args, **kwds):
range = self.childrenBounds(*args, **kwds)
tr = self.targetRange()
if range[0] is None:
range[0] = tr[0]
if range[1] is None:
range[1] = tr[1]
bounds = QtCore.QRectF(range[0][0], range[1][0], range[0][1]-range[0][0], range[1][1]-range[1][0])
return bounds
# Including a prepareForPaint call is part of the Qt strategy to
# defer expensive redraw opertions until requested by a 'sigPrepareForPaint' signal
#
# However, as currently implemented, a call to prepareForPaint as part of the regular
# 'update' call results in an undesired reset of pan/zoom:
# https://github.com/pyqtgraph/pyqtgraph/issues/2029
#
# def update(self, *args, **kwargs):
# self.prepareForPaint()
# GraphicsWidget.update(self, *args, **kwargs)
def updateViewRange(self, forceX=False, forceY=False):
## Update viewRange to match targetRange as closely as possible, given
## aspect ratio constraints. The *force* arguments are used to indicate
## which axis (if any) should be unchanged when applying constraints.
viewRange = [self.state['targetRange'][0][:], self.state['targetRange'][1][:]]
changed = [False, False]
#-------- Make correction for aspect ratio constraint ----------
# aspect is (widget w/h) / (view range w/h)
aspect = self.state['aspectLocked'] # size ratio / view ratio
tr = self.targetRect()
bounds = self.rect()
limits = self._effectiveLimits()
# print('upd:limits ', limits) # diagnostic output should reflect additional limit in log mode
minRng = [self.state['limits']['xRange'][0], self.state['limits']['yRange'][0]]
maxRng = [self.state['limits']['xRange'][1], self.state['limits']['yRange'][1]]
for axis in [0, 1]:
if limits[axis][0] is None and limits[axis][1] is None and minRng[axis] is None and maxRng[axis] is None:
continue
# max range cannot be larger than bounds, if they are given
if limits[axis][0] is not None and limits[axis][1] is not None:
if maxRng[axis] is not None:
maxRng[axis] = min(maxRng[axis], limits[axis][1] - limits[axis][0])
else:
maxRng[axis] = limits[axis][1] - limits[axis][0]
if aspect is not False and 0 not in [aspect, tr.height(), bounds.height(), bounds.width()]:
## This is the view range aspect ratio we have requested
targetRatio = tr.width() / tr.height() if tr.height() != 0 else 1
## This is the view range aspect ratio we need to obey aspect constraint
viewRatio = (bounds.width() / bounds.height() if bounds.height() != 0 else 1) / aspect
viewRatio = 1 if viewRatio == 0 else viewRatio
# Calculate both the x and y ranges that would be needed to obtain the desired aspect ratio
dy = 0.5 * (tr.width() / viewRatio - tr.height())
dx = 0.5 * (tr.height() * viewRatio - tr.width())
rangeY = [self.state['targetRange'][1][0] - dy, self.state['targetRange'][1][1] + dy]
rangeX = [self.state['targetRange'][0][0] - dx, self.state['targetRange'][0][1] + dx]
canidateRange = [rangeX, rangeY]
# Decide which range to try to keep unchanged
#print self.name, "aspect:", aspect, "changed:", changed, "auto:", self.state['autoRange']
if forceX:
ax = 0
elif forceY:
ax = 1
else:
# if we are not required to keep a particular axis unchanged,
# then try to make the entire target range visible
ax = 0 if targetRatio > viewRatio else 1
target = 0 if ax == 1 else 1
# See if this choice would cause out-of-range issues
if maxRng is not None or minRng is not None:
diff = canidateRange[target][1] - canidateRange[target][0]
if maxRng[target] is not None and diff > maxRng[target] or \
minRng[target] is not None and diff < minRng[target]:
# tweak the target range down so we can still pan properly
viewRange[ax] = canidateRange[ax]
self.state['viewRange'][ax] = viewRange[ax]
self._resetTarget()
ax = target # Switch the "fixed" axes
if ax == 0:
## view range needs to be taller than target
if dy != 0:
changed[1] = True
viewRange[1] = rangeY
else:
## view range needs to be wider than target
if dx != 0:
changed[0] = True
viewRange[0] = rangeX
# Ensure, that the new viewRange obeys all the limits
for axis in [0, 1]:
range = viewRange[axis][1] - viewRange[axis][0]
if minRng[axis] is not None and minRng[axis] > range:
viewRange[axis][1] = viewRange[axis][0] + minRng[axis]
self.state["targetRange"][axis] = viewRange[axis]
if maxRng[axis] is not None and maxRng[axis] < range:
viewRange[axis][1] = viewRange[axis][0] + maxRng[axis]
self.state["targetRange"][axis] = viewRange[axis]
if limits[axis][0] is not None and viewRange[axis][0] < limits[axis][0]:
delta = limits[axis][0] - viewRange[axis][0]
viewRange[axis][0] += delta
viewRange[axis][1] += delta
self.state["targetRange"][axis] = viewRange[axis]
if limits[axis][1] is not None and viewRange[axis][1] > limits[axis][1]:
delta = viewRange[axis][1] - limits[axis][1]
viewRange[axis][0] -= delta
viewRange[axis][1] -= delta
self.state["targetRange"][axis] = viewRange[axis]
# Consider only as 'changed' if the differences are larger than floating point inaccuracies,
# which regularly appear in magnitude of around 1e-15. Therefore, 1e-9 as factor was chosen
# more or less arbitrarily.
thresholds = [(viewRange[axis][1] - viewRange[axis][0]) * 1.0e-9 for axis in (0,1)]
changed = [
(abs(viewRange[axis][0] - self.state["viewRange"][axis][0]) > thresholds[axis])
or (abs(viewRange[axis][1] - self.state["viewRange"][axis][1]) > thresholds[axis])
for axis in (0, 1)
]
self.state['viewRange'] = viewRange
if any(changed):
self._matrixNeedsUpdate = True
self.update()
# Inform linked views that the range has changed
for ax in [0, 1]:
if not changed[ax]:
continue
link = self.linkedView(ax)
if link is not None:
link.linkedViewChanged(self, ax)
# emit range change signals
# print('announcing view range changes:',self.state['viewRange'] )
if changed[0]:
self.sigXRangeChanged.emit(self, tuple(self.state['viewRange'][0]))
if changed[1]:
self.sigYRangeChanged.emit(self, tuple(self.state['viewRange'][1]))
self.sigRangeChanged.emit(self, self.state['viewRange'], changed)
def updateMatrix(self, changed=None):
if not self._matrixNeedsUpdate:
return
## Make the childGroup's transform match the requested viewRange.
bounds = self.rect()
vr = self.viewRect()
if vr.height() == 0 or vr.width() == 0:
return
scale = Point(bounds.width()/vr.width(), bounds.height()/vr.height())
if not self.state['yInverted']:
scale = scale * Point(1, -1)
if self.state['xInverted']:
scale = scale * Point(-1, 1)
m = QtGui.QTransform()
## First center the viewport at 0
center = bounds.center()
m.translate(center.x(), center.y())
## Now scale and translate properly
m.scale(scale[0], scale[1])
st = Point(vr.center())
m.translate(-st[0], -st[1])
self.childGroup.setTransform(m)
self._matrixNeedsUpdate = False
self.sigTransformChanged.emit(self) ## segfaults here: 1
def paint(self, p, opt, widget):
if self.border is not None:
bounds = self.shape()
p.setPen(self.border)
#p.fillRect(bounds, QtGui.QColor(0, 0, 0))
p.drawPath(bounds)
#p.setPen(fn.mkPen('r'))
#path = QtGui.QPainterPath()
#path.addRect(self.targetRect())
#tr = self.mapFromView(path)
#p.drawPath(tr)
def updateBackground(self):
bg = self.state['background']
if bg is None:
self.background.hide()
else:
self.background.show()
self.background.setBrush(fn.mkBrush(bg))
def updateViewLists(self):
try:
self.window()
except RuntimeError: ## this view has already been deleted; it will probably be collected shortly.
return
def view_key(view):
return (view.window() is self.window(), view.name)
## make a sorted list of all named views
nv = sorted(ViewBox.NamedViews.values(), key=view_key)
if self in nv:
nv.remove(self)
if self.menu is not None:
self.menu.setViewList(nv)
for ax in [0,1]:
link = self.state['linkedViews'][ax]
if isinstance(link, str): ## axis has not been linked yet; see if it's possible now
for v in nv:
if link == v.name:
self.linkView(ax, v)
@staticmethod
def updateAllViewLists():
for v in ViewBox.AllViews:
v.updateViewLists()
@staticmethod
def forgetView(vid, name):
if ViewBox is None: ## can happen as python is shutting down
return
if QtWidgets.QApplication.instance() is None:
return
## Called with ID and name of view (the view itself is no longer available)
for v in list(ViewBox.AllViews.keys()):
if id(v) == vid:
ViewBox.AllViews.pop(v)
break
ViewBox.NamedViews.pop(name, None)
ViewBox.updateAllViewLists()
@staticmethod
def quit():
## called when the application is about to exit.
## this disables all callbacks, which might otherwise generate errors if invoked during exit.
for k in ViewBox.AllViews:
if isQObjectAlive(k) and getConfigOption('crashWarning'):
sys.stderr.write('Warning: ViewBox should be closed before application exit.\n')
# PySide >= 6.7 prints a warning if we attempt to disconnect
# a signal that isn't connected.
if (
QT_LIB == 'PySide6' and
isQObjectAlive(k) and
k.receivers(QtCore.SIGNAL("destroyed()")) == 0
):
continue
try:
k.destroyed.disconnect()
except RuntimeError: ## signal is already disconnected.
pass
except TypeError: ## view has already been deleted (?)
pass
except AttributeError: # PySide has deleted signal
pass
def locate(self, item, timeout=3.0, children=False):
"""
Temporarily display the bounding rect of an item and lines connecting to the center of the view.
This is useful for determining the location of items that may be out of the range of the ViewBox.
if allChildren is True, then the bounding rect of all item's children will be shown instead.
"""
self.clearLocate()
if item.scene() is not self.scene():
raise Exception("Item does not share a scene with this ViewBox.")
c = self.viewRect().center()
if children:
br = self.mapFromItemToView(item, item.childrenBoundingRect()).boundingRect()
else:
br = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
g = ItemGroup()
g.setParentItem(self.childGroup)
self.locateGroup = g
g.box = QtWidgets.QGraphicsRectItem(br)
g.box.setParentItem(g)
g.lines = []
for p in (br.topLeft(), br.bottomLeft(), br.bottomRight(), br.topRight()):
line = QtWidgets.QGraphicsLineItem(c.x(), c.y(), p.x(), p.y())
line.setParentItem(g)
g.lines.append(line)
for item in g.childItems():
item.setPen(fn.mkPen(color='y', width=3))
g.setZValue(1000000)
if children:
g.path = QtWidgets.QGraphicsPathItem(g.childrenShape())
else:
g.path = QtWidgets.QGraphicsPathItem(g.shape())
g.path.setParentItem(g)
g.path.setPen(fn.mkPen('g'))
g.path.setZValue(100)
QtCore.QTimer.singleShot(timeout*1000, self.clearLocate)
def clearLocate(self):
if self.locateGroup is None:
return
self.scene().removeItem(self.locateGroup)
self.locateGroup = None
from .ViewBoxMenu import ViewBoxMenu
|
ViewBox
|
python
|
tensorflow__tensorflow
|
tensorflow/python/debug/wrappers/hooks.py
|
{
"start": 8323,
"end": 11438
}
|
class ____(session_run_hook.SessionRunHook):
"""A hook that streams debugger-related events to any grpc_debug_server.
For example, the debugger data server is a grpc_debug_server. The debugger
data server writes debugger-related events it receives via GRPC to logdir.
This enables debugging features in Tensorboard such as health pills.
When the arguments of debug_utils.watch_graph changes, strongly consider
changing arguments here too so that features are available to tflearn users.
Can be used as a hook for `tf.compat.v1.train.MonitoredSession`.
"""
def __init__(self,
grpc_debug_server_addresses,
watch_fn=None,
thread_name_filter=None):
"""Constructs a GrpcDebugHook.
Args:
grpc_debug_server_addresses: (`list` of `str`) A list of the gRPC debug
server addresses, in the format of <host:port>, with or without the
"grpc://" prefix. For example: ["localhost:7000", "192.168.0.2:8000"]
watch_fn: A function that allows for customizing which ops to watch at
which specific steps. See doc of
`dumping_wrapper.DumpingDebugWrapperSession.__init__` for details.
thread_name_filter: Regular-expression white list for threads on which the
wrapper session will be active. See doc of `BaseDebugWrapperSession` for
more details.
"""
self._grpc_debug_wrapper_session = None
self._thread_name_filter = thread_name_filter
self._grpc_debug_server_addresses = (
grpc_debug_server_addresses
if isinstance(grpc_debug_server_addresses, list) else
[grpc_debug_server_addresses])
self._watch_fn = watch_fn
def before_run(self, run_context):
"""Called right before a session is run.
Args:
run_context: A session_run_hook.SessionRunContext. Encapsulates
information on the run.
Returns:
A session_run_hook.SessionRunArgs object.
"""
if not self._grpc_debug_wrapper_session:
self._grpc_debug_wrapper_session = grpc_wrapper.GrpcDebugWrapperSession(
run_context.session,
self._grpc_debug_server_addresses,
watch_fn=self._watch_fn,
thread_name_filter=self._thread_name_filter)
fetches = run_context.original_args.fetches
feed_dict = run_context.original_args.feed_dict
watch_options = self._watch_fn(fetches, feed_dict)
run_options = config_pb2.RunOptions()
debug_utils.watch_graph(
run_options,
run_context.session.graph,
debug_urls=self._grpc_debug_wrapper_session.prepare_run_debug_urls(
fetches, feed_dict),
debug_ops=watch_options.debug_ops,
node_name_regex_allowlist=watch_options.node_name_regex_allowlist,
op_type_regex_allowlist=watch_options.op_type_regex_allowlist,
tensor_dtype_regex_allowlist=watch_options.tensor_dtype_regex_allowlist,
tolerate_debug_op_creation_failures=(
watch_options.tolerate_debug_op_creation_failures))
return session_run_hook.SessionRunArgs(
None, feed_dict=None, options=run_options)
|
GrpcDebugHook
|
python
|
django__django
|
tests/admin_views/models.py
|
{
"start": 30050,
"end": 30250
}
|
class ____(models.Model):
m2m = models.ManyToManyField(CamelCaseModel, related_name="m2m")
fk = models.ForeignKey(CamelCaseModel, on_delete=models.CASCADE, related_name="fk")
|
CamelCaseRelatedModel
|
python
|
numba__numba
|
numba/np/polynomial/polynomial_core.py
|
{
"start": 490,
"end": 9003
}
|
class ____(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('coef', fe_type.coef),
('domain', fe_type.domain),
('window', fe_type.window)
# Introduced in NumPy 1.24, maybe leave it out for now
# ('symbol', types.string)
]
super(PolynomialModel, self).__init__(dmm, fe_type, members)
@type_callable(Polynomial)
def type_polynomial(context):
def typer(coef, domain=None, window=None):
default_domain = types.Array(types.int64, 1, 'C')
double_domain = types.Array(types.double, 1, 'C')
default_window = types.Array(types.int64, 1, 'C')
double_window = types.Array(types.double, 1, 'C')
double_coef = types.Array(types.double, 1, 'C')
warnings.warn("Polynomial class is experimental",
category=NumbaExperimentalFeatureWarning)
if isinstance(coef, types.Array) and \
all([a is None for a in (domain, window)]):
if coef.ndim == 1:
# If Polynomial(coef) is called, coef is cast to double dtype,
# and domain and window are set to equal [-1, 1], i.e. have
# integer dtype
return types.PolynomialType(double_coef,
default_domain,
default_window,
1)
else:
msg = 'Coefficient array is not 1-d'
raise NumbaValueError(msg)
elif all([isinstance(a, types.Array) for a in (coef, domain, window)]):
if coef.ndim == 1:
if all([a.ndim == 1 for a in (domain, window)]):
# If Polynomial(coef, domain, window) is called, then coef,
# domain and window are cast to double dtype
return types.PolynomialType(double_coef,
double_domain,
double_window,
3)
else:
msg = 'Coefficient array is not 1-d'
raise NumbaValueError(msg)
return typer
make_attribute_wrapper(types.PolynomialType, 'coef', 'coef')
make_attribute_wrapper(types.PolynomialType, 'domain', 'domain')
make_attribute_wrapper(types.PolynomialType, 'window', 'window')
# Introduced in NumPy 1.24, maybe leave it out for now
# make_attribute_wrapper(types.PolynomialType, 'symbol', 'symbol')
@lower_builtin(Polynomial, types.Array)
def impl_polynomial1(context, builder, sig, args):
def to_double(arr):
return np.asarray(arr, dtype=np.double)
def const_impl():
return np.asarray([-1, 1])
typ = sig.return_type
polynomial = cgutils.create_struct_proxy(typ)(context, builder)
sig_coef = sig.args[0].copy(dtype=types.double)(sig.args[0])
coef_cast = context.compile_internal(builder, to_double, sig_coef, args)
sig_domain = sig.args[0].copy(dtype=types.intp)()
sig_window = sig.args[0].copy(dtype=types.intp)()
domain_cast = context.compile_internal(builder, const_impl, sig_domain, ())
window_cast = context.compile_internal(builder, const_impl, sig_window, ())
polynomial.coef = coef_cast
polynomial.domain = domain_cast
polynomial.window = window_cast
return polynomial._getvalue()
@lower_builtin(Polynomial, types.Array, types.Array, types.Array)
def impl_polynomial3(context, builder, sig, args):
def to_double(coef):
return np.asarray(coef, dtype=np.double)
typ = sig.return_type
polynomial = cgutils.create_struct_proxy(typ)(context, builder)
coef_sig = sig.args[0].copy(dtype=types.double)(sig.args[0])
domain_sig = sig.args[1].copy(dtype=types.double)(sig.args[1])
window_sig = sig.args[2].copy(dtype=types.double)(sig.args[2])
coef_cast = context.compile_internal(builder,
to_double, coef_sig,
(args[0],))
domain_cast = context.compile_internal(builder,
to_double, domain_sig,
(args[1],))
window_cast = context.compile_internal(builder,
to_double, window_sig,
(args[2],))
domain_helper = context.make_helper(builder,
domain_sig.return_type,
value=domain_cast)
window_helper = context.make_helper(builder,
window_sig.return_type,
value=window_cast)
i64 = ir.IntType(64)
two = i64(2)
s1 = builder.extract_value(domain_helper.shape, 0)
s2 = builder.extract_value(window_helper.shape, 0)
pred1 = builder.icmp_signed('!=', s1, two)
pred2 = builder.icmp_signed('!=', s2, two)
with cgutils.if_unlikely(builder, pred1):
context.call_conv.return_user_exc(
builder, ValueError,
("Domain has wrong number of elements.",))
with cgutils.if_unlikely(builder, pred2):
context.call_conv.return_user_exc(
builder, ValueError,
("Window has wrong number of elements.",))
polynomial.coef = coef_cast
polynomial.domain = domain_helper._getvalue()
polynomial.window = window_helper._getvalue()
return polynomial._getvalue()
@unbox(types.PolynomialType)
def unbox_polynomial(typ, obj, c):
"""
Convert a Polynomial object to a native polynomial structure.
"""
is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit)
polynomial = cgutils.create_struct_proxy(typ)(c.context, c.builder)
with ExitStack() as stack:
natives = []
for name in ("coef", "domain", "window"):
attr = c.pyapi.object_getattr_string(obj, name)
with cgutils.early_exit_if_null(c.builder, stack, attr):
c.builder.store(cgutils.true_bit, is_error_ptr)
t = getattr(typ, name)
native = c.unbox(t, attr)
c.pyapi.decref(attr)
with cgutils.early_exit_if(c.builder, stack, native.is_error):
c.builder.store(cgutils.true_bit, is_error_ptr)
natives.append(native)
polynomial.coef = natives[0]
polynomial.domain = natives[1]
polynomial.window = natives[2]
return NativeValue(polynomial._getvalue(),
is_error=c.builder.load(is_error_ptr))
@box(types.PolynomialType)
def box_polynomial(typ, val, c):
"""
Convert a native polynomial structure to a Polynomial object.
"""
ret_ptr = cgutils.alloca_once(c.builder, c.pyapi.pyobj)
fail_obj = c.pyapi.get_null_object()
with ExitStack() as stack:
polynomial = cgutils.create_struct_proxy(typ)(c.context, c.builder,
value=val)
coef_obj = c.box(typ.coef, polynomial.coef)
with cgutils.early_exit_if_null(c.builder, stack, coef_obj):
c.builder.store(fail_obj, ret_ptr)
domain_obj = c.box(typ.domain, polynomial.domain)
with cgutils.early_exit_if_null(c.builder, stack, domain_obj):
c.builder.store(fail_obj, ret_ptr)
window_obj = c.box(typ.window, polynomial.window)
with cgutils.early_exit_if_null(c.builder, stack, window_obj):
c.builder.store(fail_obj, ret_ptr)
class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Polynomial))
with cgutils.early_exit_if_null(c.builder, stack, class_obj):
c.pyapi.decref(coef_obj)
c.pyapi.decref(domain_obj)
c.pyapi.decref(window_obj)
c.builder.store(fail_obj, ret_ptr)
if typ.n_args == 1:
res1 = c.pyapi.call_function_objargs(class_obj, (coef_obj,))
c.builder.store(res1, ret_ptr)
else:
res3 = c.pyapi.call_function_objargs(class_obj, (coef_obj,
domain_obj,
window_obj))
c.builder.store(res3, ret_ptr)
c.pyapi.decref(coef_obj)
c.pyapi.decref(domain_obj)
c.pyapi.decref(window_obj)
c.pyapi.decref(class_obj)
return c.builder.load(ret_ptr)
|
PolynomialModel
|
python
|
redis__redis-py
|
redis/commands/bf/info.py
|
{
"start": 34,
"end": 716
}
|
class ____:
capacity = None
size = None
filterNum = None
insertedNum = None
expansionRate = None
def __init__(self, args):
response = dict(zip(map(nativestr, args[::2]), args[1::2]))
self.capacity = response["Capacity"]
self.size = response["Size"]
self.filterNum = response["Number of filters"]
self.insertedNum = response["Number of items inserted"]
self.expansionRate = response["Expansion rate"]
def get(self, item):
try:
return self.__getitem__(item)
except AttributeError:
return None
def __getitem__(self, item):
return getattr(self, item)
|
BFInfo
|
python
|
psf__black
|
src/black/handle_ipynb_magics.py
|
{
"start": 10944,
"end": 11952
}
|
class ____(ast.NodeVisitor):
r"""Find cell magics.
Note that the source of the abstract syntax tree
will already have been processed by IPython's
TransformerManager().transform_cell.
For example,
%%time\n
foo()
would have been transformed to
get_ipython().run_cell_magic('time', '', 'foo()\n')
and we look for instances of the latter.
"""
def __init__(self, cell_magic: CellMagic | None = None) -> None:
self.cell_magic = cell_magic
def visit_Expr(self, node: ast.Expr) -> None:
"""Find cell magic, extract header and body."""
if (
isinstance(node.value, ast.Call)
and _is_ipython_magic(node.value.func)
and node.value.func.attr == "run_cell_magic"
):
args = _get_str_args(node.value.args)
self.cell_magic = CellMagic(name=args[0], params=args[1], body=args[2])
self.generic_visit(node)
@dataclasses.dataclass(frozen=True)
|
CellMagicFinder
|
python
|
more-itertools__more-itertools
|
tests/test_more.py
|
{
"start": 185642,
"end": 187608
}
|
class ____(TestCase):
def test_basic(self):
for iterable, expected in [
([], []),
([1, 2, 3], []),
([1, 1], [1]),
([1, 2, 1, 2], [1, 2]),
([1, 2, 3, '1'], []),
]:
with self.subTest(args=(iterable,)):
self.assertEqual(
list(mi.duplicates_everseen(iterable)), expected
)
def test_non_hashable(self):
self.assertEqual(list(mi.duplicates_everseen([[1, 2], [3, 4]])), [])
self.assertEqual(
list(mi.duplicates_everseen([[1, 2], [3, 4], [1, 2]])), [[1, 2]]
)
def test_partially_hashable(self):
self.assertEqual(
list(mi.duplicates_everseen([[1, 2], [3, 4], (5, 6)])), []
)
self.assertEqual(
list(mi.duplicates_everseen([[1, 2], [3, 4], (5, 6), [1, 2]])),
[[1, 2]],
)
self.assertEqual(
list(mi.duplicates_everseen([[1, 2], [3, 4], (5, 6), (5, 6)])),
[(5, 6)],
)
def test_key_hashable(self):
iterable = 'HEheHEhe'
self.assertEqual(list(mi.duplicates_everseen(iterable)), list('HEhe'))
self.assertEqual(
list(mi.duplicates_everseen(iterable, str.lower)),
list('heHEhe'),
)
def test_key_non_hashable(self):
iterable = [[1, 2], [3, 0], [5, -2], [5, 6]]
self.assertEqual(
list(mi.duplicates_everseen(iterable, lambda x: x)), []
)
self.assertEqual(
list(mi.duplicates_everseen(iterable, sum)), [[3, 0], [5, -2]]
)
def test_key_partially_hashable(self):
iterable = [[1, 2], (1, 2), [1, 2], [5, 6]]
self.assertEqual(
list(mi.duplicates_everseen(iterable, lambda x: x)), [[1, 2]]
)
self.assertEqual(
list(mi.duplicates_everseen(iterable, list)), [(1, 2), [1, 2]]
)
|
DuplicatesEverSeenTests
|
python
|
dagster-io__dagster
|
.buildkite/buildkite-shared/buildkite_shared/python_packages.py
|
{
"start": 940,
"end": 3618
}
|
class ____:
def __init__(self, setup_path: Path):
self.directory = setup_path
if (setup_path / "setup.py").exists():
# run_setup stores state in a global variable. Reload the module
# each time we use it - otherwise we'll get the previous invocation's
# distribution if our setup.py doesn't implement setup() correctly
reload(distutils_core)
distribution = distutils_core.run_setup(str(setup_path / "setup.py"), stop_after="init")
self._install_requires = distribution.install_requires # type: ignore[attr-defined]
self._extras_require = distribution.extras_require # type: ignore[attr-defined]
self.name = distribution.get_name()
else:
pyproject_toml = setup_path / "pyproject.toml"
assert pyproject_toml.exists(), (
f"expected pyproject.toml to exist in directory {setup_path}"
)
try:
with open(pyproject_toml, "rb") as f:
project = tomli.load(f)["project"]
except KeyError:
# this directory has a pyproject.toml but isn't really a python projects,
# ie docs/
self.name = setup_path.name
self._install_requires = []
self._extras_require = {}
else:
self.name = project["name"]
self._install_requires = project.get("dependencies", [])
self._extras_require = project.get("optional-dependencies", {})
@property
def install_requires(self) -> set[Requirement]:
return set(
requirement
for requirement in parse_requirements(self._install_requires)
if PythonPackages.get(requirement.name)
)
@property
def extras_require(self) -> dict[str, set[Requirement]]:
extras_require = {}
for extra, requirements in self._extras_require.items():
extras_require[extra] = set(
requirement
for requirement in parse_requirements(requirements)
if PythonPackages.get(requirement.name)
)
return extras_require
def __str__(self):
return self.name
def __repr__(self):
return f"PythonPackage({self.name})"
def __eq__(self, other):
return self.directory == other.directory
# Because we define __eq__
# https://docs.python.org/3.1/reference/datamodel.html#object.__hash__
def __hash__(self):
return hash(self.directory)
def __lt__(self, other):
return self.name < other.name
|
PythonPackage
|
python
|
huggingface__transformers
|
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
|
{
"start": 118854,
"end": 128910
}
|
class ____(MMGroundingDinoPreTrainedModel):
_tied_weights_keys = {
r"bbox_embed.(?![0])\d+": r"bbox_embed.0",
r"class_embed.(?![0])\d+": r"^class_embed.0",
"model.decoder.bbox_embed": "bbox_embed",
"model.decoder.class_embed": "class_embed",
}
def __init__(self, config: MMGroundingDinoConfig):
super().__init__(config)
self.model = MMGroundingDinoModel(config)
self.class_embed = nn.ModuleList(
[MMGroundingDinoContrastiveEmbedding(config) for _ in range(config.decoder_layers)]
)
self.bbox_embed = nn.ModuleList(
[
MMGroundingDinoMLPPredictionHead(
input_dim=config.d_model, hidden_dim=config.d_model, output_dim=4, num_layers=3
)
for _ in range(config.decoder_layers)
]
)
# Initialize weights and apply final processing
self.model.decoder.class_embed = self.class_embed # class embed has no weights so nothing to tie
self.model.decoder.bbox_embed = self.bbox_embed
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
input_ids: torch.LongTensor,
token_type_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
pixel_mask: Optional[torch.BoolTensor] = None,
encoder_outputs: Optional[Union[MMGroundingDinoEncoderOutput, tuple]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[list[dict[str, Union[torch.LongTensor, torch.FloatTensor]]]] = None,
):
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, text_sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using [`AutoTokenizer`]. See [`BertTokenizer.__call__`] for details.
token_type_ids (`torch.LongTensor` of shape `(batch_size, text_sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`: 0 corresponds to a `sentence A` token, 1 corresponds to a `sentence B` token
[What are token type IDs?](../glossary#token-type-ids)
labels (`list[Dict]` of len `(batch_size,)`, *optional*):
Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
Examples:
```python
>>> import requests
>>> import torch
>>> from PIL import Image
>>> from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
>>> model_id = "IDEA-Research/grounding-dino-tiny"
>>> device = "cuda"
>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device)
>>> image_url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(image_url, stream=True).raw)
>>> # Check for cats and remote controls
>>> text_labels = [["a cat", "a remote control"]]
>>> inputs = processor(images=image, text=text_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> results = processor.post_process_grounded_object_detection(
... outputs,
... threshold=0.4,
... text_threshold=0.3,
... target_sizes=[(image.height, image.width)]
... )
>>> # Retrieve the first image result
>>> result = results[0]
>>> for box, score, text_label in zip(result["boxes"], result["scores"], result["text_labels"]):
... box = [round(x, 2) for x in box.tolist()]
... print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a cat with confidence 0.479 at location [344.7, 23.11, 637.18, 374.28]
Detected a cat with confidence 0.438 at location [12.27, 51.91, 316.86, 472.44]
Detected a remote control with confidence 0.478 at location [38.57, 70.0, 176.78, 118.18]
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
# First, sent images through Grounding DINO base model to obtain encoder + decoder outputs
outputs = self.model(
pixel_values=pixel_values,
input_ids=input_ids,
token_type_ids=token_type_ids,
attention_mask=attention_mask,
pixel_mask=pixel_mask,
encoder_outputs=encoder_outputs,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
idx = 5 + (1 if output_attentions else 0) + (1 if output_hidden_states else 0)
enc_text_hidden_state = outputs.encoder_last_hidden_state_text if return_dict else outputs[idx]
hidden_states = outputs.intermediate_hidden_states if return_dict else outputs[2]
init_reference_points = outputs.init_reference_points if return_dict else outputs[1]
inter_references_points = outputs.intermediate_reference_points if return_dict else outputs[3]
# class logits + predicted bounding boxes
outputs_classes = []
outputs_coords = []
# hidden_states are of shape (batch_size, num_stages, height, width)
# predict class and bounding box deltas for each stage
num_levels = hidden_states.shape[1]
for level in range(num_levels):
if level == 0:
reference = init_reference_points
else:
reference = inter_references_points[:, level - 1]
reference = torch.special.logit(reference, eps=1e-5)
outputs_class = self.class_embed[level](
vision_hidden_state=hidden_states[:, level],
text_hidden_state=enc_text_hidden_state,
text_token_mask=attention_mask.bool(),
)
delta_bbox = self.bbox_embed[level](hidden_states[:, level])
reference_coordinates = reference.shape[-1]
if reference_coordinates == 4:
outputs_coord_logits = delta_bbox + reference
elif reference_coordinates == 2:
delta_bbox[..., :2] += reference
outputs_coord_logits = delta_bbox
else:
raise ValueError(f"reference.shape[-1] should be 4 or 2, but got {reference.shape[-1]}")
outputs_coord = outputs_coord_logits.sigmoid()
outputs_classes.append(outputs_class)
outputs_coords.append(outputs_coord)
outputs_class = torch.stack(outputs_classes)
outputs_coord = torch.stack(outputs_coords)
logits = outputs_class[-1]
pred_boxes = outputs_coord[-1]
loss, loss_dict, auxiliary_outputs = None, None, None
if labels is not None:
label_maps = build_label_maps(logits, input_ids)
text_mask = build_text_mask(logits, attention_mask)
loss, loss_dict, auxiliary_outputs = self.loss_function(
logits,
labels,
self.device,
pred_boxes,
self.config,
label_maps,
text_mask,
outputs_class=outputs_class,
outputs_coord=outputs_coord,
encoder_logits=outputs[-2],
encoder_pred_boxes=outputs[-1],
)
if not return_dict:
auxiliary_outputs = auxiliary_outputs if auxiliary_outputs is not None else []
output = [loss, loss_dict, logits, pred_boxes, *auxiliary_outputs, *outputs, input_ids]
output = tuple(out for out in output if out is not None)
return output
dict_outputs = MMGroundingDinoObjectDetectionOutput(
loss=loss,
loss_dict=loss_dict,
logits=logits,
pred_boxes=pred_boxes,
last_hidden_state=outputs.last_hidden_state,
auxiliary_outputs=auxiliary_outputs,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
encoder_last_hidden_state_vision=outputs.encoder_last_hidden_state_vision,
encoder_last_hidden_state_text=outputs.encoder_last_hidden_state_text,
encoder_vision_hidden_states=outputs.encoder_vision_hidden_states,
encoder_text_hidden_states=outputs.encoder_text_hidden_states,
encoder_attentions=outputs.encoder_attentions,
intermediate_hidden_states=outputs.intermediate_hidden_states,
intermediate_reference_points=outputs.intermediate_reference_points,
init_reference_points=outputs.init_reference_points,
enc_outputs_class=outputs.enc_outputs_class,
enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
encoder_logits=outputs.encoder_logits,
encoder_pred_boxes=outputs.encoder_pred_boxes,
input_ids=input_ids,
)
return dict_outputs
__all__ = ["MMGroundingDinoForObjectDetection", "MMGroundingDinoModel", "MMGroundingDinoPreTrainedModel"]
|
MMGroundingDinoForObjectDetection
|
python
|
dagster-io__dagster
|
helm/dagster/schema/schema/charts/dagster/subschema/scheduler.py
|
{
"start": 380,
"end": 548
}
|
class ____(BaseModel, extra="forbid"):
daemonScheduler: Optional[DaemonSchedulerConfig] = None
customScheduler: Optional[ConfigurableClass] = None
|
SchedulerConfig
|
python
|
pytest-dev__pluggy
|
docs/examples/toy-example.py
|
{
"start": 110,
"end": 278
}
|
class ____:
"""A hook specification namespace."""
@hookspec
def myhook(self, arg1, arg2):
"""My special little hook that you can customize."""
|
MySpec
|
python
|
tensorflow__tensorflow
|
tensorflow/python/kernel_tests/nn_ops/relu_op_test.py
|
{
"start": 9986,
"end": 14568
}
|
class ____(test.TestCase):
def _npLeakyRelu(self, np_features, alpha=0.1):
return np.maximum(np_features, alpha * np_features)
def testNpLeakyRelu(self):
self.assertAllClose(
np.array([[-0.09, 0.7, -0.05, 0.3, -0.01],
[0.1, -0.03, 0.5, -0.07, 0.9]]),
self._npLeakyRelu(
np.array([[-0.9, 0.7, -0.5, 0.3, -0.1], [0.1, -0.3, 0.5, -0.7,
0.9]]),
alpha=0.1))
def _testLeakyRelu(self, np_features, alpha):
np_leaky_relu = self._npLeakyRelu(np_features, alpha)
tf_leaky_relu = nn_ops.leaky_relu(np_features, alpha)
self.assertAllCloseAccordingToType(np_leaky_relu, tf_leaky_relu)
self.assertShapeEqual(np_leaky_relu, tf_leaky_relu)
def testNumbersCPU(self):
for t in [
np.int32, np.int64, np.float16, np.float32, np.float64,
dtypes.bfloat16.as_numpy_dtype
]:
# Force execution on CPU even if a GPU kernel is available for the type.
with ops.device("/device:CPU:0"):
self._testLeakyRelu(
np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),
alpha=0.2)
def testNumbersGPU(self):
if not test.is_gpu_available():
self.skipTest("No GPU available")
for t in [
np.float16,
np.float32,
np.float64,
dtypes.bfloat16.as_numpy_dtype,
]:
self._testLeakyRelu(
np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),
alpha=0.1)
def testNaNPropagation(self):
for t in [np.float16, np.float32, np.float64]:
self._testLeakyRelu(np.array([-1, np.nan, 1, np.nan]).astype(t),
alpha=0.2)
# The gradient test for Leaky ReLU is a bit tricky as the derivative is not
# well defined at around zero and we want to avoid that in terms of input
# values.
def testGradientFloat32(self):
with self.cached_session():
x = np.asarray(
[[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],
dtype=np.float32,
order="F")
err = gradient_checker_v2.max_error(
*gradient_checker_v2.compute_gradient(nn_ops.leaky_relu, [x]))
self.assertLess(err, 1e-4)
def testGradientFloat64(self):
with self.cached_session():
x = np.asarray(
[[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],
dtype=np.float64,
order="F")
err = gradient_checker_v2.max_error(
*gradient_checker_v2.compute_gradient(nn_ops.leaky_relu, [x]))
self.assertLess(err, 1e-10)
def testGradGradFloat32(self):
with self.cached_session():
def f(x):
assert x.dtype == dtypes.float32
with backprop.GradientTape() as tape:
tape.watch(x)
y = nn_ops.leaky_relu(x)
return tape.gradient(y, x)
x = np.asarray(
[[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],
dtype=np.float32,
order="F")
err = gradient_checker_v2.max_error(
*gradient_checker_v2.compute_gradient(f, [x]))
self.assertLess(err, 1e-4)
def testGradGradFloat64(self):
with self.cached_session():
def f(x):
assert x.dtype == dtypes.float64
with backprop.GradientTape() as tape:
tape.watch(x)
y = nn_ops.leaky_relu(x)
return tape.gradient(y, x)
x = np.asarray(
[[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],
dtype=np.float64,
order="F")
err = gradient_checker_v2.max_error(
*gradient_checker_v2.compute_gradient(f, [x]))
self.assertLess(err, 1e-10)
def testGradientScalar(self):
x = variables.Variable(-100.)
def loss():
return nn_ops.leaky_relu(x, 0.05)**2
optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.2)
self.evaluate(variables.global_variables_initializer())
self.evaluate(optimizer.minimize(loss))
self.assertAllClose(x.read_value(), -99.9)
def testUnexpectedAlphaValue(self):
self.assertAllClose(
np.array([[-9.0, 0.7, -5.0, 0.3, -0.1], [0.1, -3.0, 0.5, -27.0, 0.9]]),
nn_ops.leaky_relu(
np.array([[-0.9, 0.7, -0.5, 0.3, -0.01],
[0.1, -0.3, 0.5, -2.7, 0.9]]),
alpha=10))
self.assertAllClose(
np.array([[9.0, 0.7, 5.0, 0.3, 0.1], [0.1, 3.0, 0.5, 27.0, 0.9]]),
nn_ops.leaky_relu(
np.array([[-0.9, 0.7, -0.5, 0.3, -0.01],
[0.1, -0.3, 0.5, -2.7, 0.9]]),
alpha=-10))
|
LeakyReluTest
|
python
|
pytorch__pytorch
|
torch/distributed/checkpoint/utils.py
|
{
"start": 13202,
"end": 16563
}
|
class ____(io.IOBase):
def __init__(self, base_stream: io.IOBase, offset: int, len: int):
super().__init__()
self.offset = offset
self.len = len
self.base_stream = base_stream
self.seek(0)
def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int:
if whence == os.SEEK_SET:
offset = self.offset + offset
elif whence == os.SEEK_END:
whence = os.SEEK_SET
offset = (self.offset + self.len) - offset
return self.base_stream.seek(offset, whence)
def tell(self) -> int:
return self.base_stream.tell() - self.offset
def readable(self) -> bool:
return self.base_stream.readable()
def seekable(self) -> bool:
return self.base_stream.seekable()
def readinto(self, b):
max_size = self.len - self.tell()
if max_size == 0:
return 0
if len(b) > max_size:
b = memoryview(b)[:max_size]
return self.base_stream.readinto(b) # type: ignore[attr-defined]
def read(self, size=-1):
max_size = self.len - self.tell()
if size == -1 or size > max_size:
size = max_size
return self.base_stream.read(size)
def _create_file_view(file: io.IOBase, offset: int, length: int) -> io.IOBase:
# FIXME (kumpera) torch.load fails if we wrap with io.BufferedReader
return _ReaderView(file, offset, length)
def _normalize_device_info(device_type: str, device_id: int) -> str:
"""Device info normalization."""
if device_type == "cpu":
return "cpu"
return f"{device_type}:{device_id}"
# TODO: integrate with distributed logging flag
ENABLE_PROFILE = False
@contextmanager
def _profile():
# Only log the profiling when it is enable and is on rank0 or dist is not
# available.
if ENABLE_PROFILE and (not dist.is_available() or dist.get_rank() == 0):
profiler = cProfile.Profile()
profiler.enable()
try:
yield
finally:
profiler.disable()
stats = Stats(profiler)
stats.sort_stats("time").print_stats(10)
else:
yield
def _api_bc_check(func):
@wraps(func)
def inner_func(*args, **kwargs) -> Any:
if len(args) == 2:
warnings.warn(
f"The argument order of {func.__name__} has been changed. "
"Please check the document to avoid future breakages.",
stacklevel=2,
)
sig = inspect.signature(func)
kwonlyargs = [
p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY
]
if "storage_writer" in kwonlyargs:
if "storage_writer" in kwargs:
raise AssertionError(f"storage_writer in kwargs: {(args, kwargs)}")
kwargs["storage_writer"] = args[1]
elif "storage_reader" in kwonlyargs:
if "storage_reader" in kwargs:
raise AssertionError(f"storage_reader in kwargs: {(args, kwargs)}")
kwargs["storage_reader"] = args[1]
else:
raise RuntimeError(f"Unexpected kwonlyargs = {kwonlyargs}")
return func(args[0], **kwargs)
else:
return func(*args, **kwargs)
return inner_func
|
_ReaderView
|
python
|
django__django
|
tests/check_framework/test_templates.py
|
{
"start": 336,
"end": 530
}
|
class ____(BaseEngine):
def __init__(self, params):
params.pop("OPTIONS")
super().__init__(params)
def check(self, **kwargs):
return [Error("Example")]
|
ErrorEngine
|
python
|
pyparsing__pyparsing
|
examples/shapes.py
|
{
"start": 474,
"end": 547
}
|
class ____(Shape):
def area(self):
return self.side ** 2
|
Square
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.