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 | huggingface__transformers | tests/models/swiftformer/test_modeling_swiftformer.py | {
"start": 8525,
"end": 9520
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return ViTImageProcessor.from_pretrained("MBZUAI/swiftformer-xs") if is_vision_available() else None
@slow
def test_inference_image_classification_head(self):
model = SwiftFormerForImageClassification.from_pretrained("MBZUAI/swiftformer-xs").to(torch_device)
image_processor = self.default_image_processor
image = prepare_img()
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
# verify the logits
expected_shape = torch.Size((1, 1000))
self.assertEqual(outputs.logits.shape, expected_shape)
expected_slice = torch.tensor([[-2.1703e00, 2.1107e00, -2.0811e00]]).to(torch_device)
torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4)
| SwiftFormerModelIntegrationTest |
python | getsentry__sentry | src/sentry/apidocs/examples/release_threshold_examples.py | {
"start": 95,
"end": 1233
} | class ____:
THRESHOLD_STATUS_RESPONSE = [
OpenApiExample(
"Client key with rate limiting",
value={
f"{BASE_PROJECT['slug']}-v1.0.0": [
{
"project_id": 0,
"project_slug": BASE_PROJECT["slug"],
"environment": {
"name": "production",
},
"project": BASE_PROJECT,
"threshold_type": 0,
"trigger_type": "over",
"value": 100,
"window_in_seconds": 600,
"key": "foobar-v1.0.0",
"release": f"{BASE_PROJECT['slug']}-v1.0.0",
"is_healthy": True,
"start": "2022-02-14T19:00:00Z",
"end": "2022-02-28T18:03:00Z",
"metric_value": 0.1,
},
],
},
status_codes=["200"],
response_only=True,
),
]
| ReleaseThresholdExamples |
python | spyder-ide__spyder | spyder/utils/syntaxhighlighters.py | {
"start": 18923,
"end": 27803
} | class ____(BaseSH):
"""Python Syntax Highlighter"""
# Syntax highlighting rules:
add_kw = ['async', 'await']
PROG = re.compile(make_python_patterns(additional_keywords=add_kw), re.S)
IDPROG = re.compile(r"\s+(\w+)", re.S)
ASPROG = re.compile(r"\b(as)\b")
# Syntax highlighting states (from one text block to another):
(NORMAL, INSIDE_SQ3STRING, INSIDE_DQ3STRING,
INSIDE_SQSTRING, INSIDE_DQSTRING,
INSIDE_NON_MULTILINE_STRING) = list(range(6))
DEF_TYPES = {"def": OutlineExplorerData.FUNCTION,
"class": OutlineExplorerData.CLASS}
# Comments suitable for Outline Explorer
OECOMMENT = re.compile(r'^(# ?--[-]+|##[#]+ )[ -]*[^- ]+')
def __init__(self, parent, font=None, color_scheme='Spyder'):
BaseSH.__init__(self, parent, font, color_scheme)
self.cell_separators = CELL_LANGUAGES['Python']
# Avoid updating the outline explorer with every single letter typed
self.outline_explorer_data_update_timer = QTimer()
self.outline_explorer_data_update_timer.setSingleShot(True)
def highlight_match(self, text, match, key, value, offset,
state, import_stmt, oedata):
"""Highlight a single match."""
start, end = get_span(match, key)
start = max([0, start + offset])
end = max([0, end + offset])
length = end - start
if key == "uf_sq3string":
self.setFormat(start, length, self.formats["string"])
state = self.INSIDE_SQ3STRING
elif key == "uf_dq3string":
self.setFormat(start, length, self.formats["string"])
state = self.INSIDE_DQ3STRING
elif key == "uf_sqstring":
self.setFormat(start, length, self.formats["string"])
state = self.INSIDE_SQSTRING
elif key == "uf_dqstring":
self.setFormat(start, length, self.formats["string"])
state = self.INSIDE_DQSTRING
elif key in ["ufe_sqstring", "ufe_dqstring"]:
self.setFormat(start, length, self.formats["string"])
state = self.INSIDE_NON_MULTILINE_STRING
elif key in ["match_kw", "case_kw"]:
self.setFormat(start, length, self.formats["keyword"])
else:
self.setFormat(start, length, self.formats[key])
if key == "comment":
if text.lstrip().startswith(self.cell_separators):
oedata = OutlineExplorerData(self.currentBlock())
oedata.text = str(text).strip()
# cell_head: string containing the first group
# of '%'s in the cell header
cell_head = re.search(r"%+|$", text.lstrip()).group()
if cell_head == '':
oedata.cell_level = 0
else:
oedata.cell_level = qstring_length(cell_head) - 2
oedata.fold_level = start
oedata.def_type = OutlineExplorerData.CELL
def_name = get_code_cell_name(text)
oedata.def_name = def_name
# Keep list of cells for performence reasons
self._cell_list.append(oedata)
elif self.OECOMMENT.match(text.lstrip()):
oedata = OutlineExplorerData(self.currentBlock())
oedata.text = str(text).strip()
oedata.fold_level = start
oedata.def_type = OutlineExplorerData.COMMENT
oedata.def_name = text.strip()
elif key == "keyword":
if value in ("def", "class"):
match1 = self.IDPROG.match(text, end)
if match1:
start1, end1 = get_span(match1, 1)
self.setFormat(start1, end1-start1,
self.formats["definition"])
oedata = OutlineExplorerData(self.currentBlock())
oedata.text = str(text)
oedata.fold_level = (qstring_length(text)
- qstring_length(text.lstrip()))
oedata.def_type = self.DEF_TYPES[str(value)]
oedata.def_name = text[start1:end1]
oedata.color = self.formats["definition"]
elif value in ("elif", "else", "except", "finally",
"for", "if", "try", "while",
"with"):
if text.lstrip().startswith(value):
oedata = OutlineExplorerData(self.currentBlock())
oedata.text = str(text).strip()
oedata.fold_level = start
oedata.def_type = OutlineExplorerData.STATEMENT
oedata.def_name = text.strip()
elif value == "import":
import_stmt = text.strip()
# color all the "as" words on same line, except
# if in a comment; cheap approximation to the
# truth
if '#' in text:
endpos = qstring_length(text[:text.index('#')])
else:
endpos = qstring_length(text)
while True:
match1 = self.ASPROG.match(text, end, endpos)
if not match1:
break
start, end = get_span(match1, 1)
self.setFormat(start, length, self.formats["keyword"])
return state, import_stmt, oedata
def highlight_block(self, text):
"""Implement specific highlight for Python."""
text = str(text)
prev_state = tbh.get_state(self.currentBlock().previous())
if prev_state == self.INSIDE_DQ3STRING:
offset = -4
text = r'""" '+text
elif prev_state == self.INSIDE_SQ3STRING:
offset = -4
text = r"''' "+text
elif prev_state == self.INSIDE_DQSTRING:
offset = -2
text = r'" '+text
elif prev_state == self.INSIDE_SQSTRING:
offset = -2
text = r"' "+text
else:
offset = 0
prev_state = self.NORMAL
oedata = None
import_stmt = None
self.setFormat(0, qstring_length(text), self.formats["normal"])
state = self.NORMAL
for match in self.PROG.finditer(text):
for key, value in list(match.groupdict().items()):
if value:
state, import_stmt, oedata = self.highlight_match(
text, match, key, value, offset,
state, import_stmt, oedata)
tbh.set_state(self.currentBlock(), state)
# Use normal format for indentation and trailing spaces
# Unless we are in a string
states_multiline_string = [
self.INSIDE_DQ3STRING, self.INSIDE_SQ3STRING,
self.INSIDE_DQSTRING, self.INSIDE_SQSTRING]
states_string = states_multiline_string + [
self.INSIDE_NON_MULTILINE_STRING]
self.formats['leading'] = self.formats['normal']
if prev_state in states_multiline_string:
self.formats['leading'] = self.formats["string"]
self.formats['trailing'] = self.formats['normal']
if state in states_string:
self.formats['trailing'] = self.formats['string']
self.highlight_extras(text, offset)
block = self.currentBlock()
data = block.userData()
need_data = (oedata or import_stmt)
if need_data and not data:
data = BlockUserData(self.editor)
# Try updating
update = False
if oedata and data and data.oedata:
update = data.oedata.update(oedata)
if data and not update:
data.oedata = oedata
self.outline_explorer_data_update_timer.start(500)
if (import_stmt) or (data and data.import_statement):
data.import_statement = import_stmt
block.setUserData(data)
def get_import_statements(self):
"""Get import statment list."""
block = self.document().firstBlock()
statments = []
while block.isValid():
data = block.userData()
if data and data.import_statement:
statments.append(data.import_statement)
block = block.next()
return statments
def rehighlight(self):
BaseSH.rehighlight(self)
# =============================================================================
# IPython syntax highlighter
# =============================================================================
| PythonSH |
python | great-expectations__great_expectations | tests/expectations/test_dataclass_serializable_dot_dict_pattern.py | {
"start": 480,
"end": 556
} | class ____(SerializableDictDot):
foo: str
bar: int
@dataclass
| MyClassA |
python | ethereum__web3.py | web3/_utils/abi.py | {
"start": 9508,
"end": 9627
} | class ____(AcceptsHexStrEncoder):
subencoder_cls = encoding.ByteStringEncoder
is_strict = False
| ByteStringEncoder |
python | huggingface__transformers | tests/models/xlstm/test_modeling_xlstm.py | {
"start": 9873,
"end": 15334
} | class ____(unittest.TestCase):
def setUp(self):
self.model_id = "NX-AI/xLSTM-7b"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id, legacy=False)
self.prompt = ("[INST]Write a hello world program in C++.",)
def test_simple_generate(self):
"""
Simple generate test to avoid regressions.
Note: state-spaces (cuda) implementation and pure torch implementation
have irreconciliable differences as of now, which will cause this test to fail
in an environment with state-spaces installed.
"""
tokenizer = self.tokenizer
tokenizer.pad_token_id = tokenizer.eos_token_id
model = xLSTMForCausalLM.from_pretrained(self.model_id, dtype=torch.bfloat16, device_map=torch_device)
input_ids = tokenizer("[INST]Write a hello world program in C++.[/INST]", return_tensors="pt")["input_ids"].to(
torch_device
)
out = model.generate(input_ids, do_sample=False, use_cache=True, max_new_tokens=30)
output_sentence = tokenizer.decode(out[0])
ground_truth_sentence = """<s>[INST]Write a hello world program in C++.[/INST] Sure, here is a simple "Hello, World!" program in C++:\n\n```cpp\n#include <iostream>\n\n"""
self.assertEqual(output_sentence, ground_truth_sentence)
def test_batched_equivalence_with_cache(self):
"""
Verifies that batched generation matches individual generation.
Important because of the specific caching mechanism + statefulness of the xLSTM model.
Depending on precision and devices, differences can be observed from generation to generation.
"""
tokenizer = self.tokenizer
prompt = [
"[INST]Write C#.[/INST]",
"[INST]Write a hello world in C++.[/INST]",
"[INST] Write a simple Fibonacci number computation function in Rust that does memoization, with comments, in safe Rust.[/INST]",
]
model = xLSTMForCausalLM.from_pretrained(self.model_id, dtype=torch.bfloat16, device_map=torch_device)
tokenizer.pad_token_id = tokenizer.eos_token_id
# batched generation
tokenized_prompts = tokenizer(prompt, return_tensors="pt", padding="longest").to(torch_device)
batched_gen = model.generate(**tokenized_prompts, max_new_tokens=30, use_cache=True)
batched_output = tokenizer.batch_decode(batched_gen, skip_special_tokens=True)
# individual generation
for index_gen, individual_prompt in enumerate(prompt):
inputs = tokenizer(individual_prompt, return_tensors="pt", padding="longest").to(torch_device)
individual_gen = model.generate(**inputs, max_new_tokens=30, use_cache=True)
individual_output = tokenizer.batch_decode(individual_gen, skip_special_tokens=True)[0]
self.assertEqual(individual_output[:100], batched_output[index_gen][:100])
def test_batched_equivalence_without_cache(self):
"""
Verifies that batched generation matches individual generation without cache.
Important because of the specific caching mechanism + statefulness of the xLSTM model.
Depending on precision and devices, differences can be observed from generation to generation.
"""
tokenizer = self.tokenizer
prompt = [
"[INST]Write C#.[/INST]",
"[INST]Write a hello world in C++.[/INST]",
"[INST] Write a simple Fibonacci number computation function in Rust that does memoization, with comments, in safe Rust.[/INST]",
]
model = xLSTMForCausalLM.from_pretrained(self.model_id, dtype=torch.bfloat16, device_map=torch_device)
tokenizer.pad_token_id = tokenizer.eos_token_id
# batched generation
tokenized_prompts = tokenizer(prompt, return_tensors="pt", padding="longest").to(torch_device)
batched_gen = model.generate(**tokenized_prompts, max_new_tokens=30, use_cache=True)
batched_output = tokenizer.batch_decode(batched_gen, skip_special_tokens=True)
# individual generation
for index_gen, individual_prompt in enumerate(prompt):
inputs = tokenizer(individual_prompt, return_tensors="pt", padding="longest").to(torch_device)
individual_gen = model.generate(**inputs, max_new_tokens=30, use_cache=True)
individual_output = tokenizer.batch_decode(individual_gen, skip_special_tokens=True)[0]
self.assertEqual(individual_output[:100], batched_output[index_gen][:100])
@require_torch_gpu
def test_xlstm_block_train_vs_eval_equivalence(self):
# Based on https://github.com/sustcsonglin/flash-linear-attention/issues/63
# Credit to zhixuan-lin
B, T, D = 4, 512, 768
dtype = torch.bfloat16
config = xLSTMConfig(num_heads=24, head_dim=64, hidden_size=768, expand=2, n_groups=1)
torch.manual_seed(42)
with torch.amp.autocast(device_type="cuda", dtype=dtype):
with torch.no_grad():
block = xLSTMBlock(config.to_xlstm_block_config()).to("cuda")
hidden_states = torch.rand(size=(B, T, D), dtype=dtype, device="cuda")
block.train()
out_train = block(hidden_states)
block.eval()
out_eval = block(hidden_states)
self.assertTrue(torch.allclose(out_train, out_eval, atol=1e-3))
| xLSTMIntegrationTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/tenants.py | {
"start": 139,
"end": 883
} | class ____(str, Enum):
"""Values to be used when sending tenants to weaviate. Needed for BC."""
HOT = "HOT"
COLD = "COLD"
FROZEN = "FROZEN"
OTHER = "OTHER" # placeholder for values that we receive from the server but do not send
@staticmethod
def from_string(value: str) -> "_TenantActivistatusServerValues":
if value == "ACTIVE" or value == "HOT":
return _TenantActivistatusServerValues.HOT
if value == "INACTIVE" or value == "COLD":
return _TenantActivistatusServerValues.COLD
if value == "OFFLOADED" or value == "FROZEN":
return _TenantActivistatusServerValues.FROZEN
return _TenantActivistatusServerValues.OTHER
| _TenantActivistatusServerValues |
python | graphql-python__graphene | graphene/types/definitions.py | {
"start": 202,
"end": 659
} | class ____:
"""
A class for extending the base GraphQLType with the related
graphene_type
"""
def __init__(self, *args, **kwargs):
self.graphene_type = kwargs.pop("graphene_type")
super(GrapheneGraphQLType, self).__init__(*args, **kwargs)
def __copy__(self):
result = GrapheneGraphQLType(graphene_type=self.graphene_type)
result.__dict__.update(self.__dict__)
return result
| GrapheneGraphQLType |
python | django__django | tests/admin_changelist/models.py | {
"start": 1891,
"end": 1934
} | class ____(Musician):
pass
| ChordsMusician |
python | PrefectHQ__prefect | src/prefect/utilities/schema_tools/hydration.py | {
"start": 338,
"end": 1724
} | class ____(BaseModel):
workspace_variables: dict[
str,
StrictVariableValue,
] = Field(default_factory=dict)
render_workspace_variables: bool = Field(default=False)
raise_on_error: bool = Field(default=False)
render_jinja: bool = Field(default=False)
jinja_context: dict[str, Any] = Field(default_factory=dict)
@classmethod
async def build(
cls,
session: AsyncSession,
raise_on_error: bool = False,
render_jinja: bool = False,
render_workspace_variables: bool = False,
) -> Self:
from prefect.server.database.orm_models import Variable
from prefect.server.models.variables import read_variables
variables: Sequence[Variable]
if render_workspace_variables:
variables = await read_variables(
session=session,
)
else:
variables = []
return cls(
workspace_variables={
variable.name: variable.value for variable in variables
},
raise_on_error=raise_on_error,
render_jinja=render_jinja,
render_workspace_variables=render_workspace_variables,
)
Handler: TypeAlias = Callable[[dict[str, Any], HydrationContext], Any]
PrefectKind: TypeAlias = Optional[str]
_handlers: dict[PrefectKind, Handler] = {}
| HydrationContext |
python | pytorch__pytorch | test/test_metal.py | {
"start": 199,
"end": 6622
} | class ____(TestCase):
@staticmethod
def validate_transformed_module(
# To please flake
self,
pattern_count_map,
data_shape,
prepack_removal=False,
fuse_clamping_ops=False):
module_instance = self
scripted_model = torch.jit.script(module_instance)
scripted_model.eval()
input_data = torch.normal(1, 20, size=data_shape)
scripted_model(input_data)
torch._C._jit_pass_metal_insert_prepacked_ops(scripted_model._c)
if fuse_clamping_ops or prepack_removal:
scripted_model._c = torch._C._freeze_module(scripted_model._c)
if fuse_clamping_ops:
torch._C._jit_pass_metal_fuse_clamp_w_prepacked_conv(scripted_model._c)
if prepack_removal:
torch._C._jit_pass_metal_fold_prepacking_ops(scripted_model._c)
buffer = io.BytesIO()
torch.jit.save(scripted_model, buffer)
buffer.seek(0)
deserialized_scripted_model = torch.jit.load(buffer)
for pattern, v in pattern_count_map.items():
if (v == 0):
FileCheck().check(pattern).run(deserialized_scripted_model.graph)
elif (v == -1):
FileCheck().check_not(pattern).run(deserialized_scripted_model.graph)
else:
FileCheck().check_count(pattern, v, exactly=True).run(deserialized_scripted_model.graph)
def test_conv(self):
# Conv params
batch_size = 2
input_channels_per_group = 6
height = 16
width = 16
output_channels_per_group = 6
groups = 4
kernel_h = kernel_w = 3
stride_h = stride_w = 1
pad_h = pad_w = 1
dilation = 1
input_channels = input_channels_per_group * groups
output_channels = output_channels_per_group * groups
strides = (stride_h, stride_w)
paddings = (pad_h, pad_w)
dilations = (dilation, dilation)
conv_weight_shape = (output_channels, input_channels_per_group, kernel_h, kernel_w)
conv_bias_shape = (output_channels)
class Conv2D(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Parameter(torch.rand(conv_weight_shape), requires_grad=False)
self.bias = torch.nn.Parameter(torch.rand(conv_bias_shape), requires_grad=False)
self.strides = strides
self.paddings = paddings
self.dilations = dilations
self.groups = groups
def forward(self, x):
return F.conv2d(x, self.weight, self.bias,
self.strides, self.paddings, self.dilations, self.groups)
data_shape = (batch_size, input_channels, height, width)
pattern_count_map = {"Tensor = aten::conv2d": -1,
"metal_prepack::conv2d_prepack": 1,
"metal_prepack::conv2d_run": 1}
TestMetalRewritePass.validate_transformed_module(Conv2D(), pattern_count_map, data_shape)
class Conv2DRelu(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Parameter(torch.rand(conv_weight_shape), requires_grad=False)
self.bias = torch.nn.Parameter(torch.rand(conv_bias_shape), requires_grad=False)
self.strides = strides
self.paddings = paddings
self.dilations = dilations
self.groups = groups
def forward(self, x):
o = F.conv2d(x, self.weight, self.bias,
self.strides, self.paddings, self.dilations, self.groups)
o = F.relu(o)
return o
data_shape = (batch_size, input_channels, height, width)
pattern_count_map = {"Tensor = aten::conv2d": -1,
"metal_prepack::conv2d_prepack": 1,
"metal_prepack::conv2d_run": 1}
TestMetalRewritePass.validate_transformed_module(
Conv2DRelu(), pattern_count_map, data_shape)
pattern_count_map["aten::relu"] = 1
pattern_count_map["metal_prepack::conv2d_prepack"] = -1
TestMetalRewritePass.validate_transformed_module(
Conv2DRelu(),
pattern_count_map,
data_shape,
prepack_removal=True)
pattern_count_map["aten::relu"] = -1
TestMetalRewritePass.validate_transformed_module(
Conv2DRelu(),
pattern_count_map,
data_shape,
prepack_removal=True,
fuse_clamping_ops=True)
class Conv2DHardtanh(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Parameter(torch.rand(conv_weight_shape), requires_grad=False)
self.bias = torch.nn.Parameter(torch.rand(conv_bias_shape), requires_grad=False)
self.strides = strides
self.paddings = paddings
self.dilations = dilations
self.groups = groups
def forward(self, x):
o = F.conv2d(x, self.weight, self.bias,
self.strides, self.paddings, self.dilations, self.groups)
o = F.hardtanh(o)
return o
data_shape = (batch_size, input_channels, height, width)
pattern_count_map = {"Tensor = aten::conv2d": -1,
"metal_prepack::conv2d_prepack": 1,
"metal_prepack::conv2d_run": 1}
TestMetalRewritePass.validate_transformed_module(Conv2DHardtanh(), pattern_count_map, data_shape)
pattern_count_map["aten::hardtanh"] = 1
pattern_count_map["metal_prepack::conv2d_prepack"] = -1
TestMetalRewritePass.validate_transformed_module(
Conv2DHardtanh(),
pattern_count_map,
data_shape,
prepack_removal=True)
pattern_count_map["aten::hardtanh"] = -1
TestMetalRewritePass.validate_transformed_module(
Conv2DRelu(),
pattern_count_map,
data_shape,
prepack_removal=True,
fuse_clamping_ops=True)
if __name__ == "__main__":
run_tests()
| TestMetalRewritePass |
python | agronholm__apscheduler | src/apscheduler/executors/subprocess.py | {
"start": 325,
"end": 946
} | class ____(JobExecutor):
"""
Executes functions in a process pool.
:param max_workers: the maximum number of worker processes to keep
"""
max_workers: int = 40
_limiter: CapacityLimiter = attrs.field(init=False)
async def start(self, exit_stack: AsyncExitStack) -> None:
self._limiter = CapacityLimiter(self.max_workers)
async def run_job(self, func: Callable[..., Any], job: Job) -> Any:
wrapped = partial(func, *job.args, **job.kwargs)
return await to_process.run_sync(
wrapped, cancellable=True, limiter=self._limiter
)
| ProcessPoolJobExecutor |
python | scipy__scipy | scipy/optimize/_constraints.py | {
"start": 9458,
"end": 12567
} | class ____:
"""Bounds constraint on the variables.
The constraint has the general inequality form::
lb <= x <= ub
It is possible to use equal bounds to represent an equality constraint or
infinite bounds to represent a one-sided constraint.
Parameters
----------
lb, ub : dense array_like, optional
Lower and upper bounds on independent variables. `lb`, `ub`, and
`keep_feasible` must be the same shape or broadcastable.
Set components of `lb` and `ub` equal
to fix a variable. Use ``np.inf`` with an appropriate sign to disable
bounds on all or some variables. Note that you can mix constraints of
different types: interval, one-sided or equality, by setting different
components of `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
and ``ub = np.inf`` (no bounds).
keep_feasible : dense array_like of bool, optional
Whether to keep the constraint components feasible throughout
iterations. Must be broadcastable with `lb` and `ub`.
Default is False. Has no effect for equality constraints.
"""
# generic type compatibility with scipy-stubs
__class_getitem__ = classmethod(GenericAlias)
def _input_validation(self):
try:
res = np.broadcast_arrays(self.lb, self.ub, self.keep_feasible)
self.lb, self.ub, self.keep_feasible = res
except ValueError:
message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
raise ValueError(message)
def __init__(self, lb=-np.inf, ub=np.inf, keep_feasible=False):
if issparse(lb) or issparse(ub):
raise ValueError("Lower and upper bounds must be dense arrays.")
self.lb = np.atleast_1d(lb)
self.ub = np.atleast_1d(ub)
if issparse(keep_feasible):
raise ValueError("`keep_feasible` must be a dense array.")
self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool)
self._input_validation()
def __repr__(self):
start = f"{type(self).__name__}({self.lb!r}, {self.ub!r}"
if np.any(self.keep_feasible):
end = f", keep_feasible={self.keep_feasible!r})"
else:
end = ")"
return start + end
def residual(self, x):
"""Calculate the residual (slack) between the input and the bounds
For a bound constraint of the form::
lb <= x <= ub
the lower and upper residuals between `x` and the bounds are values
``sl`` and ``sb`` such that::
lb + sl == x == ub - sb
When all elements of ``sl`` and ``sb`` are positive, all elements of
``x`` lie within the bounds; a negative element in ``sl`` or ``sb``
indicates that the corresponding element of ``x`` is out of bounds.
Parameters
----------
x: array_like
Vector of independent variables
Returns
-------
sl, sb : array-like
The lower and upper residuals
"""
return x - self.lb, self.ub - x
| Bounds |
python | modin-project__modin | modin/logging/config.py | {
"start": 1546,
"end": 7329
} | class ____(logging.Formatter): # noqa: PR01
"""Implement custom formatter to log at microsecond granularity."""
def formatTime(
self, record: logging.LogRecord, datefmt: Optional[str] = None
) -> str:
"""
Return the creation time of the specified LogRecord as formatted text.
This custom logging formatter inherits from the logging module and
records timestamps at the microsecond level of granularity.
Parameters
----------
record : LogRecord
The specified LogRecord object.
datefmt : str, default: None
Used with time.ststrftime() to format time record.
Returns
-------
str
Datetime string containing microsecond timestamp.
"""
ct = dt.datetime.fromtimestamp(record.created)
if datefmt:
s = ct.strftime(datefmt)
else:
# Format datetime object ct to microseconds
t = ct.strftime("%Y-%m-%d %H:%M:%S")
s = f"{t},{record.msecs:03}"
return s
def bytes_int_to_str(num_bytes: int, suffix: str = "B") -> str:
"""
Scale bytes to its human-readable format (e.g: 1253656678 => '1.17GB').
Parameters
----------
num_bytes : int
Number of bytes.
suffix : str, default: "B"
Suffix to add to conversion of num_bytes.
Returns
-------
str
Human-readable string format.
"""
factor = 1000
# Convert n_bytes to float b/c we divide it by factor
n_bytes: float = num_bytes
for unit in ["", "K", "M", "G", "T", "P"]:
if n_bytes < factor:
return f"{n_bytes:.2f}{unit}{suffix}"
n_bytes /= factor
return f"{n_bytes * 1000:.2f}P{suffix}"
def _create_logger(
namespace: str, job_id: str, log_name: str, log_level: LogLevel
) -> logging.Logger:
"""
Create and configure logger as Modin expects it to be.
Parameters
----------
namespace : str
Logging namespace to use, e.g. "modin.logger.default".
job_id : str
Part of path to where logs are stored.
log_name : str
Name of the log file to create.
log_level : LogLevel
Returns
-------
Logger
Logger object configured per Modin settings.
"""
# Pathlib makes it OS agnostic.
modin_path = Path(".modin")
modin_path.mkdir(exist_ok=True)
# Add gitignore to the log directory.
ignore_modin_path = modin_path / ".gitignore"
if not ignore_modin_path.exists():
ignore_modin_path.write_text("# Automatically generated by modin.\n*\n")
log_dir = modin_path / "logs" / f"job_{job_id}"
log_dir.mkdir(parents=True, exist_ok=True)
log_filename = log_dir / f"{log_name}.log"
logger = logging.getLogger(namespace)
logfile = RotatingFileHandler(
filename=log_filename,
mode="a",
maxBytes=LogFileSize.get() * int(1e6),
backupCount=10,
)
formatter = ModinFormatter(
fmt="%(process)d, %(thread)d, %(asctime)s, %(message)s",
datefmt="%Y-%m-%d,%H:%M:%S.%f",
)
logfile.setFormatter(formatter)
logger.addHandler(logfile)
logger.setLevel(log_level)
return logger
def configure_logging() -> None:
"""Configure Modin logging by setting up directory structure and formatting."""
global __LOGGER_CONFIGURED__
current_timestamp = dt.datetime.now().strftime("%Y.%m.%d_%H-%M-%S")
job_id = f"{current_timestamp}_{uuid.uuid4().hex}"
logger = _create_logger(
DEFAULT_LOGGER_NAME,
job_id,
"trace",
LogLevel.INFO,
)
logger.info(f"OS Version: {platform.platform()}")
logger.info(f"Python Version: {platform.python_version()}")
num_physical_cores = str(psutil.cpu_count(logical=False))
num_total_cores = str(psutil.cpu_count(logical=True))
logger.info(f"Modin Version: {modin.__version__}")
logger.info(f"Pandas Version: {pandas.__version__}")
logger.info(f"Physical Cores: {num_physical_cores}")
logger.info(f"Total Cores: {num_total_cores}")
mem_sleep = LogMemoryInterval.get()
mem_logger = _create_logger("modin_memory.logger", job_id, "memory", LogLevel.DEBUG)
svmem = psutil.virtual_memory()
mem_logger.info(f"Memory Total: {bytes_int_to_str(svmem.total)}")
mem_logger.info(f"Memory Available: {bytes_int_to_str(svmem.available)}")
mem_logger.info(f"Memory Used: {bytes_int_to_str(svmem.used)}")
mem = threading.Thread(
target=memory_thread, args=[mem_logger, mem_sleep], daemon=True
)
mem.start()
_create_logger("modin.logger.errors", job_id, "error", LogLevel.INFO)
__LOGGER_CONFIGURED__ = True
def memory_thread(logger: logging.Logger, sleep_time: int) -> None:
"""
Configure Modin logging system memory profiling thread.
Parameters
----------
logger : logging.Logger
The logger object.
sleep_time : int
The interval at which to profile system memory.
"""
while True:
rss_mem = bytes_int_to_str(psutil.Process().memory_info().rss)
svmem = psutil.virtual_memory()
logger.info(f"Memory Percentage: {svmem.percent}%")
logger.info(f"RSS Memory: {rss_mem}")
time.sleep(sleep_time)
def get_logger(namespace: str = "modin.logger.default") -> logging.Logger:
"""
Configure Modin logger based on Modin config and returns the logger.
Parameters
----------
namespace : str, default: "modin.logger.default"
Which namespace to use for logging.
Returns
-------
logging.Logger
The Modin logger.
"""
if not __LOGGER_CONFIGURED__ and LogMode.get() != "disable":
configure_logging()
return logging.getLogger(namespace)
| ModinFormatter |
python | psf__black | src/black/handle_ipynb_magics.py | {
"start": 12131,
"end": 15363
} | class ____(ast.NodeVisitor):
"""Visit cell to look for get_ipython calls.
Note that the source of the abstract syntax tree
will already have been processed by IPython's
TransformerManager().transform_cell.
For example,
%matplotlib inline
would have been transformed to
get_ipython().run_line_magic('matplotlib', 'inline')
and we look for instances of the latter (and likewise for other
types of magics).
"""
def __init__(self) -> None:
self.magics: dict[int, list[OffsetAndMagic]] = collections.defaultdict(list)
def visit_Assign(self, node: ast.Assign) -> None:
"""Look for system assign magics.
For example,
black_version = !black --version
env = %env var
would have been (respectively) transformed to
black_version = get_ipython().getoutput('black --version')
env = get_ipython().run_line_magic('env', 'var')
and we look for instances of any of the latter.
"""
if isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func):
args = _get_str_args(node.value.args)
if node.value.func.attr == "getoutput":
src = f"!{args[0]}"
elif node.value.func.attr == "run_line_magic":
src = f"%{args[0]}"
if args[1]:
src += f" {args[1]}"
else:
raise AssertionError(
f"Unexpected IPython magic {node.value.func.attr!r} found. "
"Please report a bug on https://github.com/psf/black/issues."
) from None
self.magics[node.value.lineno].append(
OffsetAndMagic(node.value.col_offset, src)
)
self.generic_visit(node)
def visit_Expr(self, node: ast.Expr) -> None:
"""Look for magics in body of cell.
For examples,
!ls
!!ls
?ls
??ls
would (respectively) get transformed to
get_ipython().system('ls')
get_ipython().getoutput('ls')
get_ipython().run_line_magic('pinfo', 'ls')
get_ipython().run_line_magic('pinfo2', 'ls')
and we look for instances of any of the latter.
"""
if isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func):
args = _get_str_args(node.value.args)
if node.value.func.attr == "run_line_magic":
if args[0] == "pinfo":
src = f"?{args[1]}"
elif args[0] == "pinfo2":
src = f"??{args[1]}"
else:
src = f"%{args[0]}"
if args[1]:
src += f" {args[1]}"
elif node.value.func.attr == "system":
src = f"!{args[0]}"
elif node.value.func.attr == "getoutput":
src = f"!!{args[0]}"
else:
raise NothingChanged # unsupported magic.
self.magics[node.value.lineno].append(
OffsetAndMagic(node.value.col_offset, src)
)
self.generic_visit(node)
| MagicFinder |
python | milvus-io__pymilvus | tests/test_orm_iterator.py | {
"start": 4535,
"end": 6404
} | class ____:
"""Test SearchIterator helper methods"""
def test_search_iterator_batch_extension(self):
"""Test batch size extension logic for search iterator"""
# This tests the logic that would be used in SearchIterator
batch_size = 100
next_param = {PARAMS: {"ef": 200}}
# Test with ef parameter
result = extend_batch_size(batch_size, next_param, True)
expected = min(200, batch_size * DEFAULT_SEARCH_EXTENSION_RATE)
assert result == expected
@patch('pymilvus.orm.iterator.Path')
def test_iterator_checkpoint_operations(self, mock_path):
"""Test checkpoint file operations that iterators might use"""
mock_file = Mock()
mock_path.return_value.open.return_value.__enter__.return_value = mock_file
mock_path.return_value.exists.return_value = True
# Test checkpoint save operation
def save_checkpoint():
with mock_path.return_value.open('w') as f:
f.write('checkpoint_data')
io_operation(save_checkpoint, "Failed to save checkpoint")
# Test checkpoint load operation
def load_checkpoint():
with mock_path.return_value.open('r') as f:
return f.read()
io_operation(load_checkpoint, "Failed to load checkpoint")
def test_iterator_state_assertions(self):
"""Test state validation assertions used in iterators"""
# Test valid state
assert_info(True, "Iterator is in valid state")
# Test invalid state
with pytest.raises(MilvusException, match="Iterator exhausted"):
assert_info(False, "Iterator exhausted")
# Test collection mismatch
with pytest.raises(MilvusException, match="Collection mismatch"):
assert_info(False, "Collection mismatch")
| TestSearchIteratorHelpers |
python | PrefectHQ__prefect | src/integrations/prefect-sqlalchemy/tests/test_database.py | {
"start": 813,
"end": 1360
} | class ____:
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def execute(self, query, params):
cursor_result = MagicMock()
cursor_result.fetchall.side_effect = lambda: [
(query, params),
]
cursor_result.fetchmany.side_effect = (
lambda size: [
(query, params),
]
* size
)
return cursor_result
async def commit(self):
pass
| SQLAlchemyAsyncConnectionMock |
python | getsentry__sentry-python | sentry_sdk/integrations/dedupe.py | {
"start": 320,
"end": 1975
} | class ____(Integration):
identifier = "dedupe"
def __init__(self):
# type: () -> None
self._last_seen = ContextVar("last-seen")
@staticmethod
def setup_once():
# type: () -> None
@add_global_event_processor
def processor(event, hint):
# type: (Event, Optional[Hint]) -> Optional[Event]
if hint is None:
return event
integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
if integration is None:
return event
exc_info = hint.get("exc_info", None)
if exc_info is None:
return event
last_seen = integration._last_seen.get(None)
if last_seen is not None:
# last_seen is either a weakref or the original instance
last_seen = (
last_seen() if isinstance(last_seen, weakref.ref) else last_seen
)
exc = exc_info[1]
if last_seen is exc:
logger.info("DedupeIntegration dropped duplicated error event %s", exc)
return None
# we can only weakref non builtin types
try:
integration._last_seen.set(weakref.ref(exc))
except TypeError:
integration._last_seen.set(exc)
return event
@staticmethod
def reset_last_seen():
# type: () -> None
integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
if integration is None:
return
integration._last_seen.set(None)
| DedupeIntegration |
python | getsentry__sentry | src/sentry/models/apiapplication.py | {
"start": 1631,
"end": 1767
} | class ____:
active = 0
inactive = 1
pending_deletion = 2
deletion_in_progress = 3
@control_silo_model
| ApiApplicationStatus |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 98315,
"end": 98653
} | class ____(TestCase):
def test(self) -> None:
alert_rule = self.create_alert_rule()
trigger = create_alert_rule_trigger(alert_rule, "hi", 1000)
trigger_id = trigger.id
delete_alert_rule_trigger(trigger)
assert not AlertRuleTrigger.objects.filter(id=trigger_id).exists()
| DeleteAlertRuleTriggerTest |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 32045,
"end": 32349
} | class ____(ChainedSource):
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen(self.base)
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def name(self) -> str:
return self.base.name()
@dataclasses.dataclass(frozen=True)
| OptimizerSource |
python | numpy__numpy | numpy/polynomial/tests/test_hermite.py | {
"start": 758,
"end": 1069
} | class ____:
def test_hermdomain(self):
assert_equal(herm.hermdomain, [-1, 1])
def test_hermzero(self):
assert_equal(herm.hermzero, [0])
def test_hermone(self):
assert_equal(herm.hermone, [1])
def test_hermx(self):
assert_equal(herm.hermx, [0, .5])
| TestConstants |
python | huggingface__transformers | src/transformers/models/markuplm/modeling_markuplm.py | {
"start": 3394,
"end": 8196
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.config = config
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.max_depth = config.max_depth
self.xpath_embeddings = XPathEmbeddings(config)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
self.padding_idx = config.pad_token_id
self.position_embeddings = nn.Embedding(
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
)
@staticmethod
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings.create_position_ids_from_inputs_embeds
def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
"""
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
Args:
inputs_embeds: torch.Tensor
Returns: torch.Tensor
"""
input_shape = inputs_embeds.size()[:-1]
sequence_length = input_shape[1]
position_ids = torch.arange(
padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
)
return position_ids.unsqueeze(0).expand(input_shape)
@staticmethod
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings.create_position_ids_from_input_ids
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
"""
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
are ignored. This is modified from fairseq's `utils.make_positions`.
Args:
x: torch.Tensor x:
Returns: torch.Tensor
"""
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
mask = input_ids.ne(padding_idx).int()
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
return incremental_indices.long() + padding_idx
def forward(
self,
input_ids=None,
xpath_tags_seq=None,
xpath_subs_seq=None,
token_type_ids=None,
position_ids=None,
inputs_embeds=None,
):
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
device = input_ids.device if input_ids is not None else inputs_embeds.device
if position_ids is None:
if input_ids is not None:
# Create the position ids from the input token ids. Any padded tokens remain padded.
position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx)
else:
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
# prepare xpath seq
if xpath_tags_seq is None:
xpath_tags_seq = self.config.tag_pad_id * torch.ones(
tuple(list(input_shape) + [self.max_depth]), dtype=torch.long, device=device
)
if xpath_subs_seq is None:
xpath_subs_seq = self.config.subs_pad_id * torch.ones(
tuple(list(input_shape) + [self.max_depth]), dtype=torch.long, device=device
)
words_embeddings = inputs_embeds
position_embeddings = self.position_embeddings(position_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
xpath_embeddings = self.xpath_embeddings(xpath_tags_seq, xpath_subs_seq)
embeddings = words_embeddings + position_embeddings + token_type_embeddings + xpath_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->MarkupLM
| MarkupLMEmbeddings |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess4.py | {
"start": 1166,
"end": 1281
} | class ____:
@classmethod
def bar(cls: type[T_F]) -> T_F: ...
def baz(self) -> None:
self.bar()
| F |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 95467,
"end": 96840
} | class ____(_PrintableStructure):
_fields_ = [
('sessionId', c_uint),
('pid', c_uint),
('vgpuInstance', _nvmlVgpuInstance_t),
('displayOrdinal', c_uint),
('sessionType', c_uint),
('sessionFlags', c_uint),
('hMaxResolution', c_uint),
('vMaxResolution', c_uint),
('hResolution', c_uint),
('vResolution', c_uint),
('averageFPS', c_uint),
('averageLatency', c_uint),
]
NVML_DEVICE_MIG_DISABLE = 0x0
NVML_DEVICE_MIG_ENABLE = 0x1
NVML_GPU_INSTANCE_PROFILE_1_SLICE = 0x0
NVML_GPU_INSTANCE_PROFILE_2_SLICE = 0x1
NVML_GPU_INSTANCE_PROFILE_3_SLICE = 0x2
NVML_GPU_INSTANCE_PROFILE_4_SLICE = 0x3
NVML_GPU_INSTANCE_PROFILE_7_SLICE = 0x4
NVML_GPU_INSTANCE_PROFILE_8_SLICE = 0x5
NVML_GPU_INSTANCE_PROFILE_6_SLICE = 0x6
NVML_GPU_INSTANCE_PROFILE_1_SLICE_REV1 = 0x7
NVML_GPU_INSTANCE_PROFILE_2_SLICE_REV1 = 0x8
NVML_GPU_INSTANCE_PROFILE_1_SLICE_REV2 = 0x9
NVML_GPU_INSTANCE_PROFILE_1_SLICE_GFX = 0xA
NVML_GPU_INSTANCE_PROFILE_2_SLICE_GFX = 0xB
NVML_GPU_INSTANCE_PROFILE_4_SLICE_GFX = 0xC
NVML_GPU_INSTANCE_PROFILE_1_SLICE_NO_ME = 0xD
NVML_GPU_INSTANCE_PROFILE_2_SLICE_NO_ME = 0xE
NVML_GPU_INSTANCE_PROFILE_1_SLICE_ALL_ME = 0xF
NVML_GPU_INSTANCE_PROFILE_2_SLICE_ALL_ME = 0x10
NVML_GPU_INSTANCE_PROFILE_COUNT = 0x11
| c_nvmlFBCSession_t |
python | python-openxml__python-docx | src/docx/settings.py | {
"start": 328,
"end": 1082
} | class ____(ElementProxy):
"""Provides access to document-level settings for a document.
Accessed using the :attr:`.Document.settings` property.
"""
def __init__(self, element: BaseOxmlElement, parent: t.ProvidesXmlPart | None = None):
super().__init__(element, parent)
self._settings = cast("CT_Settings", element)
@property
def odd_and_even_pages_header_footer(self) -> bool:
"""True if this document has distinct odd and even page headers and footers.
Read/write.
"""
return self._settings.evenAndOddHeaders_val
@odd_and_even_pages_header_footer.setter
def odd_and_even_pages_header_footer(self, value: bool):
self._settings.evenAndOddHeaders_val = value
| Settings |
python | google__jax | jax/_src/core.py | {
"start": 32552,
"end": 42069
} | class ____(TracerBase, metaclass=TracerMeta):
__array_priority__ = 1000
if jaxlib_extension_version >= 388:
__slots__ = ['__weakref__', '_trace', '_line_info']
else:
__slots__ = ['_trace', '_line_info']
__hash__ = None # type: ignore
_trace: Trace
_line_info: source_info_util.SourceInfo | None
dtype = _aval_property('dtype')
ndim = _aval_property('ndim')
size = _aval_property('size')
shape = _aval_property('shape')
def __init__(self, trace: Trace):
self._trace = trace
def _error_repr(self):
if self.aval is None:
return f"traced array with aval {self.aval}"
return f"traced array with shape {self.aval.str_short()}"
def __array__(self, *args, **kw):
raise TracerArrayConversionError(self)
# helper for isinstance(tracer, jax.Array), here to avoid circular imports
def _is_traced_array(self):
return isinstance(self.aval, ShapedArray)
def __dlpack__(self, *args, **kw):
raise ConcretizationTypeError(self,
f"The __dlpack__() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
def tolist(self):
raise ConcretizationTypeError(self,
f"The tolist() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
def tobytes(self, order="C"):
del order
raise ConcretizationTypeError(self,
f"The tobytes() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
# TODO(dougalm): deprecate/delete
def full_lower(self):
raise NotImplementedError("must override: ", type(self))
def __iter__(self):
return iter(self.aval._iter(self))
def __reversed__(self):
return iter(self[::-1])
def __len__(self):
return self.aval._len(self)
def to_concrete_value(self):
# Should return the concrete value if there is one, or else None.
return None
@property
def sharding(self):
# This attribute is part of the jax.Array API, but only defined on concrete arrays.
# Raising a ConcretizationTypeError would make sense, but for backward compatibility
# we raise an AttributeError so that hasattr() and getattr() work as expected.
raise AttributeError(
f"The 'sharding' attribute is not available on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def committed(self):
raise ConcretizationTypeError(
self,
f"The 'committed' attribute is not available on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def device(self):
# This attribute is part of the jax.Array API, but only defined on concrete arrays.
# Raising a ConcretizationTypeError would make sense, but for backward compatibility
# we raise an AttributeError so that hasattr() and getattr() work as expected.
raise AttributeError(
f"The 'device' attribute is not available on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def addressable_shards(self):
raise ConcretizationTypeError(self,
f"The 'addressable_shards' attribute is not available on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def at(self):
return self.aval.at.fget(self)
@property
def aval(self):
raise NotImplementedError("must override")
def get_referent(self) -> Any:
return self # Override for object equivalence checking
def __bool__(self):
if is_concrete(self): return bool(self.to_concrete_value()) # pytype: disable=wrong-arg-types
check_bool_conversion(self)
return self.aval._bool(self)
def __int__(self):
if is_concrete(self): return int(self.to_concrete_value()) # pytype: disable=wrong-arg-types
check_scalar_conversion(self)
return self.aval._int(self)
def __float__(self):
check_scalar_conversion(self)
return self.aval._float(self)
def __complex__(self):
check_scalar_conversion(self)
return self.aval._complex(self)
def __hex__(self):
if is_concrete(self): return hex(self.to_concrete_value()) # pytype: disable=wrong-arg-types
check_integer_conversion(self)
return self.aval._hex(self)
def __oct__(self):
if is_concrete(self): return oct(self.to_concrete_value()) # pytype: disable=wrong-arg-types
check_integer_conversion(self)
return self.aval._oct(self)
def __index__(self):
if is_concrete(self): return operator.index(self.to_concrete_value()) # pytype: disable=wrong-arg-types
check_integer_conversion(self)
return self.aval._index(self)
# raises a useful error on attempts to pickle a Tracer.
def __reduce__(self):
raise ConcretizationTypeError(
self, ("The error occurred in the __reduce__ method, which may "
"indicate an attempt to serialize/pickle a traced value."))
# raises the better error message from ShapedArray
def __setitem__(self, idx, val): return self.aval._setitem(self, idx, val)
# NumPy also only looks up special methods on classes.
def __array_module__(self, types): return self.aval._array_module(self, types)
def __getattr__(self, name):
# if the aval property raises an AttributeError, gets caught here
assert not config.enable_checks.value or name != "aval"
if name == 'sharding':
raise AttributeError(
f"The 'sharding' attribute is not available on {self._error_repr()}."
f"{self._origin_msg()}")
try:
attr = getattr(self.aval, name)
except AttributeError as err:
raise AttributeError(
f"{self.__class__.__name__} has no attribute {name}"
) from err
else:
t = type(attr)
if t is aval_property:
return attr.fget(self)
elif t is aval_method:
return types.MethodType(attr.fun, self)
else:
return attr
def _short_repr(self) -> str:
return f'{self.__class__.__name__}<{self.aval}>'
def _pretty_print(self, verbose: bool = False) -> pp.Doc:
if not verbose:
return pp.text(self._short_repr())
base = pp.text(f'Traced<{self.aval}>with<{self._trace}>')
contents = [(name, attr._pretty_print() if isinstance(attr, Tracer)
else pp.text(repr(attr))) for name, attr in self._contents()]
if contents:
base = pp.group(pp.nest(2, pp.concat([
base, pp.text(' with'), pp.brk(), pp.join(pp.brk(), [
pp.text(f'{name} = ') + pp_payload
for name, pp_payload in contents])
])))
return base
def __repr__(self):
return self._pretty_print(verbose=False).format()
def _contents(self):
try:
return [(name, getattr(self, name)) for name in self.__slots__]
except AttributeError:
return ()
def _origin_msg(self) -> str:
return ""
# Methods that are only valid for materialized arrays
def addressable_data(self, index):
raise ConcretizationTypeError(self,
f"The addressable_data() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def block_until_ready(self):
# Raise AttributeError for backward compatibility with hasattr() and getattr() checks.
raise AttributeError(
f"The 'block_until_ready' method is not available on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def copy_to_host_async(self):
# Raise AttributeError for backward compatibility with hasattr() and getattr() checks.
raise AttributeError(
f"The 'copy_to_host_async' method is not available on {self._error_repr()}."
f"{self._origin_msg()}")
def delete(self):
raise ConcretizationTypeError(self,
f"The delete() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
def devices(self):
raise ConcretizationTypeError(self,
f"The devices() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def global_shards(self):
raise ConcretizationTypeError(self,
f"The global_shards property was called on {self._error_repr()}."
f"{self._origin_msg()}")
def is_deleted(self):
raise ConcretizationTypeError(self,
f"The is_deleted() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def is_fully_addressable(self):
raise ConcretizationTypeError(self,
f"The is_fully_addressable property was called on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def is_fully_replicated(self):
raise ConcretizationTypeError(self,
f"The is_fully_replicated property was called on {self._error_repr()}."
f"{self._origin_msg()}")
def on_device_size_in_bytes(self):
raise ConcretizationTypeError(self,
f"The on_device_size_in_bytes() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
@property
def traceback(self):
raise ConcretizationTypeError(self,
f"The traceback property was called on {self._error_repr()}."
f"{self._origin_msg()}")
def unsafe_buffer_pointer(self):
raise ConcretizationTypeError(self,
f"The unsafe_buffer_pointer() method was called on {self._error_repr()}."
f"{self._origin_msg()}")
if jaxlib_extension_version >= 388:
_jax.set_tracer_class(Tracer)
# these can be used to set up forwarding of properties and instance methods from
# Tracer instances to the underlying avals
aval_property = namedtuple("aval_property", ["fget"])
aval_method = namedtuple("aval_method", ["fun"])
pytype_aval_mappings[Tracer] = lambda x: x.aval
def check_eval_args(args):
for arg in args:
if isinstance(arg, Tracer):
raise escaped_tracer_error(arg)
| Tracer |
python | Textualize__textual | docs/examples/styles/opacity.py | {
"start": 64,
"end": 494
} | class ____(App):
CSS_PATH = "opacity.tcss"
def compose(self):
yield Label("opacity: 0%", id="zero-opacity")
yield Label("opacity: 25%", id="quarter-opacity")
yield Label("opacity: 50%", id="half-opacity")
yield Label("opacity: 75%", id="three-quarter-opacity")
yield Label("opacity: 100%", id="full-opacity")
if __name__ == "__main__":
app = OpacityApp()
app.run()
| OpacityApp |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/organization_preprod_artifact_assemble.py | {
"start": 5842,
"end": 10655
} | class ____(ProjectEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (ProjectReleasePermission,)
rate_limits = RateLimitConfig(
limit_overrides={
"POST": {
RateLimitCategory.ORGANIZATION: RateLimit(limit=100, window=60),
}
}
)
def post(self, request: Request, project: Project) -> Response:
"""
Assembles a preprod artifact (mobile build, etc.) and stores it in the database.
"""
analytics.record(
PreprodArtifactApiAssembleEvent(
organization_id=project.organization_id,
project_id=project.id,
user_id=request.user.id,
)
)
if not settings.IS_DEV and not features.has(
"organizations:preprod-frontend-routes", project.organization, actor=request.user
):
return Response({"error": "Feature not enabled"}, status=403)
with sentry_sdk.start_span(op="preprod_artifact.assemble"):
data, error_message = validate_preprod_artifact_schema(request.body)
if error_message:
return Response({"error": error_message}, status=400)
# Support a limited subset of providers
provider = data.get("provider")
if provider is not None and provider not in SUPPORTED_VCS_PROVIDERS:
supported_providers = ", ".join(SUPPORTED_VCS_PROVIDERS)
return Response(
{
"error": f"Unsupported VCS provider '{provider}'. Supported providers are: {supported_providers}"
},
status=400,
)
checksum = str(data.get("checksum", ""))
chunks = data.get("chunks", [])
# Validate VCS parameters
vcs_error = validate_vcs_parameters(data)
if vcs_error:
return Response({"error": vcs_error}, status=400)
# Check if all requested chunks have been uploaded
missing_chunks = find_missing_chunks(project.organization_id, set(chunks))
if missing_chunks:
return Response(
{
"state": ChunkFileState.NOT_FOUND,
"missingChunks": missing_chunks,
}
)
# There is neither a known file nor a cached state, so we will
# have to create a new file. Assure that there are checksums.
# If not, we assume this is a poll and report NOT_FOUND
if not chunks:
return Response({"state": ChunkFileState.NOT_FOUND, "missingChunks": []})
artifact = create_preprod_artifact(
org_id=project.organization_id,
project_id=project.id,
checksum=checksum,
build_configuration_name=data.get("build_configuration"),
release_notes=data.get("release_notes"),
head_sha=data.get("head_sha"),
base_sha=data.get("base_sha"),
provider=data.get("provider"),
head_repo_name=data.get("head_repo_name"),
base_repo_name=data.get("base_repo_name"),
head_ref=data.get("head_ref"),
base_ref=data.get("base_ref"),
pr_number=data.get("pr_number"),
)
if artifact is None:
return Response(
{
"state": ChunkFileState.ERROR,
"detail": "Failed to create preprod artifact row.",
},
status=500,
)
create_preprod_status_check_task.apply_async(
kwargs={
"preprod_artifact_id": artifact.id,
}
)
assemble_preprod_artifact.apply_async(
kwargs={
"org_id": project.organization_id,
"project_id": project.id,
"checksum": checksum,
"chunks": chunks,
"artifact_id": artifact.id,
"build_configuration": data.get("build_configuration"),
}
)
if is_org_auth_token_auth(request.auth):
update_org_auth_token_last_used(request.auth, [project.id])
artifact_url = get_preprod_artifact_url(artifact)
return Response(
{
"state": ChunkFileState.CREATED,
"missingChunks": [],
"artifactUrl": artifact_url,
}
)
| ProjectPreprodArtifactAssembleEndpoint |
python | PyCQA__bandit | examples/hardcoded-passwords.py | {
"start": 85,
"end": 2505
} | class ____:
password = "class_password"
# Possible hardcoded password: 'Admin'
# Severity: Low Confidence: Medium
def someFunction(user, password="Admin"):
print("Hi " + user)
def someFunction2(password):
# Possible hardcoded password: 'root'
# Severity: Low Confidence: Medium
if password == "root":
print("OK, logged in")
def noMatch(password):
# Possible hardcoded password: ''
# Severity: Low Confidence: Medium
if password == '':
print("No password!")
def NoMatch2(password):
# Possible hardcoded password: 'ajklawejrkl42348swfgkg'
# Severity: Low Confidence: Medium
if password == "ajklawejrkl42348swfgkg":
print("Nice password!")
def noMatchObject():
obj = SomeClass()
# Possible hardcoded password: 'this cool password'
# Severity: Low Confidence: Medium
if obj.password == "this cool password":
print(obj.password)
# Possible hardcoded password: 'blerg'
# Severity: Low Confidence: Medium
def doLogin(password="blerg"):
pass
def NoMatch3(a, b):
pass
# Possible hardcoded password: 'blerg'
# Severity: Low Confidence: Medium
doLogin(password="blerg")
# Possible hardcoded password: 'blerg'
# Severity: Low Confidence: Medium
password = "blerg"
# Possible hardcoded password: 'blerg'
# Severity: Low Confidence: Medium
password["password"] = "blerg"
# Possible hardcoded password: 'secret'
# Severity: Low Confidence: Medium
EMAIL_PASSWORD = "secret"
# Possible hardcoded password: 'emails_secret'
# Severity: Low Confidence: Medium
email_pwd = 'emails_secret'
# Possible hardcoded password: 'd6s$f9g!j8mg7hw?n&2'
# Severity: Low Confidence: Medium
my_secret_password_for_email = 'd6s$f9g!j8mg7hw?n&2'
# Possible hardcoded password: '1234'
# Severity: Low Confidence: Medium
passphrase='1234'
# Possible hardcoded password: None
# Severity: High Confidence: High
def __init__(self, auth_scheme, auth_token=None, auth_username=None, auth_password=None, auth_link=None, **kwargs):
self.auth_scheme = auth_scheme
self.auth_token = auth_token
self.auth_username = auth_username
self.auth_password = auth_password
self.auth_link = auth_link
self.kwargs = kwargs
# Possible hardcoded password: None
# Severity: High Confidence: High
from oslo_config import cfg
cfg.StrOpt(
'metadata_proxy_shared_secret',
default='',
secret=True,
)
| SomeClass |
python | django__django | django/http/response.py | {
"start": 15155,
"end": 18828
} | class ____(HttpResponseBase):
"""
A streaming HTTP response class with an iterator as content.
This should only be iterated once, when the response is streamed to the
client. However, it can be appended to or replaced with a new iterator
that wraps the original content (or yields entirely new content).
"""
streaming = True
def __init__(self, streaming_content=(), *args, **kwargs):
super().__init__(*args, **kwargs)
# `streaming_content` should be an iterable of bytestrings.
# See the `streaming_content` property methods.
self.streaming_content = streaming_content
def __repr__(self):
return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % {
"cls": self.__class__.__qualname__,
"status_code": self.status_code,
"content_type": self._content_type_for_repr,
}
@property
def content(self):
raise AttributeError(
"This %s instance has no `content` attribute. Use "
"`streaming_content` instead." % self.__class__.__name__
)
@property
def text(self):
raise AttributeError(
"This %s instance has no `text` attribute." % self.__class__.__name__
)
@property
def streaming_content(self):
if self.is_async:
# pull to lexical scope to capture fixed reference in case
# streaming_content is set again later.
_iterator = self._iterator
async def awrapper():
async for part in _iterator:
yield self.make_bytes(part)
return awrapper()
else:
return map(self.make_bytes, self._iterator)
@streaming_content.setter
def streaming_content(self, value):
self._set_streaming_content(value)
def _set_streaming_content(self, value):
# Ensure we can never iterate on "value" more than once.
try:
self._iterator = iter(value)
self.is_async = False
except TypeError:
self._iterator = aiter(value)
self.is_async = True
if hasattr(value, "close"):
self._resource_closers.append(value.close)
def __iter__(self):
try:
return iter(self.streaming_content)
except TypeError:
warnings.warn(
"StreamingHttpResponse must consume asynchronous iterators in order to "
"serve them synchronously. Use a synchronous iterator instead.",
Warning,
stacklevel=2,
)
# async iterator. Consume in async_to_sync and map back.
async def to_list(_iterator):
as_list = []
async for chunk in _iterator:
as_list.append(chunk)
return as_list
return map(self.make_bytes, iter(async_to_sync(to_list)(self._iterator)))
async def __aiter__(self):
try:
async for part in self.streaming_content:
yield part
except TypeError:
warnings.warn(
"StreamingHttpResponse must consume synchronous iterators in order to "
"serve them asynchronously. Use an asynchronous iterator instead.",
Warning,
stacklevel=2,
)
# sync iterator. Consume via sync_to_async and yield via async
# generator.
for part in await sync_to_async(list)(self.streaming_content):
yield part
def getvalue(self):
return b"".join(self.streaming_content)
| StreamingHttpResponse |
python | cherrypy__cherrypy | cherrypy/test/test_config_server.py | {
"start": 259,
"end": 4166
} | class ____(helper.CPWebCase):
@staticmethod
def setup_server():
class Root:
@cherrypy.expose
def index(self):
return cherrypy.request.wsgi_environ['SERVER_PORT']
@cherrypy.expose
def upload(self, file):
return 'Size: %s' % len(file.file.read())
@cherrypy.expose
@cherrypy.config(**{'request.body.maxbytes': 100})
def tinyupload(self):
return cherrypy.request.body.read()
cherrypy.tree.mount(Root())
cherrypy.config.update(
{
'server.socket_host': '0.0.0.0',
'server.socket_port': 9876,
'server.max_request_body_size': 200,
'server.max_request_header_size': 500,
'server.socket_timeout': 0.5,
# Test explicit server.instance
'server.2.instance': 'cherrypy._cpwsgi_server.CPWSGIServer',
'server.2.socket_port': 9877,
# Test non-numeric <servername>
# Also test default server.instance = builtin server
'server.yetanother.socket_port': 9878,
},
)
PORT = 9876
def testBasicConfig(self):
self.getPage('/')
self.assertBody(str(self.PORT))
def testAdditionalServers(self):
if self.scheme == 'https':
return self.skip('not available under ssl')
self.PORT = 9877
self.getPage('/')
self.assertBody(str(self.PORT))
self.PORT = 9878
self.getPage('/')
self.assertBody(str(self.PORT))
def testMaxRequestSizePerHandler(self):
if getattr(cherrypy.server, 'using_apache', False):
return self.skip('skipped due to known Apache differences... ')
self.getPage(
'/tinyupload',
method='POST',
headers=[
('Content-Type', 'text/plain'),
('Content-Length', '100'),
],
body='x' * 100,
)
self.assertStatus(200)
self.assertBody('x' * 100)
self.getPage(
'/tinyupload',
method='POST',
headers=[
('Content-Type', 'text/plain'),
('Content-Length', '101'),
],
body='x' * 101,
)
self.assertStatus(413)
def testMaxRequestSize(self):
if getattr(cherrypy.server, 'using_apache', False):
return self.skip('skipped due to known Apache differences... ')
for size in (500, 5000, 50000):
self.getPage('/', headers=[('From', 'x' * 500)])
self.assertStatus(413)
# Test for https://github.com/cherrypy/cherrypy/issues/421
# (Incorrect border condition in readline of SizeCheckWrapper).
# This hangs in rev 891 and earlier.
lines256 = 'x' * 248
self.getPage(
'/',
headers=[
('Host', '%s:%s' % (self.HOST, self.PORT)),
('From', lines256),
],
)
# Test upload
cd = (
'Content-Disposition: form-data; name="file"; filename="hello.txt"'
)
body = '\r\n'.join(
['--x', cd, 'Content-Type: text/plain', '', '%s', '--x--'],
)
partlen = 200 - len(body)
b = body % ('x' * partlen)
h = [
('Content-type', 'multipart/form-data; boundary=x'),
('Content-Length', '%s' % len(b)),
]
self.getPage('/upload', h, 'POST', b)
self.assertBody('Size: %d' % partlen)
b = body % ('x' * 200)
h = [
('Content-type', 'multipart/form-data; boundary=x'),
('Content-Length', '%s' % len(b)),
]
self.getPage('/upload', h, 'POST', b)
self.assertStatus(413)
| ServerConfigTests |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_alabama_zip.py | {
"start": 1743,
"end": 4078
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Alabama zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"valid_alabama_zip": ["36671", "36695", "35960", "36867"],
"invalid_alabama_zip": ["-10000", "1234", "99999", "25487"],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "valid_alabama_zip"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "invalid_alabama_zip"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_alabama_zip"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"hackathon",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73", # Don't forget to add your github handle here!
],
"requirements": ["zipcodes"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidAlabamaZip().print_diagnostic_checklist()
| ExpectColumnValuesToBeValidAlabamaZip |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_import_export.py | {
"start": 17991,
"end": 18704
} | class ____(TestCase):
"""
Test issue 1852.
Ensure import works when a relation has a custom primary key.
"""
def setUp(self):
super().setUp()
# The name for this object is the PK
self.named_author = NamedAuthor.objects.create(name="Ian Fleming")
self.resource = UUIDBookResource()
def test_custom_column_name_warns_if_not_present(self):
dataset = tablib.Dataset(
*[("Moonraker", "Ian Fleming")], headers=["name", "author"]
)
self.assertEqual(0, UUIDBook.objects.count())
self.resource.import_data(dataset, raise_errors=True)
self.assertEqual(1, UUIDBook.objects.count())
| CustomPrimaryKeyRelationImportTest |
python | falconry__falcon | falcon/testing/client.py | {
"start": 93835,
"end": 94280
} | class ____:
def __init__(self, coro: Awaitable[StreamedResult]):
self._coro = coro
self._obj: StreamedResult | None = None
async def __aenter__(self) -> StreamedResult:
self._obj = await self._coro
return self._obj
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
assert self._obj is not None
await self._obj.finalize()
self._obj = None
| _AsyncContextManager |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 12701,
"end": 12939
} | class ____:
def test_assign(self):
a = np.arange(10, dtype=np.float32)
a.dtype = [("int", "<0i4"), ("float", "<2f4")]
assert_(a['int'].shape == (5, 0))
assert_(a['float'].shape == (5, 2))
| TestEmptyField |
python | getsentry__sentry | tests/sentry/integrations/discord/test_views.py | {
"start": 2187,
"end": 3450
} | class ____(DiscordIntegrationLinkIdentityTestBase):
def setUp(self) -> None:
super().setUp()
self.identity = self.create_identity(self.user, self.provider, self.discord_user_id)
def test_basic_flow(self) -> None:
url = build_unlinking_url(self.discord_integration, self.discord_user_id) # type: ignore[arg-type]
response = self.client.get(url)
assert response.status_code == 200
self.assertTemplateUsed(response, "sentry/auth-unlink-identity.html")
response = self.client.post(url)
assert response.status_code == 200
self.assertTemplateUsed(response, "sentry/integrations/discord/unlinked.html")
assert not Identity.objects.filter(
external_id=self.discord_user_id, user=self.user
).exists()
@mock.patch("sentry.integrations.messaging.linkage.unsign")
def test_expired_signature(self, mock_sign: mock.MagicMock) -> None:
mock_sign.side_effect = SignatureExpired
url = build_unlinking_url(self.discord_integration, self.discord_user_id) # type: ignore[arg-type]
response = self.client.get(url)
self.assertTemplateUsed(response, "sentry/integrations/discord/expired-link.html")
| DiscordIntegrationUnlinkIdentityTest |
python | python-openxml__python-docx | src/docx/oxml/comments.py | {
"start": 3553,
"end": 4912
} | class ____(BaseOxmlElement):
"""`w:comment` element, representing a single comment.
A comment is a so-called "story" and can contain paragraphs and tables much like a table-cell.
While probably most often used for a single sentence or phrase, a comment can contain rich
content, including multiple rich-text paragraphs, hyperlinks, images, and tables.
"""
# -- attributes on `w:comment` --
id: int = RequiredAttribute("w:id", ST_DecimalNumber) # pyright: ignore[reportAssignmentType]
author: str = RequiredAttribute("w:author", ST_String) # pyright: ignore[reportAssignmentType]
initials: str | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
"w:initials", ST_String
)
date: dt.datetime | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
"w:date", ST_DateTime
)
# -- children --
p = ZeroOrMore("w:p", successors=())
tbl = ZeroOrMore("w:tbl", successors=())
# -- type-declarations for methods added by metaclass --
add_p: Callable[[], CT_P]
p_lst: list[CT_P]
tbl_lst: list[CT_Tbl]
_insert_tbl: Callable[[CT_Tbl], CT_Tbl]
@property
def inner_content_elements(self) -> list[CT_P | CT_Tbl]:
"""Generate all `w:p` and `w:tbl` elements in this comment."""
return self.xpath("./w:p | ./w:tbl")
| CT_Comment |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_media/generate/async_.py | {
"start": 316,
"end": 469
} | class ____(
Generic[Properties, References],
_NearMediaGenerateExecutor[ConnectionAsync, Properties, References],
):
pass
| _NearMediaGenerateAsync |
python | facebook__pyre-check | client/commands/report_any_expressions.py | {
"start": 1285,
"end": 2088
} | class ____(json_mixins.SnakeCaseAndExcludeJsonMixin):
expression_type: str
reasons: List[str]
root_cause_function_name: Optional[str]
location: coverage_data.Location
@staticmethod
def from_typed_backend_data(
data: expression_level_coverage.CoverageGap,
) -> AnyExpression:
return AnyExpression(
expression_type=data.type_,
reasons=data.reason,
root_cause_function_name=data.function_name,
location=coverage_data.Location(
start_line=data.location.start.line,
start_column=data.location.start.column,
end_line=data.location.stop.line,
end_column=data.location.stop.column,
),
)
@dataclasses.dataclass(frozen=True)
| AnyExpression |
python | openai__gym | tests/envs/utils_envs.py | {
"start": 13,
"end": 280
} | class ____(gym.Env):
"""Used in `test_registration.py` to check if `env.make` can import and register an env"""
def __init__(self):
self.action_space = gym.spaces.Discrete(1)
self.observation_space = gym.spaces.Discrete(1)
| RegisterDuringMakeEnv |
python | django__django | tests/model_fields/tests.py | {
"start": 486,
"end": 5150
} | class ____(SimpleTestCase):
def test_show_hidden_initial(self):
"""
Fields with choices respect show_hidden_initial as a kwarg to
formfield().
"""
choices = [(0, 0), (1, 1)]
model_field = models.Field(choices=choices)
form_field = model_field.formfield(show_hidden_initial=True)
self.assertTrue(form_field.show_hidden_initial)
form_field = model_field.formfield(show_hidden_initial=False)
self.assertFalse(form_field.show_hidden_initial)
def test_field_repr(self):
"""
__repr__() of a field displays its name.
"""
f = Foo._meta.get_field("a")
self.assertEqual(repr(f), "<django.db.models.fields.CharField: a>")
f = models.fields.CharField()
self.assertEqual(repr(f), "<django.db.models.fields.CharField>")
def test_field_repr_nested(self):
"""__repr__() uses __qualname__ for nested class support."""
self.assertEqual(repr(Nested.Field()), "<model_fields.tests.Nested.Field>")
def test_field_name(self):
"""
A defined field name (name="fieldname") is used instead of the model
model's attribute name (modelname).
"""
instance = RenamedField()
self.assertTrue(hasattr(instance, "get_fieldname_display"))
self.assertFalse(hasattr(instance, "get_modelname_display"))
def test_field_verbose_name(self):
m = VerboseNameField
for i in range(1, 22):
self.assertEqual(
m._meta.get_field("field%d" % i).verbose_name, "verbose field%d" % i
)
self.assertEqual(m._meta.get_field("id").verbose_name, "verbose pk")
def test_choices_form_class(self):
"""Can supply a custom choices form class to Field.formfield()"""
choices = [("a", "a")]
field = models.CharField(choices=choices)
klass = forms.TypedMultipleChoiceField
self.assertIsInstance(field.formfield(choices_form_class=klass), klass)
def test_formfield_disabled(self):
"""Field.formfield() sets disabled for fields with choices."""
field = models.CharField(choices=[("a", "b")])
form_field = field.formfield(disabled=True)
self.assertIs(form_field.disabled, True)
def test_field_str(self):
f = models.Field()
self.assertEqual(str(f), "<django.db.models.fields.Field>")
f = Foo._meta.get_field("a")
self.assertEqual(str(f), "model_fields.Foo.a")
def test_field_ordering(self):
"""Fields are ordered based on their creation."""
f1 = models.Field()
f2 = models.Field(auto_created=True)
f3 = models.Field()
self.assertLess(f2, f1)
self.assertGreater(f3, f1)
self.assertIsNotNone(f1)
self.assertNotIn(f2, (None, 1, ""))
def test_field_instance_is_picklable(self):
"""Field instances can be pickled."""
field = models.Field(max_length=100, default="a string")
# Must be picklable with this cached property populated (#28188).
field._get_default
pickle.dumps(field)
def test_deconstruct_nested_field(self):
"""deconstruct() uses __qualname__ for nested class support."""
name, path, args, kwargs = Nested.Field().deconstruct()
self.assertEqual(path, "model_fields.tests.Nested.Field")
def test_abstract_inherited_fields(self):
"""Field instances from abstract models are not equal."""
class AbstractModel(models.Model):
field = models.IntegerField()
class Meta:
abstract = True
class InheritAbstractModel1(AbstractModel):
pass
class InheritAbstractModel2(AbstractModel):
pass
abstract_model_field = AbstractModel._meta.get_field("field")
inherit1_model_field = InheritAbstractModel1._meta.get_field("field")
inherit2_model_field = InheritAbstractModel2._meta.get_field("field")
self.assertNotEqual(abstract_model_field, inherit1_model_field)
self.assertNotEqual(abstract_model_field, inherit2_model_field)
self.assertNotEqual(inherit1_model_field, inherit2_model_field)
self.assertLess(abstract_model_field, inherit1_model_field)
self.assertLess(abstract_model_field, inherit2_model_field)
self.assertLess(inherit1_model_field, inherit2_model_field)
def test_hash_immutability(self):
field = models.IntegerField()
field_hash = hash(field)
class MyModel(models.Model):
rank = field
self.assertEqual(field_hash, hash(field))
| BasicFieldTests |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-couchbase/llama_index/vector_stores/couchbase/base.py | {
"start": 953,
"end": 1088
} | class ____(str, Enum):
"""Enum for search types supported by Couchbase GSI."""
ANN = "ANN"
KNN = "KNN"
| QueryVectorSearchType |
python | django__django | django/core/exceptions.py | {
"start": 2344,
"end": 2436
} | class ____(Exception):
"""Some kind of problem with a model field."""
pass
| FieldError |
python | numba__llvmlite | llvmlite/tests/customize.py | {
"start": 5168,
"end": 8097
} | class ____(runner.TextTestResult):
warmup = 3
repetitions = 6
def _huntLeaks(self, test):
self.stream.flush()
repcount = self.repetitions
nwarmup = self.warmup
rc_deltas = [0] * (repcount - nwarmup)
alloc_deltas = [0] * (repcount - nwarmup)
# Preallocate ints likely to be stored in rc_deltas and alloc_deltas,
# to make sys.getallocatedblocks() less flaky.
_int_pool = IntPool()
for i in range(-200, 200):
_int_pool[i]
alloc_before = rc_before = 0
for i in range(repcount):
# Use a pristine, silent result object to avoid recursion
res = result.TestResult()
test.run(res)
# Poorly-written tests may fail when run several times.
# In this case, abort the refleak run and report the failure.
if not res.wasSuccessful():
self.failures.extend(res.failures)
self.errors.extend(res.errors)
raise AssertionError
del res
alloc_after, rc_after = _refleak_cleanup()
if i >= nwarmup:
rc_deltas[i - nwarmup] = _int_pool[rc_after - rc_before]
alloc_deltas[i -
nwarmup] = _int_pool[alloc_after -
alloc_before]
alloc_before, rc_before = alloc_after, rc_after
return rc_deltas, alloc_deltas
def addSuccess(self, test):
try:
rc_deltas, alloc_deltas = self._huntLeaks(test)
except AssertionError:
# Test failed when repeated
assert not self.wasSuccessful()
return
# These checkers return False on success, True on failure
def check_rc_deltas(deltas):
return any(deltas)
def check_alloc_deltas(deltas):
# At least 1/3rd of 0s
if 3 * deltas.count(0) < len(deltas):
return True
# Nothing else than 1s, 0s and -1s
if not set(deltas) <= set((1, 0, -1)):
return True
return False
failed = False
for deltas, item_name, checker in [
(rc_deltas, 'references', check_rc_deltas),
(alloc_deltas, 'memory blocks', check_alloc_deltas)]:
if checker(deltas):
msg = '%s leaked %s %s, sum=%s' % (
test, deltas, item_name, sum(deltas))
failed = True
try:
raise ReferenceLeakError(msg)
except Exception:
exc_info = sys.exc_info()
if self.showAll:
self.stream.write("%s = %r " % (item_name, deltas))
self.addFailure(test, exc_info)
if not failed:
super(RefleakTestResult, self).addSuccess(test)
| RefleakTestResult |
python | wandb__wandb | wandb/sdk/data_types/_dtypes.py | {
"start": 13341,
"end": 13779
} | class ____(Type):
"""A backup type that keeps track of the python object name."""
name = "pythonObject"
legacy_names = ["object"]
types: t.ClassVar[t.List[type]] = []
def __init__(self, class_name: str):
self.params.update({"class_name": class_name})
@classmethod
def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "PythonObjectType":
return cls(py_obj.__class__.__name__)
| PythonObjectType |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_adls_create.py | {
"start": 1130,
"end": 1943
} | class ____:
@mock.patch("airflow.providers.microsoft.azure.operators.adls.AzureDataLakeStorageV2Hook")
def test_execute_success_when_local_data(self, mock_hook):
operator = ADLSCreateObjectOperator(
task_id=TASK_ID,
file_system_name=FILE_SYSTEM_NAME,
file_name=REMOTE_PATH,
data=DATA,
replace=True,
)
operator.execute(None)
data_lake_file_client_mock = mock_hook.return_value.create_file
data_lake_file_client_mock.assert_called_once_with(
file_system_name=FILE_SYSTEM_NAME, file_name=REMOTE_PATH
)
upload_data_mock = data_lake_file_client_mock.return_value.upload_data
upload_data_mock.assert_called_once_with(data=DATA, length=None, overwrite=True)
| TestADLSUploadOperator |
python | tiangolo__fastapi | docs_src/security/tutorial002_an.py | {
"start": 259,
"end": 815
} | class ____(BaseModel):
username: str
email: Union[str, None] = None
full_name: Union[str, None] = None
disabled: Union[bool, None] = None
def fake_decode_token(token):
return User(
username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
)
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
user = fake_decode_token(token)
return user
@app.get("/users/me")
async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]):
return current_user
| User |
python | pennersr__django-allauth | allauth/socialaccount/providers/foursquare/views.py | {
"start": 181,
"end": 1316
} | class ____(OAuth2Adapter):
provider_id = "foursquare"
access_token_url = "https://foursquare.com/oauth2/access_token" # nosec
# Issue ?? -- this one authenticates over and over again...
# authorize_url = 'https://foursquare.com/oauth2/authorize'
authorize_url = "https://foursquare.com/oauth2/authenticate"
profile_url = "https://api.foursquare.com/v2/users/self"
def complete_login(self, request, app, token, **kwargs):
# Foursquare needs a version number for their API requests as
# documented here
# https://developer.foursquare.com/overview/versioning
resp = (
get_adapter()
.get_requests_session()
.get(
self.profile_url,
params={"oauth_token": token.token, "v": "20140116"},
)
)
extra_data = resp.json()["response"]["user"]
return self.get_provider().sociallogin_from_response(request, extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FoursquareOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FoursquareOAuth2Adapter)
| FoursquareOAuth2Adapter |
python | patrick-kidger__equinox | equinox/_module/_prebuilt.py | {
"start": 1182,
"end": 2563
} | class ____(Module, Generic[_Return]):
"""Like `functools.partial`, but treats the wrapped function, and partially-applied
args and kwargs, as a PyTree.
This is very much like `jax.tree_util.Partial`. The difference is that the JAX
version requires that `func` be specifically a *function* -- and will silently
misbehave if given any non-function callable, e.g. [`equinox.nn.MLP`][]. In contrast
the Equinox version allows for arbitrary callables.
"""
func: Callable[..., _Return]
args: tuple[Any, ...]
keywords: dict[str, Any]
def __init__(self, func: Callable[..., _Return], /, *args: Any, **kwargs: Any):
"""**Arguments:**
- `func`: the callable to partially apply.
- `*args`: any positional arguments to apply.
- `**kwargs`: any keyword arguments to apply.
"""
self.func = func
self.args = args
self.keywords = kwargs
def __call__(self, *args: Any, **kwargs: Any) -> _Return:
"""Call the wrapped `self.func`.
**Arguments:**
- `*args`: the arguments to apply. Passed after those arguments passed during
`__init__`.
- `**kwargs`: any keyword arguments to apply.
**Returns:**
The result of the wrapped function.
"""
return self.func(*self.args, *args, **kwargs, **self.keywords)
| Partial |
python | spyder-ide__spyder | spyder/utils/snippets/nodes.py | {
"start": 8781,
"end": 9568
} | class ____(TabstopSnippetNode):
"""
Node that represents an int tabstop placeholder snippet.
This node represents the expression ${int: placeholder}, where placeholder
can be a snippet or text.
"""
KIND = SnippetKind.PLACEHOLDER
def __init__(self, number, placeholder=''):
TabstopSnippetNode.__init__(self, number, placeholder)
def text(self):
if isinstance(self._placeholder, str):
return self._placeholder
elif isinstance(self._placeholder, ASTNode):
return self._placeholder.text()
else:
raise ValueError('Placeholder should be of type '
'SnippetASTNode or str, got {0}'.format(
type(self._placeholder)))
| PlaceholderNode |
python | getsentry__sentry | src/sentry/users/services/lost_password_hash/service.py | {
"start": 445,
"end": 1198
} | class ____(RpcService):
key = "lost_password_hash"
local_mode = SiloMode.CONTROL
@classmethod
def get_local_implementation(cls) -> RpcService:
from sentry.users.services.lost_password_hash.impl import DatabaseLostPasswordHashService
return DatabaseLostPasswordHashService()
# TODO: Denormalize this scim enabled flag onto organizations?
# This is potentially a large list
@rpc_method
@abstractmethod
def get_or_create(
self,
*,
user_id: int,
) -> RpcLostPasswordHash:
"""
This method returns a valid RpcLostPasswordHash for a user
:return:
"""
lost_password_hash_service = LostPasswordHashService.create_delegation()
| LostPasswordHashService |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial005.py | {
"start": 100,
"end": 1583
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero).where(Hero.age < 35)
results = session.exec(statement)
for hero in results:
print(hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | kamyu104__LeetCode-Solutions | Python/circle-and-rectangle-overlapping.py | {
"start": 29,
"end": 602
} | class ____(object):
def checkOverlap(self, radius, x_center, y_center, x1, y1, x2, y2):
"""
:type radius: int
:type x_center: int
:type y_center: int
:type x1: int
:type y1: int
:type x2: int
:type y2: int
:rtype: bool
"""
x1 -= x_center
y1 -= y_center
x2 -= x_center
y2 -= y_center
x = x1 if x1 > 0 else x2 if x2 < 0 else 0
y = y1 if y1 > 0 else y2 if y2 < 0 else 0
return x**2 + y**2 <= radius**2
# Time: O(1)
# Space: O(1)
| Solution |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 2667,
"end": 3552
} | class ____:
"""
Output of FX wrapper codegen. Exposes the same methods as ModuleType, but these
map back to a GraphModule instead of Python source.
"""
gm: GraphModule
compiled_fn: Callable[..., Any]
def __post_init__(self) -> None:
# Write the code to a file for compatibility with debugging utilities.
# The file is deleted upon program termination.
self.tempfile = tempfile.NamedTemporaryFile(
mode="w+", suffix=".py", delete=False
)
atexit.register(os.remove, self.tempfile.name)
with self.tempfile as f:
f.write(self.value)
@property
def __file__(self) -> str:
return self.tempfile.name
def call(self, args: list[Any]) -> Any:
return self.compiled_fn(*args)
@property
def value(self) -> str:
return self.gm.code
| FileBackedGraphModule |
python | doocs__leetcode | solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/Solution.py | {
"start": 0,
"end": 316
} | class ____:
def maxCount(self, banned: List[int], n: int, maxSum: int) -> int:
ans = s = 0
ban = set(banned)
for i in range(1, n + 1):
if s + i > maxSum:
break
if i not in ban:
ans += 1
s += i
return ans
| Solution |
python | gevent__gevent | src/gevent/tests/test__destroy.py | {
"start": 87,
"end": 1765
} | class ____(unittest.TestCase):
def test_destroy_hub(self):
# Loop of initial Hub is default loop.
hub = gevent.get_hub()
self.assertTrue(hub.loop.default)
# Save `gevent.core.loop` object for later comparison.
initloop = hub.loop
# Increase test complexity via threadpool creation.
# Implicitly creates fork watcher connected to the current event loop.
tp = hub.threadpool
self.assertIsNotNone(tp)
# Destroy hub. Does not destroy libev default loop if not explicitly told to.
hub.destroy()
# Create new hub. Must re-use existing libev default loop.
hub = gevent.get_hub()
self.assertTrue(hub.loop.default)
# Ensure that loop object is identical to the initial one.
self.assertIs(hub.loop, initloop)
# Destroy hub including default loop.
hub.destroy(destroy_loop=True)
# Create new hub and explicitly request creation of a new default loop.
# (using default=True, but that's no longer possible.)
hub = gevent.get_hub()
self.assertTrue(hub.loop.default)
# `gevent.core.loop` objects as well as libev loop pointers must differ.
self.assertIsNot(hub.loop, initloop)
self.assertIsNot(hub.loop.ptr, initloop.ptr)
self.assertNotEqual(hub.loop.ptr, initloop.ptr)
# Destroy hub including default loop. The default loop regenerates.
hub.destroy(destroy_loop=True)
hub = gevent.get_hub()
self.assertTrue(hub.loop.default)
hub.destroy()
if __name__ == '__main__':
unittest.main() # pragma: testrunner-no-combine
| TestDestroyHub |
python | sanic-org__sanic | sanic/exceptions.py | {
"start": 452,
"end": 3514
} | class ____(Exception):
"""Generic exception that will generate an HTTP response when raised in the context of a request lifecycle.
Usually, it is best practice to use one of the more specific exceptions
than this generic one. Even when trying to raise a 500, it is generally
preferable to use `ServerError`.
Args:
message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None`,
then the appropriate HTTP response status message will be used instead. Defaults to `None`.
status_code (Optional[int], optional): The HTTP response code to send, if applicable. If `None`,
then it will be 500. Defaults to `None`.
quiet (Optional[bool], optional): When `True`, the error traceback will be suppressed from the logs.
Defaults to `None`.
context (Optional[Dict[str, Any]], optional): Additional mapping of key/value data that will be
sent to the client upon exception. Defaults to `None`.
extra (Optional[Dict[str, Any]], optional): Additional mapping of key/value data that will NOT be
sent to the client when in PRODUCTION mode. Defaults to `None`.
headers (Optional[Dict[str, Any]], optional): Additional headers that should be sent with the HTTP
response. Defaults to `None`.
Examples:
```python
raise SanicException(
"Something went wrong",
status_code=999,
context={
"info": "Some additional details to send to the client",
},
headers={
"X-Foo": "bar"
}
)
```
""" # noqa: E501
status_code: int = 500
quiet: Optional[bool] = False
headers: dict[str, str] = {}
message: str = ""
def __init__(
self,
message: Optional[Union[str, bytes]] = None,
status_code: Optional[int] = None,
*,
quiet: Optional[bool] = None,
context: Optional[dict[str, Any]] = None,
extra: Optional[dict[str, Any]] = None,
headers: Optional[dict[str, str]] = None,
) -> None:
self.context = context
self.extra = extra
status_code = status_code or getattr(
self.__class__, "status_code", None
)
quiet = (
quiet
if quiet is not None
else getattr(self.__class__, "quiet", None)
)
headers = headers or getattr(self.__class__, "headers", {})
if message is None:
message = self.message
if not message and status_code:
msg = STATUS_CODES.get(status_code, b"")
message = msg.decode()
elif isinstance(message, bytes):
message = message.decode()
super().__init__(message)
self.status_code = status_code or self.status_code
self.quiet = quiet
self.headers = headers
try:
self.message = message
except AttributeError:
...
| SanicException |
python | mwaskom__seaborn | seaborn/_marks/area.py | {
"start": 4162,
"end": 5222
} | class ____(AreaBase, Mark):
"""
A fill mark representing an interval between values.
See also
--------
Area : A fill mark drawn from a baseline to data values.
Examples
--------
.. include:: ../docstrings/objects.Band.rst
"""
color: MappableColor = Mappable("C0", )
alpha: MappableFloat = Mappable(.2, )
fill: MappableBool = Mappable(True, )
edgecolor: MappableColor = Mappable(depend="color", )
edgealpha: MappableFloat = Mappable(1, )
edgewidth: MappableFloat = Mappable(0, )
edgestyle: MappableFloat = Mappable("-", )
def _standardize_coordinate_parameters(self, data, orient):
# dv = {"x": "y", "y": "x"}[orient]
# TODO assert that all(ymax >= ymin)?
# TODO what if only one exist?
other = {"x": "y", "y": "x"}[orient]
if not set(data.columns) & {f"{other}min", f"{other}max"}:
agg = {f"{other}min": (other, "min"), f"{other}max": (other, "max")}
data = data.groupby(orient).agg(**agg).reset_index()
return data
| Band |
python | google__jax | tests/pallas/tpu_pallas_pipeline_test.py | {
"start": 72505,
"end": 76293
} | class ____(parameterized.TestCase):
def test_block_spec_bounded_slice_invalid_index(self):
if not jtu.is_device_tpu():
self.skipTest('Only works on TPU.')
shape = (16, 8, 128)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
def main(refs):
x_ref, y_ref = refs
@pl.core_map(pltpu.create_tensorcore_mesh('core'))
def _():
pltpu.emit_pipeline(
kernel,
grid=(1,),
in_specs=(
pl.BlockSpec(
(pl.BoundedSlice(8), 8, 128),
lambda i: (0, 0, 0), # first index needs to be a pl.ds
),
),
out_specs=pl.BlockSpec(
(8, 8, 128),
lambda i: (0, 0, 0),
),
)(x_ref, y_ref)
@jax.jit
def f(x):
y = jnp.ones((8, 8, 128), dtype=jnp.int32)
_, y = pl.run_state(main)((x, y))
return y
with self.assertRaisesRegex(
ValueError,
'Must return a pl.ds from the index_map for a BoundedSlice dimension.'
):
f.trace(jax.ShapeDtypeStruct(shape, jnp.int32))
def test_block_spec_bounded_slice_static(self):
if not jtu.is_device_tpu():
self.skipTest('Only works on TPU.')
if not jtu.is_device_tpu_at_least(4):
self.skipTest('Only works on TPU v4+')
shape = (16, 8, 128)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
def main(refs):
x_ref, y_ref = refs
@pl.core_map(pltpu.create_tensorcore_mesh('core'))
def _():
pltpu.emit_pipeline(
kernel,
grid=(1,),
in_specs=(
pl.BlockSpec(
(pl.BoundedSlice(8), 8, 128),
lambda i: (pl.ds(4, 8), 0, 0),
),
),
out_specs=pl.BlockSpec(
(8, 8, 128),
lambda i: (0, 0, 0),
),
)(x_ref, y_ref)
x = jnp.arange(np.prod(shape), dtype=np.int32).reshape(shape)
@jax.jit
def f(x):
y = jnp.ones((8, 8, 128), dtype=jnp.int32)
_, y = pl.run_state(main)((x, y))
return y
out = f(x)
np.testing.assert_allclose(out, x[4:12])
def test_block_spec_bounded_slice_dynamic(self):
if not jtu.is_device_tpu():
self.skipTest('Only works on TPU.')
if not jtu.is_device_tpu_at_least(4):
self.skipTest('Only works on TPU v4+')
shape = (16, 8, 128)
slices = jnp.array([[0, 3], [3, 8], [8, 11], [11, 16]], dtype=jnp.int32)[
::-1
]
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
def main(refs):
x_ref, y_ref, slices_ref = refs
@pl.core_map(pltpu.create_tensorcore_mesh('core'))
def _():
@functools.partial(
pl.run_scoped, slices_smem=pltpu.SMEM(slices.shape, slices.dtype)
)
def _(slices_smem):
pltpu.sync_copy(slices_ref, slices_smem)
def index_map(i):
return (
pl.ds(slices_smem[i, 0], slices_smem[i, 1] - slices_smem[i, 0]),
0,
0,
)
block_spec = pl.BlockSpec(
(pl.BoundedSlice(16), 8, 128),
index_map,
)
pltpu.emit_pipeline(
kernel,
grid=(slices.shape[0],),
in_specs=(block_spec,),
out_specs=block_spec,
)(x_ref, y_ref)
x = jnp.arange(np.prod(shape), dtype=np.int32).reshape(shape)
@jax.jit
def f(x, slices):
y = pl.empty_like(x)
_, y, _ = pl.run_state(main)((x, y, slices))
return y
out = f(x, slices)
np.testing.assert_allclose(out, x)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| PallasCallBoundedSliceIndexingTest |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/codemods/test_codemod_cli.py | {
"start": 875,
"end": 2157
} | class ____:
def complex_numbers(self, **kw): pass
complex_numbers(min_magnitude=None) # defined in a different scope
"""
BEFORE += _unchanged
AFTER += _unchanged
del _unchanged
def run(command, *, cwd=None, input=None):
return subprocess.run(
command,
input=input,
capture_output=True,
shell=True,
text=True,
cwd=cwd,
encoding="utf-8",
)
def test_codemod_single_file(tmp_path):
fname = tmp_path / "mycode.py"
fname.write_text(BEFORE, encoding="utf-8")
result = run("hypothesis codemod mycode.py", cwd=tmp_path)
assert result.returncode == 0
assert fname.read_text(encoding="utf-8") == AFTER
def test_codemod_multiple_files(tmp_path):
# LibCST had some trouble with multiprocessing on Windows
files = [tmp_path / "mycode1.py", tmp_path / "mycode2.py"]
for f in files:
f.write_text(BEFORE, encoding="utf-8")
result = run("hypothesis codemod mycode1.py mycode2.py", cwd=tmp_path)
assert result.returncode == 0
for f in files:
assert f.read_text(encoding="utf-8") == AFTER
def test_codemod_from_stdin():
result = run("hypothesis codemod -", input=BEFORE)
assert result.returncode == 0
assert result.stdout.rstrip() == AFTER.rstrip()
| Foo |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/control_flow/control_flow_ops_py_test.py | {
"start": 187616,
"end": 190496
} | class ____(test.TestCase):
def testCond(self):
with context.eager_mode():
pred = math_ops.less(1, 2)
fn1 = lambda: [constant_op.constant(10)]
fn2 = lambda: [constant_op.constant(20)]
r = tf_cond.cond(pred, fn1, fn2)
self.assertAllEqual(r.numpy(), 10)
self.assertFalse(isinstance(r, list))
# TODO(b/117279927): Re-enable once msan failure is fixed.
def DISABLED_testCondInDefun(self):
with context.eager_mode():
@eager_def_function.function
def foo(pred):
# TODO(b/111124878): this only needs to output one element.
fn1 = lambda: (constant_op.constant(10), constant_op.constant(100))
fn2 = lambda: (constant_op.constant(20), constant_op.constant(200))
return tf_cond.cond(constant_op.constant(pred), fn1, fn2)
r = foo(True)
self.assertAllEqual(r[0].numpy(), 10)
self.assertNotIsInstance(r, list)
r = foo(False)
self.assertAllEqual(r[0].numpy(), 20)
self.assertFalse(isinstance(r, list))
def testWhileLoop(self):
with context.eager_mode():
tensor = constant_op.constant([1, 2, 3, 4, 5])
self.assertAllEqual(isum(tensor).numpy(), [46, 47, 48, 49, 50])
def testWhileLoopWithMaxIterations(self):
with context.eager_mode():
tensor = constant_op.constant([1, 2, 3, 4, 5])
self.assertAllEqual(
isum(tensor, maximum_iterations=3).numpy(),
[1 + 3, 2 + 3, 3 + 3, 4 + 3, 5 + 3])
@test_util.run_v1_only("b/120545219")
def testWhileWithMaximumIterationsAndSingleArgument(self):
with context.eager_mode():
tensor = constant_op.constant(0)
r = while_loop_tf.while_loop(
lambda i: i < 3, lambda i: i + 1, [tensor], maximum_iterations=1)
self.assertEqual(1, r.numpy())
def testWithDependencies(self):
with context.eager_mode():
t1 = constant_op.constant(1)
t2 = constant_op.constant(2)
t3 = control_flow_ops.with_dependencies(t1, t2)
self.assertAllEqual(t2.numpy(), t3.numpy())
def testTuple(self):
with context.eager_mode():
t1 = constant_op.constant(1)
t2 = constant_op.constant(2)
tup1, tup2 = control_flow_ops.tuple([t1, t2])
self.assertAllEqual(t1.numpy(), tup1.numpy())
self.assertAllEqual(t2.numpy(), tup2.numpy())
@test_util.run_v1_only("b/120545219")
def testCase(self):
with context.eager_mode():
x = constant_op.constant(1)
y = constant_op.constant(2)
z = constant_op.constant(3)
f1 = lambda: constant_op.constant(17)
f2 = lambda: constant_op.constant(23)
f3 = lambda: constant_op.constant(-1)
r1 = control_flow_case.case([(x < y, f1), (x > z, f2)],
default=f3,
exclusive=True)
self.assertAllEqual(r1.numpy(), 17)
if __name__ == "__main__":
test.main()
| EagerTest |
python | django__django | tests/auth_tests/test_remote_user.py | {
"start": 15191,
"end": 16062
} | class ____(RemoteUserTest):
"""
Contains the same tests as RemoteUserTest, but using a custom auth backend
class that doesn't create unknown users.
"""
backend = "auth_tests.test_remote_user.RemoteUserNoCreateBackend"
def test_unknown_user(self):
num_users = User.objects.count()
response = self.client.get("/remote_user/", **{self.header: "newuser"})
self.assertTrue(response.context["user"].is_anonymous)
self.assertEqual(User.objects.count(), num_users)
async def test_unknown_user_async(self):
num_users = await User.objects.acount()
response = await self.async_client.get(
"/remote_user/", **{self.header: "newuser"}
)
self.assertTrue(response.context["user"].is_anonymous)
self.assertEqual(await User.objects.acount(), num_users)
| RemoteUserNoCreateTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels08.py | {
"start": 315,
"end": 1570
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "scatter"})
chart.axis_ids = [45740416, 45705856]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
"data_labels": {"value": 1, "position": "right"},
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | facebookresearch__faiss | tests/test_index.py | {
"start": 5633,
"end": 9235
} | class ____(unittest.TestCase):
def test_IndexIVFPQ(self):
d = 32
nb = 1000
nt = 1500
nq = 200
(xt, xb, xq) = get_dataset_2(d, nt, nb, nq)
gt_index = faiss.IndexFlatL2(d)
gt_index.add(xb)
D, gt_nns = gt_index.search(xq, 1)
coarse_quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFPQ(coarse_quantizer, d, 32, 8, 8)
index.cp.min_points_per_centroid = 5 # quiet warning
index.train(xt)
index.add(xb)
index.nprobe = 4
D, nns = index.search(xq, 10)
n_ok = (nns == gt_nns).sum()
nq = xq.shape[0]
self.assertGreater(n_ok, nq * 0.66)
# check that and Index2Layer gives the same reconstruction
# this is a bit fragile: it assumes 2 runs of training give
# the exact same result.
index2 = faiss.Index2Layer(coarse_quantizer, 32, 8)
if True:
index2.train(xt)
else:
index2.pq = index.pq
index2.is_trained = True
index2.add(xb)
ref_recons = index.reconstruct_n(0, nb)
new_recons = index2.reconstruct_n(0, nb)
self.assertTrue(np.all(ref_recons == new_recons))
def test_IMI(self):
d = 32
nb = 1000
nt = 1500
nq = 200
(xt, xb, xq) = get_dataset_2(d, nt, nb, nq)
d = xt.shape[1]
gt_index = faiss.IndexFlatL2(d)
gt_index.add(xb)
D, gt_nns = gt_index.search(xq, 1)
nbits = 5
coarse_quantizer = faiss.MultiIndexQuantizer(d, 2, nbits)
index = faiss.IndexIVFPQ(coarse_quantizer, d, (1 << nbits) ** 2, 8, 8)
index.quantizer_trains_alone = 1
index.train(xt)
index.add(xb)
index.nprobe = 100
D, nns = index.search(xq, 10)
n_ok = (nns == gt_nns).sum()
# Should return 166 on mac, and 170 on linux.
self.assertGreater(n_ok, 165)
############# replace with explicit assignment indexes
nbits = 5
pq = coarse_quantizer.pq
centroids = faiss.vector_to_array(pq.centroids)
centroids = centroids.reshape(pq.M, pq.ksub, pq.dsub)
ai0 = faiss.IndexFlatL2(pq.dsub)
ai0.add(centroids[0])
ai1 = faiss.IndexFlatL2(pq.dsub)
ai1.add(centroids[1])
coarse_quantizer_2 = faiss.MultiIndexQuantizer2(d, nbits, ai0, ai1)
coarse_quantizer_2.pq = pq
coarse_quantizer_2.is_trained = True
index.quantizer = coarse_quantizer_2
index.reset()
index.add(xb)
D, nns = index.search(xq, 10)
n_ok = (nns == gt_nns).sum()
# should return the same result
self.assertGreater(n_ok, 165)
def test_IMI_2(self):
d = 32
nb = 1000
nt = 1500
nq = 200
(xt, xb, xq) = get_dataset_2(d, nt, nb, nq)
d = xt.shape[1]
gt_index = faiss.IndexFlatL2(d)
gt_index.add(xb)
D, gt_nns = gt_index.search(xq, 1)
############# redo including training
nbits = 5
ai0 = faiss.IndexFlatL2(int(d / 2))
ai1 = faiss.IndexFlatL2(int(d / 2))
coarse_quantizer = faiss.MultiIndexQuantizer2(d, nbits, ai0, ai1)
index = faiss.IndexIVFPQ(coarse_quantizer, d, (1 << nbits) ** 2, 8, 8)
index.quantizer_trains_alone = 1
index.train(xt)
index.add(xb)
index.nprobe = 100
D, nns = index.search(xq, 10)
n_ok = (nns == gt_nns).sum()
# should return the same result
self.assertGreater(n_ok, 165)
| EvalIVFPQAccuracy |
python | getsentry__sentry | src/sentry/api/serializers/models/commit.py | {
"start": 3854,
"end": 5672
} | class ____(CommitSerializer):
def __init__(self, exclude=None, include=None, type=None, *args, **kwargs):
Serializer.__init__(self, *args, **kwargs)
self.exclude = frozenset(exclude if exclude else ())
self.type = type or ""
def get_attrs(self, item_list, user, **kwargs):
from sentry.models.releasecommit import ReleaseCommit
attrs = super().get_attrs(item_list, user)
releases_by_commit = defaultdict(list)
queryset = ReleaseCommit.objects.filter(commit__in=item_list).select_related("release")[
:1000
]
for row in queryset:
releases_by_commit[row.commit_id].append(row.release)
for item in item_list:
attrs[item]["releases"] = releases_by_commit[item.id]
return attrs
def serialize(self, obj, attrs, user, **kwargs) -> CommitSerializerResponseWithReleases:
data = super().serialize(obj, attrs, user)
ret: CommitSerializerResponseWithReleases = {
"id": data["id"],
"message": data["message"],
"dateCreated": data["dateCreated"],
"pullRequest": data["pullRequest"],
"suspectCommitType": data["suspectCommitType"],
"releases": [
{
"version": r.version,
"shortVersion": r.version,
"ref": r.ref,
"url": r.url,
"dateReleased": r.date_released,
"dateCreated": r.date_added,
}
for r in attrs["releases"]
],
}
if "repository" in data:
ret["repository"] = attrs["repository"]
if "author" in data:
ret["author"] = attrs["user"]
return ret
| CommitWithReleaseSerializer |
python | simonw__datasette | datasette/utils/testing.py | {
"start": 1047,
"end": 5036
} | class ____:
max_redirects = 5
def __init__(self, ds):
self.ds = ds
def actor_cookie(self, actor):
return self.ds.sign({"a": actor}, "actor")
@async_to_sync
async def get(
self,
path,
follow_redirects=False,
redirect_count=0,
method="GET",
params=None,
cookies=None,
if_none_match=None,
headers=None,
):
if params:
path += "?" + urlencode(params, doseq=True)
return await self._request(
path=path,
follow_redirects=follow_redirects,
redirect_count=redirect_count,
method=method,
cookies=cookies,
if_none_match=if_none_match,
headers=headers,
)
@async_to_sync
async def post(
self,
path,
post_data=None,
body=None,
follow_redirects=False,
redirect_count=0,
content_type="application/x-www-form-urlencoded",
cookies=None,
headers=None,
csrftoken_from=None,
):
cookies = cookies or {}
post_data = post_data or {}
assert not (post_data and body), "Provide one or other of body= or post_data="
# Maybe fetch a csrftoken first
if csrftoken_from is not None:
assert body is None, "body= is not compatible with csrftoken_from="
if csrftoken_from is True:
csrftoken_from = path
token_response = await self._request(csrftoken_from, cookies=cookies)
csrftoken = token_response.cookies["ds_csrftoken"]
cookies["ds_csrftoken"] = csrftoken
post_data["csrftoken"] = csrftoken
if post_data:
body = urlencode(post_data, doseq=True)
return await self._request(
path=path,
follow_redirects=follow_redirects,
redirect_count=redirect_count,
method="POST",
cookies=cookies,
headers=headers,
post_body=body,
content_type=content_type,
)
@async_to_sync
async def request(
self,
path,
follow_redirects=True,
redirect_count=0,
method="GET",
cookies=None,
headers=None,
post_body=None,
content_type=None,
if_none_match=None,
):
return await self._request(
path,
follow_redirects=follow_redirects,
redirect_count=redirect_count,
method=method,
cookies=cookies,
headers=headers,
post_body=post_body,
content_type=content_type,
if_none_match=if_none_match,
)
async def _request(
self,
path,
follow_redirects=True,
redirect_count=0,
method="GET",
cookies=None,
headers=None,
post_body=None,
content_type=None,
if_none_match=None,
):
await self.ds.invoke_startup()
headers = headers or {}
if content_type:
headers["content-type"] = content_type
if if_none_match:
headers["if-none-match"] = if_none_match
httpx_response = await self.ds.client.request(
method,
path,
follow_redirects=follow_redirects,
avoid_path_rewrites=True,
cookies=cookies,
headers=headers,
content=post_body,
)
response = TestResponse(httpx_response)
if follow_redirects and response.status in (301, 302):
assert (
redirect_count < self.max_redirects
), f"Redirected {redirect_count} times, max_redirects={self.max_redirects}"
location = response.headers["Location"]
return await self._request(
location, follow_redirects=True, redirect_count=redirect_count + 1
)
return response
| TestClient |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 51505,
"end": 55871
} | class ____:
def test_no_extensions(self, backend):
cert = _load_cert(
os.path.join("x509", "verisign_md2_root.pem"),
x509.load_pem_x509_certificate,
)
ext = cert.extensions
assert len(ext) == 0
assert list(ext) == []
with pytest.raises(x509.ExtensionNotFound) as exc:
ext.get_extension_for_oid(ExtensionOID.BASIC_CONSTRAINTS)
assert exc.value.oid == ExtensionOID.BASIC_CONSTRAINTS
def test_one_extension(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom", "basic_constraints_not_critical.pem"
),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.BasicConstraints)
assert ext is not None
assert ext.value.ca is False
def test_duplicate_extension(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "two_basic_constraints.pem"),
x509.load_pem_x509_certificate,
)
with pytest.raises(x509.DuplicateExtension) as exc:
cert.extensions
assert exc.value.oid == ExtensionOID.BASIC_CONSTRAINTS
def test_unsupported_critical_extension(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom", "unsupported_extension_critical.pem"
),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_oid(
x509.ObjectIdentifier("1.2.3.4")
)
assert isinstance(ext.value, x509.UnrecognizedExtension)
assert ext.value.value == b"value"
def test_unsupported_extension(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "unsupported_extension_2.pem"),
x509.load_pem_x509_certificate,
)
extensions = cert.extensions
assert len(extensions) == 2
assert extensions[0].critical is False
assert extensions[0].oid == x509.ObjectIdentifier(
"1.3.6.1.4.1.41482.2"
)
assert extensions[0].value == x509.UnrecognizedExtension(
x509.ObjectIdentifier("1.3.6.1.4.1.41482.2"),
b"1.3.6.1.4.1.41482.1.2",
)
assert extensions[1].critical is False
assert extensions[1].oid == x509.ObjectIdentifier(
"1.3.6.1.4.1.45724.2.1.1"
)
assert extensions[1].value == x509.UnrecognizedExtension(
x509.ObjectIdentifier("1.3.6.1.4.1.45724.2.1.1"), b"\x03\x02\x040"
)
def test_no_extensions_get_for_class(self, backend):
cert = _load_cert(
os.path.join("x509", "cryptography.io.pem"),
x509.load_pem_x509_certificate,
)
exts = cert.extensions
with pytest.raises(x509.ExtensionNotFound) as exc:
exts.get_extension_for_class(x509.IssuerAlternativeName)
assert exc.value.oid == ExtensionOID.ISSUER_ALTERNATIVE_NAME
def test_unrecognized_extension_for_class(self):
exts = x509.Extensions([])
with pytest.raises(TypeError):
exts.get_extension_for_class(x509.UnrecognizedExtension)
def test_indexing(self, backend):
cert = _load_cert(
os.path.join("x509", "cryptography.io.pem"),
x509.load_pem_x509_certificate,
)
exts = cert.extensions
assert exts[-1] == exts[7]
assert exts[2:6:2] == [exts[2], exts[4]]
def test_one_extension_get_for_class(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom", "basic_constraints_not_critical.pem"
),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.BasicConstraints)
assert ext is not None
def test_repr(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom", "basic_constraints_not_critical.pem"
),
x509.load_pem_x509_certificate,
)
assert repr(cert.extensions) == (
"<Extensions([<Extension(oid=<ObjectIdentifier(oid=2.5.29.19, name"
"=basicConstraints)>, critical=False, value=<BasicConstraints(ca=F"
"alse, path_length=None)>)>])>"
)
| TestExtensions |
python | networkx__networkx | networkx/classes/reportviews.py | {
"start": 42700,
"end": 44310
} | class ____(OutEdgeView):
"""A EdgeView class for outward edges of a MultiDiGraph"""
__slots__ = ()
dataview = OutMultiEdgeDataView
def __len__(self):
return sum(
len(kdict) for n, nbrs in self._nodes_nbrs() for nbr, kdict in nbrs.items()
)
def __iter__(self):
for n, nbrs in self._nodes_nbrs():
for nbr, kdict in nbrs.items():
for key in kdict:
yield (n, nbr, key)
def __contains__(self, e):
N = len(e)
if N == 3:
u, v, k = e
elif N == 2:
u, v = e
k = 0
else:
raise ValueError("MultiEdge must have length 2 or 3")
try:
return k in self._adjdict[u][v]
except KeyError:
return False
def __getitem__(self, e):
if isinstance(e, slice):
raise nx.NetworkXError(
f"{type(self).__name__} does not support slicing, "
f"try list(G.edges)[{e.start}:{e.stop}:{e.step}]"
)
u, v, k = e
return self._adjdict[u][v][k]
def __call__(self, nbunch=None, data=False, *, default=None, keys=False):
if nbunch is None and data is False and keys is True:
return self
return self.dataview(self, nbunch, data, default=default, keys=keys)
def data(self, data=True, default=None, nbunch=None, keys=False):
if nbunch is None and data is False and keys is True:
return self
return self.dataview(self, nbunch, data, default=default, keys=keys)
| OutMultiEdgeView |
python | doocs__leetcode | solution/2500-2599/2525.Categorize Box According to Criteria/Solution.py | {
"start": 0,
"end": 355
} | class ____:
def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:
v = length * width * height
bulky = int(any(x >= 10000 for x in (length, width, height)) or v >= 10**9)
heavy = int(mass >= 100)
i = heavy << 1 | bulky
d = ['Neither', 'Bulky', 'Heavy', 'Both']
return d[i]
| Solution |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 166177,
"end": 166359
} | class ____(RecvmsgIntoTests, SendrecvmsgUDPLITETestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
| RecvmsgIntoUDPLITETest |
python | huggingface__transformers | src/transformers/models/lxmert/modeling_lxmert.py | {
"start": 16873,
"end": 17671
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.self = LxmertAttention(config)
self.output = LxmertAttentionOutput(config)
def forward(self, input_tensor, attention_mask, output_attentions=False):
# Self attention attends to itself, thus keys and queries are the same (input_tensor).
output = self.self(
input_tensor,
input_tensor,
attention_mask,
output_attentions=output_attentions,
)
if output_attentions:
attention_probs = output[1]
attention_output = self.output(output[0], input_tensor)
outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
return outputs
| LxmertSelfAttentionLayer |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_alaska_zip.py | {
"start": 1735,
"end": 4062
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Alaska zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"valid_alaska_zip": ["99501", "99621", "99752", "99950"],
"invalid_alaska_zip": ["-10000", "1234", "99999", "25487"],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "valid_alaska_zip"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "invalid_alaska_zip"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_alaska_zip"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"hackathon",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73", # Don't forget to add your github handle here!
],
"requirements": ["zipcodes"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidAlaskaZip().print_diagnostic_checklist()
| ExpectColumnValuesToBeValidAlaskaZip |
python | TheAlgorithms__Python | other/davis_putnam_logemann_loveland.py | {
"start": 3066,
"end": 11716
} | class ____:
"""
| A formula represented in Conjunctive Normal Form.
| A formula is a set of clauses.
| For example,
| {{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1))
"""
def __init__(self, clauses: Iterable[Clause]) -> None:
"""
Represent the number of clauses and the clauses themselves.
"""
self.clauses = list(clauses)
def __str__(self) -> str:
"""
To print a formula as in Conjunctive Normal Form.
>>> str(Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]))
"{{A1 , A2' , A3} , {A5' , A2' , A1}}"
"""
return "{" + " , ".join(str(clause) for clause in self.clauses) + "}"
def generate_clause() -> Clause:
"""
| Randomly generate a clause.
| All literals have the name Ax, where x is an integer from ``1`` to ``5``.
"""
literals = []
no_of_literals = random.randint(1, 5)
base_var = "A"
i = 0
while i < no_of_literals:
var_no = random.randint(1, 5)
var_name = base_var + str(var_no)
var_complement = random.randint(0, 1)
if var_complement == 1:
var_name += "'"
if var_name in literals:
i -= 1
else:
literals.append(var_name)
i += 1
return Clause(literals)
def generate_formula() -> Formula:
"""
Randomly generate a formula.
"""
clauses: set[Clause] = set()
no_of_clauses = random.randint(1, 10)
while len(clauses) < no_of_clauses:
clauses.add(generate_clause())
return Formula(clauses)
def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]:
"""
| Return the clauses and symbols from a formula.
| A symbol is the uncomplemented form of a literal.
For example,
* Symbol of A3 is A3.
* Symbol of A5' is A5.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> clauses_list = [str(i) for i in clauses]
>>> clauses_list
["{A1 , A2' , A3}", "{A5' , A2' , A1}"]
>>> symbols
['A1', 'A2', 'A3', 'A5']
"""
clauses = formula.clauses
symbols_set = []
for clause in formula.clauses:
for literal in clause.literals:
symbol = literal[:2]
if symbol not in symbols_set:
symbols_set.append(symbol)
return clauses, symbols_set
def find_pure_symbols(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[list[str], dict[str, bool | None]]:
"""
| Return pure symbols and their values to satisfy clause.
| Pure symbols are symbols in a formula that exist only in one form,
| either complemented or otherwise.
| For example,
| {{A4 , A3 , A5' , A1 , A3'} , {A4} , {A3}} has pure symbols A4, A5' and A1.
This has the following steps:
1. Ignore clauses that have already evaluated to be ``True``.
2. Find symbols that occur only in one form in the rest of the clauses.
3. Assign value ``True`` or ``False`` depending on whether the symbols occurs
in normal or complemented form respectively.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> pure_symbols, values = find_pure_symbols(clauses, symbols, {})
>>> pure_symbols
['A1', 'A2', 'A3', 'A5']
>>> values
{'A1': True, 'A2': False, 'A3': True, 'A5': False}
"""
pure_symbols = []
assignment: dict[str, bool | None] = {}
literals = []
for clause in clauses:
if clause.evaluate(model):
continue
for literal in clause.literals:
literals.append(literal)
for s in symbols:
sym = s + "'"
if (s in literals and sym not in literals) or (
s not in literals and sym in literals
):
pure_symbols.append(s)
for p in pure_symbols:
assignment[p] = None
for s in pure_symbols:
sym = s + "'"
if s in literals:
assignment[s] = True
elif sym in literals:
assignment[s] = False
return pure_symbols, assignment
def find_unit_clauses(
clauses: list[Clause],
model: dict[str, bool | None], # noqa: ARG001
) -> tuple[list[str], dict[str, bool | None]]:
"""
Returns the unit symbols and their values to satisfy clause.
Unit symbols are symbols in a formula that are:
- Either the only symbol in a clause
- Or all other literals in that clause have been assigned ``False``
This has the following steps:
1. Find symbols that are the only occurrences in a clause.
2. Find symbols in a clause where all other literals are assigned ``False``.
3. Assign ``True`` or ``False`` depending on whether the symbols occurs in
normal or complemented form respectively.
>>> clause1 = Clause(["A4", "A3", "A5'", "A1", "A3'"])
>>> clause2 = Clause(["A4"])
>>> clause3 = Clause(["A3"])
>>> clauses, symbols = generate_parameters(Formula([clause1, clause2, clause3]))
>>> unit_clauses, values = find_unit_clauses(clauses, {})
>>> unit_clauses
['A4', 'A3']
>>> values
{'A4': True, 'A3': True}
"""
unit_symbols = []
for clause in clauses:
if len(clause) == 1:
unit_symbols.append(next(iter(clause.literals.keys())))
else:
f_count, n_count = 0, 0
for literal, value in clause.literals.items():
if value is False:
f_count += 1
elif value is None:
sym = literal
n_count += 1
if f_count == len(clause) - 1 and n_count == 1:
unit_symbols.append(sym)
assignment: dict[str, bool | None] = {}
for i in unit_symbols:
symbol = i[:2]
assignment[symbol] = len(i) == 2
unit_symbols = [i[:2] for i in unit_symbols]
return unit_symbols, assignment
def dpll_algorithm(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[bool | None, dict[str, bool | None] | None]:
"""
Returns the model if the formula is satisfiable, else ``None``
This has the following steps:
1. If every clause in clauses is ``True``, return ``True``.
2. If some clause in clauses is ``False``, return ``False``.
3. Find pure symbols.
4. Find unit symbols.
>>> formula = Formula([Clause(["A4", "A3", "A5'", "A1", "A3'"]), Clause(["A4"])])
>>> clauses, symbols = generate_parameters(formula)
>>> soln, model = dpll_algorithm(clauses, symbols, {})
>>> soln
True
>>> model
{'A4': True}
"""
check_clause_all_true = True
for clause in clauses:
clause_check = clause.evaluate(model)
if clause_check is False:
return False, None
elif clause_check is None:
check_clause_all_true = False
continue
if check_clause_all_true:
return True, model
try:
pure_symbols, assignment = find_pure_symbols(clauses, symbols, model)
except RecursionError:
print("raises a RecursionError and is")
return None, {}
p = None
if len(pure_symbols) > 0:
p, value = pure_symbols[0], assignment[pure_symbols[0]]
if p:
tmp_model = model
tmp_model[p] = value
tmp_symbols = list(symbols)
if p in tmp_symbols:
tmp_symbols.remove(p)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
unit_symbols, assignment = find_unit_clauses(clauses, model)
p = None
if len(unit_symbols) > 0:
p, value = unit_symbols[0], assignment[unit_symbols[0]]
if p:
tmp_model = model
tmp_model[p] = value
tmp_symbols = list(symbols)
if p in tmp_symbols:
tmp_symbols.remove(p)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
p = symbols[0]
rest = symbols[1:]
tmp1, tmp2 = model, model
tmp1[p], tmp2[p] = True, False
return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2)
if __name__ == "__main__":
import doctest
doctest.testmod()
formula = generate_formula()
print(f"The formula {formula} is", end=" ")
clauses, symbols = generate_parameters(formula)
solution, model = dpll_algorithm(clauses, symbols, {})
if solution:
print(f"satisfiable with the assignment {model}.")
else:
print("not satisfiable.")
| Formula |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 66668,
"end": 67471
} | class ____(themeable):
"""
y-axis tick direction
Parameters
----------
theme_element : Literal["in", "out"]
`in` for ticks inside the panel.
`out` for ticks outside the panel.
"""
def __init__(self, theme_element):
msg = (
f"Themeable '{self.__class__.__name__}' is deprecated and"
"will be removed in a future version. "
"Use +ve/-ve/complex values of the axis_ticks_length"
"to affect the direction of the ticks."
)
warn(msg, FutureWarning, stacklevel=1)
super().__init__(theme_element)
def apply_ax(self, ax: Axes):
super().apply_ax(ax)
ax.yaxis.set_tick_params(
which="major", tickdir=self.properties["value"]
)
| axis_ticks_direction_y |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 121879,
"end": 121986
} | class ____(BaseModel):
deleted_points: int = Field(..., description="")
| ShardCleanStatusProgressTelemetry |
python | apache__airflow | providers/common/sql/src/airflow/providers/common/sql/operators/sql.py | {
"start": 33978,
"end": 37163
} | class ____(BaseSQLOperator):
"""
Performs a simple value check using sql code.
:param sql: the sql to be executed. (templated)
:param conn_id: the connection ID used to connect to the database.
:param database: name of database which overwrite the defined one in connection
"""
__mapper_args__ = {"polymorphic_identity": "SQLValueCheckOperator"}
template_fields: Sequence[str] = ("sql", "pass_value", *BaseSQLOperator.template_fields)
template_ext: Sequence[str] = (
".hql",
".sql",
)
template_fields_renderers: ClassVar[dict] = {"sql": "sql"}
ui_color = "#fff7e6"
def __init__(
self,
*,
sql: str,
pass_value: Any,
tolerance: Any = None,
conn_id: str | None = None,
database: str | None = None,
parameters: Iterable | Mapping[str, Any] | None = None,
**kwargs,
):
super().__init__(conn_id=conn_id, database=database, **kwargs)
self.sql = sql
self.pass_value = str(pass_value)
tol = _convert_to_float_if_possible(tolerance)
self.tol = tol if isinstance(tol, float) else None
self.has_tolerance = self.tol is not None
self.parameters = parameters
def check_value(self, records):
if not records:
self._raise_exception(f"The following query returned zero rows: {self.sql}")
pass_value_conv = _convert_to_float_if_possible(self.pass_value)
is_numeric_value_check = isinstance(pass_value_conv, float)
error_msg = (
f"Test failed.\n"
f"Pass value:{pass_value_conv}\n"
f"Tolerance:{f'{self.tol:.1%}' if self.tol is not None else None}\n"
f"Query:\n{self.sql}\n"
f"Results:\n{records!s}"
)
if not is_numeric_value_check:
tests = self._get_string_matches(records, pass_value_conv)
elif is_numeric_value_check:
try:
numeric_records = self._to_float(records)
except (ValueError, TypeError):
raise AirflowException(f"Converting a result to float failed.\n{error_msg}")
tests = self._get_numeric_matches(numeric_records, pass_value_conv)
else:
tests = []
if not all(tests):
self._raise_exception(error_msg)
def execute(self, context: Context):
self.log.info("Executing SQL check: %s", self.sql)
records = self.get_db_hook().get_first(self.sql, self.parameters)
self.check_value(records)
def _to_float(self, records):
return [float(record) for record in records]
def _get_string_matches(self, records, pass_value_conv):
return [str(record) == pass_value_conv for record in records]
def _get_numeric_matches(self, numeric_records, numeric_pass_value_conv):
if self.has_tolerance:
return [
numeric_pass_value_conv * (1 - self.tol) <= record <= numeric_pass_value_conv * (1 + self.tol)
for record in numeric_records
]
return [record == numeric_pass_value_conv for record in numeric_records]
| SQLValueCheckOperator |
python | protocolbuffers__protobuf | python/minimal_test.py | {
"start": 5275,
"end": 7417
} | class ____(unittest.TestCase):
def setUp(self):
msg = unittest_pb2.NestedTestAllTypes()
m = msg
for i in range(101):
m = m.child
m.Clear()
self.p_serialized = msg.SerializeToString()
def testAssertOversizeProto(self):
from google.protobuf.pyext._message import SetAllowOversizeProtos
SetAllowOversizeProtos(False)
q = unittest_pb2.NestedTestAllTypes()
with self.assertRaises(message.DecodeError):
q.ParseFromString(self.p_serialized)
print(q)
def testSucceedOversizeProto(self):
from google.protobuf.pyext._message import SetAllowOversizeProtos
SetAllowOversizeProtos(True)
q = unittest_pb2.NestedTestAllTypes()
q.ParseFromString(self.p_serialized)
def testExtensionIter(self):
extendee_proto = more_extensions_pb2.ExtendedMessage()
extension_int32 = more_extensions_pb2.optional_int_extension
extendee_proto.Extensions[extension_int32] = 23
extension_repeated = more_extensions_pb2.repeated_int_extension
extendee_proto.Extensions[extension_repeated].append(11)
extension_msg = more_extensions_pb2.optional_message_extension
extendee_proto.Extensions[extension_msg].foreign_message_int = 56
# Set some normal fields.
extendee_proto.optional_int32 = 1
extendee_proto.repeated_string.append('hi')
expected = {
extension_int32: True,
extension_msg: True,
extension_repeated: True
}
count = 0
for item in extendee_proto.Extensions:
del expected[item]
self.assertIn(item, extendee_proto.Extensions)
count += 1
self.assertEqual(count, 3)
self.assertEqual(len(expected), 0)
def testIsInitializedStub(self):
proto = unittest_pb2.TestRequiredForeign()
self.assertTrue(proto.IsInitialized())
self.assertFalse(proto.optional_message.IsInitialized())
errors = []
self.assertFalse(proto.optional_message.IsInitialized(errors))
self.assertEqual(['a', 'b', 'c'], errors)
self.assertRaises(message.EncodeError, proto.optional_message.SerializeToString)
if __name__ == '__main__':
unittest.main(verbosity=2)
| OversizeProtosTest |
python | walkccc__LeetCode | solutions/2917. Find the K-or of an Array/2917.py | {
"start": 0,
"end": 207
} | class ____:
def findKOr(self, nums: list[int], k: int) -> int:
MAX_BIT = 30
return sum(2**i
for i in range(MAX_BIT + 1)
if sum(num >> i & 1 for num in nums) >= k)
| Solution |
python | conda__conda | conda/core/path_actions.py | {
"start": 7452,
"end": 17805
} | class ____(CreateInPrefixPathAction):
@classmethod
def create_file_link_actions(
cls, transaction_context, package_info, target_prefix, requested_link_type
):
def get_prefix_replace(source_path_data):
if source_path_data.path_type == PathType.softlink:
link_type = LinkType.copy
prefix_placehoder, file_mode = "", None
elif source_path_data.prefix_placeholder:
link_type = LinkType.copy
prefix_placehoder = source_path_data.prefix_placeholder
file_mode = source_path_data.file_mode
elif source_path_data.no_link:
link_type = LinkType.copy
prefix_placehoder, file_mode = "", None
else:
link_type = requested_link_type
prefix_placehoder, file_mode = "", None
return link_type, prefix_placehoder, file_mode
def make_file_link_action(source_path_data):
# TODO: this inner function is still kind of a mess
noarch = package_info.repodata_record.noarch
if noarch is None and package_info.package_metadata is not None:
# Look in package metadata in case it was omitted from repodata (see issue #8311)
noarch = package_info.package_metadata.noarch
if noarch is not None:
noarch = noarch.type
if noarch == NoarchType.python:
sp_dir = transaction_context["target_site_packages_short_path"]
if sp_dir is None:
raise CondaError(
"Unable to determine python site-packages "
"dir in target_prefix!\nPlease make sure "
f"python is installed in {target_prefix}"
)
target_short_path = get_python_noarch_target_path(
source_path_data.path, sp_dir
)
elif noarch is None or noarch == NoarchType.generic:
target_short_path = source_path_data.path
else:
raise CondaUpgradeError(
dals(
"""
The current version of conda is too old to install this package.
Please update conda."""
)
)
link_type, placeholder, fmode = get_prefix_replace(source_path_data)
if placeholder:
return PrefixReplaceLinkAction(
transaction_context,
package_info,
package_info.extracted_package_dir,
source_path_data.path,
target_prefix,
target_short_path,
requested_link_type,
placeholder,
fmode,
source_path_data,
)
else:
return LinkPathAction(
transaction_context,
package_info,
package_info.extracted_package_dir,
source_path_data.path,
target_prefix,
target_short_path,
link_type,
source_path_data,
)
return tuple(
make_file_link_action(spi) for spi in package_info.paths_data.paths
)
@classmethod
def create_directory_actions(
cls,
transaction_context,
package_info,
target_prefix,
requested_link_type,
file_link_actions,
):
leaf_directories = get_leaf_directories(
axn.target_short_path for axn in file_link_actions
)
return tuple(
cls(
transaction_context,
package_info,
None,
None,
target_prefix,
directory_short_path,
LinkType.directory,
None,
)
for directory_short_path in leaf_directories
)
@classmethod
def create_python_entry_point_windows_exe_action(
cls,
transaction_context,
package_info,
target_prefix,
requested_link_type,
entry_point_def,
):
source_directory = context.conda_prefix
source_short_path = "Scripts/conda.exe"
command, _, _ = parse_entry_point_def(entry_point_def)
target_short_path = f"Scripts/{command}.exe"
source_path_data = PathDataV1(
_path=target_short_path,
path_type=PathType.windows_python_entry_point_exe,
)
return cls(
transaction_context,
package_info,
source_directory,
source_short_path,
target_prefix,
target_short_path,
requested_link_type,
source_path_data,
)
def __init__(
self,
transaction_context,
package_info,
extracted_package_dir,
source_short_path,
target_prefix,
target_short_path,
link_type,
source_path_data,
):
super().__init__(
transaction_context,
package_info,
extracted_package_dir,
source_short_path,
target_prefix,
target_short_path,
)
self.link_type = link_type
self._execute_successful = False
self.source_path_data = source_path_data
self.prefix_path_data = None
def verify(self):
if self.link_type != LinkType.directory and not lexists(
self.source_full_path
): # pragma: no cover
return CondaVerificationError(
dals(
f"""
The package for {self.package_info.repodata_record.name} located at {self.package_info.extracted_package_dir}
appears to be corrupted. The path '{self.source_short_path}'
specified in the package manifest cannot be found.
"""
)
)
source_path_data = self.source_path_data
try:
source_path_type = source_path_data.path_type
except AttributeError:
source_path_type = None
if source_path_type in PathType.basic_types:
# this let's us keep the non-generic path types like windows_python_entry_point_exe
source_path_type = None
if self.link_type == LinkType.directory:
self.prefix_path_data = None
elif self.link_type == LinkType.softlink:
self.prefix_path_data = PathDataV1.from_objects(
self.source_path_data,
path_type=source_path_type or PathType.softlink,
)
elif (
self.link_type == LinkType.copy
and source_path_data.path_type == PathType.softlink
):
self.prefix_path_data = PathDataV1.from_objects(
self.source_path_data,
path_type=source_path_type or PathType.softlink,
)
elif source_path_data.path_type == PathType.hardlink:
try:
reported_size_in_bytes = source_path_data.size_in_bytes
except AttributeError:
reported_size_in_bytes = None
source_size_in_bytes = 0
if reported_size_in_bytes:
source_size_in_bytes = getsize(self.source_full_path)
if reported_size_in_bytes != source_size_in_bytes:
return SafetyError(
dals(
f"""
The package for {self.package_info.repodata_record.name} located at {self.package_info.extracted_package_dir}
appears to be corrupted. The path '{self.source_short_path}'
has an incorrect size.
reported size: {reported_size_in_bytes} bytes
actual size: {source_size_in_bytes} bytes
"""
)
)
try:
reported_sha256 = source_path_data.sha256
except AttributeError:
reported_sha256 = None
# sha256 is expensive. Only run if file sizes agree, and then only if enabled
if (
source_size_in_bytes
and reported_size_in_bytes == source_size_in_bytes
and context.extra_safety_checks
):
source_sha256 = compute_sum(self.source_full_path, "sha256")
if reported_sha256 and reported_sha256 != source_sha256:
return SafetyError(
dals(
f"""
The package for {self.package_info.repodata_record.name} located at {self.package_info.extracted_package_dir}
appears to be corrupted. The path '{self.source_short_path}'
has a sha256 mismatch.
reported sha256: {reported_sha256}
actual sha256: {source_sha256}
"""
)
)
self.prefix_path_data = PathDataV1.from_objects(
source_path_data,
sha256=reported_sha256,
sha256_in_prefix=reported_sha256,
path_type=source_path_type or PathType.hardlink,
)
elif source_path_data.path_type == PathType.windows_python_entry_point_exe:
self.prefix_path_data = source_path_data
else:
raise NotImplementedError()
self._verified = True
def execute(self):
log.log(TRACE, "linking %s => %s", self.source_full_path, self.target_full_path)
create_link(
self.source_full_path,
self.target_full_path,
self.link_type,
force=context.force,
)
self._execute_successful = True
def reverse(self):
if self._execute_successful:
log.log(TRACE, "reversing link creation %s", self.target_prefix)
if not isdir(self.target_full_path):
rm_rf(self.target_full_path, clean_empty_parents=True)
| LinkPathAction |
python | facebookresearch__faiss | tests/test_index_binary.py | {
"start": 9768,
"end": 11115
} | class ____(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
d = 32
nt = 0
nb = 1500
nq = 500
(_, self.xb, self.xq) = make_binary_dataset(d, nt, nb, nq)
def test_hnsw_exact_distances(self):
d = self.xq.shape[1] * 8
nq = self.xq.shape[0]
index = faiss.IndexBinaryHNSW(d, 16)
index.add(self.xb)
Dists, Ids = index.search(self.xq, 3)
for i in range(nq):
for j, dj in zip(Ids[i], Dists[i]):
ref_dis = binary_dis(self.xq[i], self.xb[j])
self.assertEqual(dj, ref_dis)
def test_hnsw(self):
d = self.xq.shape[1] * 8
# NOTE(hoss): Ensure the HNSW construction is deterministic.
nthreads = faiss.omp_get_max_threads()
faiss.omp_set_num_threads(1)
index_hnsw_float = faiss.IndexHNSWFlat(d, 16)
index_hnsw_ref = faiss.IndexBinaryFromFloat(index_hnsw_float)
index_hnsw_bin = faiss.IndexBinaryHNSW(d, 16)
index_hnsw_ref.add(self.xb)
index_hnsw_bin.add(self.xb)
faiss.omp_set_num_threads(nthreads)
Dref, Iref = index_hnsw_ref.search(self.xq, 3)
Dbin, Ibin = index_hnsw_bin.search(self.xq, 3)
self.assertTrue((Dref == Dbin).all())
| TestHNSW |
python | pytorch__pytorch | test/distributed/tensor/test_op_strategy.py | {
"start": 4005,
"end": 6063
} | class ____(DTensorOpTestBase):
@property
def world_size(self) -> int:
return 4
def test_mm_1d_mesh(self):
mesh = self.build_device_mesh()
all_strats = gen_einsum_strategies("mk,kn->mn", mesh)
self.assertEqual(len(all_strats.strategies), 4)
def test_mm_2d_mesh(self):
mesh = DeviceMesh(self.device_type, torch.arange(self.world_size).reshape(2, 2))
all_strats = gen_einsum_strategies("mk,kn->mn", mesh)
self.assertEqual(len(all_strats.strategies), 16)
def test_bmm_1d_mesh(self):
mesh = self.build_device_mesh()
all_strats = gen_einsum_strategies("bmk,bkn->bmn", mesh)
self.assertEqual(len(all_strats.strategies), 5)
def test_bmm_diffinndim_2d_mesh(self):
mesh = DeviceMesh(self.device_type, torch.arange(self.world_size).reshape(2, 2))
all_strats = gen_einsum_strategies("bmk,kn->bmn", mesh)
self.assertEqual(len(all_strats.strategies), 25)
def test_bmm_diffoutndim_2d_mesh(self):
mesh = DeviceMesh(self.device_type, torch.arange(self.world_size).reshape(2, 2))
all_strats = gen_einsum_strategies("bmk,k->bm", mesh)
self.assertEqual(len(all_strats.strategies), 16)
def test_bmm_2d_mesh(self):
mesh = DeviceMesh(self.device_type, torch.arange(self.world_size).reshape(2, 2))
all_strats = gen_einsum_strategies("bmk,bkn->bmn", mesh)
self.assertEqual(len(all_strats.strategies), 25)
def test_pointwise_1d_mesh(self):
mesh = self.build_device_mesh()
simple_strats = gen_einsum_strategies("abcd,abcd->abcd", mesh)
self.assertEqual(len(simple_strats.strategies), 5)
broadcast_strats = gen_einsum_strategies("bcd,abcd->abcd", mesh)
self.assertEqual(len(broadcast_strats.strategies), 5)
def test_linearity_1d_mesh(self):
mesh = self.build_device_mesh()
all_strats = gen_einsum_strategies("abcd,abcd->abcd", mesh, linearity=True)
self.assertEqual(len(all_strats.strategies), 6)
| TestEinsumStrategies |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 4364,
"end": 4777
} | class ____:
def m[S](self: S) -> S:
# `S` is not a local variable here, and `del` can only be used with local variables,
# so `del S` here is not actually a reference to the type variable `S`.
# This `del` statement is therefore not touched by the autofix (it raises `UnboundLocalError`
# both before and after the autofix)
del S
return self
| DeletionsAreNotTouched |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 89810,
"end": 97804
} | class ____(SocketDummyServerTestCase):
@pytest.mark.parametrize("content_length", [None, 0])
@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH"])
def test_content_length_0_by_default(
self, method: str, content_length: int | None
) -> None:
buffer = bytearray()
def socket_handler(listener: socket.socket) -> None:
nonlocal buffer
sock = listener.accept()[0]
while not buffer.endswith(b"\r\n\r\n"):
buffer += sock.recv(65536)
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
b"Server: example.com\r\n"
b"Content-Length: 0\r\n\r\n"
)
sock.close()
self._start_server(socket_handler)
headers = {}
if content_length is not None:
headers["Content-Length"] = str(content_length)
with HTTPConnectionPool(self.host, self.port, timeout=3) as pool:
resp = pool.request(method, "/")
assert resp.status == 200
sent_bytes = bytes(buffer)
assert b"Accept-Encoding: identity\r\n" in sent_bytes
assert b"Content-Length: 0\r\n" in sent_bytes
assert b"transfer-encoding" not in sent_bytes.lower()
@pytest.mark.parametrize("chunked", [True, False])
@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH"])
@pytest.mark.parametrize("body_type", ["file", "generator", "bytes"])
def test_chunked_specified(
self, method: str, chunked: bool, body_type: str
) -> None:
quit_event = threading.Event()
buffer = bytearray()
expected_bytes = b"\r\n\r\na\r\nxxxxxxxxxx\r\n0\r\n\r\n"
def socket_handler(listener: socket.socket) -> None:
nonlocal buffer
listener.settimeout(LONG_TIMEOUT)
while True:
if quit_event.is_set():
return
try:
sock = listener.accept()[0]
break
except (TimeoutError, socket.timeout):
continue
sock.settimeout(LONG_TIMEOUT)
while expected_bytes not in buffer:
if quit_event.is_set():
return
with contextlib.suppress(BlockingIOError):
buffer += sock.recv(65536)
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
b"Server: example.com\r\n"
b"Content-Length: 0\r\n\r\n"
)
sock.close()
self._start_server(socket_handler, quit_event=quit_event)
body: typing.Any
if body_type == "generator":
def body_generator() -> typing.Generator[bytes]:
yield b"x" * 10
body = body_generator()
elif body_type == "file":
body = io.BytesIO(b"x" * 10)
body.seek(0, 0)
else:
if chunked is False:
pytest.skip("urllib3 uses Content-Length in this case")
body = b"x" * 10
with HTTPConnectionPool(
self.host, self.port, timeout=LONG_TIMEOUT, retries=False
) as pool:
resp = pool.request(method, "/", chunked=chunked, body=body)
assert resp.status == 200
sent_bytes = bytes(buffer)
assert sent_bytes.count(b":") == 5
assert b"Host: localhost:" in sent_bytes
assert b"Accept-Encoding: identity\r\n" in sent_bytes
assert b"Transfer-Encoding: chunked\r\n" in sent_bytes
assert b"User-Agent: python-urllib3/" in sent_bytes
assert b"content-length" not in sent_bytes.lower()
assert expected_bytes in sent_bytes
@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH"])
@pytest.mark.parametrize(
"body_type", ["file", "generator", "bytes", "bytearray", "file_text"]
)
def test_chunked_not_specified(self, method: str, body_type: str) -> None:
buffer = bytearray()
expected_bytes: bytes
body: typing.Any
if body_type == "generator":
def body_generator() -> typing.Generator[bytes]:
yield b"x" * 10
body = body_generator()
should_be_chunked = True
elif body_type == "file":
body = io.BytesIO(b"x" * 10)
body.seek(0, 0)
should_be_chunked = True
elif body_type == "file_text":
body = io.StringIO("x" * 10)
body.seek(0, 0)
should_be_chunked = True
elif body_type == "bytearray":
body = bytearray(b"x" * 10)
should_be_chunked = False
else:
body = b"x" * 10
should_be_chunked = False
if should_be_chunked:
expected_bytes = b"\r\n\r\na\r\nxxxxxxxxxx\r\n0\r\n\r\n"
else:
expected_bytes = b"\r\n\r\nxxxxxxxxxx"
def socket_handler(listener: socket.socket) -> None:
nonlocal buffer
sock = listener.accept()[0]
sock.settimeout(0)
while expected_bytes not in buffer:
with contextlib.suppress(BlockingIOError):
buffer += sock.recv(65536)
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
b"Server: example.com\r\n"
b"Content-Length: 0\r\n\r\n"
)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(
self.host, self.port, timeout=LONG_TIMEOUT, retries=False
) as pool:
resp = pool.request(method, "/", body=body)
assert resp.status == 200
sent_bytes = bytes(buffer)
assert sent_bytes.count(b":") == 5
assert b"Host: localhost:" in sent_bytes
assert b"Accept-Encoding: identity\r\n" in sent_bytes
assert b"User-Agent: python-urllib3/" in sent_bytes
if should_be_chunked:
assert b"content-length" not in sent_bytes.lower()
assert b"Transfer-Encoding: chunked\r\n" in sent_bytes
assert expected_bytes in sent_bytes
else:
assert b"Content-Length: 10\r\n" in sent_bytes
assert b"transfer-encoding" not in sent_bytes.lower()
assert sent_bytes.endswith(expected_bytes)
@pytest.mark.parametrize(
"header_transform",
[str.lower, str.title, str.upper],
)
@pytest.mark.parametrize(
["header", "header_value", "expected"],
[
("content-length", "10", b": 10\r\n\r\nxxxxxxxx"),
(
"transfer-encoding",
"chunked",
b": chunked\r\n\r\n8\r\nxxxxxxxx\r\n0\r\n\r\n",
),
],
)
def test_framing_set_via_headers(
self,
header_transform: typing.Callable[[str], str],
header: str,
header_value: str,
expected: bytes,
) -> None:
buffer = bytearray()
def socket_handler(listener: socket.socket) -> None:
nonlocal buffer
sock = listener.accept()[0]
sock.settimeout(0)
while expected not in buffer:
with contextlib.suppress(BlockingIOError):
buffer += sock.recv(65536)
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
b"Server: example.com\r\n"
b"Content-Length: 0\r\n\r\n"
)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(
self.host, self.port, timeout=LONG_TIMEOUT, retries=False
) as pool:
resp = pool.request(
"POST",
"/",
body=b"xxxxxxxx",
headers={header_transform(header): header_value},
)
assert resp.status == 200
sent_bytes = bytes(buffer)
assert sent_bytes.endswith(expected)
| TestContentFraming |
python | huggingface__transformers | src/transformers/models/hunyuan_v1_moe/modular_hunyuan_v1_moe.py | {
"start": 2018,
"end": 4374
} | class ____(LlamaAttention):
def __init__(self, config: HunYuanMoEV1Config, layer_idx: int):
super().__init__(config, layer_idx)
self.query_layernorm = HunYuanMoEV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.key_layernorm = HunYuanMoEV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
query_states = self.query_layernorm(query_states)
key_states = self.key_layernorm(key_states)
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
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_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| HunYuanMoEV1Attention |
python | ray-project__ray | python/ray/autoscaler/v2/tests/test_sdk.py | {
"start": 3938,
"end": 7871
} | class ____:
node_id: Optional[str] = None
node_status: Optional[str] = None
idle_time_check_cb: Optional[Callable] = None
instance_id: Optional[str] = None
ray_node_type_name: Optional[str] = None
instance_type_name: Optional[str] = None
ip_address: Optional[str] = None
details: Optional[str] = None
# Check those resources are included in the actual node info.
total_resources: Optional[dict] = None
available_resources: Optional[dict] = None
def assert_nodes(actual_nodes: List[NodeInfo], expected_nodes: List[ExpectedNodeInfo]):
assert len(actual_nodes) == len(expected_nodes)
# Sort the nodes by id.
actual_nodes = sorted(actual_nodes, key=lambda node: node.node_id)
expected_nodes = sorted(expected_nodes, key=lambda node: node.node_id)
for actual_node, expected_node in zip(actual_nodes, expected_nodes):
if expected_node.node_id is not None:
assert actual_node.node_id == expected_node.node_id
if expected_node.node_status is not None:
assert actual_node.node_status == expected_node.node_status
if expected_node.instance_id is not None:
assert actual_node.instance_id == expected_node.instance_id
if expected_node.ray_node_type_name is not None:
assert actual_node.ray_node_type_name == expected_node.ray_node_type_name
if expected_node.instance_type_name is not None:
assert actual_node.instance_type_name == expected_node.instance_type_name
if expected_node.ip_address is not None:
assert actual_node.ip_address == expected_node.ip_address
if expected_node.details is not None:
assert expected_node.details in actual_node.details
if expected_node.idle_time_check_cb:
assert expected_node.idle_time_check_cb(
actual_node.resource_usage.idle_time_ms
)
if expected_node.total_resources:
for resource_name, total in expected_node.total_resources.items():
assert (
total
== get_total_resources(actual_node.resource_usage.usage)[
resource_name
]
)
if expected_node.available_resources:
for resource_name, available in expected_node.available_resources.items():
assert (
available
== get_available_resources(actual_node.resource_usage.usage)[
resource_name
]
)
def assert_launches(
cluster_status: ClusterStatus,
expected_pending_launches: List[LaunchRequest],
expected_failed_launches: List[LaunchRequest],
):
def assert_launches(actuals, expects):
for actual, expect in zip(actuals, expects):
assert actual.instance_type_name == expect.instance_type_name
assert actual.ray_node_type_name == expect.ray_node_type_name
assert actual.count == expect.count
assert actual.state == expect.state
assert actual.request_ts_s == expect.request_ts_s
assert len(cluster_status.pending_launches) == len(expected_pending_launches)
assert len(cluster_status.failed_launches) == len(expected_failed_launches)
actual_pending = sorted(
cluster_status.pending_launches, key=lambda launch: launch.ray_node_type_name
)
expected_pending = sorted(
expected_pending_launches, key=lambda launch: launch.ray_node_type_name
)
assert_launches(actual_pending, expected_pending)
actual_failed = sorted(
cluster_status.failed_launches, key=lambda launch: launch.ray_node_type_name
)
expected_failed = sorted(
expected_failed_launches, key=lambda launch: launch.ray_node_type_name
)
assert_launches(actual_failed, expected_failed)
@dataclass
| ExpectedNodeInfo |
python | tiangolo__fastapi | docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py | {
"start": 36,
"end": 124
} | class ____(BaseModel):
name: str
description: str | None = None
size: float
| Item |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 5171,
"end": 5398
} | class ____(graphene.Union):
class Meta:
types = (
GrapheneRepositoryLocation,
GraphenePythonError,
)
name = "RepositoryLocationOrLoadError"
| GrapheneRepositoryLocationOrLoadError |
python | weaviate__weaviate-python-client | weaviate/collections/queries/hybrid/generate/sync.py | {
"start": 307,
"end": 448
} | class ____(
Generic[Properties, References],
_HybridGenerateExecutor[ConnectionSync, Properties, References],
):
pass
| _HybridGenerate |
python | pytorch__pytorch | torch/distributed/_tools/sac_estimator.py | {
"start": 2807,
"end": 3258
} | class ____:
"""
Stores metadata for a module for SAC.
Attributes:
start_idx (int): The starting index of the module's operators.
force_store_random (bool): Whether to force store random operators in the module.
sac_metadata (List[_SACMetadata]): List of metadata for each operator in the module.
"""
start_idx: int
force_store_random: bool
sac_metadata: list[_SACMetadata]
@dataclass
| _SACModMetadata |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 1818,
"end": 1873
} | class ____(Class6[T_contra, T_contra]): ...
| Class6_Child3 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/eks_test_constants.py | {
"start": 5768,
"end": 5925
} | class ____:
"""Sizes of test data batches to generate."""
SINGLE: int = 1
SMALL: int = 10
MEDIUM: int = 20
LARGE: int = 200
| BatchCountSize |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 47764,
"end": 48056
} | class ____(FieldValues):
"""
Values for `DateField` with no output format.
"""
valid_inputs = {}
invalid_inputs = {}
outputs = {
datetime.date(2001, 1, 1): datetime.date(2001, 1, 1)
}
field = serializers.DateField(format=None)
| TestNoOutputFormatDateField |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 42771,
"end": 43248
} | class ____(BuiltinFunctionT):
_id = "selfdestruct"
_inputs = [("to", AddressT())]
_is_terminus = True
@process_inputs
def build_IR(self, expr, args, kwargs, context):
vyper_warn(
"`selfdestruct` is deprecated! The opcode is no longer recommended for use.", expr
)
context.check_is_not_constant("selfdestruct", expr)
return IRnode.from_list(ensure_eval_once("selfdestruct", ["selfdestruct", args[0]]))
| SelfDestruct |
python | doocs__leetcode | solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/Solution.py | {
"start": 0,
"end": 676
} | class ____:
def distanceLimitedPathsExist(
self, n: int, edgeList: List[List[int]], queries: List[List[int]]
) -> List[bool]:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
edgeList.sort(key=lambda x: x[2])
j = 0
ans = [False] * len(queries)
for i, (a, b, limit) in sorted(enumerate(queries), key=lambda x: x[1][2]):
while j < len(edgeList) and edgeList[j][2] < limit:
u, v, _ = edgeList[j]
p[find(u)] = find(v)
j += 1
ans[i] = find(a) == find(b)
return ans
| Solution |
python | streamlit__streamlit | lib/streamlit/elements/lib/column_types.py | {
"start": 4121,
"end": 4323
} | class ____(TypedDict):
type: Literal["area_chart"]
y_min: NotRequired[int | float | None]
y_max: NotRequired[int | float | None]
color: NotRequired[ChartColor | None]
| AreaChartColumnConfig |
python | doocs__leetcode | lcof2/剑指 Offer II 041. 滑动窗口的平均值/Solution2.py | {
"start": 0,
"end": 445
} | class ____:
def __init__(self, size: int):
self.n = size
self.s = 0
self.q = deque()
def next(self, val: int) -> float:
if len(self.q) == self.n:
self.s -= self.q.popleft()
self.q.append(val)
self.s += val
return self.s / len(self.q)
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)
| MovingAverage |
python | getsentry__sentry | tests/sentry/integrations/github_enterprise/test_search.py | {
"start": 212,
"end": 1186
} | class ____(test_search.GithubSearchTest):
# Inherit test methods/scenarios from GithubSearchTest
# and fill out the slots that customize it to use github:enterprise
provider = "github_enterprise"
base_url = "https://github.example.org/api/v3"
def _create_integration(self) -> Integration:
future = datetime.now() + timedelta(hours=1)
return self.create_provider_integration(
provider=self.provider,
name="test",
external_id=9999,
metadata={
"domain_name": "github.example.org",
"account_type": "Organization",
"access_token": "123456789",
"expires_at": future.replace(microsecond=0).isoformat(),
"installation": {
"private_key": "some private key",
"id": 123456,
"verify_ssl": True,
},
},
)
| GithubEnterpriseSearchTest |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 40879,
"end": 42313
} | class ____:
def test_basic(self, xp):
# Analytical results:
# sinc(x) = sinc(-x)
# sinc(pi) = 0, sinc(0) = 1
# Hand computation on WolframAlpha:
# sinc(2 pi / 3) = 0.413496672
# sinc(pi / 3) = 0.826993343
# sinc(3 pi / 5) = 0.504551152
# sinc(pi / 5) = 0.935489284
xp_assert_close(windows.lanczos(6, sym=False, xp=xp),
xp.asarray([0., 0.413496672,
0.826993343, 1., 0.826993343,
0.413496672], dtype=xp.float64),
atol=1e-9)
xp_assert_close(windows.lanczos(6, xp=xp),
xp.asarray([0., 0.504551152,
0.935489284, 0.935489284,
0.504551152, 0.], dtype=xp.float64),
atol=1e-9)
xp_assert_close(windows.lanczos(7, sym=True, xp=xp),
xp.asarray([0., 0.413496672,
0.826993343, 1., 0.826993343,
0.413496672, 0.], dtype=xp.float64),
atol=1e-9)
def test_array_size(self, xp):
for n in [0, 10, 11]:
assert windows.lanczos(n, sym=False, xp=xp).shape[0] == n
assert windows.lanczos(n, sym=True, xp=xp).shape[0] == n
@make_xp_test_case(windows.get_window)
| TestLanczos |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 18610,
"end": 18723
} | class ____(permissions.BasePermission):
def has_permission(self, request, view):
return False
| BasicPerm |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.