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 | openai__openai-python | tests/api_resources/beta/threads/test_runs.py | {
"start": 484,
"end": 21999
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_create_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.create(
thread_id="thread_id",
assistant_id="assistant_id",
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.create(
thread_id="thread_id",
assistant_id="assistant_id",
include=["step_details.tool_calls[*].file_search.results[*].content"],
additional_instructions="additional_instructions",
additional_messages=[
{
"content": "string",
"role": "user",
"attachments": [
{
"file_id": "file_id",
"tools": [{"type": "code_interpreter"}],
}
],
"metadata": {"foo": "string"},
}
],
instructions="instructions",
max_completion_tokens=256,
max_prompt_tokens=256,
metadata={"foo": "string"},
model="string",
parallel_tool_calls=True,
reasoning_effort="none",
response_format="auto",
stream=False,
temperature=1,
tool_choice="none",
tools=[{"type": "code_interpreter"}],
top_p=1,
truncation_strategy={
"type": "auto",
"last_messages": 1,
},
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_raw_response_create_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.create(
thread_id="thread_id",
assistant_id="assistant_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_streaming_response_create_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.create(
thread_id="thread_id",
assistant_id="assistant_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_create_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.create(
thread_id="",
assistant_id="assistant_id",
)
@parametrize
def test_method_create_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run_stream = client.beta.threads.runs.create(
thread_id="thread_id",
assistant_id="assistant_id",
stream=True,
)
run_stream.response.close()
@parametrize
def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run_stream = client.beta.threads.runs.create(
thread_id="thread_id",
assistant_id="assistant_id",
stream=True,
include=["step_details.tool_calls[*].file_search.results[*].content"],
additional_instructions="additional_instructions",
additional_messages=[
{
"content": "string",
"role": "user",
"attachments": [
{
"file_id": "file_id",
"tools": [{"type": "code_interpreter"}],
}
],
"metadata": {"foo": "string"},
}
],
instructions="instructions",
max_completion_tokens=256,
max_prompt_tokens=256,
metadata={"foo": "string"},
model="string",
parallel_tool_calls=True,
reasoning_effort="none",
response_format="auto",
temperature=1,
tool_choice="none",
tools=[{"type": "code_interpreter"}],
top_p=1,
truncation_strategy={
"type": "auto",
"last_messages": 1,
},
)
run_stream.response.close()
@parametrize
def test_raw_response_create_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.create(
thread_id="thread_id",
assistant_id="assistant_id",
stream=True,
)
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
stream = response.parse()
stream.close()
@parametrize
def test_streaming_response_create_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.create(
thread_id="thread_id",
assistant_id="assistant_id",
stream=True,
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
stream = response.parse()
stream.close()
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_create_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.create(
thread_id="",
assistant_id="assistant_id",
stream=True,
)
@parametrize
def test_method_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.retrieve(
run_id="run_id",
thread_id="thread_id",
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_raw_response_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.retrieve(
run_id="run_id",
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_streaming_response_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.retrieve(
run_id="run_id",
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.retrieve(
run_id="run_id",
thread_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"):
client.beta.threads.runs.with_raw_response.retrieve(
run_id="",
thread_id="thread_id",
)
@parametrize
def test_method_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.update(
run_id="run_id",
thread_id="thread_id",
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_method_update_with_all_params(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.update(
run_id="run_id",
thread_id="thread_id",
metadata={"foo": "string"},
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_raw_response_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.update(
run_id="run_id",
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_streaming_response_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.update(
run_id="run_id",
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.update(
run_id="run_id",
thread_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"):
client.beta.threads.runs.with_raw_response.update(
run_id="",
thread_id="thread_id",
)
@parametrize
def test_method_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.list(
thread_id="thread_id",
)
assert_matches_type(SyncCursorPage[Run], run, path=["response"])
@parametrize
def test_method_list_with_all_params(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.list(
thread_id="thread_id",
after="after",
before="before",
limit=0,
order="asc",
)
assert_matches_type(SyncCursorPage[Run], run, path=["response"])
@parametrize
def test_raw_response_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.list(
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(SyncCursorPage[Run], run, path=["response"])
@parametrize
def test_streaming_response_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.list(
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(SyncCursorPage[Run], run, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.list(
thread_id="",
)
@parametrize
def test_method_cancel(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.cancel(
run_id="run_id",
thread_id="thread_id",
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_raw_response_cancel(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.cancel(
run_id="run_id",
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_streaming_response_cancel(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.cancel(
run_id="run_id",
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_cancel(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.cancel(
run_id="run_id",
thread_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"):
client.beta.threads.runs.with_raw_response.cancel(
run_id="",
thread_id="thread_id",
)
@parametrize
def test_method_submit_tool_outputs_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.submit_tool_outputs(
run_id="run_id",
thread_id="thread_id",
tool_outputs=[{}],
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_method_submit_tool_outputs_with_all_params_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run = client.beta.threads.runs.submit_tool_outputs(
run_id="run_id",
thread_id="thread_id",
tool_outputs=[
{
"output": "output",
"tool_call_id": "tool_call_id",
}
],
stream=False,
)
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_raw_response_submit_tool_outputs_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.submit_tool_outputs(
run_id="run_id",
thread_id="thread_id",
tool_outputs=[{}],
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
@parametrize
def test_streaming_response_submit_tool_outputs_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.submit_tool_outputs(
run_id="run_id",
thread_id="thread_id",
tool_outputs=[{}],
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
run = response.parse()
assert_matches_type(Run, run, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_submit_tool_outputs_overload_1(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.submit_tool_outputs(
run_id="run_id",
thread_id="",
tool_outputs=[{}],
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"):
client.beta.threads.runs.with_raw_response.submit_tool_outputs(
run_id="",
thread_id="thread_id",
tool_outputs=[{}],
)
@parametrize
def test_method_submit_tool_outputs_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
run_stream = client.beta.threads.runs.submit_tool_outputs(
run_id="run_id",
thread_id="thread_id",
stream=True,
tool_outputs=[{}],
)
run_stream.response.close()
@parametrize
def test_raw_response_submit_tool_outputs_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.runs.with_raw_response.submit_tool_outputs(
run_id="run_id",
thread_id="thread_id",
stream=True,
tool_outputs=[{}],
)
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
stream = response.parse()
stream.close()
@parametrize
def test_streaming_response_submit_tool_outputs_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.runs.with_streaming_response.submit_tool_outputs(
run_id="run_id",
thread_id="thread_id",
stream=True,
tool_outputs=[{}],
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
stream = response.parse()
stream.close()
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_submit_tool_outputs_overload_2(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.runs.with_raw_response.submit_tool_outputs(
run_id="run_id",
thread_id="",
stream=True,
tool_outputs=[{}],
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"):
client.beta.threads.runs.with_raw_response.submit_tool_outputs(
run_id="",
thread_id="thread_id",
stream=True,
tool_outputs=[{}],
)
| TestRuns |
python | kamyu104__LeetCode-Solutions | Python/guess-number-higher-or-lower.py | {
"start": 32,
"end": 392
} | class ____(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 1, n
while left <= right:
mid = left + (right - left) / 2
if guess(mid) <= 0: # noqa
right = mid - 1
else:
left = mid + 1
return left
| Solution |
python | scipy__scipy | scipy/signal/tests/test_dltisys.py | {
"start": 17491,
"end": 20190
} | class ____:
def test_manual(self):
# Test bode() magnitude calculation (manual sanity check).
# 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
dt = 0.1
system = TransferFunction(0.3, [1, -0.2], dt=dt)
w = [0.1, 0.5, 1, np.pi]
w2, mag, phase = dbode(system, w=w)
# Test mag
expected_mag = [-8.5329, -8.8396, -9.6162, -12.0412]
assert_almost_equal(mag, expected_mag, decimal=4)
# Test phase
expected_phase = [-7.1575, -35.2814, -67.9809, -180.0000]
assert_almost_equal(phase, expected_phase, decimal=4)
# Test frequency
xp_assert_equal(np.array(w) / dt, w2)
def test_auto(self):
# Test bode() magnitude calculation.
# 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
system = TransferFunction(0.3, [1, -0.2], dt=0.1)
w = np.array([0.1, 0.5, 1, np.pi])
w2, mag, phase = dbode(system, w=w)
jw = np.exp(w * 1j)
y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
# Test mag
expected_mag = 20.0 * np.log10(abs(y))
assert_almost_equal(mag, expected_mag)
# Test phase
expected_phase = np.rad2deg(np.angle(y))
assert_almost_equal(phase, expected_phase)
def test_range(self):
# Test that bode() finds a reasonable frequency range.
# 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
dt = 0.1
system = TransferFunction(0.3, [1, -0.2], dt=0.1)
n = 10
# Expected range is from 0.01 to 10.
expected_w = np.linspace(0, np.pi, n, endpoint=False) / dt
w, mag, phase = dbode(system, n=n)
assert_almost_equal(w, expected_w)
def test_pole_one(self):
# Test that freqresp() doesn't fail on a system with a pole at 0.
# integrator, pole at zero: H(s) = 1 / s
system = TransferFunction([1], [1, -1], dt=0.1)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "divide by zero", RuntimeWarning)
warnings.filterwarnings(
"ignore", "invalid value encountered", RuntimeWarning)
w, mag, phase = dbode(system, n=2)
assert w[0] == 0. # a fail would give not-a-number
def test_imaginary(self):
# bode() should not fail on a system with pure imaginary poles.
# The test passes if bode doesn't raise an exception.
system = TransferFunction([1], [1, 0, 100], dt=0.1)
dbode(system, n=2)
def test_error(self):
# Raise an error for continuous-time systems
system = lti([1], [1, 1])
assert_raises(AttributeError, dbode, system)
| Test_bode |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py | {
"start": 3060,
"end": 4585
} | class ____(TypedDict):
"""Configuration for an action requiring human in the loop.
This is the configuration format used in the `HumanInTheLoopMiddleware.__init__`
method.
"""
allowed_decisions: list[DecisionType]
"""The decisions that are allowed for this action."""
description: NotRequired[str | _DescriptionFactory]
"""The description attached to the request for human input.
Can be either:
- A static string describing the approval request
- A callable that dynamically generates the description based on agent state,
runtime, and tool call information
Example:
```python
# Static string description
config = ToolConfig(
allowed_decisions=["approve", "reject"],
description="Please review this tool execution"
)
# Dynamic callable description
def format_tool_description(
tool_call: ToolCall,
state: AgentState,
runtime: Runtime
) -> str:
import json
return (
f"Tool: {tool_call['name']}\\n"
f"Arguments:\\n{json.dumps(tool_call['args'], indent=2)}"
)
config = InterruptOnConfig(
allowed_decisions=["approve", "edit", "reject"],
description=format_tool_description
)
```
"""
args_schema: NotRequired[dict[str, Any]]
"""JSON schema for the args associated with the action, if edits are allowed."""
| InterruptOnConfig |
python | getsentry__sentry | tests/sentry/event_manager/test_event_manager_grouping.py | {
"start": 1457,
"end": 14885
} | class ____(TestCase):
def test_puts_events_with_matching_fingerprints_in_same_group(self) -> None:
event = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["maisey"]}, self.project
)
# Normally this should go into a different group, since the messages don't match, but the
# fingerprint takes precedence.
event2 = save_new_event(
{"message": "Adopt don't shop", "fingerprint": ["maisey"]}, self.project
)
assert event.group_id == event2.group_id
def test_puts_events_with_different_fingerprints_in_different_groups(self) -> None:
event = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["maisey"]}, self.project
)
# Normally this should go into the same group, since the message matches, but the
# fingerprint takes precedence.
event2 = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["charlie"]}, self.project
)
assert event.group_id != event2.group_id
def test_puts_events_with_only_partial_message_match_in_different_groups(self) -> None:
# We had a regression which caused the default hash to just be 'event.message' instead of
# '[event.message]' which caused it to generate a hash per letter
event1 = save_new_event({"message": "Dogs are great!"}, self.project)
event2 = save_new_event({"message": "Dogs are really great!"}, self.project)
assert event1.group_id != event2.group_id
def test_adds_default_fingerprint_if_none_in_event(self) -> None:
event = save_new_event({"message": "Dogs are great!"}, self.project)
assert event.data["fingerprint"] == ["{{ default }}"]
def test_ignores_fingerprint_on_transaction_event(self) -> None:
error_event = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["charlie"]}, self.project
)
transaction_event = save_new_event(
{
"transaction": "dogpark",
"fingerprint": ["charlie"],
"type": "transaction",
"contexts": {
"trace": {
"parent_span_id": "1121201212312012",
"op": "sniffing",
"trace_id": "11212012123120120415201309082013",
"span_id": "1231201211212012",
}
},
"start_timestamp": time(),
"timestamp": time(),
},
self.project,
)
# Events are assigned to different groups even though they had identical fingerprints
assert error_event.group_id != transaction_event.group_id
def test_none_exception(self) -> None:
"""Test that when the exception is None, the group is still formed."""
event = save_new_event({"exception": None}, self.project)
assert event.group
def test_updates_group_metadata(self) -> None:
event1 = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["maisey"]}, self.project
)
assert event1.group_id is not None
group = Group.objects.get(id=event1.group_id)
assert group.times_seen == 1
assert group.last_seen == event1.datetime
assert group.message == event1.message
assert group.data["metadata"]["title"] == event1.title
# Normally this should go into a different group, since the messages don't match, but the
# fingerprint takes precedence. (We need to make the messages different in order to show
# that the group's message gets updated.)
event2 = save_new_event(
{"message": "Adopt don't shop", "fingerprint": ["maisey"]}, self.project
)
assert event1.group_id is not None and event2.group_id is not None
assert event1.group_id == event2.group_id
group = Group.objects.get(id=event2.group_id)
assert group.times_seen == 2
assert group.last_seen == event2.datetime
assert group.message == event2.message
assert group.data["metadata"]["title"] == event2.title
def test_loads_default_config_if_stored_config_option_is_invalid(self) -> None:
self.project.update_option("sentry:grouping_config", "dogs.are.great")
config_dict = get_grouping_config_dict_for_project(self.project)
assert config_dict["id"] == DEFAULT_GROUPING_CONFIG
self.project.update_option("sentry:grouping_config", {"not": "a string"})
config_dict = get_grouping_config_dict_for_project(self.project)
assert config_dict["id"] == DEFAULT_GROUPING_CONFIG
def test_auto_updates_grouping_config_even_if_config_is_gone(self) -> None:
"""This tests that setups with deprecated configs will auto-upgrade."""
self.project.update_option("sentry:grouping_config", "non_existing_config")
save_new_event({"message": "foo"}, self.project)
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert self.project.get_option("sentry:secondary_grouping_config") is None
def test_auto_updates_grouping_config(self) -> None:
self.project.update_option("sentry:grouping_config", NO_MSG_PARAM_CONFIG)
# Set platform to prevent additional audit log entry from platform inference
self.project.platform = "python"
self.project.save()
save_new_event({"message": "Adopt don't shop"}, self.project)
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
with assume_test_silo_mode_of(AuditLogEntry):
audit_log_entry = AuditLogEntry.objects.get()
assert audit_log_entry.event == audit_log.get_event_id("PROJECT_EDIT")
assert audit_log_entry.actor_label == "Sentry"
assert audit_log_entry.data == {
"sentry:grouping_config": DEFAULT_GROUPING_CONFIG,
"sentry:secondary_grouping_config": NO_MSG_PARAM_CONFIG,
"sentry:secondary_grouping_expiry": ANY, # tested separately below
"id": self.project.id,
"slug": self.project.slug,
"name": self.project.name,
"status": 0,
"public": False,
}
# When the config upgrade is actually happening, the expiry value is set before the
# audit log entry is created, which means the expiry is based on a timestamp
# ever-so-slightly before the audit log entry's timestamp, making a one-second tolerance
# necessary.
actual_expiry = audit_log_entry.data["sentry:secondary_grouping_expiry"]
expected_expiry = (
int(audit_log_entry.datetime.timestamp()) + SENTRY_GROUPING_CONFIG_TRANSITION_DURATION
)
assert actual_expiry == expected_expiry or actual_expiry == expected_expiry - 1
@patch(
"sentry.event_manager.update_or_set_grouping_config_if_needed",
wraps=update_or_set_grouping_config_if_needed,
)
def test_sets_default_grouping_config_project_option_if_missing(
self, update_config_spy: MagicMock
):
# To start, the project defaults to the current config but doesn't have its own config
# option set in the DB
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert (
ProjectOption.objects.filter(
project_id=self.project.id, key="sentry:grouping_config"
).first()
is None
)
save_new_event({"message": "Dogs are great!"}, self.project)
update_config_spy.assert_called_with(self.project, "ingest")
# After the function has been called, the config still defaults to the current one (and no
# transition has started), but the project now has its own config record in the DB
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert self.project.get_option("sentry:secondary_grouping_config") is None
assert self.project.get_option("sentry:secondary_grouping_expiry") == 0
assert ProjectOption.objects.filter(
project_id=self.project.id, key="sentry:grouping_config"
).exists()
@patch(
"sentry.event_manager.update_or_set_grouping_config_if_needed",
wraps=update_or_set_grouping_config_if_needed,
)
def test_no_ops_if_grouping_config_project_option_exists_and_is_current(
self, update_config_spy: MagicMock
):
self.project.update_option("sentry:grouping_config", DEFAULT_GROUPING_CONFIG)
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert ProjectOption.objects.filter(
project_id=self.project.id, key="sentry:grouping_config"
).exists()
save_new_event({"message": "Dogs are great!"}, self.project)
update_config_spy.assert_called_with(self.project, "ingest")
# After the function has been called, the config still defaults to the current one and no
# transition has started
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert self.project.get_option("sentry:secondary_grouping_config") is None
assert self.project.get_option("sentry:secondary_grouping_expiry") == 0
@patch(
"sentry.event_manager.update_or_set_grouping_config_if_needed",
wraps=update_or_set_grouping_config_if_needed,
)
def test_no_ops_if_sample_rate_test_fails(self, update_config_spy: MagicMock):
with (
# Ensure our die roll will fall outside the sample rate
patch("sentry.grouping.ingest.config.random", return_value=0.1121),
override_options({"grouping.config_transition.config_upgrade_sample_rate": 0.0908}),
):
self.project.update_option("sentry:grouping_config", NO_MSG_PARAM_CONFIG)
assert self.project.get_option("sentry:grouping_config") == NO_MSG_PARAM_CONFIG
save_new_event({"message": "Dogs are great!"}, self.project)
update_config_spy.assert_called_with(self.project, "ingest")
# After the function has been called, the config hasn't changed and no transition has
# started
assert self.project.get_option("sentry:grouping_config") == NO_MSG_PARAM_CONFIG
assert self.project.get_option("sentry:secondary_grouping_config") is None
assert self.project.get_option("sentry:secondary_grouping_expiry") == 0
@patch(
"sentry.event_manager.update_or_set_grouping_config_if_needed",
wraps=update_or_set_grouping_config_if_needed,
)
def test_ignores_sample_rate_if_current_config_is_invalid(self, update_config_spy: MagicMock):
with (
# Ensure our die roll will fall outside the sample rate
patch("sentry.grouping.ingest.config.random", return_value=0.1121),
override_options({"grouping.config_transition.config_upgrade_sample_rate": 0.0908}),
):
self.project.update_option("sentry:grouping_config", "not_a_real_config")
assert self.project.get_option("sentry:grouping_config") == "not_a_real_config"
save_new_event({"message": "Dogs are great!"}, self.project)
update_config_spy.assert_called_with(self.project, "ingest")
# The config has been updated, but no transition has started because we can't calculate
# a secondary hash using a config that doesn't exist
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert self.project.get_option("sentry:secondary_grouping_config") is None
assert self.project.get_option("sentry:secondary_grouping_expiry") == 0
@patch(
"sentry.event_manager.update_or_set_grouping_config_if_needed",
wraps=update_or_set_grouping_config_if_needed,
)
def test_ignores_sample_rate_if_no_record_exists(self, update_config_spy: MagicMock):
with (
# Ensure our die roll will fall outside the sample rate
patch("sentry.grouping.ingest.config.random", return_value=0.1121),
override_options({"grouping.config_transition.config_upgrade_sample_rate": 0.0908}),
):
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert not ProjectOption.objects.filter(
project_id=self.project.id, key="sentry:grouping_config"
).exists()
save_new_event({"message": "Dogs are great!"}, self.project)
update_config_spy.assert_called_with(self.project, "ingest")
# The config hasn't been updated, but now the project has its own record. No transition
# has started because the config was already up to date.
assert self.project.get_option("sentry:grouping_config") == DEFAULT_GROUPING_CONFIG
assert ProjectOption.objects.filter(
project_id=self.project.id, key="sentry:grouping_config"
).exists()
assert self.project.get_option("sentry:secondary_grouping_config") is None
assert self.project.get_option("sentry:secondary_grouping_expiry") == 0
| EventManagerGroupingTest |
python | huggingface__transformers | src/transformers/models/swiftformer/configuration_swiftformer.py | {
"start": 799,
"end": 5300
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SwiftFormerModel`]. It is used to instantiate an
SwiftFormer model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the SwiftFormer
[MBZUAI/swiftformer-xs](https://huggingface.co/MBZUAI/swiftformer-xs) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of each image
num_channels (`int`, *optional*, defaults to 3):
The number of input channels
depths (`list[int]`, *optional*, defaults to `[3, 3, 6, 4]`):
Depth of each stage
embed_dims (`list[int]`, *optional*, defaults to `[48, 56, 112, 220]`):
The embedding dimension at each stage
mlp_ratio (`int`, *optional*, defaults to 4):
Ratio of size of the hidden dimensionality of an MLP to the dimensionality of its input.
downsamples (`list[bool]`, *optional*, defaults to `[True, True, True, True]`):
Whether or not to downsample inputs between two stages.
hidden_act (`str`, *optional*, defaults to `"gelu"`):
The non-linear activation function (string). `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
down_patch_size (`int`, *optional*, defaults to 3):
The size of patches in downsampling layers.
down_stride (`int`, *optional*, defaults to 2):
The stride of convolution kernels in downsampling layers.
down_pad (`int`, *optional*, defaults to 1):
Padding in downsampling layers.
drop_path_rate (`float`, *optional*, defaults to 0.0):
Rate at which to increase dropout probability in DropPath.
drop_mlp_rate (`float`, *optional*, defaults to 0.0):
Dropout rate for the MLP component of SwiftFormer.
drop_conv_encoder_rate (`float`, *optional*, defaults to 0.0):
Dropout rate for the ConvEncoder component of SwiftFormer.
use_layer_scale (`bool`, *optional*, defaults to `True`):
Whether to scale outputs from token mixers.
layer_scale_init_value (`float`, *optional*, defaults to 1e-05):
Factor by which outputs from token mixers are scaled.
batch_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the batch normalization layers.
Example:
```python
>>> from transformers import SwiftFormerConfig, SwiftFormerModel
>>> # Initializing a SwiftFormer swiftformer-base-patch16-224 style configuration
>>> configuration = SwiftFormerConfig()
>>> # Initializing a model (with random weights) from the swiftformer-base-patch16-224 style configuration
>>> model = SwiftFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "swiftformer"
def __init__(
self,
image_size=224,
num_channels=3,
depths=[3, 3, 6, 4],
embed_dims=[48, 56, 112, 220],
mlp_ratio=4,
downsamples=[True, True, True, True],
hidden_act="gelu",
down_patch_size=3,
down_stride=2,
down_pad=1,
drop_path_rate=0.0,
drop_mlp_rate=0.0,
drop_conv_encoder_rate=0.0,
use_layer_scale=True,
layer_scale_init_value=1e-5,
batch_norm_eps=1e-5,
**kwargs,
):
super().__init__(**kwargs)
self.image_size = image_size
self.num_channels = num_channels
self.depths = depths
self.embed_dims = embed_dims
self.mlp_ratio = mlp_ratio
self.downsamples = downsamples
self.hidden_act = hidden_act
self.down_patch_size = down_patch_size
self.down_stride = down_stride
self.down_pad = down_pad
self.drop_path_rate = drop_path_rate
self.drop_mlp_rate = drop_mlp_rate
self.drop_conv_encoder_rate = drop_conv_encoder_rate
self.use_layer_scale = use_layer_scale
self.layer_scale_init_value = layer_scale_init_value
self.batch_norm_eps = batch_norm_eps
__all__ = ["SwiftFormerConfig"]
| SwiftFormerConfig |
python | huggingface__transformers | tests/models/lightglue/test_modeling_lightglue.py | {
"start": 1279,
"end": 4443
} | class ____:
def __init__(
self,
parent,
batch_size=2,
image_width=80,
image_height=60,
keypoint_detector_config={
"encoder_hidden_sizes": [32, 32, 64],
"decoder_hidden_size": 64,
"keypoint_decoder_dim": 65,
"descriptor_decoder_dim": 64,
"keypoint_threshold": 0.005,
"max_keypoints": 256,
"nms_radius": 4,
"border_removal_distance": 4,
},
descriptor_dim: int = 64,
num_layers: int = 2,
num_heads: int = 4,
depth_confidence: float = 1.0,
width_confidence: float = 1.0,
filter_threshold: float = 0.1,
matching_threshold: float = 0.0,
):
self.parent = parent
self.batch_size = batch_size
self.image_width = image_width
self.image_height = image_height
self.keypoint_detector_config = keypoint_detector_config
self.descriptor_dim = descriptor_dim
self.num_layers = num_layers
self.num_heads = num_heads
self.depth_confidence = depth_confidence
self.width_confidence = width_confidence
self.filter_threshold = filter_threshold
self.matching_threshold = matching_threshold
def prepare_config_and_inputs(self):
# LightGlue expects a grayscale image as input
pixel_values = floats_tensor([self.batch_size, 2, 3, self.image_height, self.image_width])
config = self.get_config()
return config, pixel_values
def get_config(self):
return LightGlueConfig(
keypoint_detector_config=self.keypoint_detector_config,
descriptor_dim=self.descriptor_dim,
num_hidden_layers=self.num_layers,
num_attention_heads=self.num_heads,
depth_confidence=self.depth_confidence,
width_confidence=self.width_confidence,
filter_threshold=self.filter_threshold,
matching_threshold=self.matching_threshold,
attn_implementation="eager",
)
def create_and_check_model(self, config, pixel_values):
model = LightGlueForKeypointMatching(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values)
maximum_num_matches = result.mask.shape[-1]
self.parent.assertEqual(
result.keypoints.shape,
(self.batch_size, 2, maximum_num_matches, 2),
)
self.parent.assertEqual(
result.matches.shape,
(self.batch_size, 2, maximum_num_matches),
)
self.parent.assertEqual(
result.matching_scores.shape,
(self.batch_size, 2, maximum_num_matches),
)
self.parent.assertEqual(
result.prune.shape,
(self.batch_size, 2, maximum_num_matches),
)
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, pixel_values = config_and_inputs
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
| LightGlueModelTester |
python | keras-team__keras | keras/src/layers/normalization/unit_normalization.py | {
"start": 163,
"end": 2064
} | class ____(Layer):
"""Unit normalization layer.
Normalize a batch of inputs so that each input in the batch has a L2 norm
equal to 1 (across the axes specified in `axis`).
Example:
>>> data = np.arange(6).reshape(2, 3)
>>> normalized_data = keras.layers.UnitNormalization()(data)
>>> np.sum(normalized_data[0, :] ** 2)
1.0
Args:
axis: Integer or list/tuple. The axis or axes to normalize across.
Typically, this is the features axis or axes. The left-out axes are
typically the batch axis or axes. `-1` is the last dimension
in the input. Defaults to `-1`.
"""
def __init__(self, axis=-1, **kwargs):
super().__init__(**kwargs)
if isinstance(axis, (list, tuple)):
self.axis = list(axis)
elif isinstance(axis, int):
self.axis = axis
else:
raise TypeError(
"Invalid value for `axis` argument: "
"expected an int or a list/tuple of ints. "
f"Received: axis={axis}"
)
self.supports_masking = True
self._build_at_init()
def call(self, inputs):
return ops.normalize(inputs, axis=self.axis, order=2, epsilon=1e-12)
def compute_output_shape(self, input_shape):
# Ensure axis is always treated as a list
if isinstance(self.axis, int):
axes = [self.axis]
else:
axes = self.axis
for axis in axes:
if axis >= len(input_shape) or axis < -len(input_shape):
raise ValueError(
f"Axis {self.axis} is out of bounds for "
f"input shape {input_shape}."
)
return input_shape
def get_config(self):
config = super().get_config()
config.update({"axis": self.axis})
return config
| UnitNormalization |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 458660,
"end": 459108
} | class ____(sgqlc.types.Interface):
"""Comments that can be updated."""
__schema__ = github_schema
__field_names__ = ("viewer_cannot_update_reasons",)
viewer_cannot_update_reasons = sgqlc.types.Field(
sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(CommentCannotUpdateReason))), graphql_name="viewerCannotUpdateReasons"
)
"""Reasons why the current viewer can not update this comment."""
| UpdatableComment |
python | pyca__cryptography | tests/hazmat/primitives/test_dsa.py | {
"start": 1798,
"end": 17000
} | class ____:
def test_generate_dsa_parameters(self, backend):
parameters = dsa.generate_parameters(2048, backend)
assert isinstance(parameters, dsa.DSAParameters)
def test_generate_invalid_dsa_parameters(self, backend):
with pytest.raises(ValueError):
dsa.generate_parameters(1, backend)
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "DSA", "FIPS_186-3", "KeyPair.rsp"),
load_fips_dsa_key_pair_vectors,
),
)
def test_generate_dsa_keys(self, vector, backend):
parameters = dsa.DSAParameterNumbers(
p=vector["p"], q=vector["q"], g=vector["g"]
).parameters(backend)
skey = parameters.generate_private_key()
numbers = skey.private_numbers()
skey_parameters = numbers.public_numbers.parameter_numbers
pkey = skey.public_key()
parameters = pkey.parameters()
parameter_numbers = parameters.parameter_numbers()
assert parameter_numbers.p == skey_parameters.p
assert parameter_numbers.q == skey_parameters.q
assert parameter_numbers.g == skey_parameters.g
assert skey_parameters.p == vector["p"]
assert skey_parameters.q == vector["q"]
assert skey_parameters.g == vector["g"]
assert skey.key_size == vector["p"].bit_length()
assert pkey.key_size == skey.key_size
public_numbers = pkey.public_numbers()
assert numbers.public_numbers.y == public_numbers.y
assert numbers.public_numbers.y == pow(
skey_parameters.g, numbers.x, skey_parameters.p
)
def test_generate_dsa_private_key_and_parameters(self, backend):
skey = dsa.generate_private_key(2048, backend)
assert skey
numbers = skey.private_numbers()
skey_parameters = numbers.public_numbers.parameter_numbers
assert numbers.public_numbers.y == pow(
skey_parameters.g, numbers.x, skey_parameters.p
)
@pytest.mark.parametrize(
("p", "q", "g"),
[
(
2**1000,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
),
(
2**2000,
DSA_KEY_2048.public_numbers.parameter_numbers.q,
DSA_KEY_2048.public_numbers.parameter_numbers.g,
),
(
2**3000,
DSA_KEY_3072.public_numbers.parameter_numbers.q,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
),
(
2**3100,
DSA_KEY_3072.public_numbers.parameter_numbers.q,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
2**150,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
),
(
DSA_KEY_2048.public_numbers.parameter_numbers.p,
2**250,
DSA_KEY_2048.public_numbers.parameter_numbers.g,
),
(
DSA_KEY_3072.public_numbers.parameter_numbers.p,
2**260,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
0,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
1,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
2**1200,
),
],
)
def test_invalid_parameters_values(self, p, q, g, backend):
with pytest.raises(ValueError):
dsa.DSAParameterNumbers(p, q, g).parameters(backend)
@pytest.mark.parametrize(
("p", "q", "g", "y", "x"),
[
(
2**1000,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
DSA_KEY_1024.x,
),
(
2**2000,
DSA_KEY_2048.public_numbers.parameter_numbers.q,
DSA_KEY_2048.public_numbers.parameter_numbers.g,
DSA_KEY_2048.public_numbers.y,
DSA_KEY_2048.x,
),
(
2**3000,
DSA_KEY_3072.public_numbers.parameter_numbers.q,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
DSA_KEY_3072.public_numbers.y,
DSA_KEY_3072.x,
),
(
2**3100,
DSA_KEY_3072.public_numbers.parameter_numbers.q,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
DSA_KEY_3072.public_numbers.y,
DSA_KEY_3072.x,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
2**150,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
DSA_KEY_1024.x,
),
(
DSA_KEY_2048.public_numbers.parameter_numbers.p,
2**250,
DSA_KEY_2048.public_numbers.parameter_numbers.g,
DSA_KEY_2048.public_numbers.y,
DSA_KEY_2048.x,
),
(
DSA_KEY_3072.public_numbers.parameter_numbers.p,
2**260,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
DSA_KEY_3072.public_numbers.y,
DSA_KEY_3072.x,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
0,
DSA_KEY_1024.public_numbers.y,
DSA_KEY_1024.x,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
1,
DSA_KEY_1024.public_numbers.y,
DSA_KEY_1024.x,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
2**1200,
DSA_KEY_1024.public_numbers.y,
DSA_KEY_1024.x,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
0,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
-2,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
2**159,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
2**200,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
2**100,
DSA_KEY_1024.x,
),
],
)
def test_invalid_dsa_private_key_arguments(self, p, q, g, y, x, backend):
with pytest.raises(ValueError):
dsa.DSAPrivateNumbers(
public_numbers=dsa.DSAPublicNumbers(
parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g),
y=y,
),
x=x,
).private_key(backend)
@pytest.mark.parametrize(
("p", "q", "g", "y"),
[
(
2**1000,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
),
(
2**2000,
DSA_KEY_2048.public_numbers.parameter_numbers.q,
DSA_KEY_2048.public_numbers.parameter_numbers.g,
DSA_KEY_2048.public_numbers.y,
),
(
2**3000,
DSA_KEY_3072.public_numbers.parameter_numbers.q,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
DSA_KEY_3072.public_numbers.y,
),
(
2**3100,
DSA_KEY_3072.public_numbers.parameter_numbers.q,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
DSA_KEY_3072.public_numbers.y,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
2**150,
DSA_KEY_1024.public_numbers.parameter_numbers.g,
DSA_KEY_1024.public_numbers.y,
),
(
DSA_KEY_2048.public_numbers.parameter_numbers.p,
2**250,
DSA_KEY_2048.public_numbers.parameter_numbers.g,
DSA_KEY_2048.public_numbers.y,
),
(
DSA_KEY_3072.public_numbers.parameter_numbers.p,
2**260,
DSA_KEY_3072.public_numbers.parameter_numbers.g,
DSA_KEY_3072.public_numbers.y,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
0,
DSA_KEY_1024.public_numbers.y,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
1,
DSA_KEY_1024.public_numbers.y,
),
(
DSA_KEY_1024.public_numbers.parameter_numbers.p,
DSA_KEY_1024.public_numbers.parameter_numbers.q,
2**1200,
DSA_KEY_1024.public_numbers.y,
),
],
)
def test_invalid_dsa_public_key_arguments(self, p, q, g, y, backend):
with pytest.raises(ValueError):
dsa.DSAPublicNumbers(
parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g), y=y
).public_key(backend)
def test_large_p(self, backend):
key = load_vectors_from_file(
os.path.join("asymmetric", "PEM_Serialization", "dsa_4096.pem"),
lambda pemfile: serialization.load_pem_private_key(
pemfile.read(), None, backend
),
mode="rb",
)
assert isinstance(key, dsa.DSAPrivateKey)
pn = key.private_numbers()
assert pn.public_numbers.parameter_numbers.p.bit_length() == 4096
# Turn it back into a key to confirm that values this large pass
# verification
dsa.DSAPrivateNumbers(
public_numbers=dsa.DSAPublicNumbers(
parameter_numbers=dsa.DSAParameterNumbers(
p=pn.public_numbers.parameter_numbers.p,
q=pn.public_numbers.parameter_numbers.q,
g=pn.public_numbers.parameter_numbers.g,
),
y=pn.public_numbers.y,
),
x=pn.x,
).private_key(backend)
def test_public_key_equality(self, backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None).public_key()
key2 = serialization.load_pem_private_key(key_bytes, None).public_key()
key3 = DSA_KEY_2048.private_key().public_key()
assert key1 == key2
assert key1 != key3
assert key1 != object()
with pytest.raises(TypeError):
key1 < key2 # type: ignore[operator]
def test_public_key_copy(self):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None).public_key()
key2 = copy.copy(key1)
assert key1 == key2
def test_public_key_deepcopy(self):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None).public_key()
key2 = copy.deepcopy(key1)
assert key1 == key2
key_bytes = load_vectors_from_file(
os.path.join(
"asymmetric",
"Traditional_OpenSSL_Serialization",
"dsa.1024.pem",
),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None).public_key()
assert key1 != key2
def test_private_key_copy(self):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None)
key2 = copy.copy(key1)
assert key1 == key2
def test_private_key_deepcopy(self):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None)
key2 = copy.deepcopy(key1)
assert key1 == key2
key_bytes = load_vectors_from_file(
os.path.join(
"asymmetric",
"Traditional_OpenSSL_Serialization",
"dsa.1024.pem",
),
lambda pemfile: pemfile.read().encode(),
)
key1 = serialization.load_pem_private_key(key_bytes, None)
assert key1 != key2
@pytest.mark.supported(
only_if=lambda backend: backend.dsa_supported(),
skip_message="Does not support DSA.",
)
| TestDSA |
python | crytic__slither | slither/detectors/source/rtlo.py | {
"start": 238,
"end": 3472
} | class ____(AbstractDetector):
"""
Detect the usage of a Right-To-Left-Override (U+202E) character
"""
ARGUMENT = "rtlo"
HELP = "Right-To-Left-Override control character is used"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#right-to-left-override-character"
WIKI_TITLE = "Right-to-Left-Override character"
WIKI_DESCRIPTION = "An attacker can manipulate the logic of the contract by using a right-to-left-override character (`U+202E)`."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract Token
{
address payable o; // owner
mapping(address => uint) tokens;
function withdraw() external returns(uint)
{
uint amount = tokens[msg.sender];
address payable d = msg.sender;
tokens[msg.sender] = 0;
_withdraw(/*owner/*noitanitsed*/ d, o/*
/*value */, amount);
}
function _withdraw(address payable fee_receiver, address payable destination, uint value) internal
{
fee_receiver.transfer(1);
destination.transfer(value);
}
}
```
`Token` uses the right-to-left-override character when calling `_withdraw`. As a result, the fee is incorrectly sent to `msg.sender`, and the token balance is sent to the owner.
"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Special control characters must not be allowed."
RTLO_CHARACTER_ENCODED = "\u202e".encode("utf8")
STANDARD_JSON = False
def _detect(self) -> List[Output]:
results = []
pattern = re.compile(".*\u202e.*".encode("utf8"))
for filename, source in self.slither.source_code.items():
# Attempt to find all RTLO characters in this source file.
original_source_encoded = source.encode("utf8")
start_index = 0
# Keep searching all file contents for the character.
while True:
source_encoded = original_source_encoded[start_index:]
result_index = source_encoded.find(self.RTLO_CHARACTER_ENCODED)
# If we couldn't find the character in the remainder of source, stop.
if result_index == -1:
break
# We found another instance of the character, define our output
idx = start_index + result_index
relative = self.slither.crytic_compile.filename_lookup(filename).relative
info: DETECTOR_INFO = f"{relative} contains a unicode right-to-left-override character at byte offset {idx}:\n"
# We have a patch, so pattern.find will return at least one result
info += f"\t- {pattern.findall(source_encoded)[0]}\n"
res = self.generate_result(info)
res.add_other(
"rtlo-character",
(filename, idx, len(self.RTLO_CHARACTER_ENCODED)),
self.compilation_unit,
)
results.append(res)
# Advance the start index for the next iteration
start_index = idx + 1
return results
| RightToLeftOverride |
python | huggingface__transformers | tests/utils/test_generic.py | {
"start": 1119,
"end": 5707
} | class ____(unittest.TestCase):
def test_flatten_dict(self):
input_dict = {
"task_specific_params": {
"summarization": {"length_penalty": 1.0, "max_length": 128, "min_length": 12, "num_beams": 4},
"summarization_cnn": {"length_penalty": 2.0, "max_length": 142, "min_length": 56, "num_beams": 4},
"summarization_xsum": {"length_penalty": 1.0, "max_length": 62, "min_length": 11, "num_beams": 6},
}
}
expected_dict = {
"task_specific_params.summarization.length_penalty": 1.0,
"task_specific_params.summarization.max_length": 128,
"task_specific_params.summarization.min_length": 12,
"task_specific_params.summarization.num_beams": 4,
"task_specific_params.summarization_cnn.length_penalty": 2.0,
"task_specific_params.summarization_cnn.max_length": 142,
"task_specific_params.summarization_cnn.min_length": 56,
"task_specific_params.summarization_cnn.num_beams": 4,
"task_specific_params.summarization_xsum.length_penalty": 1.0,
"task_specific_params.summarization_xsum.max_length": 62,
"task_specific_params.summarization_xsum.min_length": 11,
"task_specific_params.summarization_xsum.num_beams": 6,
}
self.assertEqual(flatten_dict(input_dict), expected_dict)
def test_transpose_numpy(self):
x = np.random.randn(3, 4)
self.assertTrue(np.allclose(transpose(x), x.transpose()))
x = np.random.randn(3, 4, 5)
self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), x.transpose((1, 2, 0))))
@require_torch
def test_transpose_torch(self):
x = np.random.randn(3, 4)
t = torch.tensor(x)
self.assertTrue(np.allclose(transpose(x), transpose(t).numpy()))
x = np.random.randn(3, 4, 5)
t = torch.tensor(x)
self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), transpose(t, axes=(1, 2, 0)).numpy()))
@require_torch
def test_reshape_torch(self):
x = np.random.randn(3, 4)
t = torch.tensor(x)
self.assertTrue(np.allclose(reshape(x, (4, 3)), reshape(t, (4, 3)).numpy()))
x = np.random.randn(3, 4, 5)
t = torch.tensor(x)
self.assertTrue(np.allclose(reshape(x, (12, 5)), reshape(t, (12, 5)).numpy()))
@require_torch
def test_squeeze_torch(self):
x = np.random.randn(1, 3, 4)
t = torch.tensor(x)
self.assertTrue(np.allclose(squeeze(x), squeeze(t).numpy()))
x = np.random.randn(1, 4, 1, 5)
t = torch.tensor(x)
self.assertTrue(np.allclose(squeeze(x, axis=2), squeeze(t, axis=2).numpy()))
def test_expand_dims_numpy(self):
x = np.random.randn(3, 4)
self.assertTrue(np.allclose(expand_dims(x, axis=1), np.expand_dims(x, axis=1)))
@require_torch
def test_expand_dims_torch(self):
x = np.random.randn(3, 4)
t = torch.tensor(x)
self.assertTrue(np.allclose(expand_dims(x, axis=1), expand_dims(t, axis=1).numpy()))
def test_to_py_obj_native(self):
self.assertTrue(to_py_obj(1) == 1)
self.assertTrue(to_py_obj([1, 2, 3]) == [1, 2, 3])
self.assertTrue(to_py_obj([((1.0, 1.1), 1.2), (2, 3)]) == [[[1.0, 1.1], 1.2], [2, 3]])
def test_to_py_obj_numpy(self):
x1 = [[1, 2, 3], [4, 5, 6]]
t1 = np.array(x1)
self.assertTrue(to_py_obj(t1) == x1)
x2 = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
t2 = np.array(x2)
self.assertTrue(to_py_obj(t2) == x2)
self.assertTrue(to_py_obj([t1, t2]) == [x1, x2])
@require_torch
def test_to_py_obj_torch(self):
x1 = [[1, 2, 3], [4, 5, 6]]
t1 = torch.tensor(x1)
self.assertTrue(to_py_obj(t1) == x1)
x2 = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
t2 = torch.tensor(x2)
self.assertTrue(to_py_obj(t2) == x2)
self.assertTrue(to_py_obj([t1, t2]) == [x1, x2])
def test_model_output_subclass(self):
# testing with “dict-like init” case
out = CausalLMOutputWithPast({"logits": torch.ones(2, 3, 4)})
self.assertTrue(out["logits"] is not None)
self.assertTrue(out.loss is None)
self.assertTrue(len(out.to_tuple()) == 1)
# testing with dataclass init case
out = CausalLMOutputWithPast(logits=torch.ones(2, 3, 4))
self.assertTrue(out["logits"] is not None)
self.assertTrue(out.loss is None)
self.assertTrue(len(out.to_tuple()) == 1)
| GenericTester |
python | arrow-py__arrow | arrow/locales.py | {
"start": 1519,
"end": 8005
} | class ____:
"""Represents locale-specific data and functionality."""
names: ClassVar[List[str]] = []
timeframes: ClassVar[Mapping[TimeFrameLiteral, _TimeFrameElements]] = {
"now": "",
"second": "",
"seconds": "",
"minute": "",
"minutes": "",
"hour": "",
"hours": "",
"day": "",
"days": "",
"week": "",
"weeks": "",
"month": "",
"months": "",
"quarter": "",
"quarters": "",
"year": "",
"years": "",
}
meridians: ClassVar[Dict[str, str]] = {"am": "", "pm": "", "AM": "", "PM": ""}
past: ClassVar[str]
future: ClassVar[str]
and_word: ClassVar[Optional[str]] = None
month_names: ClassVar[List[str]] = []
month_abbreviations: ClassVar[List[str]] = []
day_names: ClassVar[List[str]] = []
day_abbreviations: ClassVar[List[str]] = []
ordinal_day_re: ClassVar[str] = r"(\d+)"
_month_name_to_ordinal: Optional[Dict[str, int]]
def __init_subclass__(cls, **kwargs: Any) -> None:
for locale_name in cls.names:
if locale_name in _locale_map:
raise LookupError(f"Duplicated locale name: {locale_name}")
_locale_map[locale_name.lower().replace("_", "-")] = cls
def __init__(self) -> None:
self._month_name_to_ordinal = None
def describe(
self,
timeframe: TimeFrameLiteral,
delta: Union[float, int] = 0,
only_distance: bool = False,
) -> str:
"""Describes a delta within a timeframe in plain language.
:param timeframe: a string representing a timeframe.
:param delta: a quantity representing a delta in a timeframe.
:param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords
"""
humanized = self._format_timeframe(timeframe, trunc(delta))
if not only_distance:
humanized = self._format_relative(humanized, timeframe, delta)
return humanized
def describe_multi(
self,
timeframes: Sequence[Tuple[TimeFrameLiteral, Union[int, float]]],
only_distance: bool = False,
) -> str:
"""Describes a delta within multiple timeframes in plain language.
:param timeframes: a list of string, quantity pairs each representing a timeframe and delta.
:param only_distance: return only distance eg: "2 hours and 11 seconds" without "in" or "ago" keywords
"""
parts = [
self._format_timeframe(timeframe, trunc(delta))
for timeframe, delta in timeframes
]
if self.and_word:
parts.insert(-1, self.and_word)
humanized = " ".join(parts)
if not only_distance:
# Needed to determine the correct relative string to use
timeframe_value = 0
for _, unit_value in timeframes:
if trunc(unit_value) != 0:
timeframe_value = trunc(unit_value)
break
# Note it doesn't matter the timeframe unit we use on the call, only the value
humanized = self._format_relative(humanized, "seconds", timeframe_value)
return humanized
def day_name(self, day: int) -> str:
"""Returns the day name for a specified day of the week.
:param day: the ``int`` day of the week (1-7).
"""
return self.day_names[day]
def day_abbreviation(self, day: int) -> str:
"""Returns the day abbreviation for a specified day of the week.
:param day: the ``int`` day of the week (1-7).
"""
return self.day_abbreviations[day]
def month_name(self, month: int) -> str:
"""Returns the month name for a specified month of the year.
:param month: the ``int`` month of the year (1-12).
"""
return self.month_names[month]
def month_abbreviation(self, month: int) -> str:
"""Returns the month abbreviation for a specified month of the year.
:param month: the ``int`` month of the year (1-12).
"""
return self.month_abbreviations[month]
def month_number(self, name: str) -> Optional[int]:
"""Returns the month number for a month specified by name or abbreviation.
:param name: the month name or abbreviation.
"""
if self._month_name_to_ordinal is None:
self._month_name_to_ordinal = self._name_to_ordinal(self.month_names)
self._month_name_to_ordinal.update(
self._name_to_ordinal(self.month_abbreviations)
)
return self._month_name_to_ordinal.get(name)
def year_full(self, year: int) -> str:
"""Returns the year for specific locale if available
:param year: the ``int`` year (4-digit)
"""
return f"{year:04d}"
def year_abbreviation(self, year: int) -> str:
"""Returns the year for specific locale if available
:param year: the ``int`` year (4-digit)
"""
return f"{year:04d}"[2:]
def meridian(self, hour: int, token: Any) -> Optional[str]:
"""Returns the meridian indicator for a specified hour and format token.
:param hour: the ``int`` hour of the day.
:param token: the format token.
"""
if token == "a":
return self.meridians["am"] if hour < 12 else self.meridians["pm"]
if token == "A":
return self.meridians["AM"] if hour < 12 else self.meridians["PM"]
return None
def ordinal_number(self, n: int) -> str:
"""Returns the ordinal format of a given integer
:param n: an integer
"""
return self._ordinal_number(n)
def _ordinal_number(self, n: int) -> str:
return f"{n}"
def _name_to_ordinal(self, lst: Sequence[str]) -> Dict[str, int]:
return {elem.lower(): i for i, elem in enumerate(lst[1:], 1)}
def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str:
# TODO: remove cast
return cast(str, self.timeframes[timeframe]).format(trunc(abs(delta)))
def _format_relative(
self,
humanized: str,
timeframe: TimeFrameLiteral,
delta: Union[float, int],
) -> str:
if timeframe == "now":
return humanized
direction = self.past if delta < 0 else self.future
return direction.format(humanized)
| Locale |
python | astropy__astropy | astropy/cosmology/_src/tests/io/test_latex.py | {
"start": 2788,
"end": 3639
} | class ____(ReadWriteDirectTestBase, WriteLATEXTestMixin):
"""
Directly test ``write_latex``.
These are not public API and are discouraged from use, in favor of
``Cosmology.write(..., format="latex")``, but should be
tested regardless b/c they are used internally.
"""
def setup_class(self):
self.functions = {"write": write_latex}
def test_rename_direct_latex_columns(self, write, tmp_path):
"""Tests renaming columns"""
fp = tmp_path / "test_rename_latex_columns.tex"
write(fp, latex_names=True)
tbl = QTable.read(fp)
# asserts each column name has not been reverted yet
for column_name in tbl.colnames[2:]:
# for now, Cosmology as metadata and name is stored in first 2 slots
assert column_name in _FORMAT_TABLE.values()
| TestReadWriteLaTex |
python | apache__airflow | airflow-core/src/airflow/models/hitl.py | {
"start": 2684,
"end": 4298
} | class ____:
"""The property part of HITLDetail and HITLDetailHistory."""
responded_at: datetime | None
responded_by: dict[str, Any] | None
assignees: list[dict[str, str]] | None
@hybrid_property
def response_received(self) -> bool:
return self.responded_at is not None
@response_received.expression # type: ignore[no-redef]
def response_received(cls):
return cls.responded_at.is_not(None)
@hybrid_property
def responded_by_user_id(self) -> str | None:
return self.responded_by["id"] if self.responded_by else None
@responded_by_user_id.expression # type: ignore[no-redef]
def responded_by_user_id(cls):
return JSONExtract(cls.responded_by, "id")
@hybrid_property
def responded_by_user_name(self) -> str | None:
return self.responded_by["name"] if self.responded_by else None
@responded_by_user_name.expression # type: ignore[no-redef]
def responded_by_user_name(cls):
return JSONExtract(cls.responded_by, "name")
@hybrid_property
def assigned_users(self) -> list[HITLUser]:
if not self.assignees:
return []
return [
HITLUser(
id=assignee["id"],
name=assignee["name"],
)
for assignee in self.assignees
]
@hybrid_property
def responded_by_user(self) -> HITLUser | None:
if self.responded_by is None:
return None
return HITLUser(
id=self.responded_by["id"],
name=self.responded_by["name"],
)
| HITLDetailPropertyMixin |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_artifacts/client.py | {
"start": 730,
"end": 1046
} | class ____(TypedDict, total=False):
flow_run_filter: Annotated[Optional["FlowRunFilter"], Field(default=None)]
task_run_filter: Annotated[Optional["TaskRunFilter"], Field(default=None)]
limit: Annotated[Optional[int], Field(default=None)]
offset: Annotated[int, Field(default=0)]
| BaseArtifactReadParams |
python | getsentry__sentry | src/sentry/spans/buffer.py | {
"start": 5860,
"end": 5920
} | class ____(NamedTuple):
payload: dict[str, Any]
| OutputSpan |
python | python__mypy | mypyc/irbuild/targets.py | {
"start": 1969,
"end": 2313
} | class ____(AssignmentTarget):
"""x, ..., y as assignment target"""
def __init__(self, items: list[AssignmentTarget], star_idx: int | None = None) -> None:
self.items = items
self.star_idx = star_idx
def __repr__(self) -> str:
return f"AssignmentTargetTuple({self.items}, {self.star_idx})"
| AssignmentTargetTuple |
python | plotly__plotly.py | plotly/graph_objs/icicle/legendgrouptitle/_font.py | {
"start": 233,
"end": 9921
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle.legendgrouptitle"
_path_str = "icicle.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
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 family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this legend group's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.icicle.legendgrouptitle.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
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.icicle.legendgrouptitle.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.icicle.legendgrouptitle.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | PrefectHQ__prefect | src/prefect/utilities/visualization.py | {
"start": 448,
"end": 524
} | class ____:
current: Optional["TaskVizTracker"] = None
| TaskVizTrackerState |
python | PyCQA__pylint | tests/functional/s/signature_differs.py | {
"start": 236,
"end": 421
} | class ____(Abcd):
def __init__(self, aaa):
Abcd.__init__(self)
self.aaa = aaa
def abcd(self, aaa, bbbb=None): # [signature-differs]
return aaa, bbbb
| Cdef |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 34167,
"end": 34835
} | class ____(Structure):
_fields_ = (("offset", p_uint32), ("length", p_uint32), ("kind", p_uint32))
def describe(self):
return {"offset": self.offset, "length": self.length, "kind": self.kind}
DICE_KIND_DATA = 0x0001
DICE_KIND_JUMP_TABLE8 = 0x0002
DICE_KIND_JUMP_TABLE16 = 0x0003
DICE_KIND_JUMP_TABLE32 = 0x0004
DICE_KIND_ABS_JUMP_TABLE32 = 0x0005
DATA_IN_CODE_KINDS = {
DICE_KIND_DATA: "DICE_KIND_DATA",
DICE_KIND_JUMP_TABLE8: "DICE_KIND_JUMP_TABLE8",
DICE_KIND_JUMP_TABLE16: "DICE_KIND_JUMP_TABLE16",
DICE_KIND_JUMP_TABLE32: "DICE_KIND_JUMP_TABLE32",
DICE_KIND_ABS_JUMP_TABLE32: "DICE_KIND_ABS_JUMP_TABLE32",
}
| data_in_code_entry |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 47107,
"end": 47900
} | class ____(PrefectFilterBaseModel):
"""Filter by `Log.level`."""
ge_: Optional[int] = Field(
default=None,
description="Include logs with a level greater than or equal to this level",
examples=[20],
)
le_: Optional[int] = Field(
default=None,
description="Include logs with a level less than or equal to this level",
examples=[50],
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
filters: list[sa.ColumnExpressionArgument[bool]] = []
if self.ge_ is not None:
filters.append(db.Log.level >= self.ge_)
if self.le_ is not None:
filters.append(db.Log.level <= self.le_)
return filters
| LogFilterLevel |
python | kamyu104__LeetCode-Solutions | Python/maximum-product-of-first-and-last-elements-of-a-subsequence.py | {
"start": 60,
"end": 481
} | class ____(object):
def maximumProduct(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
result = mx = float("-inf")
mn = float("inf")
for i in xrange(len(nums)-(m-1)):
mx = max(mx, nums[i])
mn = min(mn, nums[i])
result = max(result, nums[i+(m-1)]*mx, nums[i+(m-1)]*mn)
return result
| Solution |
python | catalyst-team__catalyst | catalyst/contrib/data/transforms.py | {
"start": 3491,
"end": 4920
} | class ____(object):
"""Normalize a tensor image with mean and standard deviation.
Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])``
for ``n`` channels, this transform will normalize each channel of the input
``torch.*Tensor`` i.e.,
``output[channel] = (input[channel] - mean[channel]) / std[channel]``
.. note::
This transform acts out of place, i.e.,
it does not mutate the input tensor.
"""
def __init__(self, mean, std, inplace=False):
"""
Args:
mean: Sequence of means for each channel.
std: Sequence of standard deviations for each channel.
inplace(bool,optional): Bool to make this operation in-place.
"""
self.mean = mean
self.std = std
self.inplace = inplace
def __call__(self, tensor):
"""
Args:
tensor: Tensor image of size (C, H, W) to be normalized.
Returns:
torch.Tensor: Normalized Tensor image.
"""
return normalize_image(tensor, self.mean, self.std, self.inplace)
def __repr__(self):
"""@TODO: Docs. Contribution is welcome."""
return self.__class__.__name__ + "(mean={0}, std={1})".format(
self.mean, self.std
)
__all__ = [
"Compose",
"NormalizeImage",
"ImageToTensor",
"image_to_tensor",
"normalize_image",
]
| NormalizeImage |
python | explosion__spaCy | spacy/util.py | {
"start": 4338,
"end": 4404
} | class ____:
CONFIG_OVERRIDES = "SPACY_CONFIG_OVERRIDES"
| ENV_VARS |
python | matplotlib__matplotlib | galleries/examples/units/basic_units.py | {
"start": 1436,
"end": 1970
} | class ____(PassThroughProxy):
def __init__(self, fn_name, obj):
super().__init__(fn_name, obj)
self.unit = obj.unit
def __call__(self, *args):
converted_args = []
for a in args:
try:
converted_args.append(a.convert_to(self.unit))
except AttributeError:
converted_args.append(TaggedValue(a, self.unit))
converted_args = tuple([c.get_value() for c in converted_args])
return super().__call__(*converted_args)
| ConvertArgsProxy |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 9940,
"end": 10075
} | class ____(_ConfigUpdateModel):
autoTenantCreation: Optional[bool]
autoTenantActivation: Optional[bool]
| _MultiTenancyConfigUpdate |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 201715,
"end": 208097
} | class ____(VegaLiteSchema):
"""
BrushConfig schema wrapper.
Parameters
----------
cursor : :class:`Cursor`, Literal['auto', 'default', 'none', 'context-menu', 'help', 'pointer', 'progress', 'wait', 'cell', 'crosshair', 'text', 'vertical-text', 'alias', 'copy', 'move', 'no-drop', 'not-allowed', 'e-resize', 'n-resize', 'ne-resize', 'nw-resize', 's-resize', 'se-resize', 'sw-resize', 'w-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'col-resize', 'row-resize', 'all-scroll', 'zoom-in', 'zoom-out', 'grab', 'grabbing']
The mouse cursor used over the interval mark. Any valid `CSS cursor type
<https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values>`__ can be used.
fill : str, :class:`Color`, :class:`HexColor`, :class:`ColorName`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple']
The fill color of the interval mark.
**Default value:** ``"#333333"``
fillOpacity : float
The fill opacity of the interval mark (a value between ``0`` and ``1``).
**Default value:** ``0.125``
stroke : str, :class:`Color`, :class:`HexColor`, :class:`ColorName`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple']
The stroke color of the interval mark.
**Default value:** ``"#ffffff"``
strokeDash : Sequence[float]
An array of alternating stroke and space lengths, for creating dashed or dotted
lines.
strokeDashOffset : float
The offset (in pixels) with which to begin drawing the stroke dash array.
strokeOpacity : float
The stroke opacity of the interval mark (a value between ``0`` and ``1``).
strokeWidth : float
The stroke width of the interval mark.
"""
_schema = {"$ref": "#/definitions/BrushConfig"}
def __init__(
self,
cursor: Optional[SchemaBase | Cursor_T] = Undefined,
fill: Optional[str | SchemaBase | ColorName_T] = Undefined,
fillOpacity: Optional[float] = Undefined,
stroke: Optional[str | SchemaBase | ColorName_T] = Undefined,
strokeDash: Optional[Sequence[float]] = Undefined,
strokeDashOffset: Optional[float] = Undefined,
strokeOpacity: Optional[float] = Undefined,
strokeWidth: Optional[float] = Undefined,
**kwds,
):
super().__init__(
cursor=cursor,
fill=fill,
fillOpacity=fillOpacity,
stroke=stroke,
strokeDash=strokeDash,
strokeDashOffset=strokeDashOffset,
strokeOpacity=strokeOpacity,
strokeWidth=strokeWidth,
**kwds,
)
| BrushConfig |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 73692,
"end": 75803
} | class ____(__TestCase):
def test_cube(self):
g = cube(3) # vert --> {v1, v2, v3}
vertices1 = set(g)
self.assertEqual(len(vertices1), 8) # eight vertices
for edge in g.values():
self.assertEqual(len(edge), 3) # each vertex connects to three edges
vertices2 = set(v for edges in g.values() for v in edges)
self.assertEqual(vertices1, vertices2) # edge vertices in original set
cubefaces = faces(g)
self.assertEqual(len(cubefaces), 6) # six faces
for face in cubefaces:
self.assertEqual(len(face), 4) # each face is a square
def test_cuboctahedron(self):
# http://en.wikipedia.org/wiki/Cuboctahedron
# 8 triangular faces and 6 square faces
# 12 identical vertices each connecting a triangle and square
g = cube(3)
cuboctahedron = linegraph(g) # V( --> {V1, V2, V3, V4}
self.assertEqual(len(cuboctahedron), 12)# twelve vertices
vertices = set(cuboctahedron)
for edges in cuboctahedron.values():
self.assertEqual(len(edges), 4) # each vertex connects to four other vertices
othervertices = set(edge for edges in cuboctahedron.values() for edge in edges)
self.assertEqual(vertices, othervertices) # edge vertices in original set
cubofaces = faces(cuboctahedron)
facesizes = collections.defaultdict(int)
for face in cubofaces:
facesizes[len(face)] += 1
self.assertEqual(facesizes[3], 8) # eight triangular faces
self.assertEqual(facesizes[4], 6) # six square faces
for vertex in cuboctahedron:
edge = vertex # Cuboctahedron vertices are edges in Cube
self.assertEqual(len(edge), 2) # Two cube vertices define an edge
for cubevert in edge:
self.assertIn(cubevert, g)
#==============================================================================
if __name__ == "__main__":
run_tests()
| TestGraphs |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 15186,
"end": 15316
} | class ____(_TestDSTBase):
def setup_method(self):
self.rdt = int
self.dec = 6
self.type = 2
| TestDSTIIInt |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_north_carolina_zip.py | {
"start": 777,
"end": 1798
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_north_carolina_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_north_carolina_zip(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidNorthCarolinaZip |
python | viewflow__viewflow | viewflow/workflow/flow/viewset.py | {
"start": 7542,
"end": 10517
} | class ____(BaseFlowViewsMixin, BulkActionsViewsMixin, Application):
"""
Viewset includes flow as an separate App into Site.
`Cookbook sample <https://github.com/viewflow/cookbook/blob/main/workflow101/config/urls.py>`_
Usage:
.. code-block:: python
site = Site(
viewsets=[
FlowAppViewset(
ShipmentFlow,
icon="local_shipping",
viewsets=[
ShipmentCRUDViewset()
]
]
)
urlpatterns = [path("", site.urls)]
"""
menu_template_name = "viewflow/workflow/flow_menu.html"
base_template_name = "viewflow/workflow/base_page.html"
"""
Inbox
"""
inbox_view_class = views.FlowInboxListView
def get_inbox_view_kwargs(self, **kwargs):
return self.filter_kwargs(self.inbox_view_class, **kwargs)
@viewprop
def inbox_view(self):
return self.inbox_view_class.as_view(**self.get_inbox_view_kwargs())
@property
def inbox_path(self):
return path("inbox/", self.inbox_view, name="inbox")
"""
Queue
"""
queue_view_class = views.FlowQueueListView
def get_queue_view_kwargs(self, **kwargs):
return self.filter_kwargs(self.queue_view_class, **kwargs)
@viewprop
def queue_view(self):
return self.queue_view_class.as_view(**self.get_queue_view_kwargs())
@property
def queue_path(self):
return path("queue/", self.queue_view, name="queue")
"""
Archive
"""
archive_view_class = views.FlowArchiveListView
def get_archive_view_kwargs(self, **kwargs):
return self.filter_kwargs(self.archive_view_class, **kwargs)
@viewprop
def archive_view(self):
return self.archive_view_class.as_view(**self.get_archive_view_kwargs())
@property
def archive_path(self):
return path("archive/", self.archive_view, name="archive")
"""
Other staff
"""
def _get_urls(self):
own_patterns = super()._get_urls()
flow_patterns, _, _ = self._flow_class.instance.urls
self._flow_class.parent = self
self._flow_class.app_name = None
return own_patterns + flow_patterns
def _get_resolver_extra(self):
return {
"app": self,
"viewset": self,
"flow_viewset": self,
"flow": self._flow_class.instance,
}
@viewprop
def app_name(self):
return self._flow_class.instance.app_name
@viewprop
def title(self):
return self._flow_class.process_title
def get_context_data(self, request):
manager = self._flow_class.task_class._default_manager
inbox = manager.inbox([self._flow_class], request.user)
queue = manager.queue([self._flow_class], request.user)
return {
"user_inbox": inbox,
"user_queue": queue,
}
| FlowAppViewset |
python | walkccc__LeetCode | solutions/3080. Mark Elements on Array by Performing Queries/3080.py | {
"start": 0,
"end": 602
} | class ____:
def unmarkedSumArray(
self,
nums: list[int],
queries: list[list[int]],
) -> list[int]:
ans = []
marked = set()
summ = sum(nums)
minHeap = [(num, i) for i, num in enumerate(nums)]
heapq.heapify(minHeap)
for index, k in queries:
if index not in marked:
marked.add(index)
summ -= nums[index]
popped = 0
while popped < k and minHeap:
num, i = heapq.heappop(minHeap)
if i not in marked:
marked.add(i)
summ -= num
popped += 1
ans.append(summ)
return ans
| Solution |
python | celery__celery | t/unit/tasks/test_stamping.py | {
"start": 11999,
"end": 15106
} | class ____(StampingVisitor):
"""
The canvas stamping mechanism traverses the canvas automatically, so we can ride
it to traverse the canvas recursively and assert that all signatures have the correct
stamp in options["stamped_headers"]
"""
def __init__(self, visitor: StampingVisitor, subtests):
self.visitor = visitor
self.subtests = subtests
def assertion_check(self, actual_sig: Signature, expected_stamped_header: str) -> None:
if any(
[
isinstance(actual_sig, group),
isinstance(actual_sig, _chain),
isinstance(actual_sig, _chord),
]
):
with self.subtests.test(f'Check if "stamped_headers" is not in {actual_sig.options}'):
assertion_check = "stamped_headers" not in actual_sig.options
assertion_error = f"{actual_sig} should not have stamped_headers in options"
assert assertion_check, assertion_error
return
actual_stamped_headers = actual_sig.options["stamped_headers"]
with self.subtests.test(f'Check if {actual_sig}["stamped_headers"] has: {expected_stamped_header}'):
assertion_check = expected_stamped_header in actual_stamped_headers
assertion_error = (
f'{actual_sig}["stamped_headers"] {actual_stamped_headers} does '
f"not contain {expected_stamped_header}"
)
assert assertion_check, assertion_error
def on_signature(self, actual_sig: Signature, **headers) -> dict:
self.assertion_check(actual_sig, "on_signature")
return super().on_signature(actual_sig, **headers)
def on_group_start(self, actual_sig: Signature, **headers) -> dict:
self.assertion_check(actual_sig, "on_group_start")
return super().on_group_start(actual_sig, **headers)
def on_chain_start(self, actual_sig: Signature, **headers) -> dict:
self.assertion_check(actual_sig, "on_chain_start")
return super().on_chain_start(actual_sig, **headers)
def on_chord_header_start(self, actual_sig: Signature, **header) -> dict:
self.assertion_check(actual_sig, "on_chord_header_start")
if issubclass(type(actual_sig.tasks), Signature):
self.assertion_check(actual_sig.tasks, "on_chord_header_start")
return super().on_chord_header_start(actual_sig, **header)
def on_chord_body(self, actual_sig: chord, **header) -> dict:
self.assertion_check(actual_sig.body, "on_chord_body")
return super().on_chord_body(actual_sig, **header)
def on_callback(self, actual_link_sig: Signature, **header) -> dict:
self.assertion_check(actual_link_sig, "on_callback")
return super().on_callback(actual_link_sig, **header)
def on_errback(self, actual_linkerr_sig: Signature, **header) -> dict:
self.assertion_check(actual_linkerr_sig, "on_errback")
return super().on_errback(actual_linkerr_sig, **header)
def return_True(*args, **kwargs):
return True
| StampedHeadersAssertionVisitor |
python | openai__openai-python | src/openai/types/beta/assistant_stream_event.py | {
"start": 2205,
"end": 2436
} | class ____(BaseModel):
data: Run
"""
Represents an execution run on a
[thread](https://platform.openai.com/docs/api-reference/threads).
"""
event: Literal["thread.run.requires_action"]
| ThreadRunRequiresAction |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_scalarinherit.py | {
"start": 680,
"end": 1335
} | class ____(TestCase):
def test_init(self):
x = B(1.0)
assert_(str(x) == "1.0")
y = C(2.0)
assert_(str(y) == "2.0")
z = D(3.0)
assert_(str(z) == "3.0")
def test_init2(self):
x = B0(1.0)
assert_(str(x) == "1.0")
y = C0(2.0)
assert_(str(y) == "2.0")
def test_gh_15395(self):
# HasNew is the second base, so `np.float64` should have priority
x = B1(1.0)
assert_(str(x) == "1.0")
# previously caused RecursionError!?
with pytest.raises(TypeError):
B1(1.0, 2.0)
if __name__ == "__main__":
run_tests()
| TestInherit |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/ColorMapWidget.py | {
"start": 7211,
"end": 8854
} | class ____(ptree.types.ColorMapParameter):
mapType = 'range'
def __init__(self, name, opts):
self.fieldName = name
units = opts.get('units', '')
ptree.types.ColorMapParameter.__init__(self,
name=name, autoIncrementName=True, type='colormap', removable=True, renamable=True,
children=[
#dict(name="Field", type='list', value=name, limits=fields),
dict(name='Min', type='float', value=0.0, suffix=units, siPrefix=True),
dict(name='Max', type='float', value=1.0, suffix=units, siPrefix=True),
dict(name='Operation', type='list', value='Overlay', limits=['Overlay', 'Add', 'Multiply', 'Set']),
dict(name='Channels..', type='group', expanded=False, children=[
dict(name='Red', type='bool', value=True),
dict(name='Green', type='bool', value=True),
dict(name='Blue', type='bool', value=True),
dict(name='Alpha', type='bool', value=True),
]),
dict(name='Enabled', type='bool', value=True),
dict(name='NaN', type='color'),
])
def map(self, data):
data = data[self.fieldName]
scaled = fn.clip_array((data-self['Min']) / (self['Max']-self['Min']), 0, 1)
cmap = self.value()
colors = cmap.map(scaled, mode='float')
mask = np.invert(np.isfinite(data))
nanColor = self['NaN']
nanColor = nanColor.getRgbF()
colors[mask] = nanColor
return colors
| RangeColorMapItem |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_dev_tests/ai_review_tests/test_ai_review_cache.py | {
"start": 132,
"end": 2438
} | class ____:
"""Basic smoke tests for the ai-review-cache command."""
def test_import_and_basic_structure(self):
"""Test that command can be imported and has expected structure."""
from automation.dagster_dev.commands.ai_review_cache import ai_review_cache
assert ai_review_cache is not None
assert ai_review_cache.name == "ai-review-cache"
assert callable(ai_review_cache)
def test_help_command(self):
"""Test that help command works."""
from automation.dagster_dev.commands.ai_review_cache import ai_review_cache
runner = CliRunner()
result = runner.invoke(ai_review_cache, ["--help"])
assert result.exit_code == 0
assert "ai-review-cache" in result.output
assert "--action" in result.output
assert "--format" in result.output
def test_status_with_no_cache(self):
"""Test status command when cache doesn't exist."""
with patch(
"automation.dagster_dev.commands.ai_review_cache.CacheManager"
) as mock_cache_manager:
mock_instance = Mock()
mock_instance.get_cache_status.return_value = {
"exists": False,
"size_bytes": 0,
"entries": 0,
}
mock_cache_manager.return_value = mock_instance
from automation.dagster_dev.commands.ai_review_cache import ai_review_cache
runner = CliRunner()
result = runner.invoke(ai_review_cache, ["--action", "status"])
assert result.exit_code == 0
assert "No cache found" in result.output
def test_clear_command(self):
"""Test cache clear command."""
with patch(
"automation.dagster_dev.commands.ai_review_cache.CacheManager"
) as mock_cache_manager:
mock_instance = Mock()
mock_instance.clear_cache.return_value = True
mock_cache_manager.return_value = mock_instance
from automation.dagster_dev.commands.ai_review_cache import ai_review_cache
runner = CliRunner()
result = runner.invoke(ai_review_cache, ["--action", "clear"])
assert result.exit_code == 0
mock_instance.clear_cache.assert_called_once()
| TestAiReviewCache |
python | pytest-dev__pytest | src/_pytest/nodes.py | {
"start": 21481,
"end": 22075
} | class ____(FSCollector, abc.ABC):
"""Base class for collecting files from a directory.
A basic directory collector does the following: goes over the files and
sub-directories in the directory and creates collectors for them by calling
the hooks :hook:`pytest_collect_directory` and :hook:`pytest_collect_file`,
after checking that they are not ignored using
:hook:`pytest_ignore_collect`.
The default directory collectors are :class:`~pytest.Dir` and
:class:`~pytest.Package`.
.. versionadded:: 8.0
:ref:`custom directory collectors`.
"""
| Directory |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_slugs.py | {
"start": 67,
"end": 559
} | class ____(util.MdCase):
"""Test Unicode slugs."""
extension = ['markdown.extensions.toc']
extension_configs = {
'markdown.extensions.toc': {
"slugify": slugs.slugify(case="lower")
}
}
def test_slug(self):
"""Test the slug output."""
self.check_markdown(
r'# Testing unicode-slugs_headers ±♠Ωℑ',
r'<h1 id="testing-unicode-slugs_headers-ωℑ">Testing unicode-slugs_headers ±♠Ωℑ</h1>'
)
| TestUslugify |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 12850,
"end": 13284
} | class ____(Binding):
"""
Represents binding a name to a type without an associated value.
As long as this name is not assigned a value in another binding, it is considered
undefined for most purposes. One notable exception is using the name as a type
annotation.
"""
def redefines(self, other):
"""An Annotation doesn't define any name, so it cannot redefine one."""
return False
| Annotation |
python | sympy__sympy | sympy/physics/quantum/pauli.py | {
"start": 6636,
"end": 8883
} | class ____(SigmaOpBase):
"""Pauli sigma minus operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent, Dagger
>>> from sympy.physics.quantum.pauli import SigmaMinus
>>> sm = SigmaMinus()
>>> sm
SigmaMinus()
>>> Dagger(sm)
SigmaPlus()
>>> represent(sm)
Matrix([
[0, 0],
[1, 0]])
"""
is_annihilation = True
def __new__(cls, *args, **hints):
return SigmaOpBase.__new__(cls, *args)
def _eval_commutator_SigmaX(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return -SigmaZ(self.name)
def _eval_commutator_SigmaY(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return I * SigmaZ(self.name)
def _eval_commutator_SigmaZ(self, other, **hints):
return 2 * self
def _eval_commutator_SigmaMinus(self, other, **hints):
return SigmaZ(self.name)
def _eval_anticommutator_SigmaZ(self, other, **hints):
return S.Zero
def _eval_anticommutator_SigmaX(self, other, **hints):
return S.One
def _eval_anticommutator_SigmaY(self, other, **hints):
return I * S.NegativeOne
def _eval_anticommutator_SigmaPlus(self, other, **hints):
return S.One
def _eval_adjoint(self):
return SigmaPlus(self.name)
def _eval_power(self, e):
if e.is_Integer and e.is_positive:
return S.Zero
def _print_contents_latex(self, printer, *args):
if self.use_name:
return r'{\sigma_-^{(%s)}}' % str(self.name)
else:
return r'{\sigma_-}'
def _print_contents(self, printer, *args):
return 'SigmaMinus()'
def _represent_default_basis(self, **options):
format = options.get('format', 'sympy')
if format == 'sympy':
return Matrix([[0, 0], [1, 0]])
else:
raise NotImplementedError('Representation in format ' +
format + ' not implemented.')
| SigmaMinus |
python | doocs__leetcode | solution/1700-1799/1781.Sum of Beauty of All Substrings/Solution2.py | {
"start": 0,
"end": 576
} | class ____:
def beautySum(self, s: str) -> int:
ans, n = 0, len(s)
for i in range(n):
cnt = Counter()
freq = Counter()
mi = mx = 1
for j in range(i, n):
freq[cnt[s[j]]] -= 1
cnt[s[j]] += 1
freq[cnt[s[j]]] += 1
if cnt[s[j]] == 1:
mi = 1
if freq[mi] == 0:
mi += 1
if cnt[s[j]] > mx:
mx = cnt[s[j]]
ans += mx - mi
return ans
| Solution |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/relationships/fields.py | {
"start": 155,
"end": 271
} | class ____:
def __init__(self, x: P):
self.x = x # receives object, not created → Aggregation
| Aggregation1 |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 27368,
"end": 27581
} | class ____(BaseRealtimeConnectionResource):
@cached_property
def item(self) -> RealtimeConversationItemResource:
return RealtimeConversationItemResource(self._connection)
| RealtimeConversationResource |
python | huggingface__transformers | src/transformers/models/llava_next/modeling_llava_next.py | {
"start": 8551,
"end": 9522
} | class ____(nn.Module):
def __init__(self, config: LlavaNextConfig):
super().__init__()
# We have hidden_size * the number of vision feature layers
num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
self.linear_1 = nn.Linear(
config.vision_config.hidden_size * num_feature_layers,
config.text_config.hidden_size,
bias=config.multimodal_projector_bias,
)
self.act = ACT2FN[config.projector_hidden_act]
self.linear_2 = nn.Linear(
config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
)
def forward(self, image_features):
hidden_states = self.linear_1(image_features)
hidden_states = self.act(hidden_states)
hidden_states = self.linear_2(hidden_states)
return hidden_states
@auto_docstring
| LlavaNextMultiModalProjector |
python | pandas-dev__pandas | pandas/io/formats/info.py | {
"start": 23985,
"end": 27341
} | class ____(_TableBuilderAbstract):
"""
Mixin for verbose info output.
"""
SPACING: str = " " * 2
strrows: Sequence[Sequence[str]]
gross_column_widths: Sequence[int]
with_counts: bool
@property
@abstractmethod
def headers(self) -> Sequence[str]:
"""Headers names of the columns in verbose table."""
@property
def header_column_widths(self) -> Sequence[int]:
"""Widths of header columns (only titles)."""
return [len(col) for col in self.headers]
def _get_gross_column_widths(self) -> Sequence[int]:
"""Get widths of columns containing both headers and actual content."""
body_column_widths = self._get_body_column_widths()
return [
max(*widths)
for widths in zip(
self.header_column_widths, body_column_widths, strict=False
)
]
def _get_body_column_widths(self) -> Sequence[int]:
"""Get widths of table content columns."""
strcols: Sequence[Sequence[str]] = list(zip(*self.strrows, strict=True))
return [max(len(x) for x in col) for col in strcols]
def _gen_rows(self) -> Iterator[Sequence[str]]:
"""
Generator function yielding rows content.
Each element represents a row comprising a sequence of strings.
"""
if self.with_counts:
return self._gen_rows_with_counts()
else:
return self._gen_rows_without_counts()
@abstractmethod
def _gen_rows_with_counts(self) -> Iterator[Sequence[str]]:
"""Iterator with string representation of body data with counts."""
@abstractmethod
def _gen_rows_without_counts(self) -> Iterator[Sequence[str]]:
"""Iterator with string representation of body data without counts."""
def add_header_line(self) -> None:
header_line = self.SPACING.join(
[
_put_str(header, col_width)
for header, col_width in zip(
self.headers, self.gross_column_widths, strict=True
)
]
)
self._lines.append(header_line)
def add_separator_line(self) -> None:
separator_line = self.SPACING.join(
[
_put_str("-" * header_colwidth, gross_colwidth)
for header_colwidth, gross_colwidth in zip(
self.header_column_widths, self.gross_column_widths, strict=True
)
]
)
self._lines.append(separator_line)
def add_body_lines(self) -> None:
for row in self.strrows:
body_line = self.SPACING.join(
[
_put_str(col, gross_colwidth)
for col, gross_colwidth in zip(
row, self.gross_column_widths, strict=True
)
]
)
self._lines.append(body_line)
def _gen_non_null_counts(self) -> Iterator[str]:
"""Iterator with string representation of non-null counts."""
for count in self.non_null_counts:
yield f"{count} non-null"
def _gen_dtypes(self) -> Iterator[str]:
"""Iterator with string representation of column dtypes."""
for dtype in self.dtypes:
yield pprint_thing(dtype)
| _TableBuilderVerboseMixin |
python | eventlet__eventlet | eventlet/hubs/timer.py | {
"start": 279,
"end": 2554
} | class ____:
def __init__(self, seconds, cb, *args, **kw):
"""Create a timer.
seconds: The minimum number of seconds to wait before calling
cb: The callback to call when the timer has expired
*args: The arguments to pass to cb
**kw: The keyword arguments to pass to cb
This timer will not be run unless it is scheduled in a runloop by
calling timer.schedule() or runloop.add_timer(timer).
"""
self.seconds = seconds
self.tpl = cb, args, kw
self.called = False
if _g_debug:
self.traceback = io.StringIO()
traceback.print_stack(file=self.traceback)
@property
def pending(self):
return not self.called
def __repr__(self):
secs = getattr(self, 'seconds', None)
cb, args, kw = getattr(self, 'tpl', (None, None, None))
retval = "Timer(%s, %s, *%s, **%s)" % (
secs, cb, args, kw)
if _g_debug and hasattr(self, 'traceback'):
retval += '\n' + self.traceback.getvalue()
return retval
def copy(self):
cb, args, kw = self.tpl
return self.__class__(self.seconds, cb, *args, **kw)
def schedule(self):
"""Schedule this timer to run in the current runloop.
"""
self.called = False
self.scheduled_time = eventlet.hubs.get_hub().add_timer(self)
return self
def __call__(self, *args):
if not self.called:
self.called = True
cb, args, kw = self.tpl
try:
cb(*args, **kw)
finally:
try:
del self.tpl
except AttributeError:
pass
def cancel(self):
"""Prevent this timer from being called. If the timer has already
been called or canceled, has no effect.
"""
if not self.called:
self.called = True
eventlet.hubs.get_hub().timer_canceled(self)
try:
del self.tpl
except AttributeError:
pass
# No default ordering in 3.x. heapq uses <
# FIXME should full set be added?
def __lt__(self, other):
return id(self) < id(other)
| Timer |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 33115,
"end": 33292
} | class ____:
xlCalculating = 1 # from enum XlCalculationState
xlDone = 0 # from enum XlCalculationState
xlPending = 2 # from enum XlCalculationState
| CalculationState |
python | FactoryBoy__factory_boy | factory/base.py | {
"start": 23223,
"end": 23298
} | class ____(BaseDictFactory):
class Meta:
model = dict
| DictFactory |
python | getsentry__sentry | src/sentry/identity/providers/dummy.py | {
"start": 450,
"end": 759
} | class ____:
def dispatch(self, request: HttpRequest, pipeline: IdentityPipeline) -> HttpResponseBase:
if "email" in request.POST:
pipeline.bind_state("email", request.POST.get("email"))
return pipeline.next_step()
return HttpResponse(DummyProvider.TEMPLATE)
| AskEmail |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_requests/post_comment_votes_request_builder.py | {
"start": 274,
"end": 1719
} | class ____(ZendeskSupportBaseRequestBuilder):
@classmethod
def post_comment_votes_endpoint(
cls, authenticator: Authenticator, post_id: int, post_comment_id: int
) -> "PostCommentVotesRequestBuilder":
return cls("d3v-airbyte", f"community/posts/{post_id}/comments/{post_comment_id}/votes").with_authenticator(authenticator)
def __init__(self, subdomain: str, resource: str) -> None:
super().__init__(subdomain, resource)
self._start_time: int = None
self._page_size: int = None
self._page_after: str = None
@property
def query_params(self):
params = super().query_params or {}
if self._start_time:
params["start_time"] = self._start_time
if self._page_size:
params["page[size]"] = self._page_size
if self._page_after:
params["page[after]"] = self._page_after
return params
def with_start_time(self, start_time: str) -> "PostCommentVotesRequestBuilder":
self._start_time: int = calendar.timegm(ab_datetime_parse(start_time).utctimetuple())
return self
def with_page_size(self, page_size: int) -> "PostCommentVotesRequestBuilder":
self._page_size: int = page_size
return self
def with_page_after(self, next_page_token: str) -> "PostCommentVotesRequestBuilder":
self._page_after = next_page_token
return self
| PostCommentVotesRequestBuilder |
python | astropy__astropy | astropy/extern/configobj/configobj.py | {
"start": 5703,
"end": 5812
} | class ____(ConfigObjError):
"""
The keyword or section specified already exists.
"""
| DuplicateError |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 81162,
"end": 82430
} | class ____:
def test_timeframes(self):
assert self.locale._format_timeframe("hours", 2) == "2 jam"
assert self.locale._format_timeframe("months", 2) == "2 bulan"
assert self.locale._format_timeframe("days", 2) == "2 hari"
assert self.locale._format_timeframe("years", 2) == "2 tahun"
assert self.locale._format_timeframe("hours", 3) == "3 jam"
assert self.locale._format_timeframe("months", 4) == "4 bulan"
assert self.locale._format_timeframe("days", 3) == "3 hari"
assert self.locale._format_timeframe("years", 5) == "5 tahun"
assert self.locale._format_timeframe("weeks", 2) == "2 minggu"
assert self.locale._format_timeframe("quarters", 3) == "3 kuartal"
def test_format_relative_now(self):
assert self.locale._format_relative("baru saja", "now", 0) == "baru saja"
def test_format_relative_past(self):
assert self.locale._format_relative("1 jam", "hour", 1) == "dalam 1 jam"
assert self.locale._format_relative("1 detik", "seconds", 1) == "dalam 1 detik"
def test_format_relative_future(self):
assert self.locale._format_relative("1 jam", "hour", -1) == "1 jam yang lalu"
@pytest.mark.usefixtures("lang_locale")
| TestIndonesianLocale |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 10482,
"end": 16628
} | class ____(NonStrictDataModel):
"""
:param total_runtime: Total run time of all tasks in project (in seconds)
:type total_runtime: int
:param total_tasks: Number of tasks
:type total_tasks: int
:param completed_tasks_24h: Number of tasks completed in the last 24 hours
:type completed_tasks_24h: int
:param last_task_run: The most recent started time of a task
:type last_task_run: int
:param status_count: Status counts
:type status_count: dict
"""
_schema = {
"properties": {
"completed_tasks_24h": {
"description": "Number of tasks completed in the last 24 hours",
"type": ["integer", "null"],
},
"last_task_run": {
"description": "The most recent started time of a task",
"type": ["integer", "null"],
},
"status_count": {
"description": "Status counts",
"properties": {
"closed": {
"description": "Number of 'closed' tasks in project",
"type": "integer",
},
"completed": {
"description": "Number of 'completed' tasks in project",
"type": "integer",
},
"created": {
"description": "Number of 'created' tasks in project",
"type": "integer",
},
"failed": {
"description": "Number of 'failed' tasks in project",
"type": "integer",
},
"in_progress": {
"description": "Number of 'in_progress' tasks in project",
"type": "integer",
},
"published": {
"description": "Number of 'published' tasks in project",
"type": "integer",
},
"queued": {
"description": "Number of 'queued' tasks in project",
"type": "integer",
},
"stopped": {
"description": "Number of 'stopped' tasks in project",
"type": "integer",
},
"unknown": {
"description": "Number of 'unknown' tasks in project",
"type": "integer",
},
},
"type": ["object", "null"],
},
"total_runtime": {
"description": "Total run time of all tasks in project (in seconds)",
"type": ["integer", "null"],
},
"total_tasks": {
"description": "Number of tasks",
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(
self,
total_runtime: Optional[int] = None,
total_tasks: Optional[int] = None,
completed_tasks_24h: Optional[int] = None,
last_task_run: Optional[int] = None,
status_count: Optional[dict] = None,
**kwargs: Any
) -> None:
super(StatsStatusCount, self).__init__(**kwargs)
self.total_runtime = total_runtime
self.total_tasks = total_tasks
self.completed_tasks_24h = completed_tasks_24h
self.last_task_run = last_task_run
self.status_count = status_count
@schema_property("total_runtime")
def total_runtime(self) -> Optional[int]:
return self._property_total_runtime
@total_runtime.setter
def total_runtime(self, value: Optional[int]) -> None:
if value is None:
self._property_total_runtime = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "total_runtime", six.integer_types)
self._property_total_runtime = value
@schema_property("total_tasks")
def total_tasks(self) -> Optional[int]:
return self._property_total_tasks
@total_tasks.setter
def total_tasks(self, value: Optional[int]) -> None:
if value is None:
self._property_total_tasks = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "total_tasks", six.integer_types)
self._property_total_tasks = value
@schema_property("completed_tasks_24h")
def completed_tasks_24h(self) -> Optional[int]:
return self._property_completed_tasks_24h
@completed_tasks_24h.setter
def completed_tasks_24h(self, value: Optional[int]) -> None:
if value is None:
self._property_completed_tasks_24h = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "completed_tasks_24h", six.integer_types)
self._property_completed_tasks_24h = value
@schema_property("last_task_run")
def last_task_run(self) -> Optional[int]:
return self._property_last_task_run
@last_task_run.setter
def last_task_run(self, value: Optional[int]) -> None:
if value is None:
self._property_last_task_run = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "last_task_run", six.integer_types)
self._property_last_task_run = value
@schema_property("status_count")
def status_count(self) -> Optional[dict]:
return self._property_status_count
@status_count.setter
def status_count(self, value: Optional[dict]) -> None:
if value is None:
self._property_status_count = None
return
self.assert_isinstance(value, "status_count", (dict,))
self._property_status_count = value
| StatsStatusCount |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 83871,
"end": 84480
} | class ____(SimpleHandlerTestCase):
class Handler(RequestHandler):
SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ( # type: ignore
"OTHER",
)
def patch(self):
self.write("patch")
def other(self):
self.write("other")
def test_patch(self):
response = self.fetch("/", method="PATCH", body=b"")
self.assertEqual(response.body, b"patch")
def test_other(self):
response = self.fetch("/", method="OTHER", allow_nonstandard_methods=True)
self.assertEqual(response.body, b"other")
| PatchMethodTest |
python | automl__auto-sklearn | autosklearn/experimental/selector.py | {
"start": 12783,
"end": 13554
} | class ____(OneVSOneSelector):
def __init__(self, n_estimators, **kwargs):
super().__init__(**kwargs)
self.n_estimators = n_estimators
def fit_pairwise_model(self, X, y, weights, rng, configuration):
base_model = sklearn.ensemble.RandomForestClassifier(
random_state=rng,
n_estimators=self.n_estimators,
bootstrap=True if configuration["bootstrap"] == "True" else False,
min_samples_split=configuration["min_samples_split"],
min_samples_leaf=configuration["min_samples_leaf"],
max_features=int(configuration["max_features"]),
max_depth=configuration["max_depth"],
)
base_model.fit(X, y, sample_weight=weights)
return base_model
| OVORF |
python | huggingface__transformers | src/transformers/models/led/modeling_led.py | {
"start": 3502,
"end": 32128
} | class ____(nn.Module):
def __init__(self, config, layer_id):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.num_heads = config.num_attention_heads
self.head_dim = int(config.hidden_size / config.num_attention_heads)
self.embed_dim = config.hidden_size
self.query = nn.Linear(config.hidden_size, self.embed_dim)
self.key = nn.Linear(config.hidden_size, self.embed_dim)
self.value = nn.Linear(config.hidden_size, self.embed_dim)
# separate projection layers for tokens with global attention
self.query_global = nn.Linear(config.hidden_size, self.embed_dim)
self.key_global = nn.Linear(config.hidden_size, self.embed_dim)
self.value_global = nn.Linear(config.hidden_size, self.embed_dim)
self.dropout = config.attention_probs_dropout_prob
self.layer_id = layer_id
attention_window = config.attention_window[self.layer_id]
assert attention_window % 2 == 0, (
f"`attention_window` for layer {self.layer_id} has to be an even value. Given {attention_window}"
)
assert attention_window > 0, (
f"`attention_window` for layer {self.layer_id} has to be positive. Given {attention_window}"
)
self.one_sided_attn_window_size = attention_window // 2
self.config = config
def forward(
self,
hidden_states,
attention_mask=None,
is_index_masked=None,
is_index_global_attn=None,
is_global_attn=None,
output_attentions=False,
):
"""
[`LEDEncoderSelfAttention`] expects *len(hidden_states)* to be multiple of *attention_window*. Padding to
*attention_window* happens in [`LEDEncoderModel.forward`] to avoid redoing the padding on each layer.
The *attention_mask* is changed in [`LEDEncoderModel.forward`] from 0, 1, 2 to:
- -10000: no attention
- 0: local attention
- +10000: global attention
"""
hidden_states = hidden_states.transpose(0, 1)
# project hidden states
query_vectors = self.query(hidden_states)
key_vectors = self.key(hidden_states)
value_vectors = self.value(hidden_states)
seq_len, batch_size, embed_dim = hidden_states.size()
assert embed_dim == self.embed_dim, (
f"hidden_states should have embed_dim = {self.embed_dim}, but has {embed_dim}"
)
# normalize query
query_vectors /= math.sqrt(self.head_dim)
query_vectors = query_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
key_vectors = key_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
attn_scores = self._sliding_chunks_query_key_matmul(
query_vectors, key_vectors, self.one_sided_attn_window_size
)
# values to pad for attention probs
remove_from_windowed_attention_mask = (attention_mask != 0)[:, :, None, None]
# cast to fp32/fp16 then replace 1's with -inf
float_mask = remove_from_windowed_attention_mask.type_as(query_vectors).masked_fill(
remove_from_windowed_attention_mask, torch.finfo(query_vectors.dtype).min
)
# diagonal mask with zeros everywhere and -inf inplace of padding
diagonal_mask = self._sliding_chunks_query_key_matmul(
float_mask.new_ones(size=float_mask.size()), float_mask, self.one_sided_attn_window_size
)
# pad local attention probs
attn_scores += diagonal_mask
assert list(attn_scores.size()) == [
batch_size,
seq_len,
self.num_heads,
self.one_sided_attn_window_size * 2 + 1,
], (
f"local_attn_probs should be of size ({batch_size}, {seq_len}, {self.num_heads},"
f" {self.one_sided_attn_window_size * 2 + 1}), but is of size {attn_scores.size()}"
)
# compute local attention probs from global attention keys and contact over window dim
if is_global_attn:
# compute global attn indices required through out forward fn
(
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
) = self._get_global_attn_indices(is_index_global_attn)
# calculate global attn probs from global key
global_key_attn_scores = self._concat_with_global_key_attn_probs(
query_vectors=query_vectors,
key_vectors=key_vectors,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
)
# concat to local_attn_probs
# (batch_size, seq_len, num_heads, extra attention count + 2*window+1)
attn_scores = torch.cat((global_key_attn_scores, attn_scores), dim=-1)
# free memory
del global_key_attn_scores
attn_probs = nn.functional.softmax(
attn_scores, dim=-1, dtype=torch.float32
) # use fp32 for numerical stability
# softmax sometimes inserts NaN if all positions are masked, replace them with 0
attn_probs = torch.masked_fill(attn_probs, is_index_masked[:, :, None, None], 0.0)
attn_probs = attn_probs.type_as(attn_scores)
# free memory
del attn_scores
# apply dropout
attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
value_vectors = value_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
# compute local attention output with global attention value and add
if is_global_attn:
# compute sum of global and local attn
attn_output = self._compute_attn_output_with_global_indices(
value_vectors=value_vectors,
attn_probs=attn_probs,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
)
else:
# compute local attn only
attn_output = self._sliding_chunks_matmul_attn_probs_value(
attn_probs, value_vectors, self.one_sided_attn_window_size
)
assert attn_output.size() == (batch_size, seq_len, self.num_heads, self.head_dim), "Unexpected size"
attn_output = attn_output.transpose(0, 1).reshape(seq_len, batch_size, embed_dim).contiguous()
# compute value for global attention and overwrite to attention output
# TODO: remove the redundant computation
if is_global_attn:
global_attn_output, global_attn_probs = self._compute_global_attn_output_from_hidden(
hidden_states=hidden_states,
max_num_global_attn_indices=max_num_global_attn_indices,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
is_index_masked=is_index_masked,
)
# get only non zero global attn output
nonzero_global_attn_output = global_attn_output[
is_local_index_global_attn_nonzero[0], :, is_local_index_global_attn_nonzero[1]
]
# overwrite values with global attention
attn_output[is_index_global_attn_nonzero[::-1]] = nonzero_global_attn_output.view(
len(is_local_index_global_attn_nonzero[0]), -1
)
# The attention weights for tokens with global attention are
# just filler values, they were never used to compute the output.
# Fill with 0 now, the correct values are in 'global_attn_probs'.
attn_probs[is_index_global_attn_nonzero] = 0
outputs = (attn_output.transpose(0, 1),)
if output_attentions:
outputs += (attn_probs,)
return outputs + (global_attn_probs,) if (is_global_attn and output_attentions) else outputs
@staticmethod
def _pad_and_transpose_last_two_dims(hidden_states_padded, padding):
"""pads rows and then flips rows and columns"""
hidden_states_padded = nn.functional.pad(
hidden_states_padded, padding
) # padding value is not important because it will be overwritten
hidden_states_padded = hidden_states_padded.view(
*hidden_states_padded.size()[:-2], hidden_states_padded.size(-1), hidden_states_padded.size(-2)
)
return hidden_states_padded
@staticmethod
def _pad_and_diagonalize(chunked_hidden_states):
"""
shift every row 1 step right, converting columns into diagonals.
Example:
```python
chunked_hidden_states: [
0.4983,
2.6918,
-0.0071,
1.0492,
-1.8348,
0.7672,
0.2986,
0.0285,
-0.7584,
0.4206,
-0.0405,
0.1599,
2.0514,
-1.1600,
0.5372,
0.2629,
]
window_overlap = num_rows = 4
```
(pad & diagonalize) => [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000
0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 0.0000, 0.0000, -0.7584, 0.4206,
-0.0405, 0.1599, 0.0000 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ]
"""
total_num_heads, num_chunks, window_overlap, hidden_dim = chunked_hidden_states.size()
chunked_hidden_states = nn.functional.pad(
chunked_hidden_states, (0, window_overlap + 1)
) # total_num_heads x num_chunks x window_overlap x (hidden_dim+window_overlap+1). Padding value is not important because it'll be overwritten
chunked_hidden_states = chunked_hidden_states.view(
total_num_heads, num_chunks, -1
) # total_num_heads x num_chunks x window_overlap*window_overlap+window_overlap
chunked_hidden_states = chunked_hidden_states[
:, :, :-window_overlap
] # total_num_heads x num_chunks x window_overlap*window_overlap
chunked_hidden_states = chunked_hidden_states.view(
total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim
)
chunked_hidden_states = chunked_hidden_states[:, :, :, :-1]
return chunked_hidden_states
@staticmethod
def _chunk(hidden_states, window_overlap, onnx_export: bool = False):
"""convert into overlapping chunks. Chunk size = 2w, overlap size = w"""
if not onnx_export:
# non-overlapping chunks of size = 2w
hidden_states = hidden_states.view(
hidden_states.size(0),
torch.div(hidden_states.size(1), (window_overlap * 2), rounding_mode="trunc"),
window_overlap * 2,
hidden_states.size(2),
)
# use `as_strided` to make the chunks overlap with an overlap size = window_overlap
chunk_size = list(hidden_states.size())
chunk_size[1] = chunk_size[1] * 2 - 1
chunk_stride = list(hidden_states.stride())
chunk_stride[1] = chunk_stride[1] // 2
return hidden_states.as_strided(size=chunk_size, stride=chunk_stride)
# When exporting to ONNX, use this separate logic
# have to use slow implementation since as_strided, unfold and 2d-tensor indexing aren't supported (yet) in ONNX export
# TODO replace this with
# > return hidden_states.unfold(dimension=1, size=window_overlap * 2, step=window_overlap).transpose(2, 3)
# once `unfold` is supported
# the case hidden_states.size(1) == window_overlap * 2 can also simply return hidden_states.unsqueeze(1), but that's control flow
chunk_size = [
hidden_states.size(0),
torch.div(hidden_states.size(1), window_overlap, rounding_mode="trunc") - 1,
window_overlap * 2,
hidden_states.size(2),
]
overlapping_chunks = torch.empty(chunk_size, device=hidden_states.device)
for chunk in range(chunk_size[1]):
overlapping_chunks[:, chunk, :, :] = hidden_states[
:, chunk * window_overlap : chunk * window_overlap + 2 * window_overlap, :
]
return overlapping_chunks
@staticmethod
def _mask_invalid_locations(input_tensor, affected_seq_len) -> torch.Tensor:
beginning_mask_2d = input_tensor.new_ones(affected_seq_len, affected_seq_len + 1).tril().flip(dims=[0])
beginning_mask = beginning_mask_2d[None, :, None, :]
ending_mask = beginning_mask.flip(dims=(1, 3))
beginning_input = input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1]
beginning_mask = beginning_mask.expand(beginning_input.size())
input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1] = torch.full_like(
beginning_input, -float("inf")
).where(beginning_mask.bool(), beginning_input)
ending_input = input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :]
ending_mask = ending_mask.expand(ending_input.size())
input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :] = torch.full_like(
ending_input, -float("inf")
).where(ending_mask.bool(), ending_input)
def _sliding_chunks_query_key_matmul(self, query: torch.Tensor, key: torch.Tensor, window_overlap: int):
"""
Matrix multiplication of query and key tensors using with a sliding window attention pattern. This
implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained LEDEncoder) with an
overlap of size window_overlap
"""
batch_size, seq_len, num_heads, head_dim = query.size()
assert seq_len % (window_overlap * 2) == 0, (
f"Sequence length should be multiple of {window_overlap * 2}. Given {seq_len}"
)
assert query.size() == key.size()
chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size window_overlap * 2
query = query.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
key = key.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
query = self._chunk(query, window_overlap, getattr(self.config, "onnx_export", False))
key = self._chunk(key, window_overlap, getattr(self.config, "onnx_export", False))
# matrix multiplication
# bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap
diagonal_chunked_attention_scores = torch.einsum("bcxd,bcyd->bcxy", (query, key)) # multiply
# convert diagonals into columns
diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims(
diagonal_chunked_attention_scores, padding=(0, 0, 0, 1)
)
# allocate space for the overall attention matrix where the chunks are combined. The last dimension
# has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to
# window_overlap previous words). The following column is attention score from each word to itself, then
# followed by window_overlap columns for the upper triangle.
diagonal_attention_scores = diagonal_chunked_attention_scores.new_zeros(
(batch_size * num_heads, chunks_count + 1, window_overlap, window_overlap * 2 + 1)
)
# copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions
# - copying the main diagonal and the upper triangle
diagonal_attention_scores[:, :-1, :, window_overlap:] = diagonal_chunked_attention_scores[
:, :, :window_overlap, : window_overlap + 1
]
diagonal_attention_scores[:, -1, :, window_overlap:] = diagonal_chunked_attention_scores[
:, -1, window_overlap:, : window_overlap + 1
]
# - copying the lower triangle
diagonal_attention_scores[:, 1:, :, :window_overlap] = diagonal_chunked_attention_scores[
:, :, -(window_overlap + 1) : -1, window_overlap + 1 :
]
diagonal_attention_scores[:, 0, 1:window_overlap, 1:window_overlap] = diagonal_chunked_attention_scores[
:, 0, : window_overlap - 1, 1 - window_overlap :
]
# separate batch_size and num_heads dimensions again
diagonal_attention_scores = diagonal_attention_scores.view(
batch_size, num_heads, seq_len, 2 * window_overlap + 1
).transpose(2, 1)
self._mask_invalid_locations(diagonal_attention_scores, window_overlap)
return diagonal_attention_scores
def _sliding_chunks_matmul_attn_probs_value(
self, attn_probs: torch.Tensor, value: torch.Tensor, window_overlap: int
):
"""
Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the
same shape as `attn_probs`
"""
batch_size, seq_len, num_heads, head_dim = value.size()
assert seq_len % (window_overlap * 2) == 0
assert attn_probs.size()[:3] == value.size()[:3]
assert attn_probs.size(3) == 2 * window_overlap + 1
chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap
chunked_attn_probs = attn_probs.transpose(1, 2).reshape(
batch_size * num_heads,
torch.div(seq_len, window_overlap, rounding_mode="trunc"),
window_overlap,
2 * window_overlap + 1,
)
# group batch_size and num_heads dimensions into one
value = value.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
# pad seq_len with w at the beginning of the sequence and another window overlap at the end
padded_value = nn.functional.pad(value, (0, 0, window_overlap, window_overlap), value=-1)
# chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap
chunked_value_size = (batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim)
chunked_value_stride = padded_value.stride()
chunked_value_stride = (
chunked_value_stride[0],
window_overlap * chunked_value_stride[1],
chunked_value_stride[1],
chunked_value_stride[2],
)
chunked_value = padded_value.as_strided(size=chunked_value_size, stride=chunked_value_stride)
chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs)
context = torch.einsum("bcwd,bcdh->bcwh", (chunked_attn_probs, chunked_value))
return context.view(batch_size, num_heads, seq_len, head_dim).transpose(1, 2)
@staticmethod
def _get_global_attn_indices(is_index_global_attn):
"""compute global attn indices required throughout forward pass"""
# helper variable
num_global_attn_indices = is_index_global_attn.long().sum(dim=1)
# max number of global attn indices in batch
max_num_global_attn_indices = num_global_attn_indices.max()
# indices of global attn
is_index_global_attn_nonzero = is_index_global_attn.nonzero(as_tuple=True)
# helper variable
is_local_index_global_attn = torch.arange(
max_num_global_attn_indices, device=is_index_global_attn.device
) < num_global_attn_indices.unsqueeze(dim=-1)
# location of the non-padding values within global attention indices
is_local_index_global_attn_nonzero = is_local_index_global_attn.nonzero(as_tuple=True)
# location of the padding values within global attention indices
is_local_index_no_global_attn_nonzero = (is_local_index_global_attn == 0).nonzero(as_tuple=True)
return (
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
)
def _concat_with_global_key_attn_probs(
self,
key_vectors,
query_vectors,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
):
batch_size = key_vectors.shape[0]
# create only global key vectors
key_vectors_only_global = key_vectors.new_zeros(
batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
)
key_vectors_only_global[is_local_index_global_attn_nonzero] = key_vectors[is_index_global_attn_nonzero]
# (batch_size, seq_len, num_heads, max_num_global_attn_indices)
attn_probs_from_global_key = torch.einsum("blhd,bshd->blhs", (query_vectors, key_vectors_only_global))
# need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
attn_probs_from_global_key[
is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
] = torch.finfo(attn_probs_from_global_key.dtype).min
attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
return attn_probs_from_global_key
def _compute_attn_output_with_global_indices(
self,
value_vectors,
attn_probs,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
):
batch_size = attn_probs.shape[0]
# cut local attn probs to global only
attn_probs_only_global = attn_probs.narrow(-1, 0, max_num_global_attn_indices)
# get value vectors for global only
value_vectors_only_global = value_vectors.new_zeros(
batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
)
value_vectors_only_global[is_local_index_global_attn_nonzero] = value_vectors[is_index_global_attn_nonzero]
# use `matmul` because `einsum` crashes sometimes with fp16
# attn = torch.einsum('blhs,bshd->blhd', (selected_attn_probs, selected_v))
# compute attn output only global
attn_output_only_global = torch.matmul(
attn_probs_only_global.transpose(1, 2).clone(), value_vectors_only_global.transpose(1, 2).clone()
).transpose(1, 2)
# reshape attn probs
attn_probs_without_global = attn_probs.narrow(
-1, max_num_global_attn_indices, attn_probs.size(-1) - max_num_global_attn_indices
).contiguous()
# compute attn output with global
attn_output_without_global = self._sliding_chunks_matmul_attn_probs_value(
attn_probs_without_global, value_vectors, self.one_sided_attn_window_size
)
return attn_output_only_global + attn_output_without_global
def _compute_global_attn_output_from_hidden(
self,
hidden_states,
max_num_global_attn_indices,
is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
is_index_masked,
):
seq_len, batch_size = hidden_states.shape[:2]
# prepare global hidden states
global_attn_hidden_states = hidden_states.new_zeros(max_num_global_attn_indices, batch_size, self.embed_dim)
global_attn_hidden_states[is_local_index_global_attn_nonzero[::-1]] = hidden_states[
is_index_global_attn_nonzero[::-1]
]
# global key, query, value
global_query_vectors_only_global = self.query_global(global_attn_hidden_states)
global_key_vectors = self.key_global(hidden_states)
global_value_vectors = self.value_global(hidden_states)
# normalize
global_query_vectors_only_global /= math.sqrt(self.head_dim)
# reshape
global_query_vectors_only_global = (
global_query_vectors_only_global.contiguous()
.view(max_num_global_attn_indices, batch_size * self.num_heads, self.head_dim)
.transpose(0, 1)
) # (batch_size * self.num_heads, max_num_global_attn_indices, head_dim)
global_key_vectors = (
global_key_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
) # batch_size * self.num_heads, seq_len, head_dim)
global_value_vectors = (
global_value_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
) # batch_size * self.num_heads, seq_len, head_dim)
# compute attn scores
global_attn_scores = torch.bmm(global_query_vectors_only_global, global_key_vectors.transpose(1, 2))
assert list(global_attn_scores.size()) == [
batch_size * self.num_heads,
max_num_global_attn_indices,
seq_len,
], (
"global_attn_scores have the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)}, but is"
f" {global_attn_scores.size()}."
)
global_attn_scores = global_attn_scores.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
# need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
global_attn_scores = global_attn_scores.transpose(1, 2)
global_attn_scores[
is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
] = torch.finfo(global_attn_scores.dtype).min
global_attn_scores = global_attn_scores.transpose(1, 2)
global_attn_scores = global_attn_scores.masked_fill(
is_index_masked[:, None, None, :],
torch.finfo(global_attn_scores.dtype).min,
)
global_attn_scores = global_attn_scores.view(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)
# compute global attn probs
global_attn_probs_float = nn.functional.softmax(
global_attn_scores, dim=-1, dtype=torch.float32
) # use fp32 for numerical stability
global_attn_probs = nn.functional.dropout(
global_attn_probs_float.type_as(global_attn_scores), p=self.dropout, training=self.training
)
# global attn output
global_attn_output = torch.bmm(global_attn_probs, global_value_vectors)
assert list(global_attn_output.size()) == [
batch_size * self.num_heads,
max_num_global_attn_indices,
self.head_dim,
], (
"global_attn_output tensor has the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim)}, but is"
f" {global_attn_output.size()}."
)
global_attn_probs = global_attn_probs.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
global_attn_output = global_attn_output.view(
batch_size, self.num_heads, max_num_global_attn_indices, self.head_dim
)
return global_attn_output, global_attn_probs
| LEDEncoderSelfAttention |
python | numpy__numpy | numpy/_core/tests/test_simd.py | {
"start": 8045,
"end": 10928
} | class ____(_Test_Utility):
"""
To test all integer vector types at once
"""
def test_operators_shift(self):
if self.sfx in ("u8", "s8"):
return
data_a = self._data(self._int_max() - self.nlanes)
data_b = self._data(self._int_min(), reverse=True)
vdata_a, vdata_b = self.load(data_a), self.load(data_b)
for count in range(self._scalar_size()):
# load to cast
data_shl_a = self.load([a << count for a in data_a])
# left shift
shl = self.shl(vdata_a, count)
assert shl == data_shl_a
# load to cast
data_shr_a = self.load([a >> count for a in data_a])
# right shift
shr = self.shr(vdata_a, count)
assert shr == data_shr_a
# shift by zero or max or out-range immediate constant is not
# applicable and illogical
for count in range(1, self._scalar_size()):
# load to cast
data_shl_a = self.load([a << count for a in data_a])
# left shift by an immediate constant
shli = self.shli(vdata_a, count)
assert shli == data_shl_a
# load to cast
data_shr_a = self.load([a >> count for a in data_a])
# right shift by an immediate constant
shri = self.shri(vdata_a, count)
assert shri == data_shr_a
def test_arithmetic_subadd_saturated(self):
if self.sfx in ("u32", "s32", "u64", "s64"):
return
data_a = self._data(self._int_max() - self.nlanes)
data_b = self._data(self._int_min(), reverse=True)
vdata_a, vdata_b = self.load(data_a), self.load(data_b)
data_adds = self._int_clip([a + b for a, b in zip(data_a, data_b)])
adds = self.adds(vdata_a, vdata_b)
assert adds == data_adds
data_subs = self._int_clip([a - b for a, b in zip(data_a, data_b)])
subs = self.subs(vdata_a, vdata_b)
assert subs == data_subs
def test_math_max_min(self):
data_a = self._data()
data_b = self._data(self.nlanes)
vdata_a, vdata_b = self.load(data_a), self.load(data_b)
data_max = [max(a, b) for a, b in zip(data_a, data_b)]
simd_max = self.max(vdata_a, vdata_b)
assert simd_max == data_max
data_min = [min(a, b) for a, b in zip(data_a, data_b)]
simd_min = self.min(vdata_a, vdata_b)
assert simd_min == data_min
@pytest.mark.parametrize("start", [-100, -10000, 0, 100, 10000])
def test_reduce_max_min(self, start):
"""
Test intrinsics:
npyv_reduce_max_##sfx
npyv_reduce_min_##sfx
"""
vdata_a = self.load(self._data(start))
assert self.reduce_max(vdata_a) == max(vdata_a)
assert self.reduce_min(vdata_a) == min(vdata_a)
| _SIMD_INT |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/operators/teradata_compute_cluster.py | {
"start": 8021,
"end": 13287
} | class ____(_TeradataComputeClusterOperator):
"""
Creates the new Computer Cluster with specified Compute Group Name and Compute Profile Name.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:TeradataComputeClusterProvisionOperator`
:param compute_profile_name: Name of the Compute Profile to manage.
:param compute_group_name: Name of compute group to which compute profile belongs.
:param query_strategy: Query strategy to use. Refers to the approach or method used by the
Teradata Optimizer to execute SQL queries efficiently within a Teradata computer cluster.
Valid query_strategy value is either 'STANDARD' or 'ANALYTIC'. Default at database level is STANDARD.
:param compute_map: ComputeMapName of the compute map. The compute_map in a compute cluster profile refers
to the mapping of compute resources to a specific node or set of nodes within the cluster.
:param compute_attribute: Optional attributes of compute profile. Example compute attribute
MIN_COMPUTE_COUNT(1) MAX_COMPUTE_COUNT(5) INITIALLY_SUSPENDED('FALSE')
:param teradata_conn_id: The :ref:`Teradata connection id <howto/connection:teradata>`
reference to a specific Teradata database.
:param timeout: Time elapsed before the task times out and fails.
"""
template_fields: Sequence[str] = (
"compute_profile_name",
"compute_group_name",
"query_strategy",
"compute_map",
"compute_attribute",
"teradata_conn_id",
"timeout",
)
ui_color = "#e07c24"
def __init__(
self,
query_strategy: str | None = None,
compute_map: str | None = None,
compute_attribute: str | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.query_strategy = query_strategy
self.compute_map = compute_map
self.compute_attribute = compute_attribute
def _build_ccp_setup_query(self):
create_cp_query = "CREATE COMPUTE PROFILE " + self.compute_profile_name
if self.compute_group_name:
create_cp_query = create_cp_query + " IN " + self.compute_group_name
if self.compute_map is not None:
create_cp_query = create_cp_query + ", INSTANCE = " + self.compute_map
if self.query_strategy is not None:
create_cp_query = create_cp_query + ", INSTANCE TYPE = " + self.query_strategy
if self.compute_attribute is not None:
create_cp_query = create_cp_query + " USING " + self.compute_attribute
return create_cp_query
def execute(self, context: Context):
"""
Initiate the execution of CREATE COMPUTE SQL statement.
Initiate the execution of the SQL statement for provisioning the compute cluster within Teradata Vantage
Lake, effectively creates the compute cluster.
Airflow runs this method on the worker and defers using the trigger.
"""
return self._compute_cluster_execute()
def _compute_cluster_execute(self, operation: str | None = None):
super()._compute_cluster_execute("Provision")
if self.compute_group_name:
cg_status_query = (
"SELECT count(1) FROM DBC.ComputeGroups WHERE UPPER(ComputeGroupName) = UPPER('"
+ self.compute_group_name
+ "')"
)
cg_status_result = self._hook_run(cg_status_query, _single_result_row_handler)
if cg_status_result is not None:
cg_status_result = str(cg_status_result)
else:
cg_status_result = 0
if int(cg_status_result) == 0:
create_cg_query = "CREATE COMPUTE GROUP " + self.compute_group_name
if self.query_strategy is not None:
create_cg_query = (
create_cg_query + " USING QUERY_STRATEGY ('" + self.query_strategy + "')"
)
self._hook_run(create_cg_query, _single_result_row_handler)
cp_status_query = (
"SEL ComputeProfileState FROM DBC.ComputeProfilesVX WHERE UPPER(ComputeProfileName) = UPPER('"
+ self.compute_profile_name
+ "')"
)
if self.compute_group_name:
cp_status_query += " AND UPPER(ComputeGroupName) = UPPER('" + self.compute_group_name + "')"
cp_status_result = self._hook_run(cp_status_query, handler=_single_result_row_handler)
if cp_status_result is not None:
cp_status_result = str(cp_status_result)
msg = f"Compute Profile '{self.compute_profile_name}' already exists under Compute Group '{self.compute_group_name}'. Status: {cp_status_result}."
self.log.info(msg)
return cp_status_result
create_cp_query = self._build_ccp_setup_query()
operation = Constants.CC_CREATE_OPR
initially_suspended = self._get_initially_suspended(create_cp_query)
if initially_suspended == "TRUE":
operation = Constants.CC_CREATE_SUSPEND_OPR
return self._handle_cc_status(operation, create_cp_query)
| TeradataComputeClusterProvisionOperator |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/int.py | {
"start": 1308,
"end": 6676
} | class ____(ZDType[TIntDType_co, TIntScalar_co], HasItemSize):
"""
A base class for integer data types in Zarr.
This class provides methods for serialization and deserialization of integer types
in both Zarr v2 and v3 formats, as well as methods for checking and casting scalars.
"""
_zarr_v2_names: ClassVar[tuple[str, ...]]
@classmethod
def _check_json_v2(cls, data: object) -> TypeGuard[DTypeConfig_V2[str, None]]:
"""
Check that the input is a valid JSON representation of this integer data type in Zarr V2.
This method verifies that the provided data matches the expected Zarr V2 representation
for this data type. The input data must be a mapping that contains a "name" key that is
one of the strings from cls._zarr_v2_names and an "object_codec_id" key that is None.
Parameters
----------
data : object
The JSON data to check.
Returns
-------
TypeGuard[DTypeConfig_V2[str, None]]
True if the input is a valid representation of this class in Zarr V2,
False otherwise.
"""
return (
check_dtype_spec_v2(data)
and data["name"] in cls._zarr_v2_names
and data["object_codec_id"] is None
)
@classmethod
def _check_json_v3(cls, data: object) -> TypeGuard[str]:
"""
Check that the input is a valid JSON representation of this class in Zarr V3.
Parameters
----------
data : object
The JSON data to check.
Returns
-------
TypeGuard[str]
True if the input is a valid representation of this class in Zarr v3,
False otherwise.
"""
return data == cls._zarr_v3_name
def _check_scalar(self, data: object) -> TypeGuard[IntLike]:
"""
Check if the input object is of an IntLike type.
This method verifies whether the provided data can be considered as an integer-like
value, which includes objects supporting integer conversion.
Parameters
----------
data : object
The data to check.
Returns
-------
TypeGuard[IntLike]
True if the data is IntLike, False otherwise.
"""
return isinstance(data, IntLike)
def _cast_scalar_unchecked(self, data: IntLike) -> TIntScalar_co:
"""
Casts a given scalar value to the native integer scalar type without type checking.
Parameters
----------
data : IntLike
The scalar value to cast.
Returns
-------
TIntScalar_co
The casted integer scalar of the native dtype.
"""
return self.to_native_dtype().type(data) # type: ignore[return-value]
def cast_scalar(self, data: object) -> TIntScalar_co:
"""
Attempt to cast a given object to a NumPy integer scalar.
Parameters
----------
data : object
The data to be cast to a NumPy integer scalar.
Returns
-------
TIntScalar_co
The data cast as a NumPy integer scalar.
Raises
------
TypeError
If the data cannot be converted to a NumPy integer scalar.
"""
if self._check_scalar(data):
return self._cast_scalar_unchecked(data)
msg = (
f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the "
f"data type {self}."
)
raise TypeError(msg)
def default_scalar(self) -> TIntScalar_co:
"""
Get the default value, which is 0 cast to this dtype.
Returns
-------
TIntScalar_co
The default value.
"""
return self._cast_scalar_unchecked(0)
def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TIntScalar_co:
"""
Read a JSON-serializable value as a NumPy int scalar.
Parameters
----------
data : JSON
The JSON-serializable value.
zarr_format : ZarrFormat
The Zarr format version.
Returns
-------
TIntScalar_co
The NumPy int scalar.
Raises
------
TypeError
If the input is not a valid integer type.
"""
if check_json_int(data):
return self._cast_scalar_unchecked(data)
if check_json_intish_float(data):
return self._cast_scalar_unchecked(int(data))
if check_json_intish_str(data):
return self._cast_scalar_unchecked(int(data))
raise TypeError(f"Invalid type: {data}. Expected an integer.")
def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> int:
"""
Convert an object to a JSON serializable scalar. For the integer data types,
the JSON form is a plain integer.
Parameters
----------
data : object
The value to convert.
zarr_format : ZarrFormat
The Zarr format version.
Returns
-------
int
The JSON-serializable form of the scalar.
"""
return int(self.cast_scalar(data))
@dataclass(frozen=True, kw_only=True)
| BaseInt |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/matrix_mult_test.py | {
"start": 825,
"end": 2067
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, B, M, N, K, device, op_func):
self.inputs = {
"input_one": torch.rand(B, M, N, device=device),
"input_two": torch.rand(B, N, K, device=device),
}
self.op_func = op_func
def forward(self, input_one, input_two):
if self.op_func.__name__ == "einsum":
return torch.einsum("bij,bjk->bik", input_one, input_two)
else:
return torch.bmm(input_one, input_two)
"""
Microbenchmarks for element-wise matrix mult with einsum and torch.mul.
"""
batch_elementwise_configs_short = op_bench.config_list(
attr_names=["B", "M", "N"],
attrs=[
[4, 5, 3],
[32, 25, 20],
[100, 90, 110],
],
cross_product_configs={
"device": ["cpu", "cuda"],
},
tags=["short"],
)
batch_elementwise_configs_long = op_bench.cross_product_configs(
B=[128, 512, 1024],
M=[128, 512, 1024],
N=[128, 512, 1024],
device=["cpu", "cuda"],
tags=["long"],
)
batch_elementwise_op_list = op_bench.op_list(
attr_names=["op_name", "op_func"],
attrs=[
["einsum_elementwise", torch.einsum],
["mul", torch.mul],
],
)
| BatchMatrixMultBenchmark |
python | coleifer__peewee | playhouse/shortcuts.py | {
"start": 11059,
"end": 12447
} | class ____(Metadata):
"""
Metadata class to allow swapping database at run-time in a multi-threaded
application. To use:
class Base(Model):
class Meta:
model_metadata_class = ThreadSafeDatabaseMetadata
"""
def __init__(self, *args, **kwargs):
# The database attribute is stored in a thread-local.
self._database = None
self._table = None
self._lock = threading.Lock()
self._local = threading.local()
super(ThreadSafeDatabaseMetadata, self).__init__(*args, **kwargs)
def _get_db(self):
return getattr(self._local, 'database', self._database)
def _set_db(self, db):
if self._database is None:
self._database = db
self._local.database = db
database = property(_get_db, _set_db)
def set_database(self, database):
with self._lock:
return super(ThreadSafeDatabaseMetadata,
self).set_database(database)
@property
def table(self):
if getattr(self._local, 'table', None) is None:
self._local.table = super(ThreadSafeDatabaseMetadata, self).table
return self._local.table
@table.setter
def table(self, value):
raise AttributeError('Cannot set the "table".')
@table.deleter
def table(self):
self._local.table = None
| ThreadSafeDatabaseMetadata |
python | readthedocs__readthedocs.org | readthedocs/analytics/admin.py | {
"start": 123,
"end": 441
} | class ____(admin.ModelAdmin):
raw_id_fields = ("project", "version")
list_display = ("project", "version", "path", "view_count", "date")
search_fields = ("project__slug", "version__slug", "path")
readonly_fields = ("date",)
list_select_related = ("project", "version", "version__project")
| PageViewAdmin |
python | getsentry__sentry | tests/sentry/workflow_engine/migration_helpers/test_rule_conditions.py | {
"start": 374,
"end": 9157
} | class ____(ConditionTestCase):
def setUp(self) -> None:
self.dcg = self.create_data_condition_group()
def assert_basic_condition_translated(self, payload):
dc = self.translate_to_data_condition(payload, self.dcg)
condition, filters = translate_to_rule_condition_filters(dc, is_filter=False)
assert condition == payload
assert filters == []
def assert_basic_filter_translated(self, payload):
dc = self.translate_to_data_condition(payload, self.dcg)
condition, filters = translate_to_rule_condition_filters(dc, is_filter=True)
assert condition == {}
assert filters == [payload]
def test_escalating_event(self) -> None:
payload = {"id": "sentry.rules.conditions.reappeared_event.ReappearedEventCondition"}
self.assert_basic_condition_translated(payload)
def test_regression_event(self) -> None:
payload = {"id": "sentry.rules.conditions.regression_event.RegressionEventCondition"}
self.assert_basic_condition_translated(payload)
def test_existing_high_priority_issue(self) -> None:
payload = {
"id": "sentry.rules.conditions.high_priority_issue.ExistingHighPriorityIssueCondition"
}
self.assert_basic_condition_translated(payload)
def test_event_attribute_condition(self) -> None:
payload = {
"id": "sentry.rules.conditions.event_attribute.EventAttributeCondition",
"attribute": "http.url",
"match": "nc",
"value": "localhost",
}
self.assert_basic_condition_translated(payload)
def test_event_attribute_filter(self) -> None:
payload = {
"id": "sentry.rules.filters.event_attribute.EventAttributeFilter",
"attribute": "http.url",
"match": "nc",
"value": "localhost",
}
self.assert_basic_filter_translated(payload)
def test_first_seen_event(self) -> None:
payload = {"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"}
self.assert_basic_condition_translated(payload)
def test_new_high_priority_issue(self) -> None:
payload = {
"id": "sentry.rules.conditions.high_priority_issue.NewHighPriorityIssueCondition"
}
self.assert_basic_condition_translated(payload)
def test_level_condition(self) -> None:
payload = {
"id": "sentry.rules.conditions.level.LevelCondition",
"match": "eq",
"level": "50",
}
self.assert_basic_condition_translated(payload)
def test_level_filter(self) -> None:
payload = {
"id": "sentry.rules.filters.level.LevelFilter",
"match": "eq",
"level": "50",
}
self.assert_basic_filter_translated(payload)
def test_tagged_event_condition(self) -> None:
payload = {
"id": "sentry.rules.conditions.tagged_event.TaggedEventCondition",
"key": "level",
"match": "eq",
"value": "error",
}
self.assert_basic_condition_translated(payload)
def test_tagged_event_filter(self) -> None:
payload = {
"id": "sentry.rules.filters.tagged_event.TaggedEventFilter",
"key": "level",
"match": "eq",
"value": "error",
}
self.assert_basic_filter_translated(payload)
def test_age_comparison_filter(self) -> None:
payload = {
"id": "sentry.rules.filters.age_comparison.AgeComparisonFilter",
"comparison_type": "older",
"value": 3,
"time": "week",
}
self.assert_basic_filter_translated(payload)
def test_assigned_to_filter(self) -> None:
payload: dict[str, Any] = {
"id": "sentry.rules.filters.assigned_to.AssignedToFilter",
"targetType": "Unassigned",
}
self.assert_basic_filter_translated(payload)
payload = {
"id": "sentry.rules.filters.assigned_to.AssignedToFilter",
"targetType": "Member",
"targetIdentifier": 895329789,
}
self.assert_basic_filter_translated(payload)
def test_issue_category(self) -> None:
payload = {"id": "sentry.rules.filters.issue_category.IssueCategoryFilter", "value": 2}
self.assert_basic_filter_translated(payload)
def test_issue_occurrences(self) -> None:
payload = {
"id": "sentry.rules.filters.issue_occurrences.IssueOccurrencesFilter",
"value": 120,
}
self.assert_basic_filter_translated(payload)
def test_latest_release(self) -> None:
payload = {"id": "sentry.rules.filters.latest_release.LatestReleaseFilter"}
self.assert_basic_filter_translated(payload)
def test_latest_adopted_release(self) -> None:
payload = {
"id": "sentry.rules.filters.latest_adopted_release_filter.LatestAdoptedReleaseFilter",
"oldest_or_newest": "oldest",
"older_or_newer": "newer",
"environment": "prod",
}
self.assert_basic_filter_translated(payload)
def test_event_frequency_count(self) -> None:
payload = {
"interval": "1h",
"id": "sentry.rules.conditions.event_frequency.EventFrequencyCondition",
"value": 50,
"comparisonType": "count",
}
self.assert_basic_condition_translated(payload)
def test_event_frequency_percent(self) -> None:
payload = {
"interval": "1h",
"id": "sentry.rules.conditions.event_frequency.EventFrequencyCondition",
"value": 50,
"comparisonType": "percent",
"comparisonInterval": "1h",
}
self.assert_basic_condition_translated(payload)
def test_event_unique_user_frequency_count(self) -> None:
payload = {
"interval": "1h",
"id": "sentry.rules.conditions.event_frequency.EventUniqueUserFrequencyCondition",
"value": 50,
"comparisonType": "count",
}
self.assert_basic_condition_translated(payload)
def test_event_unique_user_frequency_percent(self) -> None:
payload = {
"interval": "1h",
"id": "sentry.rules.conditions.event_frequency.EventUniqueUserFrequencyCondition",
"value": 50,
"comparisonType": "percent",
"comparisonInterval": "1h",
}
self.assert_basic_condition_translated(payload)
def test_percent_sessions_count(self) -> None:
payload = {
"interval": "1h",
"id": "sentry.rules.conditions.event_frequency.EventFrequencyPercentCondition",
"value": 17.2,
"comparisonType": "count",
}
self.assert_basic_condition_translated(payload)
def test_percent_sessions_percent(self) -> None:
payload = {
"interval": "1h",
"id": "sentry.rules.conditions.event_frequency.EventFrequencyPercentCondition",
"value": 17.2,
"comparisonType": "percent",
"comparisonInterval": "1h",
}
self.assert_basic_condition_translated(payload)
def test_event_unique_user_frequency_with_conditions(self) -> None:
payload: dict[str, str | int | float] = {
"interval": "1h",
"id": "sentry.rules.conditions.event_frequency.EventUniqueUserFrequencyConditionWithConditions",
"value": 50,
"comparisonType": "count",
}
conditions = [
{
"id": "sentry.rules.filters.tagged_event.TaggedEventFilter",
"match": "eq",
"key": "LOGGER",
"value": "sentry.example",
},
{
"id": "sentry.rules.filters.tagged_event.TaggedEventFilter",
"match": "is",
"key": "environment",
"value": "",
},
{
"id": "sentry.rules.filters.event_attribute.EventAttributeFilter",
"match": "nc",
"value": "hi",
"attribute": "message",
},
]
dc = create_event_unique_user_frequency_condition_with_conditions(
payload, self.dcg, conditions
)
dc.save()
condition, filters = translate_to_rule_condition_filters(dc, is_filter=False)
assert condition == payload
assert len(filters) == len(conditions)
# Check that the filters are the same as the conditions (dictionaries)
for filter in filters:
assert filter in conditions
| RuleConditionTranslationTest |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 496937,
"end": 498704
} | class ____(Response):
"""
Response of tasks.set_requirements endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "set_requirements"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"fields": {
"additionalProperties": True,
"description": "Updated fields names and values",
"type": ["object", "null"],
},
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(self, updated=None, fields=None, **kwargs):
super(SetRequirementsResponse, self).__init__(**kwargs)
self.updated = updated
self.fields = fields
@schema_property("updated")
def updated(self):
return self._property_updated
@updated.setter
def updated(self, value):
if value is None:
self._property_updated = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated", six.integer_types)
self._property_updated = value
@schema_property("fields")
def fields(self):
return self._property_fields
@fields.setter
def fields(self, value):
if value is None:
self._property_fields = None
return
self.assert_isinstance(value, "fields", (dict,))
self._property_fields = value
| SetRequirementsResponse |
python | apache__airflow | providers/mysql/tests/unit/mysql/hooks/test_mysql.py | {
"start": 1807,
"end": 12236
} | class ____:
def setup_method(self):
self.connection = Connection(
conn_id="test_conn_id",
conn_type="mysql",
login="login",
password="password",
host="host",
schema="schema",
)
self.db_hook = MySqlHook()
self.db_hook.get_connection = mock.Mock()
self.db_hook.get_connection.return_value = self.connection
@mock.patch("MySQLdb.connect")
def test_get_conn(self, mock_connect):
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["user"] == "login"
assert kwargs["passwd"] == "password"
assert kwargs["host"] == "host"
assert kwargs["db"] == "schema"
@mock.patch("MySQLdb.connect")
def test_dummy_connection_setter(self, mock_connect):
self.db_hook.get_conn()
self.db_hook.connection = "Won't affect anything"
assert self.db_hook.connection != "Won't affect anything"
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["user"] == "login"
assert kwargs["passwd"] == "password"
assert kwargs["host"] == "host"
assert kwargs["db"] == "schema"
@mock.patch("MySQLdb.connect")
@pytest.mark.parametrize(
("connection_params", "expected_uri"),
[
pytest.param(
{
"login": "login",
"password": "password",
"host": "host",
"schema": "schema",
"port": None,
"extra": json.dumps({"charset": "utf-8"}),
},
"mysql://login:password@host/schema?charset=utf-8",
id="basic_connection_with_charset",
),
pytest.param(
{
"login": "user@domain",
"password": "pass/word!",
"host": "host",
"schema": "schema",
"port": None,
"extra": json.dumps({"charset": "utf-8"}),
},
"mysql://user%40domain:pass%2Fword%21@host/schema?charset=utf-8",
id="special_chars_in_credentials",
),
pytest.param(
{
"login": "user@domain",
"password": "password",
"host": "host",
"schema": "schema",
"port": None,
"extra": json.dumps({"client": "mysql-connector-python"}),
},
"mysql+mysqlconnector://user%40domain:password@host/schema",
id="mysql_connector_python",
),
pytest.param(
{
"login": "user@domain",
"password": "password",
"host": "host",
"schema": "schema",
"port": None,
"extra": json.dumps({"client": "pymysql"}),
},
"mysql+pymysql://user%40domain:password@host/schema",
id="mysql_connector_pymysql",
),
pytest.param(
{
"login": "user@domain",
"password": "password",
"host": "host",
"schema": "schema",
"port": 3307,
"extra": json.dumps({"client": "mysql-connector-python"}),
},
"mysql+mysqlconnector://user%40domain:password@host:3307/schema",
id="mysql_connector_with_port",
),
pytest.param(
{
"login": "user@domain",
"password": "password",
"host": "host",
"schema": "db/name",
"port": 3307,
"extra": json.dumps({"client": "mysql-connector-python"}),
},
"mysql+mysqlconnector://user%40domain:password@host:3307/db%2Fname",
id="special_chars_in_schema",
),
pytest.param(
{
"login": "user@domain",
"password": "password",
"host": "host",
"schema": "schema",
"port": 3307,
"extra": json.dumps(
{
"client": "mysql-connector-python",
"ssl_ca": "/path/to/ca",
"ssl_cert": "/path/to/cert with space",
}
),
},
"mysql+mysqlconnector://user%40domain:password@host:3307/schema?ssl_ca=%2Fpath%2Fto%2Fca&ssl_cert=%2Fpath%2Fto%2Fcert+with+space",
id="ssl_parameters",
),
],
)
def test_get_uri(self, mock_connect, connection_params, expected_uri):
"""Test get_uri method with various connection parameters."""
for key, value in connection_params.items():
setattr(self.connection, key, value)
assert self.db_hook.get_uri() == expected_uri
@mock.patch("MySQLdb.connect")
def test_get_conn_from_connection(self, mock_connect):
conn = Connection(
conn_id="test_conn_id",
conn_type="mysql",
login="login-conn",
password="password-conn",
host="host",
schema="schema",
)
hook = MySqlHook(connection=conn)
hook.get_conn()
mock_connect.assert_called_once_with(
user="login-conn", passwd="password-conn", host="host", db="schema", port=3306
)
@mock.patch("MySQLdb.connect")
def test_get_conn_from_connection_with_schema(self, mock_connect):
conn = Connection(
conn_id="test_conn_id",
conn_type="mysql",
login="login-conn",
password="password-conn",
host="host",
schema="schema",
)
hook = MySqlHook(connection=conn, schema="schema-override")
hook.get_conn()
mock_connect.assert_called_once_with(
user="login-conn", passwd="password-conn", host="host", db="schema-override", port=3306
)
@mock.patch("MySQLdb.connect")
def test_get_conn_port(self, mock_connect):
self.connection.port = 3307
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["port"] == 3307
@mock.patch("MySQLdb.connect")
def test_get_conn_charset(self, mock_connect):
self.connection.extra = json.dumps({"charset": "utf-8"})
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["charset"] == "utf-8"
assert kwargs["use_unicode"] is True
@mock.patch("MySQLdb.connect")
def test_get_conn_cursor(self, mock_connect):
self.connection.extra = json.dumps({"cursor": "sscursor"})
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["cursorclass"] == MySQLdb.cursors.SSCursor
@mock.patch("MySQLdb.connect")
def test_get_conn_local_infile(self, mock_connect):
self.db_hook.local_infile = True
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["local_infile"] == 1
@mock.patch("MySQLdb.connect")
def test_get_con_unix_socket(self, mock_connect):
self.connection.extra = json.dumps({"unix_socket": "/tmp/socket"})
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["unix_socket"] == "/tmp/socket"
@mock.patch("MySQLdb.connect")
def test_get_conn_ssl_as_dictionary(self, mock_connect):
self.connection.extra = json.dumps({"ssl": SSL_DICT})
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["ssl"] == SSL_DICT
@mock.patch("MySQLdb.connect")
def test_get_conn_ssl_as_string(self, mock_connect):
self.connection.extra = json.dumps({"ssl": json.dumps(SSL_DICT)})
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["ssl"] == SSL_DICT
@mock.patch("MySQLdb.connect")
def test_get_ssl_mode(self, mock_connect):
self.connection.extra = json.dumps({"ssl_mode": "DISABLED"})
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["ssl_mode"] == "DISABLED"
@mock.patch("MySQLdb.connect")
@mock.patch("airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook.get_client_type")
def test_get_conn_rds_iam(self, mock_client, mock_connect, monkeypatch):
monkeypatch.setenv("AIRFLOW_CONN_TEST_AWS_IAM_CONN", '{"conn_type": "aws"}')
self.connection.extra = '{"iam":true, "aws_conn_id": "test_aws_iam_conn"}'
mock_client.return_value.generate_db_auth_token.return_value = "aws_token"
self.db_hook.get_conn()
mock_connect.assert_called_once_with(
user="login",
passwd="aws_token",
host="host",
db="schema",
port=3306,
read_default_group="enable-cleartext-plugin",
)
@mock.patch("MySQLdb.connect")
def test_get_conn_init_command(self, mock_connect):
self.db_hook.init_command = "SET time_zone = '+00:00';"
self.db_hook.get_conn()
assert mock_connect.call_count == 1
args, kwargs = mock_connect.call_args
assert args == ()
assert kwargs["init_command"] == "SET time_zone = '+00:00';"
| TestMySqlHookConn |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure_tests/pipes_tests/test_azureml.py | {
"start": 855,
"end": 1614
} | class ____:
def __init__(self, name: str, command: Command):
self.name = name
self.command = command
cmd_parts = self.command.component.command.split() # pyright: ignore
cmd_parts[0] = _PYTHON_EXECUTABLE
env = {**self.command.environment_variables} if self.command.environment_variables else {}
self._process = subprocess.Popen(
cmd_parts,
env={**os.environ, **env},
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
@property
def status(self):
if self._process.poll() is None:
return "Running"
elif self._process.poll() == 0:
return "Completed"
else:
return "Failed"
| MockAzureMLJob |
python | wandb__wandb | wandb/vendor/pygments/lexers/dotnet.py | {
"start": 5691,
"end": 12300
} | class ____(RegexLexer):
"""
For `Nemerle <http://nemerle.org>`_ source code.
Additional options accepted:
`unicodelevel`
Determines which Unicode characters this lexer allows for identifiers.
The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This
is the fastest selection.
* ``basic`` -- all Unicode characters from the specification except
category ``Lo`` are allowed.
* ``full`` -- all Unicode characters as specified in the C# specs
are allowed. Note that this means a considerable slowdown since the
``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``.
.. versionadded:: 1.5
"""
name = 'Nemerle'
aliases = ['nemerle']
filenames = ['*.n']
mimetypes = ['text/x-nemerle'] # inferred
flags = re.MULTILINE | re.DOTALL | re.UNICODE
# for the range of allowed unicode characters in identifiers, see
# http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = {
'none': '@?[_a-zA-Z]\w*',
'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' +
'[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc',
'Cf', 'Mn', 'Mc') + ']*'),
'full': ('@?(?:_|[^' +
uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])'
+ '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl',
'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'),
}
tokens = {}
token_variants = True
for levelname, cs_ident in iteritems(levels):
tokens[levelname] = {
'root': [
# method names
(r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type
r'(' + cs_ident + ')' # method name
r'(\s*)(\()', # signature start
bygroups(using(this), Name.Function, Text, Punctuation)),
(r'^\s*\[.*?\]', Name.Attribute),
(r'[^\S\n]+', Text),
(r'\\\n', Text), # line continuation
(r'//.*?\n', Comment.Single),
(r'/[*].*?[*]/', Comment.Multiline),
(r'\n', Text),
(r'\$\s*"', String, 'splice-string'),
(r'\$\s*<#', String, 'splice-string2'),
(r'<#', String, 'recursive-string'),
(r'(<\[)\s*(' + cs_ident + ':)?', Keyword),
(r'\]\>', Keyword),
# quasiquotation only
(r'\$' + cs_ident, Name),
(r'(\$)(\()', bygroups(Name, Punctuation),
'splice-string-content'),
(r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
(r'[{}]', Punctuation),
(r'@"(""|[^"])*"', String),
(r'"(\\\\|\\"|[^"\n])*["\n]', String),
(r"'\\.'|'[^\\]'", String.Char),
(r"0[xX][0-9a-fA-F]+[Ll]?", Number),
(r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number),
(r'#[ \t]*(if|endif|else|elif|define|undef|'
r'line|error|warning|region|endregion|pragma)\b.*?\n',
Comment.Preproc),
(r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text,
Keyword)),
(r'(abstract|and|as|base|catch|def|delegate|'
r'enum|event|extern|false|finally|'
r'fun|implements|interface|internal|'
r'is|macro|match|matches|module|mutable|new|'
r'null|out|override|params|partial|private|'
r'protected|public|ref|sealed|static|'
r'syntax|this|throw|true|try|type|typeof|'
r'virtual|volatile|when|where|with|'
r'assert|assert2|async|break|checked|continue|do|else|'
r'ensures|for|foreach|if|late|lock|new|nolate|'
r'otherwise|regexp|repeat|requires|return|surroundwith|'
r'unchecked|unless|using|while|yield)\b', Keyword),
(r'(global)(::)', bygroups(Keyword, Punctuation)),
(r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|'
r'short|string|uint|ulong|ushort|void|array|list)\b\??',
Keyword.Type),
(r'(:>?)\s*(' + cs_ident + r'\??)',
bygroups(Punctuation, Keyword.Type)),
(r'(class|struct|variant|module)(\s+)',
bygroups(Keyword, Text), 'class'),
(r'(namespace|using)(\s+)', bygroups(Keyword, Text),
'namespace'),
(cs_ident, Name),
],
'class': [
(cs_ident, Name.Class, '#pop')
],
'namespace': [
(r'(?=\()', Text, '#pop'), # using (resource)
('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop')
],
'splice-string': [
(r'[^"$]', String),
(r'\$' + cs_ident, Name),
(r'(\$)(\()', bygroups(Name, Punctuation),
'splice-string-content'),
(r'\\"', String),
(r'"', String, '#pop')
],
'splice-string2': [
(r'[^#<>$]', String),
(r'\$' + cs_ident, Name),
(r'(\$)(\()', bygroups(Name, Punctuation),
'splice-string-content'),
(r'<#', String, '#push'),
(r'#>', String, '#pop')
],
'recursive-string': [
(r'[^#<>]', String),
(r'<#', String, '#push'),
(r'#>', String, '#pop')
],
'splice-string-content': [
(r'if|match', Keyword),
(r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation),
(cs_ident, Name),
(r'\d+', Number),
(r'\(', Punctuation, '#push'),
(r'\)', Punctuation, '#pop')
]
}
def __init__(self, **options):
level = get_choice_opt(options, 'unicodelevel', list(self.tokens),
'basic')
if level not in self._all_tokens:
# compile the regexes now
self._tokens = self.__class__.process_tokendef(level)
else:
self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
| NemerleLexer |
python | huggingface__transformers | src/transformers/models/ministral/modeling_ministral.py | {
"start": 21869,
"end": 21982
} | class ____(GenericForSequenceClassification, MinistralPreTrainedModel):
pass
| MinistralForSequenceClassification |
python | huggingface__transformers | src/transformers/models/pegasus_x/modeling_pegasus_x.py | {
"start": 32986,
"end": 33356
} | class ____(PreTrainedModel):
config: PegasusXConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = [r"PegasusXEncoderLayer", r"PegasusXDecoderLayer"]
_supports_flash_attn = True
# Flaky logits
_supports_sdpa = False
_supports_flex_attn = True
_can_compile_fullgraph = True
| PegasusXPreTrainedModel |
python | astropy__astropy | astropy/constants/codata2014.py | {
"start": 417,
"end": 3480
} | class ____(CODATA2014, EMConstant):
_registry = CODATA2014._registry
h = CODATA2014(
"h", "Planck constant", 6.626070040e-34, "J s", 0.000000081e-34, system="si"
)
hbar = CODATA2014(
"hbar",
"Reduced Planck constant",
1.054571800e-34,
"J s",
0.000000013e-34,
system="si",
)
k_B = CODATA2014(
"k_B", "Boltzmann constant", 1.38064852e-23, "J / (K)", 0.00000079e-23, system="si"
)
c = CODATA2014(
"c", "Speed of light in vacuum", 299792458.0, "m / (s)", 0.0, system="si"
)
G = CODATA2014(
"G", "Gravitational constant", 6.67408e-11, "m3 / (kg s2)", 0.00031e-11, system="si"
)
g0 = CODATA2014(
"g0", "Standard acceleration of gravity", 9.80665, "m / s2", 0.0, system="si"
)
m_p = CODATA2014(
"m_p", "Proton mass", 1.672621898e-27, "kg", 0.000000021e-27, system="si"
)
m_n = CODATA2014(
"m_n", "Neutron mass", 1.674927471e-27, "kg", 0.000000021e-27, system="si"
)
m_e = CODATA2014(
"m_e", "Electron mass", 9.10938356e-31, "kg", 0.00000011e-31, system="si"
)
u = CODATA2014("u", "Atomic mass", 1.660539040e-27, "kg", 0.000000020e-27, system="si")
sigma_sb = CODATA2014(
"sigma_sb",
"Stefan-Boltzmann constant",
5.670367e-8,
"W / (K4 m2)",
0.000013e-8,
system="si",
)
e = EMCODATA2014(
"e", "Electron charge", 1.6021766208e-19, "C", 0.0000000098e-19, system="si"
)
eps0 = EMCODATA2014(
"eps0", "Electric constant", 8.854187817e-12, "F/m", 0.0, system="si"
)
N_A = CODATA2014(
"N_A", "Avogadro's number", 6.022140857e23, "1 / (mol)", 0.000000074e23, system="si"
)
R = CODATA2014("R", "Gas constant", 8.3144598, "J / (K mol)", 0.0000048, system="si")
Ryd = CODATA2014(
"Ryd", "Rydberg constant", 10973731.568508, "1 / (m)", 0.000065, system="si"
)
a0 = CODATA2014(
"a0", "Bohr radius", 0.52917721067e-10, "m", 0.00000000012e-10, system="si"
)
muB = CODATA2014(
"muB", "Bohr magneton", 927.4009994e-26, "J/T", 0.00002e-26, system="si"
)
alpha = CODATA2014(
"alpha",
"Fine-structure constant",
7.2973525664e-3,
"",
0.0000000017e-3,
system="si",
)
atm = CODATA2014("atm", "Standard atmosphere", 101325, "Pa", 0.0, system="si")
mu0 = CODATA2014("mu0", "Magnetic constant", 4.0e-7 * np.pi, "N/A2", 0.0, system="si")
sigma_T = CODATA2014(
"sigma_T",
"Thomson scattering cross-section",
0.66524587158e-28,
"m2",
0.00000000091e-28,
system="si",
)
b_wien = CODATA2014(
"b_wien",
"Wien wavelength displacement law constant",
2.8977729e-3,
"m K",
0.0000017e-3,
system="si",
)
# cgs constants
# Only constants that cannot be converted directly from S.I. are defined here.
e_esu = EMCODATA2014(
e.abbrev,
e.name,
e.value * c.value * 10.0,
"statC",
e.uncertainty * c.value * 10.0,
system="esu",
)
e_emu = EMCODATA2014(
e.abbrev, e.name, e.value / 10, "abC", e.uncertainty / 10, system="emu"
)
e_gauss = EMCODATA2014(
e.abbrev,
e.name,
e.value * c.value * 10.0,
"Fr",
e.uncertainty * c.value * 10.0,
system="gauss",
)
| EMCODATA2014 |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 138782,
"end": 139306
} | class ____(BaseModel):
id: str = Field(..., description="")
app: "AppBuildTelemetry" = Field(..., description="")
collections: "CollectionsTelemetry" = Field(..., description="")
cluster: Optional["ClusterTelemetry"] = Field(default=None, description="")
requests: Optional["RequestsTelemetry"] = Field(default=None, description="")
memory: Optional["MemoryTelemetry"] = Field(default=None, description="")
hardware: Optional["HardwareTelemetry"] = Field(default=None, description="")
| TelemetryData |
python | paramiko__paramiko | paramiko/hostkeys.py | {
"start": 10295,
"end": 10445
} | class ____(Exception):
def __init__(self, line, exc):
self.line = line
self.exc = exc
self.args = (line, exc)
| InvalidHostKey |
python | huggingface__transformers | src/transformers/models/xmod/modeling_xmod.py | {
"start": 7914,
"end": 11129
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.config = config
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.scaling = self.attention_head_size**-0.5
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.is_decoder = config.is_decoder
self.is_causal = is_causal
self.layer_idx = layer_idx
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.attention_head_size)
# get all proj
query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
if past_key_values is not None:
# decoder-only roberta can have a simple dynamic cache for example
current_past_key_values = past_key_values
if isinstance(past_key_values, EncoderDecoderCache):
current_past_key_values = past_key_values.self_attention_cache
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
key_layer, value_layer = current_past_key_values.update(
key_layer,
value_layer,
self.layer_idx,
{"cache_position": cache_position},
)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_layer,
key_layer,
value_layer,
attention_mask,
dropout=0.0 if not self.training else self.dropout.p,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
return attn_output, attn_weights
# Copied from transformers.models.bert.modeling_bert.BertCrossAttention with Bert->Xmod
| XmodSelfAttention |
python | tensorflow__tensorflow | tensorflow/python/tpu/async_checkpoint.py | {
"start": 2145,
"end": 11076
} | class ____(basic_session_run_hooks.CheckpointSaverHook):
"""Saves checkpoints every N steps or seconds."""
def __init__(self,
checkpoint_dir: Text,
save_secs: Optional[int] = None,
save_steps: Optional[int] = None,
saver: Optional[saver_lib.Saver] = None,
checkpoint_basename: Text = "model.ckpt",
scaffold: Optional[monitored_session.Scaffold] = None,
listeners: Optional[List[
basic_session_run_hooks.CheckpointSaverListener]] = None):
"""Initializes a `CheckpointSaverHook`.
Args:
checkpoint_dir: `str`, base directory for the checkpoint files.
save_secs: `int`, save every N secs.
save_steps: `int`, save every N steps.
saver: `Saver` object, used for saving.
checkpoint_basename: `str`, base name for the checkpoint files.
scaffold: `Scaffold`, use to get saver object.
listeners: List of `CheckpointSaverListener` subclass instances. Used for
callbacks that run immediately before or after this hook saves the
checkpoint.
Raises:
ValueError: One of `save_steps` or `save_secs` should be set.
ValueError: At most one of `saver` or `scaffold` should be set.
"""
save_path = os.path.join(checkpoint_dir, checkpoint_basename)
logging.info("Create AsyncCheckpointSaverHook saving to path\n%s",
save_path)
if listeners:
logging.info(" with %d listener(s).", len(listeners))
if saver is not None and scaffold is not None:
raise ValueError("You cannot provide both saver and scaffold.")
self._saver = saver
self._save_thread = None
self._write_graph_thread = None
self._checkpoint_dir = checkpoint_dir
self._save_path = save_path
self._scaffold = scaffold
self._timer = basic_session_run_hooks.SecondOrStepTimer(
every_secs=save_secs, every_steps=save_steps)
self._listeners = listeners or []
self._steps_per_run = 1
self._summary_writer = None
self._global_step_tensor = None
self._last_checkpoint_step = None
# Initialize the first timestamp for _END_TIME_OF_LAST_WRITE.
global _END_TIME_OF_LAST_WRITE
with _END_TIME_OF_LAST_WRITE_LOCK:
if _END_TIME_OF_LAST_WRITE is None:
_END_TIME_OF_LAST_WRITE = time.time()
def _set_steps_per_run(self, steps_per_run):
self._steps_per_run = steps_per_run
def begin(self):
self._summary_writer = SummaryWriterCache.get(self._checkpoint_dir)
self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access
if self._global_step_tensor is None:
raise RuntimeError(
"Global step should be created to use CheckpointSaverHook.")
for l in self._listeners:
l.begin()
def after_create_session(self, session: session_lib.Session, coord: Any):
global_step = session.run(self._global_step_tensor)
# We do write graph and saver_def at the first call of before_run.
# We cannot do this in begin, since we let other hooks to change graph and
# add variables in begin. Graph is finalized after all begin calls.
def _write_graph_fn(self):
training_util.write_graph(
ops.get_default_graph().as_graph_def(add_shapes=True),
self._checkpoint_dir, "graph.pbtxt")
self._write_graph_thread = threading.Thread(target=_write_graph_fn,
args=[self])
self._write_graph_thread.start()
saver_def = self._get_saver().saver_def if self._get_saver() else None
graph = ops.get_default_graph()
meta_graph_def = meta_graph.create_meta_graph_def(
graph_def=graph.as_graph_def(add_shapes=True), saver_def=saver_def)
if self._summary_writer is None:
raise ValueError("Summary writer is not initialised")
self._summary_writer.add_graph(graph)
self._summary_writer.add_meta_graph(meta_graph_def)
# The checkpoint saved here is the state at step "global_step".
self._save(session, global_step)
self._timer.update_last_triggered_step(global_step)
def before_run(self, run_context: Any): # pylint: disable=unused-argument
return session_run_hook.SessionRunArgs(self._global_step_tensor)
def after_run(self, run_context: session_run_hook.SessionRunContext,
run_values: Any):
global_step = run_context.session.run(self._global_step_tensor)
if self._timer.should_trigger_for_step(global_step):
self._timer.update_last_triggered_step(global_step)
logging.info("Triggering checkpoint. %s", global_step)
if self._save(run_context.session, global_step):
run_context.request_stop()
def end(self, session: session_lib.Session):
if self._save_thread:
logging.info("Waiting for any pending checkpoints to finish.")
self._save_thread.join()
if self._write_graph_thread:
logging.info("Waiting for any pending write_graph to finish.")
self._write_graph_thread.join()
last_step = session.run(self._global_step_tensor)
if self._last_checkpoint_step != last_step:
self._save(session, last_step, asynchronous=False)
for l in self._listeners:
l.end(session, last_step)
def _save(self, session, step, asynchronous=True):
"""Saves the latest checkpoint, returns should_stop."""
def _save_fn():
"""Run the saver process."""
logging.info("Saving checkpoints for %d into %s.", step, self._save_path)
start_time = time.time()
for l in self._listeners:
l.before_save(session, step)
self._get_saver().save(session, self._save_path, global_step=step)
if self._summary_writer is None:
raise ValueError("Summary writer is not initialised")
self._summary_writer.add_session_log(
event_pb2.SessionLog(
status=event_pb2.SessionLog.CHECKPOINT,
checkpoint_path=self._save_path), step)
for l in self._listeners:
l.after_save(session, step)
# Measure the async checkpoint write duration, i.e., non-blocking time.
end_time = time.time()
metrics.AddAsyncCheckpointWriteDuration(
api_label=_ASYNC_CHECKPOINT_V1,
microseconds=_get_duration_microseconds(start_time, end_time))
# Measure the elapsed time since the last checkpoint.
# Due to the nature of async checkpoint, here it actually captures the
# duration between the start_time of the previous checkpoint and the start
# time of this checkpoint. As a result, the duration of the final async
# checkpoint is excluded, which is fine since it does not take much time.
global _END_TIME_OF_LAST_WRITE
with _END_TIME_OF_LAST_WRITE_LOCK:
metrics.AddTrainingTimeSaved(
api_label=_ASYNC_CHECKPOINT_V1,
microseconds=_get_duration_microseconds(_END_TIME_OF_LAST_WRITE,
start_time))
_END_TIME_OF_LAST_WRITE = start_time
logging.info("Checkpoint actual writing time: (%.3f sec)",
end_time - start_time)
logging.info("Checkpoint finished for %d into %s.", step, self._save_path)
# Measure the checkpoint write duration that is blocking the main thread.
blocking_start_time = time.time()
def end_of_blocking_time():
blocking_end_time = time.time()
metrics.AddCheckpointWriteDuration(
api_label=_ASYNC_CHECKPOINT_V1,
microseconds=_get_duration_microseconds(blocking_start_time,
blocking_end_time))
if not asynchronous:
self._last_checkpoint_step = step
_save_fn()
end_of_blocking_time()
return
if self._save_thread is not None:
self._save_thread.join(timeout=0.1)
if self._save_thread.is_alive():
logging.info("Saver thread still in progress, skipping checkpoint.")
end_of_blocking_time()
return
self._last_checkpoint_step = step
self._save_thread = threading.Thread(target=_save_fn)
self._save_thread.start()
end_of_blocking_time()
def _get_saver(self):
if self._saver is not None:
return self._saver
elif self._scaffold is not None:
return self._scaffold.saver
# Get saver from the SAVERS collection if present.
collection_key = ops.GraphKeys.SAVERS
savers = ops.get_collection(collection_key)
if not savers:
raise RuntimeError(
"No items in collection {}. Please add a saver to the collection "
"or provide a saver or scaffold.".format(collection_key))
elif len(savers) > 1:
raise RuntimeError(
"More than one item in collection {}. "
"Please indicate which one to use by passing it to the constructor."
.format(collection_key))
self._saver = savers[0]
return savers[0]
| AsyncCheckpointSaverHook |
python | numba__numba | numba/tests/npyufunc/test_caching.py | {
"start": 4680,
"end": 6882
} | class ____(UfuncCacheTest):
def test_filename_prefix(self):
mod = self.import_module()
usecase = getattr(mod, "direct_gufunc_cache_usecase")
with capture_cache_log() as out:
usecase()
cachelog = out.getvalue()
# find number filename with "guf-" prefix
fmt1 = _fix_raw_path(r'/__pycache__/guf-{}')
prefixed = re.findall(fmt1.format(self.modname), cachelog)
fmt2 = _fix_raw_path(r'/__pycache__/{}')
normal = re.findall(fmt2.format(self.modname), cachelog)
# expecting 2 overloads
self.assertGreater(len(normal), 2)
# expecting equal number of wrappers and overloads cache entries
self.assertEqual(len(normal), len(prefixed))
def test_direct_gufunc_cache(self, **kwargs):
# 2 cache entry for the 2 overloads
# and 2 cache entry for the gufunc wrapper
new_ufunc, cached_ufunc = self.check_ufunc_cache(
"direct_gufunc_cache_usecase", n_overloads=2 + 2, **kwargs)
# Test the cached and original versions
inp = np.random.random(10).astype(np.float64)
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
inp = np.arange(10, dtype=np.intp)
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
def test_direct_gufunc_cache_objmode(self):
self.test_direct_gufunc_cache(forceobj=True)
def test_direct_gufunc_cache_parallel(self):
self.test_direct_gufunc_cache(target='parallel')
def test_indirect_gufunc_cache(self, **kwargs):
# 3 cache entry for the 3 overloads
# and no cache entry for the gufunc wrapper
new_ufunc, cached_ufunc = self.check_ufunc_cache(
"indirect_gufunc_cache_usecase", n_overloads=3, **kwargs)
# Test the cached and original versions
inp = np.random.random(10).astype(np.float64)
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
inp = np.arange(10, dtype=np.intp)
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
def test_indirect_gufunc_cache_parallel(self, **kwargs):
self.test_indirect_gufunc_cache(target='parallel')
| TestGUfuncCacheTest |
python | scrapy__scrapy | tests/test_downloader_handler_twisted_http11.py | {
"start": 782,
"end": 855
} | class ____(HTTP11DownloadHandlerMixin, TestHttp11Base):
pass
| TestHttp11 |
python | readthedocs__readthedocs.org | readthedocs/config/tests/test_validation.py | {
"start": 238,
"end": 791
} | class ____:
def test_it_accepts_true(self):
assert validate_bool(True) is True
def test_it_accepts_false(self):
assert validate_bool(False) is False
def test_it_accepts_0(self):
assert validate_bool(0) is False
def test_it_accepts_1(self):
assert validate_bool(1) is True
def test_it_fails_on_string(self):
with raises(ConfigValidationError) as excinfo:
validate_bool("random string")
assert excinfo.value.message_id == ConfigValidationError.INVALID_BOOL
| TestValidateBool |
python | gevent__gevent | src/gevent/tests/test__select.py | {
"start": 311,
"end": 505
} | class ____(gevent.testing.timing.AbstractGenericWaitTestCase):
def wait(self, timeout):
select.select([], [], [], timeout)
@greentest.skipOnWindows("Cant select on files")
| TestSelect |
python | conda__conda | conda/base/context.py | {
"start": 80220,
"end": 80739
} | class ____:
def __init__(
self,
search_path: PathsType = SEARCH_PATH,
argparse_args: Namespace | None = None,
):
self.set_value(search_path, argparse_args)
def set_value(
self,
search_path: PathsType = SEARCH_PATH,
argparse_args: Namespace | None = None,
) -> None:
self.search_path = search_path
self.argparse_args = argparse_args
def apply(self):
reset_context(self.search_path, self.argparse_args)
| ContextStackObject |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1330280,
"end": 1330581
} | class ____(sgqlc.types.Type, ProjectV2ItemFieldValueCommon, Node):
"""The value of a text field in a Project item."""
__schema__ = github_schema
__field_names__ = ("text",)
text = sgqlc.types.Field(String, graphql_name="text")
"""Text value of a field"""
| ProjectV2ItemFieldTextValue |
python | ray-project__ray | rllib/core/models/tests/test_recurrent_encoders.py | {
"start": 353,
"end": 5068
} | class ____(unittest.TestCase):
def test_gru_encoders(self):
"""Tests building GRU encoders properly and checks for correct architecture."""
# Loop through different combinations of hyperparameters.
inputs_dimss = [[1], [100]]
num_layerss = [1, 4]
hidden_dims = [128, 256]
use_biases = [False, True]
for permutation in itertools.product(
inputs_dimss,
num_layerss,
hidden_dims,
use_biases,
):
(
inputs_dims,
num_layers,
hidden_dim,
use_bias,
) = permutation
print(
f"Testing ...\n"
f"input_dims: {inputs_dims}\n"
f"num_layers: {num_layers}\n"
f"hidden_dim: {hidden_dim}\n"
f"use_bias: {use_bias}\n"
)
config = RecurrentEncoderConfig(
recurrent_layer_type="gru",
input_dims=inputs_dims,
num_layers=num_layers,
hidden_dim=hidden_dim,
use_bias=use_bias,
)
# Use a ModelChecker to compare all added models (different frameworks)
# with each other.
model_checker = ModelChecker(config)
# Add this framework version of the model to our checker.
outputs = model_checker.add(
framework="torch", state={"h": np.array([num_layers, hidden_dim])}
)
# Output shape: [1=B, 1=T, [output_dim]]
self.assertEqual(
outputs[ENCODER_OUT].shape,
(1, 1, config.output_dims[0]),
)
# State shapes: [1=B, 1=num_layers, [hidden_dim]]
self.assertEqual(
outputs[Columns.STATE_OUT]["h"].shape,
(1, num_layers, hidden_dim),
)
# Check all added models against each other.
model_checker.check()
def test_lstm_encoders(self):
"""Tests building LSTM encoders properly and checks for correct architecture."""
# Loop through different combinations of hyperparameters.
inputs_dimss = [[1], [100]]
num_layerss = [1, 3]
hidden_dims = [16, 128]
use_biases = [False, True]
for permutation in itertools.product(
inputs_dimss,
num_layerss,
hidden_dims,
use_biases,
):
(
inputs_dims,
num_layers,
hidden_dim,
use_bias,
) = permutation
print(
f"Testing ...\n"
f"input_dims: {inputs_dims}\n"
f"num_layers: {num_layers}\n"
f"hidden_dim: {hidden_dim}\n"
f"use_bias: {use_bias}\n"
)
config = RecurrentEncoderConfig(
recurrent_layer_type="lstm",
input_dims=inputs_dims,
num_layers=num_layers,
hidden_dim=hidden_dim,
use_bias=use_bias,
)
# Use a ModelChecker to compare all added models (different frameworks)
# with each other.
model_checker = ModelChecker(config)
# Add this framework version of the model to our checker.
outputs = model_checker.add(
framework="torch",
state={
"h": np.array([num_layers, hidden_dim]),
"c": np.array([num_layers, hidden_dim]),
},
)
# Output shape: [1=B, 1=T, [output_dim]]
self.assertEqual(
outputs[ENCODER_OUT].shape,
(1, 1, config.output_dims[0]),
)
# State shapes: [1=B, 1=num_layers, [hidden_dim]]
self.assertEqual(
outputs[Columns.STATE_OUT]["h"].shape,
(1, num_layers, hidden_dim),
)
self.assertEqual(
outputs[Columns.STATE_OUT]["c"].shape,
(1, num_layers, hidden_dim),
)
# Check all added models against each other (only if bias=False).
# See here on why pytorch uses two bias vectors per layer and tf only uses
# one:
# https://towardsdatascience.com/implementation-differences-in-lstm-
# layers-tensorflow-vs-pytorch-77a31d742f74
if use_bias is False:
model_checker.check()
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", __file__]))
| TestRecurrentEncoders |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAliasStatement1.py | {
"start": 208,
"end": 1042
} | class ____[T2]:
type TA2 = int
type TA3 = str
type TA4 = int
T2 = 4
T2 = 4
type TA5[S1, *S2, **S3] = Callable[S3, S1] | tuple[*S2]
X1 = TA5[int, tuple[int, str], ...]
type TA6 = TA5[int, tuple[int, str], ...]
val1: TA5
val2: TA6
if 1 < 2:
# This should generate an error because it is obscured.
type TA7 = int
else:
type TA7 = int
def func1() -> type[int]: ...
# This should generate an error because a call expression is not
# allowed in a type alias definition.
type TA8 = func1()
# This should generate two errors because a tuple and index expression is not
# allowed in a type alias definition.
type TA9 = (int, str, str)[0]
type TA10 = int
# This should generate an error.
TA10.bit_count(1)
# This should generate an error.
TA10(0)
list[TA10]()
# This should generate an error.
| ClassA |
python | dask__dask | dask/dataframe/dask_expr/_rolling.py | {
"start": 5338,
"end": 5394
} | class ____(RollingReduction):
how = "skew"
| RollingSkew |
python | Farama-Foundation__Gymnasium | gymnasium/spaces/dict.py | {
"start": 347,
"end": 11448
} | class ____(Space[dict[str, Any]], typing.Mapping[str, Space[Any]]):
"""A dictionary of :class:`Space` instances.
Elements of this space are (ordered) dictionaries of elements from the constituent spaces.
Example:
>>> from gymnasium.spaces import Dict, Box, Discrete
>>> observation_space = Dict({"position": Box(-1, 1, shape=(2,)), "color": Discrete(3)}, seed=42)
>>> observation_space.sample()
{'color': np.int64(0), 'position': array([-0.3991573 , 0.21649833], dtype=float32)}
With a nested dict:
>>> from gymnasium.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete
>>> Dict( # doctest: +SKIP
... {
... "ext_controller": MultiDiscrete([5, 2, 2]),
... "inner_state": Dict(
... {
... "charge": Discrete(100),
... "system_checks": MultiBinary(10),
... "job_status": Dict(
... {
... "task": Discrete(5),
... "progress": Box(low=0, high=100, shape=()),
... }
... ),
... }
... ),
... }
... )
It can be convenient to use :class:`Dict` spaces if you want to make complex observations or actions more human-readable.
Usually, it will not be possible to use elements of this space directly in learning code. However, you can easily
convert :class:`Dict` observations to flat arrays by using a :class:`gymnasium.wrappers.FlattenObservation` wrapper.
Similar wrappers can be implemented to deal with :class:`Dict` actions.
"""
def __init__(
self,
spaces: None | dict[str, Space] | Sequence[tuple[str, Space]] = None,
seed: dict | int | np.random.Generator | None = None,
**spaces_kwargs: Space,
):
"""Constructor of :class:`Dict` space.
This space can be instantiated in one of two ways: Either you pass a dictionary
of spaces to :meth:`__init__` via the ``spaces`` argument, or you pass the spaces as separate
keyword arguments (where you will need to avoid the keys ``spaces`` and ``seed``)
Args:
spaces: A dictionary of spaces. This specifies the structure of the :class:`Dict` space
seed: Optionally, you can use this argument to seed the RNGs of the spaces that make up the :class:`Dict` space.
**spaces_kwargs: If ``spaces`` is ``None``, you need to pass the constituent spaces as keyword arguments, as described above.
"""
if isinstance(spaces, OrderedDict):
spaces = dict(spaces.items())
elif isinstance(spaces, collections.abc.Mapping):
# for legacy reasons, we need to preserve the sorted dictionary items.
# as this could matter for projects flatten the dictionary.
try:
spaces = dict(sorted(spaces.items()))
except TypeError:
# Incomparable types (e.g. `int` vs. `str`, or user-defined types) found.
# The keys remain in the insertion order.
spaces = dict(spaces.items())
elif isinstance(spaces, Sequence):
spaces = dict(spaces)
elif spaces is None:
spaces = dict()
else:
raise TypeError(
f"Unexpected Dict space input, expecting dict, OrderedDict or Sequence, actual type: {type(spaces)}"
)
# Add kwargs to spaces to allow both dictionary and keywords to be used
for key, space in spaces_kwargs.items():
if key not in spaces:
spaces[key] = space
else:
raise ValueError(
f"Dict space keyword '{key}' already exists in the spaces dictionary."
)
self.spaces: dict[str, Space[Any]] = spaces
for key, space in self.spaces.items():
assert isinstance(
space, Space
), f"Dict space element is not an instance of Space: key='{key}', space={space}"
# None for shape and dtype, since it'll require special handling
super().__init__(None, None, seed) # type: ignore
@property
def is_np_flattenable(self):
"""Checks whether this space can be flattened to a :class:`spaces.Box`."""
return all(space.is_np_flattenable for space in self.spaces.values())
def seed(self, seed: int | dict[str, Any] | None = None) -> dict[str, int]:
"""Seed the PRNG of this space and all subspaces.
Depending on the type of seed, the subspaces will be seeded differently
* ``None`` - All the subspaces will use a random initial seed
* ``Int`` - The integer is used to seed the :class:`Dict` space that is used to generate seed values for each of the subspaces. Warning, this does not guarantee unique seeds for all subspaces, though is very unlikely.
* ``Dict`` - A dictionary of seeds for each subspace, requires a seed key for every subspace. This supports seeding of multiple composite subspaces (``Dict["space": Dict[...], ...]`` with ``{"space": {...}, ...}``).
Args:
seed: An optional int or dictionary of subspace keys to int to seed each PRNG. See above for more details.
Returns:
A dictionary for the seed values of the subspaces
"""
if seed is None:
return {key: subspace.seed(None) for (key, subspace) in self.spaces.items()}
elif isinstance(seed, int):
super().seed(seed)
# Using `np.int32` will mean that the same key occurring is extremely low, even for large subspaces
subseeds = self.np_random.integers(
np.iinfo(np.int32).max, size=len(self.spaces)
)
return {
key: subspace.seed(int(subseed))
for (key, subspace), subseed in zip(self.spaces.items(), subseeds)
}
elif isinstance(seed, dict):
if seed.keys() != self.spaces.keys():
raise ValueError(
f"The seed keys: {seed.keys()} are not identical to space keys: {self.spaces.keys()}"
)
return {key: self.spaces[key].seed(seed[key]) for key in seed.keys()}
else:
raise TypeError(
f"Expected seed type: dict, int or None, actual type: {type(seed)}"
)
def sample(
self,
mask: dict[str, Any] | None = None,
probability: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Generates a single random sample from this space.
The sample is an ordered dictionary of independent samples from the constituent spaces.
Args:
mask: An optional mask for each of the subspaces, expects the same keys as the space
probability: An optional probability mask for each of the subspaces, expects the same keys as the space
Returns:
A dictionary with the same key and sampled values from :attr:`self.spaces`
"""
if mask is not None and probability is not None:
raise ValueError(
f"Only one of `mask` or `probability` can be provided, actual values: mask={mask}, probability={probability}"
)
elif mask is not None:
assert isinstance(
mask, dict
), f"Expected sample mask to be a dict, actual type: {type(mask)}"
assert (
mask.keys() == self.spaces.keys()
), f"Expected sample mask keys to be same as space keys, mask keys: {mask.keys()}, space keys: {self.spaces.keys()}"
return {k: space.sample(mask=mask[k]) for k, space in self.spaces.items()}
elif probability is not None:
assert isinstance(
probability, dict
), f"Expected sample probability mask to be a dict, actual type: {type(probability)}"
assert (
probability.keys() == self.spaces.keys()
), f"Expected sample probability mask keys to be same as space keys, mask keys: {probability.keys()}, space keys: {self.spaces.keys()}"
return {
k: space.sample(probability=probability[k])
for k, space in self.spaces.items()
}
else:
return {k: space.sample() for k, space in self.spaces.items()}
def contains(self, x: Any) -> bool:
"""Return boolean specifying if x is a valid member of this space."""
if isinstance(x, dict) and x.keys() == self.spaces.keys():
return all(x[key] in self.spaces[key] for key in self.spaces.keys())
return False
def __getitem__(self, key: str) -> Space[Any]:
"""Get the space that is associated to `key`."""
return self.spaces[key]
def keys(self) -> KeysView:
"""Returns the keys of the Dict."""
return KeysView(self.spaces)
def __setitem__(self, key: str, value: Space[Any]):
"""Set the space that is associated to `key`."""
assert isinstance(
value, Space
), f"Trying to set {key} to Dict space with value that is not a gymnasium space, actual type: {type(value)}"
self.spaces[key] = value
def __iter__(self):
"""Iterator through the keys of the subspaces."""
yield from self.spaces
def __len__(self) -> int:
"""Gives the number of simpler spaces that make up the `Dict` space."""
return len(self.spaces)
def __repr__(self) -> str:
"""Gives a string representation of this space."""
return (
"Dict(" + ", ".join([f"{k!r}: {s}" for k, s in self.spaces.items()]) + ")"
)
def __eq__(self, other: Any) -> bool:
"""Check whether `other` is equivalent to this instance."""
return (
isinstance(other, Dict)
# Comparison of `OrderedDict`s is order-sensitive
and self.spaces == other.spaces # OrderedDict.__eq__
)
def to_jsonable(self, sample_n: Sequence[dict[str, Any]]) -> dict[str, list[Any]]:
"""Convert a batch of samples from this space to a JSONable data type."""
# serialize as dict-repr of vectors
return {
key: space.to_jsonable([sample[key] for sample in sample_n])
for key, space in self.spaces.items()
}
def from_jsonable(self, sample_n: dict[str, list[Any]]) -> list[dict[str, Any]]:
"""Convert a JSONable data type to a batch of samples from this space."""
dict_of_list: dict[str, list[Any]] = {
key: space.from_jsonable(sample_n[key])
for key, space in self.spaces.items()
}
n_elements = len(next(iter(dict_of_list.values())))
result = [
{key: value[n] for key, value in dict_of_list.items()}
for n in range(n_elements)
]
return result
| Dict |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 20998,
"end": 22922
} | class ____(TestCase):
def test_default(self):
err = np.geterr()
assert_equal(
err, dict(divide="warn", invalid="warn", over="warn", under="ignore")
)
def test_set(self):
err = np.seterr()
old = np.seterr(divide="print")
assert_(err == old)
new = np.seterr()
assert_(new["divide"] == "print")
np.seterr(over="raise")
assert_(np.geterr()["over"] == "raise")
assert_(new["divide"] == "print")
np.seterr(**old)
assert_(np.geterr() == old)
@xfail
@skipif(IS_WASM, reason="no wasm fp exception support")
@skipif(platform.machine() == "armv5tel", reason="See gh-413.")
def test_divide_err(self):
with assert_raises(FloatingPointError):
np.array([1.0]) / np.array([0.0])
np.seterr(divide="ignore")
np.array([1.0]) / np.array([0.0])
@skipif(IS_WASM, reason="no wasm fp exception support")
def test_errobj(self):
olderrobj = np.geterrobj()
self.called = 0
try:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
np.seterrobj([20000, 1, None])
np.array([1.0]) / np.array([0.0])
assert_equal(len(w), 1)
def log_err(*args):
self.called += 1
extobj_err = args
assert_(len(extobj_err) == 2)
assert_("divide" in extobj_err[0])
np.seterrobj([20000, 3, log_err])
np.array([1.0]) / np.array([0.0])
assert_equal(self.called, 1)
np.seterrobj(olderrobj)
np.divide(1.0, 0.0, extobj=[20000, 3, log_err])
assert_equal(self.called, 2)
finally:
np.seterrobj(olderrobj)
del self.called
@xfail # (reason="TODO")
@instantiate_parametrized_tests
| TestSeterr |
python | pypa__warehouse | tests/unit/admin/views/test_projects.py | {
"start": 13768,
"end": 17387
} | class ____:
def test_no_query(self, db_request):
project = ProjectFactory.create()
journals = sorted(
JournalEntryFactory.create_batch(30, name=project.name),
key=lambda x: (x.submitted_date, x.id),
reverse=True,
)
db_request.matchdict["project_name"] = project.normalized_name
result = views.journals_list(project, db_request)
assert result == {"journals": journals[:25], "project": project, "query": None}
def test_with_page(self, db_request):
project = ProjectFactory.create()
journals = sorted(
JournalEntryFactory.create_batch(30, name=project.name),
key=lambda x: (x.submitted_date, x.id),
reverse=True,
)
db_request.matchdict["project_name"] = project.normalized_name
db_request.GET["page"] = "2"
result = views.journals_list(project, db_request)
assert result == {"journals": journals[25:], "project": project, "query": None}
def test_with_invalid_page(self, db_request):
project = ProjectFactory.create()
db_request.matchdict["project_name"] = project.normalized_name
db_request.GET["page"] = "not an integer"
with pytest.raises(HTTPBadRequest):
views.journals_list(project, db_request)
def test_version_query(self, db_request):
project = ProjectFactory.create()
journals = sorted(
JournalEntryFactory.create_batch(30, name=project.name),
key=lambda x: (x.submitted_date, x.id),
reverse=True,
)
db_request.matchdict["project_name"] = project.normalized_name
db_request.GET["q"] = f"version:{journals[3].version}"
result = views.journals_list(project, db_request)
assert result == {
"journals": [journals[3]],
"project": project,
"query": f"version:{journals[3].version}",
}
def test_invalid_key_query(self, db_request):
project = ProjectFactory.create()
journals = sorted(
JournalEntryFactory.create_batch(30, name=project.name),
key=lambda x: (x.submitted_date, x.id),
reverse=True,
)
db_request.matchdict["project_name"] = project.normalized_name
db_request.GET["q"] = "user:username"
result = views.journals_list(project, db_request)
assert result == {
"journals": journals[:25],
"project": project,
"query": "user:username",
}
def test_basic_query(self, db_request):
project = ProjectFactory.create()
journals = sorted(
JournalEntryFactory.create_batch(30, name=project.name),
key=lambda x: (x.submitted_date, x.id),
reverse=True,
)
db_request.matchdict["project_name"] = project.normalized_name
db_request.GET["q"] = f"{journals[3].version}"
result = views.journals_list(project, db_request)
assert result == {
"journals": journals[:25],
"project": project,
"query": f"{journals[3].version}",
}
def test_non_normalized_name(self, db_request):
project = ProjectFactory.create(name="NotNormalized")
db_request.matchdict["project_name"] = str(project.name)
db_request.current_route_path = pretend.call_recorder(
lambda *a, **kw: "/admin/projects/the-redirect/journals/"
)
with pytest.raises(HTTPMovedPermanently):
views.journals_list(project, db_request)
| TestProjectJournalsList |
python | tensorflow__tensorflow | tensorflow/python/summary/summary_iterator_test.py | {
"start": 1024,
"end": 2291
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testSummaryIteratorEventsAddedAfterEndOfFile(self):
test_dir = os.path.join(self.get_temp_dir(), "events")
with writer.FileWriter(test_dir) as w:
session_log_start = event_pb2.SessionLog.START
w.add_session_log(event_pb2.SessionLog(status=session_log_start), 1)
w.flush()
path = glob.glob(os.path.join(test_dir, "event*"))[0]
rr = summary_iterator.summary_iterator(path)
# The first event should list the file_version.
ev = next(rr)
self.assertEqual("brain.Event:2", ev.file_version)
# The next event should be the START message.
ev = next(rr)
self.assertEqual(1, ev.step)
self.assertEqual(session_log_start, ev.session_log.status)
# Reached EOF.
self.assertRaises(StopIteration, lambda: next(rr))
w.add_session_log(event_pb2.SessionLog(status=session_log_start), 2)
w.flush()
# The new event is read, after previously seeing EOF.
ev = next(rr)
self.assertEqual(2, ev.step)
self.assertEqual(session_log_start, ev.session_log.status)
# Get EOF again.
self.assertRaises(StopIteration, lambda: next(rr))
if __name__ == "__main__":
test.main()
| SummaryIteratorTestCase |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingSuper1.py | {
"start": 119,
"end": 255
} | class ____:
# This should generate an error because it's missing a super().__init__ call.
def __init__(self):
pass
| ParentB |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_cross_op_test.py | {
"start": 21206,
"end": 37662
} | class ____(BaseSparseCrossOpTest):
@test_util.run_deprecated_v1
def test_sparse(self):
"""Tests a simple scenario."""
sp_inp_1 = self._sparse_tensor([['batch1-FC1-F1'],
['batch2-FC1-F1', 'batch2-FC1-F2']])
sp_inp_2 = self._sparse_tensor([['batch1-FC2-F1'],
['batch2-FC2-F1', 'batch2-FC2-F2']])
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices],
values=[sp_inp_1.values, sp_inp_2.values],
shapes=[sp_inp_1.dense_shape, sp_inp_2.dense_shape],
dense_inputs=[],
sep='_X_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
# pyformat: disable
expected_out = self._sparse_tensor([
['batch1-FC1-F1_X_batch1-FC2-F1'],
['batch2-FC1-F1_X_batch2-FC2-F1',
'batch2-FC1-F1_X_batch2-FC2-F2',
'batch2-FC1-F2_X_batch2-FC2-F1',
'batch2-FC1-F2_X_batch2-FC2-F2'
]])
# pyformat: enable
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_sparse_sep(self):
"""Tests a simple scenario."""
sp_inp_1 = self._sparse_tensor([['batch1-FC1-F1'],
['batch2-FC1-F1', 'batch2-FC1-F2']])
sp_inp_2 = self._sparse_tensor([['batch1-FC2-F1'],
['batch2-FC2-F1', 'batch2-FC2-F2']])
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices],
values=[sp_inp_1.values, sp_inp_2.values],
shapes=[sp_inp_1.dense_shape, sp_inp_2.dense_shape],
dense_inputs=[],
sep='_Y_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
# pyformat: disable
expected_out = self._sparse_tensor([
['batch1-FC1-F1_Y_batch1-FC2-F1'],
['batch2-FC1-F1_Y_batch2-FC2-F1',
'batch2-FC1-F1_Y_batch2-FC2-F2',
'batch2-FC1-F2_Y_batch2-FC2-F1',
'batch2-FC1-F2_Y_batch2-FC2-F2'
]])
# pyformat: enable
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_dense(self):
"""Tests only dense inputs."""
dense_inp_1 = constant_op.constant([['batch1-FC1-F1', 'batch1-FC1-F2'],
['batch2-FC1-F1', 'batch2-FC1-F2']],
dtypes.string)
dense_inp_2 = constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'],
['batch2-FC2-F1', 'batch2-FC2-F2']],
dtypes.string)
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[],
values=[],
shapes=[],
dense_inputs=[dense_inp_1, dense_inp_2],
sep='_X_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
# pyformat: disable
expected_out = self._sparse_tensor([
['batch1-FC1-F1_X_batch1-FC2-F1', 'batch1-FC1-F1_X_batch1-FC2-F2',
'batch1-FC1-F2_X_batch1-FC2-F1', 'batch1-FC1-F2_X_batch1-FC2-F2'
],
['batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2',
'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2'
]])
# pyformat: enable
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_dense_sep(self):
"""Tests only dense inputs."""
dense_inp_1 = constant_op.constant([['batch1-FC1-F1', 'batch1-FC1-F2'],
['batch2-FC1-F1', 'batch2-FC1-F2']],
dtypes.string)
dense_inp_2 = constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'],
['batch2-FC2-F1', 'batch2-FC2-F2']],
dtypes.string)
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[],
values=[],
shapes=[],
dense_inputs=[dense_inp_1, dense_inp_2],
sep='_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
# pyformat: disable
expected_out = self._sparse_tensor([
['batch1-FC1-F1_batch1-FC2-F1', 'batch1-FC1-F1_batch1-FC2-F2',
'batch1-FC1-F2_batch1-FC2-F1', 'batch1-FC1-F2_batch1-FC2-F2'
],
['batch2-FC1-F1_batch2-FC2-F1', 'batch2-FC1-F1_batch2-FC2-F2',
'batch2-FC1-F2_batch2-FC2-F1', 'batch2-FC1-F2_batch2-FC2-F2'
]])
# pyformat: enable
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_integer_mixed_string_sparse(self):
"""Tests mixed type."""
sp_inp_1 = self._sparse_tensor([[11], [333, 55555]])
sp_inp_2 = self._sparse_tensor([['batch1-FC2-F1'],
['batch2-FC2-F1', 'batch2-FC2-F2']])
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices],
values=[sp_inp_1.values, sp_inp_2.values],
shapes=[sp_inp_1.dense_shape, sp_inp_2.dense_shape],
dense_inputs=[],
sep='_X_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
# pyformat: disable
expected_out = self._sparse_tensor([
['11_X_batch1-FC2-F1'],
['333_X_batch2-FC2-F1', '333_X_batch2-FC2-F2',
'55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2'
]])
# pyformat: enable
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_integer_mixed_string_dense(self):
"""Tests mixed dense inputs."""
dense_inp_1 = constant_op.constant([[11, 333], [55555, 999999]],
dtypes.int64)
dense_inp_2 = constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'],
['batch2-FC2-F1', 'batch2-FC2-F2']],
dtypes.string)
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[],
values=[],
shapes=[],
dense_inputs=[dense_inp_1, dense_inp_2],
sep='_X_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
# pyformat: disable
expected_out = self._sparse_tensor([
['11_X_batch1-FC2-F1', '11_X_batch1-FC2-F2',
'333_X_batch1-FC2-F1', '333_X_batch1-FC2-F2'
],
['55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2',
'999999_X_batch2-FC2-F1', '999999_X_batch2-FC2-F2'
]])
# pyformat: enable
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_sparse_cross_dense(self):
"""Tests sparse and dense inputs."""
sp_inp = self._sparse_tensor([['batch1-FC1-F1'],
['batch2-FC1-F1', 'batch2-FC1-F2']])
dense_inp = constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'],
['batch2-FC2-F1', 'batch2-FC2-F2']],
dtypes.string)
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp.indices],
values=[sp_inp.values],
shapes=[sp_inp.dense_shape],
dense_inputs=[dense_inp],
sep='_X_')
expected_out = self._sparse_tensor(
[['batch1-FC1-F1_X_batch1-FC2-F1', 'batch1-FC1-F1_X_batch1-FC2-F2'],
[
'batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2',
'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2'
]])
out = sparse_tensor.SparseTensor(inds, vals, shapes)
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_permutation_3x3x3(self):
"""Tests 3x3x3 permutation."""
sp_inp_1 = self._sparse_tensor(
[['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']])
sp_inp_2 = self._sparse_tensor(
[['batch1-FC2-F1', 'batch1-FC2-F2', 'batch1-FC2-F3']])
sp_inp_3 = self._sparse_tensor(
[['batch1-FC3-F1', 'batch1-FC3-F2', 'batch1-FC3-F3']])
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices, sp_inp_3.indices],
values=[sp_inp_1.values, sp_inp_2.values, sp_inp_3.values],
shapes=[
sp_inp_1.dense_shape, sp_inp_2.dense_shape, sp_inp_3.dense_shape
],
dense_inputs=[],
sep='_X_')
expected_out = self._sparse_tensor([[
'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2',
'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F3',
'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F1',
'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F2',
'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F3',
'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F1',
'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F2',
'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F3',
'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2',
'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F3',
'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F1',
'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F2',
'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F3',
'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F1',
'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F2',
'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F3',
'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F2',
'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F3',
'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F1',
'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F2',
'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F3',
'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F1',
'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F2',
'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F3'
]])
out = sparse_tensor.SparseTensor(inds, vals, shapes)
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_permutation_3x1x2(self):
"""Tests 3x1x2 permutation."""
sp_inp_1 = self._sparse_tensor(
[['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']])
sp_inp_2 = self._sparse_tensor([['batch1-FC2-F1']])
sp_inp_3 = self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']])
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices, sp_inp_3.indices],
values=[sp_inp_1.values, sp_inp_2.values, sp_inp_3.values],
shapes=[
sp_inp_1.dense_shape, sp_inp_2.dense_shape, sp_inp_3.dense_shape
],
dense_inputs=[],
sep='_X_')
expected_out = self._sparse_tensor([[
'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2',
'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2',
'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F2'
]])
out = sparse_tensor.SparseTensor(inds, vals, shapes)
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_large_batch(self):
"""Tests with large batch size to force multithreading."""
batch_size = 5000
col1 = []
col2 = []
col3 = []
for b in range(batch_size):
col1.append(
['batch%d-FC1-F1' % b,
'batch%d-FC1-F2' % b,
'batch%d-FC1-F3' % b])
col2.append(['batch%d-FC2-F1' % b])
col3.append(['batch%d-FC3-F1' % b, 'batch%d-FC3-F2' % b])
sp_inp_1 = self._sparse_tensor(col1)
sp_inp_2 = self._sparse_tensor(col2)
sp_inp_3 = self._sparse_tensor(col3)
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices, sp_inp_3.indices],
values=[sp_inp_1.values, sp_inp_2.values, sp_inp_3.values],
shapes=[
sp_inp_1.dense_shape, sp_inp_2.dense_shape, sp_inp_3.dense_shape
],
dense_inputs=[],
sep='_X_')
col_out = []
for b in range(batch_size):
col_out.append([
'batch%d-FC1-F1_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b),
'batch%d-FC1-F1_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b),
'batch%d-FC1-F2_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b),
'batch%d-FC1-F2_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b),
'batch%d-FC1-F3_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b),
'batch%d-FC1-F3_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b)
])
expected_out = self._sparse_tensor(col_out)
out = sparse_tensor.SparseTensor(inds, vals, shapes)
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_one_column_empty(self):
"""Tests when one column is empty.
The crossed tensor should be empty.
"""
sp_inp_1 = self._sparse_tensor([['batch1-FC1-F1', 'batch1-FC1-F2']])
sp_inp_2 = self._sparse_tensor([], 1)
sp_inp_3 = self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']])
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices, sp_inp_3.indices],
values=[sp_inp_1.values, sp_inp_2.values, sp_inp_3.values],
shapes=[
sp_inp_1.dense_shape, sp_inp_2.dense_shape, sp_inp_3.dense_shape
],
dense_inputs=[],
sep='_X_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
with self.cached_session():
self._assert_sparse_tensor_empty(self.evaluate(out))
@test_util.run_deprecated_v1
def test_some_columns_empty(self):
"""Tests when more than one columns are empty.
Cross for the corresponding batch should be empty.
"""
sp_inp_1 = self._sparse_tensor([['batch1-FC1-F1', 'batch1-FC1-F2']], 2)
sp_inp_2 = self._sparse_tensor([['batch1-FC2-F1'], ['batch2-FC2-F1']], 2)
sp_inp_3 = self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']], 2)
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices, sp_inp_3.indices],
values=[sp_inp_1.values, sp_inp_2.values, sp_inp_3.values],
shapes=[
sp_inp_1.dense_shape, sp_inp_2.dense_shape, sp_inp_3.dense_shape
],
dense_inputs=[],
sep='_X_')
expected_out = self._sparse_tensor([[
'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2',
'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1',
'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2'
]], 2)
out = sparse_tensor.SparseTensor(inds, vals, shapes)
with self.cached_session():
self._assert_sparse_tensor_equals(expected_out, self.evaluate(out))
@test_util.run_deprecated_v1
def test_all_columns_empty(self):
"""Tests when all columns are empty.
The crossed tensor should be empty.
"""
sp_inp_1 = self._sparse_tensor([])
sp_inp_2 = self._sparse_tensor([])
sp_inp_3 = self._sparse_tensor([])
inds, vals, shapes = gen_sparse_ops.sparse_cross_v2(
indices=[sp_inp_1.indices, sp_inp_2.indices, sp_inp_3.indices],
values=[sp_inp_1.values, sp_inp_2.values, sp_inp_3.values],
shapes=[
sp_inp_1.dense_shape, sp_inp_2.dense_shape, sp_inp_3.dense_shape
],
dense_inputs=[],
sep='_X_')
out = sparse_tensor.SparseTensor(inds, vals, shapes)
with self.cached_session():
self._assert_sparse_tensor_empty(self.evaluate(out))
def testNonScalarInput(self):
with self.assertRaisesRegex(errors.InvalidArgumentError,
'Input separator should be a scalar.'):
self.evaluate(sparse_ops.sparse_cross(
inputs=[],
name='a',
separator=constant_op.constant(['a', 'b'], dtype=dtypes.string)))
| SparseCrossV2OpTest |
python | dask__distributed | distributed/shuffle/tests/utils.py | {
"start": 212,
"end": 963
} | class ____(PooledRPCCall):
def __init__(self, shuffle: ShuffleRun):
self.shuffle = shuffle
def __getattr__(self, key):
async def _(**kwargs):
from distributed.protocol.serialize import _nested_deserialize
method_name = key.replace("shuffle_", "")
kwargs.pop("shuffle_id", None)
kwargs.pop("run_id", None)
# TODO: This is a bit awkward. At some point the arguments are
# already getting wrapped with a `Serialize`. We only want to unwrap
# here.
kwargs = _nested_deserialize(kwargs)
meth = getattr(self.shuffle, method_name)
return _nested_deserialize(await meth(**kwargs))
return _
| PooledRPCShuffle |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 1931,
"end": 2201
} | class ____(WebTestCase):
"""Simplified base class for tests that work with a single handler class.
To use, define a nested class named ``Handler``.
"""
Handler = None
def get_handlers(self):
return [("/", self.Handler)]
| SimpleHandlerTestCase |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/int.py | {
"start": 42070,
"end": 47123
} | class ____(BaseInt[np.dtypes.UInt64DType, np.uint64], HasEndianness):
"""
A Zarr data type for arrays containing 64-bit unsigned integers.
Wraps the [`np.dtypes.UInt64DType`][numpy.dtypes.UInt64DType] data type. Scalars for this data type
are instances of [`np.uint64`][numpy.uint64].
Attributes
----------
dtype_cls: np.dtypes.UInt64DType
The class of the underlying NumPy dtype.
References
----------
This class implements the unsigned 64-bit integer data type defined in Zarr V2 and V3.
See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details.
"""
dtype_cls = np.dtypes.UInt64DType
_zarr_v3_name: ClassVar[Literal["uint64"]] = "uint64"
_zarr_v2_names: ClassVar[tuple[Literal[">u8"], Literal["<u8"]]] = (">u8", "<u8")
def to_native_dtype(self) -> np.dtypes.UInt64DType:
"""
Convert the data type to a native NumPy dtype.
Returns
-------
np.dtypes.UInt64DType
The native NumPy dtype.eeeeeeeeeeeeeeeee
"""
byte_order = endianness_to_numpy_str(self.endianness)
return self.dtype_cls().newbyteorder(byte_order)
@classmethod
def _from_json_v2(cls, data: DTypeJSON) -> Self:
"""
Create an instance of this data type from Zarr V2-flavored JSON.
Parameters
----------
data : DTypeJSON
The JSON data.
Returns
-------
Self
An instance of this data type.
Raises
------
DataTypeValidationError
If the input JSON is not a valid representation of this class unsigned 64-bit
integer.
"""
if cls._check_json_v2(data):
# Going via NumPy ensures that we get the endianness correct without
# annoying string parsing.
name = data["name"]
return cls.from_native_dtype(np.dtype(name))
msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected one of the strings {cls._zarr_v2_names}."
raise DataTypeValidationError(msg)
@classmethod
def _from_json_v3(cls, data: DTypeJSON) -> Self:
"""
Create an instance of this data type from Zarr V3-flavored JSON.
Parameters
----------
data : DTypeJSON
The JSON data.
Returns
-------
Self
An instance of this data type.
Raises
------
DataTypeValidationError
If the input JSON is not a valid representation of this class unsigned 64-bit
integer.
"""
if cls._check_json_v3(data):
return cls()
msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}"
raise DataTypeValidationError(msg)
@overload
def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal[">u8", "<u8"], None]: ...
@overload
def to_json(self, zarr_format: Literal[3]) -> Literal["uint64"]: ...
def to_json(
self, zarr_format: ZarrFormat
) -> DTypeConfig_V2[Literal[">u8", "<u8"], None] | Literal["uint64"]:
"""
Convert the data type to a JSON-serializable form.
Parameters
----------
zarr_format : ZarrFormat
The Zarr format version.
Returns
-------
DTypeConfig_V2[Literal[">u8", "<u8"], None] | Literal["uint64"]
The JSON-serializable representation of the data type.
"""
if zarr_format == 2:
name = self.to_native_dtype().str
return {"name": name, "object_codec_id": None}
elif zarr_format == 3:
return self._zarr_v3_name
raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover
@classmethod
def from_native_dtype(cls, dtype: TBaseDType) -> Self:
"""
Create an instance of this data type from a native NumPy dtype.
Parameters
----------
dtype : TBaseDType
The native NumPy dtype.
Returns
-------
Self
An instance of this data type.
Raises
------
DataTypeValidationError
If the input dtype is not a valid representation of this class unsigned 64-bit
integer.
"""
if cls._check_native_dtype(dtype):
return cls(endianness=get_endianness_from_numpy_dtype(dtype))
raise DataTypeValidationError(
f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}"
)
@property
def item_size(self) -> int:
"""
The size of a single scalar in bytes.
Returns
-------
int
The size of a single scalar in bytes.
"""
return 8
| UInt64 |
python | doocs__leetcode | solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/Solution.py | {
"start": 0,
"end": 431
} | class ____:
def maxDiff(self, num: int) -> int:
a, b = str(num), str(num)
for c in a:
if c != "9":
a = a.replace(c, "9")
break
if b[0] != "1":
b = b.replace(b[0], "1")
else:
for c in b[1:]:
if c not in "01":
b = b.replace(c, "0")
break
return int(a) - int(b)
| Solution |
python | pytorch__pytorch | .github/scripts/trymerge.py | {
"start": 21388,
"end": 47397
} | class ____:
def __init__(self, org: str, project: str, pr_num: int) -> None:
assert isinstance(pr_num, int)
self.org = org
self.project = project
self.pr_num = pr_num
self.info = gh_get_pr_info(org, project, pr_num)
self.changed_files: Optional[list[str]] = None
self.labels: Optional[list[str]] = None
self.conclusions: Optional[JobNameToStateDict] = None
self.comments: Optional[list[GitHubComment]] = None
self._authors: Optional[list[tuple[str, str]]] = None
self._reviews: Optional[list[tuple[str, str]]] = None
self.merge_base: Optional[str] = None
self.submodules: Optional[list[str]] = None
def is_closed(self) -> bool:
return bool(self.info["closed"])
def is_cross_repo(self) -> bool:
return bool(self.info["isCrossRepository"])
def base_ref(self) -> str:
return cast(str, self.info["baseRefName"])
def default_branch(self) -> str:
return cast(str, self.info["baseRepository"]["defaultBranchRef"]["name"])
def head_ref(self) -> str:
return cast(str, self.info["headRefName"])
def is_ghstack_pr(self) -> bool:
return RE_GHSTACK_HEAD_REF.match(self.head_ref()) is not None
def get_ghstack_orig_ref(self) -> str:
assert self.is_ghstack_pr()
return re.sub(r"/head$", "/orig", self.head_ref())
def is_base_repo_private(self) -> bool:
return bool(self.info["baseRepository"]["isPrivate"])
def get_changed_files_count(self) -> int:
return int(self.info["changedFiles"])
def last_commit(self) -> Any:
return self.info["commits"]["nodes"][-1]["commit"]
def last_commit_sha(self, default: Optional[str] = None) -> str:
# for commits, the oid is the sha
if default is None:
return str(self.last_commit()["oid"])
return str(self.last_commit().get("oid", default))
def get_merge_base(self) -> str:
if self.merge_base:
return self.merge_base
last_commit_sha = self.last_commit_sha()
# NB: We could use self.base_ref() here for regular PR, however, that doesn't
# work for ghstack where the base is the custom branch, i.e. gh/USER/ID/base,
# so let's just use main instead
self.merge_base = gh_fetch_merge_base(
self.org, self.project, last_commit_sha, self.default_branch()
)
# Fallback to baseRefOid if the API call fails, i.e. rate limit. Note that baseRefOid
# points to the base ref associated with the PR or, in other words, the head of main
# when the PR is created or rebased. This is not necessarily the merge base commit,
# but it could serve as a fallback in most cases and it's readily available as part
# of the PR info
if not self.merge_base:
self.merge_base = cast(str, self.info["baseRefOid"])
return self.merge_base
def get_changed_files(self) -> list[str]:
if self.changed_files is None:
info = self.info
unique_changed_files = set()
# Do not try to fetch more than 10K files
for _ in range(100):
unique_changed_files.update([x["path"] for x in info["files"]["nodes"]])
if not info["files"]["pageInfo"]["hasNextPage"]:
break
rc = gh_graphql(
GH_GET_PR_NEXT_FILES_QUERY,
name=self.project,
owner=self.org,
number=self.pr_num,
cursor=info["files"]["pageInfo"]["endCursor"],
)
info = rc["data"]["repository"]["pullRequest"]
self.changed_files = list(unique_changed_files)
if len(self.changed_files) != self.get_changed_files_count():
raise RuntimeError("Changed file count mismatch")
return self.changed_files
def get_submodules(self) -> list[str]:
if self.submodules is None:
rc = gh_graphql(GH_GET_REPO_SUBMODULES, name=self.project, owner=self.org)
info = rc["data"]["repository"]["submodules"]
self.submodules = [s["path"] for s in info["nodes"]]
return self.submodules
def get_changed_submodules(self) -> list[str]:
submodules = self.get_submodules()
return [f for f in self.get_changed_files() if f in submodules]
def has_invalid_submodule_updates(self) -> bool:
"""Submodule updates in PR are invalid if submodule keyword
is not mentioned in neither the title nor body/description
nor in any of the labels.
"""
return (
len(self.get_changed_submodules()) > 0
and "submodule" not in self.get_title().lower()
and "submodule" not in self.get_body().lower()
and all("submodule" not in label for label in self.get_labels())
)
def _get_reviews(self) -> list[tuple[str, str]]:
if self._reviews is None:
self._reviews = []
info = self.info
for _ in range(100):
nodes = info["reviews"]["nodes"]
self._reviews = [
(node["author"]["login"], node["state"]) for node in nodes
] + self._reviews
if not info["reviews"]["pageInfo"]["hasPreviousPage"]:
break
rc = gh_graphql(
GH_GET_PR_PREV_REVIEWS_QUERY,
name=self.project,
owner=self.org,
number=self.pr_num,
cursor=info["reviews"]["pageInfo"]["startCursor"],
)
info = rc["data"]["repository"]["pullRequest"]
reviews = {
author: state for author, state in self._reviews if state != "COMMENTED"
}
return list(reviews.items())
def get_approved_by(self) -> list[str]:
return [login for (login, state) in self._get_reviews() if state == "APPROVED"]
def get_commit_count(self) -> int:
return int(self.info["commits_with_authors"]["totalCount"])
def get_commit_sha_at_comment(self, comment_id: int) -> Optional[str]:
"""
Get the PR head commit SHA that was present when a specific comment was posted.
This ensures we only merge the state of the PR at the time the merge command was issued,
not any subsequent commits that may have been pushed after.
Returns None if no head-changing events found before the comment or if the comment was not found.
"""
head = None
try:
for event in iter_issue_timeline_until_comment(
self.org, self.project, self.pr_num, comment_id
):
etype = event.get("event")
if etype == "committed":
sha = sha_from_committed_event(event)
if sha:
head = sha
print(f"Timeline: Found commit event for SHA {sha}")
elif etype == "head_ref_force_pushed":
sha = sha_from_force_push_after(event)
if sha:
head = sha
print(f"Timeline: Found force push event for SHA {sha}")
elif etype == "commented":
if event.get("id") == comment_id:
print(f"Timeline: Found final comment with sha {sha}")
return head
except Exception as e:
print(
f"Warning: Failed to reconstruct timeline for comment {comment_id}: {e}"
)
return None
print(f"Did not find comment with id {comment_id} in the PR timeline")
return None
def get_pr_creator_login(self) -> str:
return cast(str, self.info["author"]["login"])
def _fetch_authors(self) -> list[tuple[str, str]]:
if self._authors is not None:
return self._authors
authors: list[tuple[str, str]] = []
def add_authors(info: dict[str, Any]) -> None:
for node in info["commits_with_authors"]["nodes"]:
for author_node in node["commit"]["authors"]["nodes"]:
user_node = author_node["user"]
author = f"{author_node['name']} <{author_node['email']}>"
if user_node is None:
# If author is not github user, user node will be null
authors.append(("", author))
else:
authors.append((cast(str, user_node["login"]), author))
info = self.info
for _ in range(100):
add_authors(info)
if not info["commits_with_authors"]["pageInfo"]["hasNextPage"]:
break
rc = gh_graphql(
GH_GET_PR_NEXT_AUTHORS_QUERY,
name=self.project,
owner=self.org,
number=self.pr_num,
cursor=info["commits_with_authors"]["pageInfo"]["endCursor"],
)
info = rc["data"]["repository"]["pullRequest"]
self._authors = authors
return authors
def get_committer_login(self, num: int = 0) -> str:
return self._fetch_authors()[num][0]
def get_committer_author(self, num: int = 0) -> str:
return self._fetch_authors()[num][1]
def get_labels(self) -> list[str]:
if self.labels is not None:
return self.labels
labels = (
[node["node"]["name"] for node in self.info["labels"]["edges"]]
if "labels" in self.info
else []
)
self.labels = labels
return self.labels
def get_checkrun_conclusions(self) -> JobNameToStateDict:
"""Returns dict of checkrun -> [conclusion, url]"""
if self.conclusions is not None:
return self.conclusions
orig_last_commit = self.last_commit()
def get_pr_next_check_runs(
edges: list[dict[str, dict[str, Any]]], edge_idx: int, checkruns: Any
) -> Any:
rc = gh_graphql(
GH_GET_PR_NEXT_CHECK_RUNS,
name=self.project,
owner=self.org,
number=self.pr_num,
cs_cursor=edges[edge_idx - 1]["cursor"] if edge_idx > 0 else None,
cr_cursor=checkruns["pageInfo"]["endCursor"],
)
last_commit = rc["data"]["repository"]["pullRequest"]["commits"]["nodes"][
-1
]["commit"]
checkruns = last_commit["checkSuites"]["nodes"][-1]["checkRuns"]
return checkruns
def get_pr_next_checksuites(checksuites: Any) -> Any:
rc = gh_graphql(
GH_GET_PR_NEXT_CHECKSUITES,
name=self.project,
owner=self.org,
number=self.pr_num,
cursor=checksuites["edges"][-1]["cursor"],
)
info = rc["data"]["repository"]["pullRequest"]
last_commit = info["commits"]["nodes"][-1]["commit"]
if last_commit["oid"] != orig_last_commit["oid"]:
raise RuntimeError("Last commit changed on PR")
return last_commit["checkSuites"]
checksuites = orig_last_commit["checkSuites"]
self.conclusions = add_workflow_conclusions(
checksuites, get_pr_next_check_runs, get_pr_next_checksuites
)
# Append old style statuses(like ones populated by CircleCI or EasyCLA) to conclusions
if orig_last_commit["status"] and orig_last_commit["status"]["contexts"]:
for status in orig_last_commit["status"]["contexts"]:
name = status["context"]
self.conclusions[name] = JobCheckState(
name,
status["targetUrl"],
status["state"],
classification=None,
job_id=None,
title=None,
summary=None,
)
# Making an exception for Apply lint auggestions/autoformat because the
# bot adds a merged label -> triggers workflow -> sometimes needs
# approval -> is read as failure, which results in a blocked merge, but
# this workflow doesn't provide mergability info
self.conclusions.pop("Apply lint suggestions", None)
return self.conclusions
def get_authors(self) -> dict[str, str]:
rc = {}
for idx in range(len(self._fetch_authors())):
rc[self.get_committer_login(idx)] = self.get_committer_author(idx)
return rc
def get_author(self) -> str:
authors = self.get_authors()
if len(authors) == 1:
return next(iter(authors.values()))
creator = self.get_pr_creator_login()
# If PR creator is not among authors
# Assume it was authored by first commit author
if creator not in authors:
return self.get_committer_author(0)
return authors[creator]
def get_title(self) -> str:
return cast(str, self.info["title"])
def get_body(self) -> str:
return cast(str, self.info["body"])
def get_merge_commit(self) -> Optional[str]:
mc = self.info["mergeCommit"]
return mc["oid"] if mc is not None else None
def get_pr_url(self) -> str:
return f"https://github.com/{self.org}/{self.project}/pull/{self.pr_num}"
@staticmethod
def _comment_from_node(node: Any) -> GitHubComment:
editor = node["editor"]
return GitHubComment(
body_text=node["bodyText"],
created_at=node.get("createdAt", ""),
author_login=node["author"]["login"],
author_url=node["author"].get("url", None),
author_association=node["authorAssociation"],
editor_login=editor["login"] if editor else None,
database_id=node["databaseId"],
url=node["url"],
)
def get_comments(self) -> list[GitHubComment]:
if self.comments is not None:
return self.comments
self.comments = []
info = self.info["comments"]
# Do not try to fetch more than 10K comments
for _ in range(100):
self.comments = [
self._comment_from_node(node) for node in info["nodes"]
] + self.comments
if not info["pageInfo"]["hasPreviousPage"]:
break
rc = gh_graphql(
GH_GET_PR_PREV_COMMENTS,
name=self.project,
owner=self.org,
number=self.pr_num,
cursor=info["pageInfo"]["startCursor"],
)
info = rc["data"]["repository"]["pullRequest"]["comments"]
return self.comments
def get_last_comment(self) -> GitHubComment:
return self._comment_from_node(self.info["comments"]["nodes"][-1])
def get_comment_by_id(self, database_id: int) -> GitHubComment:
if self.comments is None:
# Fastpath - try searching in partial prefetched comments
for node in self.info["comments"]["nodes"]:
comment = self._comment_from_node(node)
if comment.database_id == database_id:
return comment
for comment in self.get_comments():
if comment.database_id == database_id:
return comment
# The comment could have actually been a review left on the PR (the message written alongside the review).
# (This is generally done to trigger the merge right when a comment is left)
# Check those review comments to see if one of those was the comment in question.
for node in self.info["reviews"]["nodes"]:
# These review comments contain all the fields regular comments need
comment = self._comment_from_node(node)
if comment.database_id == database_id:
return comment
raise RuntimeError(f"Comment with id {database_id} not found")
def get_diff_revision(self) -> Optional[str]:
rc = RE_DIFF_REV.search(self.get_body())
return rc.group(1) if rc is not None else None
def has_internal_changes(self) -> bool:
checkrun_name = INTERNAL_CHANGES_CHECKRUN_NAME
if self.get_diff_revision() is None:
return False
checks = self.get_checkrun_conclusions()
if checks is None or checkrun_name not in checks:
return False
return checks[checkrun_name].status != "SUCCESS"
def has_no_connected_diff(self) -> bool:
checkrun_name = INTERNAL_CHANGES_CHECKRUN_NAME
checks = self.get_checkrun_conclusions()
if checks is None or checkrun_name not in checks:
return False
return checks[checkrun_name].title == HAS_NO_CONNECTED_DIFF_TITLE
def merge_ghstack_into(
self,
repo: GitRepo,
skip_mandatory_checks: bool,
comment_id: Optional[int] = None,
skip_all_rule_checks: bool = False,
) -> list["GitHubPR"]:
assert self.is_ghstack_pr()
ghstack_prs = get_ghstack_prs(
repo, self, open_only=False
) # raises error if out of sync
pr_dependencies = []
for pr, rev in ghstack_prs:
if pr.is_closed():
pr_dependencies.append(pr)
continue
commit_msg = pr.gen_commit_message(
filter_ghstack=True, ghstack_deps=pr_dependencies
)
if pr.pr_num != self.pr_num and not skip_all_rule_checks:
# Raises exception if matching rule is not found
find_matching_merge_rule(
pr,
repo,
skip_mandatory_checks=skip_mandatory_checks,
skip_internal_checks=can_skip_internal_checks(self, comment_id),
)
repo.cherry_pick(rev)
repo.amend_commit_message(commit_msg)
pr_dependencies.append(pr)
return [x for x, _ in ghstack_prs if not x.is_closed()]
def gen_commit_message(
self,
filter_ghstack: bool = False,
ghstack_deps: Optional[list["GitHubPR"]] = None,
) -> str:
"""Fetches title and body from PR description
adds reviewed by, pull request resolved and optionally
filters out ghstack info"""
# Adding the url here makes it clickable within the Github UI
approved_by_urls = ", ".join(
prefix_with_github_url(login) for login in self.get_approved_by()
)
# Remove "cc: " line from the message body
msg_body = re.sub(RE_PR_CC_LINE, "", self.get_body())
if filter_ghstack:
msg_body = re.sub(RE_GHSTACK_DESC, "", msg_body)
msg = self.get_title() + f" (#{self.pr_num})\n\n"
msg += msg_body
msg += f"\nPull Request resolved: {self.get_pr_url()}\n"
msg += f"Approved by: {approved_by_urls}\n"
if ghstack_deps:
msg += f"ghstack dependencies: {', '.join([f'#{pr.pr_num}' for pr in ghstack_deps])}\n"
# Mention PR co-authors, which should be at the end of the message
# And separated from the body by two newlines
first_coauthor = True
for author_login, author_name in self.get_authors().items():
if author_login != self.get_pr_creator_login():
if first_coauthor:
msg, first_coauthor = (msg + "\n", False)
msg += f"\nCo-authored-by: {author_name}"
return msg
def add_numbered_label(self, label_base: str, dry_run: bool) -> None:
labels = self.get_labels() if self.labels is not None else []
full_label = label_base
count = 0
for label in labels:
if label_base in label:
count += 1
full_label = f"{label_base}X{count}"
self.add_label(full_label, dry_run)
def add_label(self, label: str, dry_run: bool) -> None:
gh_add_labels(self.org, self.project, self.pr_num, [label], dry_run)
def merge_into(
self,
repo: GitRepo,
*,
skip_mandatory_checks: bool = False,
dry_run: bool = False,
comment_id: int,
ignore_current_checks: Optional[list[str]] = None,
) -> None:
# Raises exception if matching rule is not found
(
merge_rule,
pending_checks,
failed_checks,
ignorable_checks,
) = find_matching_merge_rule(
self,
repo,
skip_mandatory_checks=skip_mandatory_checks,
skip_internal_checks=can_skip_internal_checks(self, comment_id),
ignore_current_checks=ignore_current_checks,
)
additional_merged_prs = self.merge_changes_locally(
repo, skip_mandatory_checks, comment_id
)
repo.push(self.default_branch(), dry_run)
if not dry_run:
self.add_numbered_label(MERGE_COMPLETE_LABEL, dry_run)
for pr in additional_merged_prs:
pr.add_numbered_label(MERGE_COMPLETE_LABEL, dry_run)
# When the merge process reaches this part, we can assume that the commit
# has been successfully pushed to trunk
merge_commit_sha = repo.rev_parse(name=self.default_branch())
if comment_id and self.pr_num:
# Finally, upload the record to s3. The list of pending and failed
# checks are at the time of the merge
save_merge_record(
comment_id=comment_id,
pr_num=self.pr_num,
owner=self.org,
project=self.project,
author=self.get_author(),
pending_checks=pending_checks,
failed_checks=failed_checks,
ignore_current_checks=ignorable_checks.get("IGNORE_CURRENT_CHECK", []),
broken_trunk_checks=ignorable_checks.get("BROKEN_TRUNK", []),
flaky_checks=ignorable_checks.get("FLAKY", []),
unstable_checks=ignorable_checks.get("UNSTABLE", []),
last_commit_sha=self.last_commit_sha(default=""),
merge_base_sha=self.get_merge_base(),
merge_commit_sha=merge_commit_sha,
is_failed=False,
skip_mandatory_checks=skip_mandatory_checks,
ignore_current=bool(ignore_current_checks),
)
else:
print("Missing comment ID or PR number, couldn't upload to s3")
# Usually Github will see that the commit has "resolves <pr_num>" in the
# commit message and close the PR, but sometimes it doesn't, leading to
# confusion. When it doesn't, we close it manually.
time.sleep(60) # Give Github some time to close the PR
manually_close_merged_pr(
pr=self,
additional_merged_prs=additional_merged_prs,
merge_commit_sha=merge_commit_sha,
dry_run=dry_run,
)
def merge_changes_locally(
self,
repo: GitRepo,
skip_mandatory_checks: bool = False,
comment_id: Optional[int] = None,
branch: Optional[str] = None,
skip_all_rule_checks: bool = False,
) -> list["GitHubPR"]:
"""
:param skip_all_rule_checks: If true, skips all rule checks on ghstack PRs, useful for dry-running merge locally
"""
branch_to_merge_into = self.default_branch() if branch is None else branch
if repo.current_branch() != branch_to_merge_into:
repo.checkout(branch_to_merge_into)
# It's okay to skip the commit SHA check for ghstack PRs since
# authoring requires write access to the repo.
if self.is_ghstack_pr():
return self.merge_ghstack_into(
repo,
skip_mandatory_checks,
comment_id=comment_id,
skip_all_rule_checks=skip_all_rule_checks,
)
msg = self.gen_commit_message()
pr_branch_name = f"__pull-request-{self.pr_num}__init__"
# Determine which commit SHA to merge
commit_to_merge = None
if not comment_id:
raise ValueError("Must provide --comment-id when merging regular PRs")
# Get the commit SHA that was present when the comment was made
commit_to_merge = self.get_commit_sha_at_comment(comment_id)
if not commit_to_merge:
raise RuntimeError(
f"Could not find commit that was pushed before comment {comment_id}"
)
# Validate that this commit is the latest commit on the PR
latest_commit = self.last_commit_sha()
if commit_to_merge != latest_commit:
raise RuntimeError(
f"Commit {commit_to_merge} was HEAD when comment {comment_id} was posted "
f"but now the latest commit on the PR is {latest_commit}. "
f"Please re-issue the merge command to merge the latest commit."
)
print(f"Merging commit {commit_to_merge} locally")
repo.fetch(commit_to_merge, pr_branch_name)
repo._run_git("merge", "--squash", pr_branch_name)
repo._run_git("commit", f'--author="{self.get_author()}"', "-m", msg)
# Did the PR change since we started the merge?
pulled_sha = repo.show_ref(pr_branch_name)
latest_pr_status = GitHubPR(self.org, self.project, self.pr_num)
if (
pulled_sha != latest_pr_status.last_commit_sha()
or pulled_sha != commit_to_merge
):
raise RuntimeError(
"PR has been updated since CI checks last passed. Please rerun the merge command."
)
return []
| GitHubPR |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride6.py | {
"start": 639,
"end": 721
} | class ____(Parent1[str]):
def m1(self, x: Any) -> Any:
return x
| Child1_2 |
python | crytic__slither | slither/detectors/statements/boolean_constant_equality.py | {
"start": 513,
"end": 3159
} | class ____(AbstractDetector):
"""
Boolean constant equality
"""
ARGUMENT = "boolean-equal"
HELP = "Comparison to boolean constant"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#boolean-equality"
WIKI_TITLE = "Boolean equality"
WIKI_DESCRIPTION = """Detects the comparison to boolean constants."""
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract A {
function f(bool x) public {
// ...
if (x == true) { // bad!
// ...
}
// ...
}
}
```
Boolean constants can be used directly and do not need to be compare to `true` or `false`."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = """Remove the equality to the boolean constant."""
@staticmethod
def _detect_boolean_equality(
contract: Contract,
) -> List[Tuple[Function, Set[Node]]]:
# Create our result set.
results: List[Tuple[Function, Set[Node]]] = []
# Loop for each function and modifier.
# pylint: disable=too-many-nested-blocks
for function in contract.functions_and_modifiers_declared:
f_results = set()
# Loop for every node in this function, looking for boolean constants
for node in function.nodes:
for ir in node.irs:
if isinstance(ir, Binary):
if ir.type in [BinaryType.EQUAL, BinaryType.NOT_EQUAL]:
for r in ir.read:
if isinstance(r, Constant):
if isinstance(r.value, bool):
f_results.add(node)
results.append((function, f_results))
# Return the resulting set of nodes with improper uses of Boolean constants
return results
def _detect(self) -> List[Output]:
"""
Detect Boolean constant misuses
"""
results = []
for contract in self.contracts:
boolean_constant_misuses = self._detect_boolean_equality(contract)
for (func, nodes) in boolean_constant_misuses:
for node in nodes:
info: DETECTOR_INFO = [
func,
" compares to a boolean constant:\n\t-",
node,
"\n",
]
res = self.generate_result(info)
results.append(res)
return results
| BooleanEquality |
python | getsentry__sentry | tests/sentry/integrations/bitbucket/test_installed.py | {
"start": 779,
"end": 923
} | class ____(IssueTrackingPlugin2):
slug = "bitbucket"
name = "Bitbucket Mock Plugin"
conf_key = slug
@control_silo_test
| BitbucketPlugin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.