uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
6a9d07fe80a53b059ebb8f44
train
class
class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport): """gRPC AsyncIO backend transport for WebSecurityScanner. Cloud Web Security Scanner Service identifies security vulnerabilities in web applications hosted on Google Cloud Platform. It crawls your application, and attempts to ex...
class WebSecurityScannerGrpcAsyncIOTransport(WebSecurityScannerTransport):
"""gRPC AsyncIO backend transport for WebSecurityScanner. Cloud Web Security Scanner Service identifies security vulnerabilities in web applications hosted on Google Cloud Platform. It crawls your application, and attempts to exercise as many user inputs and event handlers as possible. This cl...
CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: igno...
256
256
4,959
13
242
googleapis/googleapis-gen
google/cloud/websecurityscanner/v1alpha/websecurityscanner-v1alpha-py/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/grpc_asyncio.py
Python
WebSecurityScannerGrpcAsyncIOTransport
WebSecurityScannerGrpcAsyncIOTransport
38
577
38
38
f4ea1d890dc6a81e4bdc926ef166b312d27c0b4b
bigcode/the-stack
train
47c18188a3822856134e142b
train
function
def create_qparam_nodes( node_name: str, scale: Any, zero_point: Any, modules: Dict[str, torch.nn.Module], quantized_graph: Graph, node_name_to_scope: Dict[str, Tuple[str, type]] ) -> Tuple[Node, Node]: """ Create getattr nodes in the quantized graph for scale and...
def create_qparam_nodes( node_name: str, scale: Any, zero_point: Any, modules: Dict[str, torch.nn.Module], quantized_graph: Graph, node_name_to_scope: Dict[str, Tuple[str, type]] ) -> Tuple[Node, Node]:
""" Create getattr nodes in the quantized graph for scale and zero point values. The nodes are registered with the root_module of the model. """ root_module = modules[''] module_path, _ = node_name_to_scope[node_name] scale_node = create_getattr_from_value(root_module, quantized_graph, (modu...
_node def create_qparam_nodes( node_name: str, scale: Any, zero_point: Any, modules: Dict[str, torch.nn.Module], quantized_graph: Graph, node_name_to_scope: Dict[str, Tuple[str, type]] ) -> Tuple[Node, Node]:
64
64
180
62
1
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
create_qparam_nodes
create_qparam_nodes
372
388
372
379
4c12e1cc8e13c51e5b75c3065c923f86fcac2174
bigcode/the-stack
train
95e6a6f3749ee7245c142699
train
function
def maybe_get_next_module( node: Node, modules: Dict[str, nn.Module], target_module_type: Type[nn.Module] = None, target_functional_type: Any = None, ) -> Optional[Node]: """ Gets the next module that matches what is needed in is_target_module_type if it exists Args: node: The node ...
def maybe_get_next_module( node: Node, modules: Dict[str, nn.Module], target_module_type: Type[nn.Module] = None, target_functional_type: Any = None, ) -> Optional[Node]:
""" Gets the next module that matches what is needed in is_target_module_type if it exists Args: node: The node whose users we want to look at target_module_type: Module type that we want to check target_functional_type: Functional type that we want to check """ for user, _...
"shape" # type: ignore[assignment] return result def maybe_get_next_module( node: Node, modules: Dict[str, nn.Module], target_module_type: Type[nn.Module] = None, target_functional_type: Any = None, ) -> Optional[Node]:
64
64
197
49
14
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
maybe_get_next_module
maybe_get_next_module
490
513
490
495
9e1b790a67d38b7c4f780840e29cf4f3ad6794b6
bigcode/the-stack
train
30b06b6f2c19ae09b00513de
train
function
def get_new_attr_name_with_prefix(prefix: str) -> Callable: prefix = prefix.replace(".", "_") def get_new_attr_name(module: torch.nn.Module): def get_attr_name(i: int): return prefix + str(i) i = 0 attr_name = get_attr_name(i) while hasattr(module, attr_name): ...
def get_new_attr_name_with_prefix(prefix: str) -> Callable:
prefix = prefix.replace(".", "_") def get_new_attr_name(module: torch.nn.Module): def get_attr_name(i: int): return prefix + str(i) i = 0 attr_name = get_attr_name(i) while hasattr(module, attr_name): i += 1 attr_name = get_attr_name(i) ...
, # >> get_new_observer_name = get_new_attr_name_with_prefix('_observer') # >> new_name = get_new_observer_name(module) # new_name will be an unused attribute name on module, e.g. `_observer_1` def get_new_attr_name_with_prefix(prefix: str) -> Callable:
64
64
100
14
50
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
get_new_attr_name_with_prefix
get_new_attr_name_with_prefix
280
292
280
280
d1832f058ee23bffc4d12201c9927e1c3c27ae7b
bigcode/the-stack
train
5d5deb4015d7b8cdfeebc793
train
function
def node_return_type_is_int(node: Node) -> bool: """ Returns true if this node results in an integer, even if some of the args are Tensors. """ return node.op == 'call_method' and node.target == 'size'
def node_return_type_is_int(node: Node) -> bool:
""" Returns true if this node results in an integer, even if some of the args are Tensors. """ return node.op == 'call_method' and node.target == 'size'
_one_tensor if cache: cache[node] = result return result else: found_one_tensor = True result = not found_one_tensor if cache: cache[node] = result return result def node_return_ty...
64
64
56
13
50
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
node_return_type_is_int
node_return_type_is_int
467
472
467
467
ac69a3e1a2bfd6158bf8e3fc0c464df5a84add5e
bigcode/the-stack
train
5a93bb239d7fad223a66a17e
train
function
def graph_pretty_str(g, shorten=True) -> str: """Returns a printable representation of the ops in the graph of g. If shorten is True, tries to abbreviate fields. """ built_in_func_re = re.compile('<built-in function (.*)>') built_in_meth_re = re.compile('<built-in method (.*) of type.*>') op_dic...
def graph_pretty_str(g, shorten=True) -> str:
"""Returns a printable representation of the ops in the graph of g. If shorten is True, tries to abbreviate fields. """ built_in_func_re = re.compile('<built-in function (.*)>') built_in_meth_re = re.compile('<built-in method (.*) of type.*>') op_dict = { 'placeholder': 'plchdr', ...
3], } NON_QUANTIZABLE_WEIGHT_OPS = {torch.nn.functional.layer_norm, torch.nn.functional.group_norm, torch.nn.functional.instance_norm} BIAS_INDEX_DICT = { torch.nn.functional.conv1d : 2, torch.nn.functional.conv2d : 2, torch.nn.functional.conv3d : 2, torch.nn.functional.linear : 2, torch.nn.functi...
179
179
597
13
166
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
graph_pretty_str
graph_pretty_str
48
112
48
48
e13ea78ebaef331b49fa0ef3b2913fc1b0b2b8f7
bigcode/the-stack
train
a63038dced678dc26f58e164
train
function
def _parent_name(target): r = target.rsplit('.', 1) if len(r) == 1: return '', r[0] else: return r[0], r[1]
def _parent_name(target):
r = target.rsplit('.', 1) if len(r) == 1: return '', r[0] else: return r[0], r[1]
.conv3d : 2, torch.nn.functional.linear : 2, torch.nn.functional.layer_norm : 3, torch.nn.functional.group_norm : 3, torch.nn.functional.instance_norm : 4, } # turn foo.bar -> ['foo', 'bar'] def _parent_name(target):
64
64
45
6
58
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
_parent_name
_parent_name
41
46
41
41
36073bcb512eab9947fe7cc48ea4c32dac171987
bigcode/the-stack
train
cd3cfa93fb4a00fed186c136
train
function
def collect_producer_nodes(node: Node) -> Optional[List[Node]]: r''' Starting from a target node, trace back until we hit inpu or getattr node. This is used to extract the chain of operators starting from getattr to the target node, for example def forward(self, x): observed = self.observer(self.w...
def collect_producer_nodes(node: Node) -> Optional[List[Node]]:
r''' Starting from a target node, trace back until we hit inpu or getattr node. This is used to extract the chain of operators starting from getattr to the target node, for example def forward(self, x): observed = self.observer(self.weight) return F.linear(x, observed) collect_producer_n...
return prefix + str(i) i = 0 attr_name = get_attr_name(i) while hasattr(module, attr_name): i += 1 attr_name = get_attr_name(i) return attr_name return get_new_attr_name def collect_producer_nodes(node: Node) -> Optional[List[Node]]:
71
71
237
15
55
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
collect_producer_nodes
collect_producer_nodes
294
319
294
294
6fc8065efbe15caac86da0de3e155677444d3747
bigcode/the-stack
train
b2f35b857ef816c2c6bb6ea8
train
function
def get_qconv_op(conv_op: Callable, has_relu: bool) -> Callable: qconv_op = { # has relu True: { torch.nn.functional.conv1d: torch.ops.quantized.conv1d_relu, torch.nn.functional.conv2d: torch.ops.quantized.conv2d_relu, torch.nn.functional.conv3d: torch.ops.quantiz...
def get_qconv_op(conv_op: Callable, has_relu: bool) -> Callable:
qconv_op = { # has relu True: { torch.nn.functional.conv1d: torch.ops.quantized.conv1d_relu, torch.nn.functional.conv2d: torch.ops.quantized.conv2d_relu, torch.nn.functional.conv3d: torch.ops.quantized.conv3d_relu }, False: { torch.nn.f...
.conv3d_prepack } prepack_op = prepack_ops.get(conv_op, None) assert prepack_op, "Didn't find prepack op for {}".format(conv_op) return prepack_op def get_qconv_op(conv_op: Callable, has_relu: bool) -> Callable:
64
64
186
18
45
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
get_qconv_op
get_qconv_op
257
273
257
257
c698eddde85e435f61868d25fc5e2a97da45675c
bigcode/the-stack
train
8bfefef634bb50d63616f41f
train
function
def get_linear_prepack_op_for_dtype(dtype): if dtype == torch.float16: return torch.ops.quantized.linear_prepack_fp16 elif dtype == torch.qint8: return torch.ops.quantized.linear_prepack else: raise Exception("can't get linear prepack op for dtype:", dtype)
def get_linear_prepack_op_for_dtype(dtype):
if dtype == torch.float16: return torch.ops.quantized.linear_prepack_fp16 elif dtype == torch.qint8: return torch.ops.quantized.linear_prepack else: raise Exception("can't get linear prepack op for dtype:", dtype)
_only"]: quant_mode_custom_module_config = custom_module_mapping.get(quant_mode, {}) quant_mode_custom_module_classes = set(quant_mode_custom_module_config.keys()) float_custom_module_classes |= quant_mode_custom_module_classes return list(float_custom_module_classes) def get_linear_prepack_...
64
64
67
10
54
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
get_linear_prepack_op_for_dtype
get_linear_prepack_op_for_dtype
239
245
239
239
9d91bb34de6f74640c48248360141ee8110d4e1e
bigcode/the-stack
train
405a1de702817809f706668f
train
function
def create_getattr_from_value(module: torch.nn.Module, graph: Graph, prefix: str, value: Any) -> Node: """ Given a value of any type, creates a getattr node corresponding to the value and registers the value as a buffer to the module. """ get_new_attr_name = get_new_attr_name_with_prefix(prefix) ...
def create_getattr_from_value(module: torch.nn.Module, graph: Graph, prefix: str, value: Any) -> Node:
""" Given a value of any type, creates a getattr node corresponding to the value and registers the value as a buffer to the module. """ get_new_attr_name = get_new_attr_name_with_prefix(prefix) attr_name = get_new_attr_name(module) device = assert_and_get_unique_device(module) module.reg...
, " "but got devices {}".format(devices) ) device = next(iter(devices)) if len(devices) > 0 else None return device def create_getattr_from_value(module: torch.nn.Module, graph: Graph, prefix: str, value: Any) -> Node:
64
64
135
27
36
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
create_getattr_from_value
create_getattr_from_value
359
370
359
359
cc4946778493f85f346a628437b568c60ac19959
bigcode/the-stack
train
52d69ad45935741e47d1f10e
train
function
def get_qconv_prepack_op(conv_op: Callable) -> Callable: prepack_ops = { torch.nn.functional.conv1d: torch.ops.quantized.conv1d_prepack, torch.nn.functional.conv2d: torch.ops.quantized.conv2d_prepack, torch.nn.functional.conv3d: torch.ops.quantized.conv3d_prepack } prepack_op = prepa...
def get_qconv_prepack_op(conv_op: Callable) -> Callable:
prepack_ops = { torch.nn.functional.conv1d: torch.ops.quantized.conv1d_prepack, torch.nn.functional.conv2d: torch.ops.quantized.conv2d_prepack, torch.nn.functional.conv3d: torch.ops.quantized.conv3d_prepack } prepack_op = prepack_ops.get(conv_op, None) assert prepack_op, "Didn't ...
return torch.ops.quantized.linear_prepack_fp16 elif dtype == torch.qint8: return torch.ops.quantized.linear_prepack else: raise Exception("can't get linear prepack op for dtype:", dtype) def get_qconv_prepack_op(conv_op: Callable) -> Callable:
64
64
115
15
49
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
get_qconv_prepack_op
get_qconv_prepack_op
247
255
247
247
869552305a8b6f28ea288cb8e3fe23629c529a9d
bigcode/the-stack
train
e0a62283a4066343ae748a21
train
function
def get_quantize_node_info(activation_post_process: Callable) -> Tuple[str, Union[Callable, str], Dict[str, Any]]: ''' Given an activation_post_process module, return node_type(e.g. call_function), quantize op(e.g. quantize_per_tensor) and a dictionary of extracted qparams from the module ''' dtype ...
def get_quantize_node_info(activation_post_process: Callable) -> Tuple[str, Union[Callable, str], Dict[str, Any]]:
''' Given an activation_post_process module, return node_type(e.g. call_function), quantize op(e.g. quantize_per_tensor) and a dictionary of extracted qparams from the module ''' dtype = activation_post_process.dtype # type: ignore[attr-defined] quantize_op : Optional[Union[Callable, str]] = No...
res_str def get_per_tensor_qparams(activation_post_process): assert is_per_tensor(activation_post_process.qscheme), 'Only per tensor quantization is supported' scale, zero_point = activation_post_process.calculate_qparams() scale = float(scale) zero_point = int(zero_point) dtype = activation_post_...
108
108
361
28
79
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
get_quantize_node_info
get_quantize_node_info
122
148
122
122
7d679ed917ce0fb9ee11aeceac774266327d6248
bigcode/the-stack
train
e9c3b2fb08d81c127c804d34
train
function
def quantize_node( in_node: Node, obs_module: torch.nn.Module, obs_node: Node, modules: Dict[str, torch.nn.Module], quantized_graph: Graph, node_name_to_scope: Dict[str, Tuple[str, type]], is_input: bool) -> Node: ''' Add quantization nodes (eg. quantize_per_t...
def quantize_node( in_node: Node, obs_module: torch.nn.Module, obs_node: Node, modules: Dict[str, torch.nn.Module], quantized_graph: Graph, node_name_to_scope: Dict[str, Tuple[str, type]], is_input: bool) -> Node:
''' Add quantization nodes (eg. quantize_per_tensor/per_channel) for given node to graph with the qparams calculated from activation_post_process (obs_module). The observer node (obs_node) is used to find the FQN of the user of act_post_process. e.g. Given input `node` in `node = self.conv(x)`, insert n...
_op = torch.quantize_per_channel else: scale = float(scale) zero_point = int(zero_point) qparams = {"_scale_": scale, "_zero_point_": zero_point, "_dtype_": dtype} quantize_op = torch.quantize_per_tensor elif dtype == torch.float16: node_type = "call_m...
203
203
677
65
137
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
quantize_node
quantize_node
150
206
150
157
d98468df0eedbed38eb268c232d6850d9a6822ce
bigcode/the-stack
train
10ae96ae8d5268daa45d6314
train
function
def graph_module_from_producer_nodes( root: GraphModule, producer_nodes: List[Node]) -> GraphModule: r''' Construct a graph module from extracted producer nodes from `collect_producer_nodes` function Args: root: the root module for the original graph producer_nodes: a list of nodes we us...
def graph_module_from_producer_nodes( root: GraphModule, producer_nodes: List[Node]) -> GraphModule:
r''' Construct a graph module from extracted producer nodes from `collect_producer_nodes` function Args: root: the root module for the original graph producer_nodes: a list of nodes we use to construct the graph Return: A graph module constructed from the producer nodes ''' ass...
in this case return None nodes.append(arg) if not (arg.op == 'call_function' and arg.target == getattr): frontier.append(arg) return nodes def graph_module_from_producer_nodes( root: GraphModule, producer_nodes: List[Node]) -> GraphModule:
64
64
213
25
38
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
graph_module_from_producer_nodes
graph_module_from_producer_nodes
321
343
321
322
282956a19d49acb113743e6ea83a5fdfd5ce59e3
bigcode/the-stack
train
843e0f7745cee130b2337a05
train
function
def get_per_tensor_qparams(activation_post_process): assert is_per_tensor(activation_post_process.qscheme), 'Only per tensor quantization is supported' scale, zero_point = activation_post_process.calculate_qparams() scale = float(scale) zero_point = int(zero_point) dtype = activation_post_process.dt...
def get_per_tensor_qparams(activation_post_process):
assert is_per_tensor(activation_post_process.qscheme), 'Only per tensor quantization is supported' scale, zero_point = activation_post_process.calculate_qparams() scale = float(scale) zero_point = int(zero_point) dtype = activation_post_process.dtype return scale, zero_point, dtype
exra note on abbreviations which change attribute names, # since users will have to un-abbreviate for further debugging if shorten: res_str += "*obs_{n} = activation_post_process_{n}\n" return res_str def get_per_tensor_qparams(activation_post_process):
64
64
77
11
52
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
get_per_tensor_qparams
get_per_tensor_qparams
114
120
114
114
958a571a46f55620f814496c4ce1f5c960f208f2
bigcode/the-stack
train
613547264f9902376d678fc4
train
function
def all_node_args_have_no_tensors(node: Node, modules: Dict[str, torch.nn.Module], cache: Dict[Node, bool]) -> bool: """ If we know for sure that all of this node's args have no tensors (are primitives), return True. If we either find a tensor or are not sure, return False. Note: this function is n...
def all_node_args_have_no_tensors(node: Node, modules: Dict[str, torch.nn.Module], cache: Dict[Node, bool]) -> bool:
""" If we know for sure that all of this node's args have no tensors (are primitives), return True. If we either find a tensor or are not sure, return False. Note: this function is not exact. """ if cache and node in cache: return cache[node] result = False # will be overwritt...
_name: str, scale: Any, zero_point: Any, modules: Dict[str, torch.nn.Module], quantized_graph: Graph, node_name_to_scope: Dict[str, Tuple[str, type]] ) -> Tuple[Node, Node]: """ Create getattr nodes in the quantized graph for scale and zero point values. The nodes are...
204
204
682
32
172
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
all_node_args_have_no_tensors
all_node_args_have_no_tensors
391
464
391
391
1dc894c123bd525c5856378ddbbad3214a20884c
bigcode/the-stack
train
6e79df752cd4b671ee1f33c0
train
function
def get_custom_module_class_keys(custom_config_dict, custom_config_dict_key) -> List[Any]: r""" Get all the unique custom module keys in the custom config dict e.g. Input: custom_config_dict = { "float_to_observed_custom_module_class": { "static": { CustomModule1: Obser...
def get_custom_module_class_keys(custom_config_dict, custom_config_dict_key) -> List[Any]:
r""" Get all the unique custom module keys in the custom config dict e.g. Input: custom_config_dict = { "float_to_observed_custom_module_class": { "static": { CustomModule1: ObservedCustomModule }, "dynamic": { CustomModule2: Dynamic...
inputs.append(qparam_node) else: # for qparams that are not scale/zero_point (like axis, dtype) we store them as literals in the graph. inputs.append(value) return graph.create_node(node_type, quantize_op, tuple(inputs), {}) def get_custom_module_class_keys(custom_config_dict, custo...
76
77
257
19
57
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
get_custom_module_class_keys
get_custom_module_class_keys
208
237
208
208
ff9fee7e4e17154e0fd93e8c534a7938475cce5e
bigcode/the-stack
train
ee0094dfb1e744f0ab405a73
train
function
def node_bool_tensor_arg_indexes(node: Node) -> List[int]: """ Returns indexes of boolean Tensor args """ if node.op == "call_method" and node.target == "masked_fill": return [1] return []
def node_bool_tensor_arg_indexes(node: Node) -> List[int]:
""" Returns indexes of boolean Tensor args """ if node.op == "call_method" and node.target == "masked_fill": return [1] return []
(node: Node) -> bool: """ Returns true if this node results in an integer, even if some of the args are Tensors. """ return node.op == 'call_method' and node.target == 'size' def node_bool_tensor_arg_indexes(node: Node) -> List[int]:
64
64
51
14
50
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
node_bool_tensor_arg_indexes
node_bool_tensor_arg_indexes
474
480
474
474
b72af389e762d47af6df384961859cdb603c8b25
bigcode/the-stack
train
a1a30df84473eae90560a05c
train
function
def assert_and_get_unique_device(module: torch.nn.Module) -> Any: """ Returns the unique device for a module, or None if no device is found. Throws an error if multiple devices are detected. """ devices = {p.device for p in module.parameters()} | \ {p.device for p in module.buffers()} as...
def assert_and_get_unique_device(module: torch.nn.Module) -> Any:
""" Returns the unique device for a module, or None if no device is found. Throws an error if multiple devices are detected. """ devices = {p.device for p in module.parameters()} | \ {p.device for p in module.buffers()} assert len(devices) <= 1, ( "prepare only works with cpu or ...
producer_node in producer_nodes: env[producer_node] = graph.node_copy(producer_node, load_arg) graph.output(load_arg(producer_nodes[-1])) graph_module = GraphModule(root, graph) return graph_module def assert_and_get_unique_device(module: torch.nn.Module) -> Any:
64
64
131
15
48
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
assert_and_get_unique_device
assert_and_get_unique_device
345
357
345
345
705b680e71d9c19a9fcf9257ac7ac2d593793f77
bigcode/the-stack
train
04953e6b2fa5e941cfd11418
train
function
def is_get_tensor_info_node(node: Node) -> bool: """ Returns True if this node is a node that takes a Tensor as input and output some meta information about the Tensor, e.g. shape, size etc. """ result: bool = \ node.op == "call_function" and node.target == getattr and node.args[1] == "shape" #...
def is_get_tensor_info_node(node: Node) -> bool:
""" Returns True if this node is a node that takes a Tensor as input and output some meta information about the Tensor, e.g. shape, size etc. """ result: bool = \ node.op == "call_function" and node.target == getattr and node.args[1] == "shape" # type: ignore[assignment] return result
def node_bool_tensor_arg_indexes(node: Node) -> List[int]: """ Returns indexes of boolean Tensor args """ if node.op == "call_method" and node.target == "masked_fill": return [1] return [] def is_get_tensor_info_node(node: Node) -> bool:
64
64
91
13
51
sanchitintel/pytorch
torch/ao/quantization/fx/utils.py
Python
is_get_tensor_info_node
is_get_tensor_info_node
482
488
482
482
ca1f573046b041cf03ed308fd2de6cb9197ec740
bigcode/the-stack
train
34f27668cb20e26d25360ecf
train
class
class AppDomainUnloadedException(SystemException,ISerializable,_Exception): """ The exception that is thrown when an attempt is made to access an unloaded application domain. AppDomainUnloadedException() AppDomainUnloadedException(message: str) AppDomainUnloadedException(message: str,innerException: Ex...
class AppDomainUnloadedException(SystemException,ISerializable,_Exception):
""" The exception that is thrown when an attempt is made to access an unloaded application domain. AppDomainUnloadedException() AppDomainUnloadedException(message: str) AppDomainUnloadedException(message: str,innerException: Exception) """ def add_SerializeObjectState(self,*args): """ add_Seriali...
class AppDomainUnloadedException(SystemException,ISerializable,_Exception):
15
90
302
15
0
hdm-dt-fb/ironpython-stubs
stubs.min/System/__init___parts/AppDomainUnloadedException.py
Python
AppDomainUnloadedException
AppDomainUnloadedException
1
37
1
1
3fac28dc75d522537618c8f447be366624d28359
bigcode/the-stack
train
9e94034b0b266bd78d2a0e63
train
class
class DeviceMonitor: """Device monitor plugin interface.""" def get_driver_version(self) -> str: """Get device's driver version.""" raise NotImplementedError def get_device_utilization(self, index: int) -> str: """ Get device utilization method. It is just a genera...
class DeviceMonitor:
"""Device monitor plugin interface.""" def get_driver_version(self) -> str: """Get device's driver version.""" raise NotImplementedError def get_device_utilization(self, index: int) -> str: """ Get device utilization method. It is just a general method that returns...
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Device monitor plugin module.""" class DeviceMonitor:
35
64
86
4
31
ssg-research/openfl
openfl/plugins/processing_units_monitor/device_monitor.py
Python
DeviceMonitor
DeviceMonitor
6
19
6
6
91eadad7b7028de9fcd760b6cdec9c280b56375c
bigcode/the-stack
train
b89527caaa41e10debb808a5
train
class
@BACKBONES.register_module() class RegNet(ResNet): """RegNet backbone. More details can be found in `paper <https://arxiv.org/abs/2003.13678>`__ . Args: arch (dict): The parameter of RegNets. - w0 (int): initial width - wa (float): slope of width - wm ...
@BACKBONES.register_module() class RegNet(ResNet):
"""RegNet backbone. More details can be found in `paper <https://arxiv.org/abs/2003.13678>`__ . Args: arch (dict): The parameter of RegNets. - w0 (int): initial width - wa (float): slope of width - wm (float): quantization parameter to quantize the width...
import copy import numpy as np import torch.nn as nn from mmcv.cnn import build_conv_layer, build_norm_layer from ..registry import BACKBONES from .resnet import ResNet from .resnext import Bottleneck @BACKBONES.register_module() class RegNet(ResNet):
66
256
2,795
14
51
jcwon0/BlurHPE
mmpose/models/backbones/regnet.py
Python
RegNet
RegNet
12
315
12
13
0b68adf435404dd3bb9c4ca990ecffec01443071
bigcode/the-stack
train
94b68dbb80d02260a17a061e
train
function
def delayProcess(iqueue): # Show count, message = 0, None while True: if not iqueue.empty(): if message is not None: print("\033[F" + message + ". ") message, count = iqueue.get(), 0 print() # New message if message is not None: count += 1 ...
def delayProcess(iqueue): # Show
count, message = 0, None while True: if not iqueue.empty(): if message is not None: print("\033[F" + message + ". ") message, count = iqueue.get(), 0 print() # New message if message is not None: count += 1 print("\033[F" + message +...
For two-dimension (matrix) parameters in Excel for i in range(values.shape[0]): for j in range(values.shape[1]): data_dict[(i+1, j+1)] = values[i][j] return data_dict def delayProcess(iqueue): # Show
64
64
131
10
53
TEAM-IMT/energy-network-optimization
main.py
Python
delayProcess
delayProcess
65
77
65
65
729029457b6211080b96fc4c900ae60d2a8281ed
bigcode/the-stack
train
25e035b0e8b88d3a89afea4f
train
function
def parse_args(): '''parse args''' parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, usage="%(prog)s [-h] [-dbf DATABASE_FILENAME] {PULP,ILS,ILSgraphics}", description='Program to execute MILP and ILS algorith...
def parse_args():
'''parse args''' parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, usage="%(prog)s [-h] [-dbf DATABASE_FILENAME] {PULP,ILS,ILSgraphics}", description='Program to execute MILP and ILS algorithms, and graphics t...
"][INFO:] Total execution time: {} s. Best solution = {} with Z = {}."\ .format(time.time() - tic_t, s_best, z_min) + Fore.RESET) local_search.setCurrentER(s_best) local_search.printResults() p_detect.terminate() ## Graphics ILSPlotResults(outname, show_plots = True) # Statistics graphics ...
196
196
655
4
192
TEAM-IMT/energy-network-optimization
main.py
Python
parse_args
parse_args
180
210
180
180
c5e93e6e07c94a005af6506006797da720612cf0
bigcode/the-stack
train
bf2fdcf597039d0f14d345fc
train
function
def ILS_algoritm(config_file = None): # Find solution using ILS method # Variables initialization tic = time.time() # Initial time tic_t = tic local_search = ILS.ILS(excel_data) # Object with ILS functions z_history, total_time, z_ls = {}, [], {} # Cost function, time processing and individual LS co...
def ILS_algoritm(config_file = None): # Find solution using ILS method # Variables initialization
tic = time.time() # Initial time tic_t = tic local_search = ILS.ILS(excel_data) # Object with ILS functions z_history, total_time, z_ls = {}, [], {} # Cost function, time processing and individual LS cost function by epochs z_history['acceptance'], z_history['perturbation'], z_history['best'], z_his...
not iqueue.empty(): if message is not None: print("\033[F" + message + ". ") message, count = iqueue.get(), 0 print() # New message if message is not None: count += 1 print("\033[F" + message + "."*count + " ") if count % 3 == 0: coun...
256
256
1,485
24
231
TEAM-IMT/energy-network-optimization
main.py
Python
ILS_algoritm
ILS_algoritm
88
172
88
89
a8469ce3147a5a52495902d82eb1326008e22274
bigcode/the-stack
train
fffe192cd8b6d52615f07815
train
function
def read_excel_data(filename, sheet_name): data = pd.read_excel(filename, sheet_name = sheet_name, header = None) values = data.values # This If is to make the code insensitive to column-wise or row-wise expression # if min(values.shape) == 1 and max(values.shape) == 1: values = values.tolist()...
def read_excel_data(filename, sheet_name):
data = pd.read_excel(filename, sheet_name = sheet_name, header = None) values = data.values # This If is to make the code insensitive to column-wise or row-wise expression # if min(values.shape) == 1 and max(values.shape) == 1: values = values.tolist() return values[0] else: ...
for the purpose of the algorithm. None = Ignore this feature. u"std_comp": 0.01 # Percentage comparison value } } ## Functions ########################################################### def read_excel_sheets_names(filename): data = pd.read_excel(filename, None) return list(data.keys()) def read_e...
69
69
230
9
60
TEAM-IMT/energy-network-optimization
main.py
Python
read_excel_data
read_excel_data
43
63
43
43
1864db2596db313ccb59037c0cddfcd13fe582b7
bigcode/the-stack
train
b3b4a43a30fa038c0afaaecc
train
function
def main(args): global sheets_list, excel_data sheets_list = read_excel_sheets_names(args.database_filename) excel_data = {} for col in sheets_list: excel_data[col] = read_excel_data(args.database_filename, col) if args.which == 'PULP': pulp_algorithm(args.ILS_compared) # PULP algoritm executed...
def main(args):
global sheets_list, excel_data sheets_list = read_excel_sheets_names(args.database_filename) excel_data = {} for col in sheets_list: excel_data[col] = read_excel_data(args.database_filename, col) if args.which == 'PULP': pulp_algorithm(args.ILS_compared) # PULP algoritm executed elif args.w...
_true', help='''Show plots in console (default = %(default)s).''') subparseGraphics.add_argument('-if', '--image_format', type=str, default='pdf', help='''Image format (default = %(default)s).''') return parser.parse_args() def main(args):
64
64
149
4
60
TEAM-IMT/energy-network-optimization
main.py
Python
main
main
212
222
212
212
28e3fe33a8c9e68d90aa7a2a1f8fcbcaa61bb19c
bigcode/the-stack
train
f5d74d22caa43a344ddb344b
train
function
def ILSPlotResults(directory_file_path, statistics = ['all'], legends_off = False, show_plots = False, imformat = 'pdf'): ILSgraph = ILSgraphics.ILSgraphics(excel_data, legends_off = legends_off) # Object with methods to graphics results ILSgraph.statisticsPlots(directory_file_path, statistics=statistics, show_...
def ILSPlotResults(directory_file_path, statistics = ['all'], legends_off = False, show_plots = False, imformat = 'pdf'):
ILSgraph = ILSgraphics.ILSgraphics(excel_data, legends_off = legends_off) # Object with methods to graphics results ILSgraph.statisticsPlots(directory_file_path, statistics=statistics, show_plots=show_plots, imformat=imformat) return ILSgraph.getCurrentER()
p_detect.terminate() ## Graphics ILSPlotResults(outname, show_plots = True) # Statistics graphics with ILSgraphics object def ILSPlotResults(directory_file_path, statistics = ['all'], legends_off = False, show_plots = False, imformat = 'pdf'):
64
64
97
31
32
TEAM-IMT/energy-network-optimization
main.py
Python
ILSPlotResults
ILSPlotResults
174
177
174
174
46d41c2d0dca311a7db674b863e52d38091e4af1
bigcode/the-stack
train
fe2e4fb10b3cae921c2c316e
train
function
def pulp_algorithm(ILS_comp = None): # Find solution using PULP method pulp_obj = PULP.PULP(excel_data) # PULP object creation pulp_obj.objective_function() # Join object function to model pulp_obj.constraints() # Join constraints to model if ILS_comp is not None: ILS_comp = ILSPlotResults(ILS_c...
def pulp_algorithm(ILS_comp = None): # Find solution using PULP method
pulp_obj = PULP.PULP(excel_data) # PULP object creation pulp_obj.objective_function() # Join object function to model pulp_obj.constraints() # Join constraints to model if ILS_comp is not None: ILS_comp = ILSPlotResults(ILS_comp, statistics = ['best_result'], legends_off = True, imformat = None)...
+ "."*count + " ") if count % 3 == 0: count = 0 # sys.stdout.flush() time.sleep(1) # Wait 1 second ## Algorithms ########################################################## def pulp_algorithm(ILS_comp = None): # Find solution using PULP method
64
64
122
18
46
TEAM-IMT/energy-network-optimization
main.py
Python
pulp_algorithm
pulp_algorithm
80
86
80
80
2aa6bdd77a33ecc3c960a41203253bc9eeeaa501
bigcode/the-stack
train
99e052cfef2b99a82f4381cd
train
function
def read_excel_sheets_names(filename): data = pd.read_excel(filename, None) return list(data.keys())
def read_excel_sheets_names(filename):
data = pd.read_excel(filename, None) return list(data.keys())
Epochs u"lenght_data_comp": 375, # Data amount to be compared for the purpose of the algorithm. None = Ignore this feature. u"std_comp": 0.01 # Percentage comparison value } } ## Functions ########################################################### def read_excel_sheets_names(filename):
64
64
24
8
56
TEAM-IMT/energy-network-optimization
main.py
Python
read_excel_sheets_names
read_excel_sheets_names
39
41
39
39
e9b1ac3c0c4dfb0ef27e9271930e764fe43b7520
bigcode/the-stack
train
82f5481773a47a011b1f14d4
train
class
class TestRepo(TestBase): def setUp(self): _rm_lock_files() def tearDown(self): for lfp in glob.glob(_tc_lock_fpaths): if osp.isfile(lfp): raise AssertionError('Previous TC left hanging git-lock file: {}'.format(lfp)) import gc gc.collect() @rai...
class TestRepo(TestBase):
def setUp(self): _rm_lock_files() def tearDown(self): for lfp in glob.glob(_tc_lock_fpaths): if osp.isfile(lfp): raise AssertionError('Previous TC left hanging git-lock file: {}'.format(lfp)) import gc gc.collect() @raises(InvalidGitRepositoryErr...
, IndexFile, Git, Reference, GitDB, Submodule, GitCmdObjectDB, Remote, BadName, GitCommandError ) from git.compat import ( PY3, is_win, string_types, win_encode, ) from git.exc import ( BadObject, ) from git.repo.fun import touch from git.test.lib import ( pat...
256
256
9,307
6
250
nemarugommula/ecommerce
Lib/site-packages/git/test/test_repo.py
Python
TestRepo
TestRepo
85
1,046
85
86
8409602319efc03692111657d70808c956519c16
bigcode/the-stack
train
3f7c8da33cd54f37f4c0cd47
train
function
def iter_flatten(lol): for items in lol: for item in items: yield item
def iter_flatten(lol):
for items in lol: for item in items: yield item
) from git.util import HIDE_WINDOWS_KNOWN_ERRORS, cygpath from git.test.lib import with_rw_directory from git.util import join_path_native, rmtree, rmfile, bin_to_hex import functools as fnt import os.path as osp def iter_flatten(lol):
64
64
23
7
56
nemarugommula/ecommerce
Lib/site-packages/git/test/test_repo.py
Python
iter_flatten
iter_flatten
67
70
67
67
4b41a8a594ef416b3db86ac37f842d2da581e165
bigcode/the-stack
train
ef6df4ca952e335b2518e3b5
train
function
def flatten(lol): return list(iter_flatten(lol))
def flatten(lol):
return list(iter_flatten(lol))
.lib import with_rw_directory from git.util import join_path_native, rmtree, rmfile, bin_to_hex import functools as fnt import os.path as osp def iter_flatten(lol): for items in lol: for item in items: yield item def flatten(lol):
64
64
14
5
58
nemarugommula/ecommerce
Lib/site-packages/git/test/test_repo.py
Python
flatten
flatten
73
74
73
73
24a238d38467918fcaeb63169e91447f933d138e
bigcode/the-stack
train
de20c3b9c65f4ba39eed2e9f
train
function
def _rm_lock_files(): for lfp in glob.glob(_tc_lock_fpaths): rmfile(lfp)
def _rm_lock_files():
for lfp in glob.glob(_tc_lock_fpaths): rmfile(lfp)
osp def iter_flatten(lol): for items in lol: for item in items: yield item def flatten(lol): return list(iter_flatten(lol)) _tc_lock_fpaths = osp.join(osp.dirname(__file__), '../../.git/*.lock') def _rm_lock_files():
64
64
25
6
58
nemarugommula/ecommerce
Lib/site-packages/git/test/test_repo.py
Python
_rm_lock_files
_rm_lock_files
80
82
80
80
6c95ea815acade25a1233fdad748880b9d289f37
bigcode/the-stack
train
6a947d53eea928273341a051
train
class
class Emulator(object): """ _Emulator_ Base class for an Emulator implementation for a given step """ def initialise(self, executorInstance): """ _initialise_ Post ctor initialisation, shortcut to some of the standard variables provided by the executor """ ...
class Emulator(object):
""" _Emulator_ Base class for an Emulator implementation for a given step """ def initialise(self, executorInstance): """ _initialise_ Post ctor initialisation, shortcut to some of the standard variables provided by the executor """ self.executor = executo...
#!/usr/bin/env python2.5 """ _Emulator_ Define the Interface for a Step Emulator """ from builtins import object class Emulator(object):
33
69
232
4
28
khurtado/WMCore
src/python/WMCore/WMSpec/Steps/Emulator.py
Python
Emulator
Emulator
12
62
12
12
2017df45b3e8f2d12ca39009ab9c58225f8e5d02
bigcode/the-stack
train
3287c813a3190fbf615b0c24
train
class
class XentOpTestBase(test.TestCase): def _opDeterminismEnabled(self): deterministic_ops = os.getenv("TF_DETERMINISTIC_OPS", "0") return deterministic_ops in ("1", "true") def _opFwdBwd(self, labels, logits, axis=-1): """ Runs the op-under-test both forwards and backwards.""" logits = ops.convert_t...
class XentOpTestBase(test.TestCase):
def _opDeterminismEnabled(self): deterministic_ops = os.getenv("TF_DETERMINISTIC_OPS", "0") return deterministic_ops in ("1", "true") def _opFwdBwd(self, labels, logits, axis=-1): """ Runs the op-under-test both forwards and backwards.""" logits = ops.convert_to_tensor(logits) # needed for the gra...
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing pe...
256
256
3,447
10
245
TOT0RoKR/tensorflow
tensorflow/python/kernel_tests/xent_op_test_base.py
Python
XentOpTestBase
XentOpTestBase
40
292
40
41
16bf1092f2b20b6fbdb1f8f59c210d2e7634bf91
bigcode/the-stack
train
1c598727f4b0874778688951
train
class
class RPCSearch(xmlrpc.XMLRPC): def __init__(self, dbpath, language): xmlrpc.XMLRPC.__init__(self, allowNone=True) self.indexer = Indexer(dbpath, language) self.db = xapian.Database(dbpath) self.stemmer = xapian.Stem(language) self.query_parser = xapian.QueryParser() ...
class RPCSearch(xmlrpc.XMLRPC):
def __init__(self, dbpath, language): xmlrpc.XMLRPC.__init__(self, allowNone=True) self.indexer = Indexer(dbpath, language) self.db = xapian.Database(dbpath) self.stemmer = xapian.Stem(language) self.query_parser = xapian.QueryParser() self.query_parser.set_stemmer(se...
import xapian from twisted.internet import defer, reactor, threads from twisted.python import log from twisted.web import xmlrpc from bnw.core import bnw_objects from bnw.search.indexer import Indexer class RPCSearch(xmlrpc.XMLRPC):
55
229
764
8
46
l29ah/bnw
bnw/search/search_server.py
Python
RPCSearch
RPCSearch
9
86
9
9
871b9fb59c45b7d72865a86dd403e0de9df3c7d3
bigcode/the-stack
train
3235bb17763490c55ddfe33a
train
function
def initial_fitter_list(psfs, images): '''Make a list of fitters Here, the psfs are assumed to contain the image data. For the fit to image[..., i], the psf[..., i] will be removed from the psf base. Parameters ---------- psfs : np.array data to be used as psf templates (images stacked...
def initial_fitter_list(psfs, images):
'''Make a list of fitters Here, the psfs are assumed to contain the image data. For the fit to image[..., i], the psf[..., i] will be removed from the psf base. Parameters ---------- psfs : np.array data to be used as psf templates (images stacked along the third dimension). T...
fitter = CSP(remove_img_from_psfbase(psfs, i), images) fitter.min_number_of_bases = 30 fitter.region_min_size = 1 fitter.manual_optmask = psfs.mask[:, :, i] return fitter def initial_fitter_list(psfs, images):
64
64
194
10
53
hamogu/Cepheids
snapshotprogram/photometry.py
Python
initial_fitter_list
initial_fitter_list
19
38
19
19
b6fe61d5d6c2c78044c2e269657b7be06b73da2a
bigcode/the-stack
train
e3d6c491336c281f01fa07cc
train
function
def mag2flux(mag, filtername): return 10**((zeropoints[filtername] - mag) / 2.5)
def mag2flux(mag, filtername):
return 10**((zeropoints[filtername] - mag) / 2.5)
Units in image are electrons/s # Images are drz -> drizzeled -> pixels are all same size. def flux2mag(flux, filtername): return -2.5 * np.log10(flux) + zeropoints[filtername] def mag2flux(mag, filtername):
64
64
32
10
54
hamogu/Cepheids
snapshotprogram/photometry.py
Python
mag2flux
mag2flux
52
53
52
52
05fa3d529b9737bbf2d982f438e1242154ab9849
bigcode/the-stack
train
236af51200c236d85b5932cb
train
function
def phot_sherpa(reduced_images621, reduced_images845, indexname, row, psf_621, psf_845, slice_size=11, debug=False, maxdxdy=1, **kwargs): '''Perform 2 band photometry This function performs two band photometry on a single source. Photometry is done by fitting a PSF model simultaneously to ...
def phot_sherpa(reduced_images621, reduced_images845, indexname, row, psf_621, psf_845, slice_size=11, debug=False, maxdxdy=1, **kwargs):
'''Perform 2 band photometry This function performs two band photometry on a single source. Photometry is done by fitting a PSF model simultaneously to data in both bands. Only a single object is fit (so this does not take into account blended sources), but this function is still providing a benefi...
[-1])] return fitterlist # Vegamag zero points are here http://www.stsci.edu/hst/wfc3/phot_zp_lbn zeropoints = {'F621M': 24.4539, 'F845M': 23.2809} # Units in image are electrons/s # Images are drz -> drizzeled -> pixels are all same size. def flux2mag(flux, filtername): return -2.5 * np.log10(flux) + zero...
256
256
1,152
47
209
hamogu/Cepheids
snapshotprogram/photometry.py
Python
phot_sherpa
phot_sherpa
62
152
62
63
551fb707a02d80206afab80588fbe2bbad76c207
bigcode/the-stack
train
d1d83de9bcd56cbdf440b66d
train
function
def flux2mag(flux, filtername): return -2.5 * np.log10(flux) + zeropoints[filtername]
def flux2mag(flux, filtername):
return -2.5 * np.log10(flux) + zeropoints[filtername]
p_lbn zeropoints = {'F621M': 24.4539, 'F845M': 23.2809} # Units in image are electrons/s # Images are drz -> drizzeled -> pixels are all same size. def flux2mag(flux, filtername):
64
64
31
10
54
hamogu/Cepheids
snapshotprogram/photometry.py
Python
flux2mag
flux2mag
48
49
48
48
91681d11dc2b4ab3b1cbec93fce3df02ebe2b19a
bigcode/the-stack
train
902a4d15ec3995ed821ec0c6
train
function
def setup_CSP(psfs, i, images): fitter = CSP(remove_img_from_psfbase(psfs, i), images) fitter.min_number_of_bases = 30 fitter.region_min_size = 1 fitter.manual_optmask = psfs.mask[:, :, i] return fitter
def setup_CSP(psfs, i, images):
fitter = CSP(remove_img_from_psfbase(psfs, i), images) fitter.min_number_of_bases = 30 fitter.region_min_size = 1 fitter.manual_optmask = psfs.mask[:, :, i] return fitter
_slices from astropy.table import Table import sherpa import sherpa.astro.models from psfsubtraction.fitpsf.fitters import CepheidSnapshotpaper as CSP from psfsubtraction.fake import remove_img_from_psfbase def setup_CSP(psfs, i, images):
64
64
65
11
52
hamogu/Cepheids
snapshotprogram/photometry.py
Python
setup_CSP
setup_CSP
11
16
11
11
a623b829de5246f92df29221133a5439ce166798
bigcode/the-stack
train
bc01b1ffe908af2cf833823c
train
function
def betamodel2mag(beta, filtername): '''Calculate photometric mag from parameters of fitted beta model''' flux = beta.ampl.val / ((beta.alpha.val - 1) / (np.pi * beta.r0.val**2)) return flux2mag(flux, filtername)
def betamodel2mag(beta, filtername):
'''Calculate photometric mag from parameters of fitted beta model''' flux = beta.ampl.val / ((beta.alpha.val - 1) / (np.pi * beta.r0.val**2)) return flux2mag(flux, filtername)
): return -2.5 * np.log10(flux) + zeropoints[filtername] def mag2flux(mag, filtername): return 10**((zeropoints[filtername] - mag) / 2.5) def betamodel2mag(beta, filtername):
64
64
62
10
54
hamogu/Cepheids
snapshotprogram/photometry.py
Python
betamodel2mag
betamodel2mag
56
59
56
56
01fbed01efd3361a152b20e0898f2e041e848548
bigcode/the-stack
train
61163b55951d8b22e9a90f00
train
function
def test_dataframe_reset_column_name(): """Test resetting column name at DataFrameSchema init on named column.""" with pytest.warns(UserWarning): DataFrameSchema(columns={"new_name": Column(name="old_name")})
def test_dataframe_reset_column_name():
"""Test resetting column name at DataFrameSchema init on named column.""" with pytest.warns(UserWarning): DataFrameSchema(columns={"new_name": Column(name="old_name")})
the regex column is required, no matches should raise an error schema_required = schema.update_column("column_", required=True) with pytest.raises( errors.SchemaError, match="Column regex name='column_' did not match" ): schema_required(no_match_df) def test_dataframe_reset_column_name():
64
64
46
7
57
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_reset_column_name
test_dataframe_reset_column_name
203
206
203
203
6a3211b2b5bd86e812574db0f331664af198a6f5
bigcode/the-stack
train
c9d538276cf669b89427e176
train
function
def _boolean_update_column_case(bool_kwarg): def _assert_bool_case(old_schema, new_schema): assert not getattr(old_schema.columns["col"], bool_kwarg) assert getattr(new_schema.columns["col"], bool_kwarg) return [ Column(Int, **{bool_kwarg: False}), "col", {bool_kwarg: Tr...
def _boolean_update_column_case(bool_kwarg):
def _assert_bool_case(old_schema, new_schema): assert not getattr(old_schema.columns["col"], bool_kwarg) assert getattr(new_schema.columns["col"], bool_kwarg) return [ Column(Int, **{bool_kwarg: False}), "col", {bool_kwarg: True}, _assert_bool_case, ]
as regex column names:") ) assert schema.get_dtype(data) == { "col1": Int.str_alias, "var1": Float.str_alias, "var2": Float.str_alias, "var3": Float.str_alias, } def _boolean_update_column_case(bool_kwarg):
64
64
84
10
54
ktroutman/pandera
tests/test_schemas.py
Python
_boolean_update_column_case
_boolean_update_column_case
895
905
895
895
ae08548fd2f9d07a33aa09f07347a4dd714ea53c
bigcode/the-stack
train
820b21a4844ec664cabc8ce8
train
function
def test_dataframe_schema_str_repr(): """Test the __str__ and __repr__ methods which are used for cleanly printing/logging of a DataFrameSchema.""" schema = DataFrameSchema( columns={ "col1": Column(Int), "col2": Column(String), "col3": Column(DateTime), }...
def test_dataframe_schema_str_repr():
"""Test the __str__ and __repr__ methods which are used for cleanly printing/logging of a DataFrameSchema.""" schema = DataFrameSchema( columns={ "col1": Column(Int), "col2": Column(String), "col3": Column(DateTime), }, index=Index(Int, name="my_in...
, 123456, 9000, 654]: sample_index = df.sample(100, random_state=seed).index df.loc[sample_index] = -1 assert schema.validate(df, sample=100, random_state=seed).equals(df) def test_dataframe_schema_str_repr():
64
64
146
7
57
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_schema_str_repr
test_dataframe_schema_str_repr
711
727
711
711
bcda994fe04b3ccff79773ae968a83e14e668389
bigcode/the-stack
train
e897aaf391aeab2b0f7ec765
train
function
@pytest.mark.parametrize( "schema_cls, data", [ [DataFrameSchema, pd.DataFrame({"column": [1]})], [SeriesSchema, pd.Series([1, 2, 3])], [partial(Column, name="column"), pd.DataFrame({"column": [1]})], [ partial(Index, name="index"), pd.DataFrame(index=pd.I...
@pytest.mark.parametrize( "schema_cls, data", [ [DataFrameSchema, pd.DataFrame({"column": [1]})], [SeriesSchema, pd.Series([1, 2, 3])], [partial(Column, name="column"), pd.DataFrame({"column": [1]})], [ partial(Index, name="index"), pd.DataFrame(index=pd.I...
"""Lazy validation handles checks returning scalar False values.""" # define a check that always returns a scalare False value check = Check( check_fn=lambda _: False, element_wise=False, error="failing check" ) schema = schema_cls(checks=check) with pytest.raises(errors.SchemaErrors): ...
@pytest.mark.parametrize( "schema_cls, data", [ [DataFrameSchema, pd.DataFrame({"column": [1]})], [SeriesSchema, pd.Series([1, 2, 3])], [partial(Column, name="column"), pd.DataFrame({"column": [1]})], [ partial(Index, name="index"), pd.DataFrame(index=pd.I...
114
64
189
114
0
ktroutman/pandera
tests/test_schemas.py
Python
test_lazy_dataframe_scalar_false_check
test_lazy_dataframe_scalar_false_check
1,131
1,151
1,131
1,143
4c3ed44fd8f7734907c456eb1bacf859c5cac7ee
bigcode/the-stack
train
9a07af4d99f2b8d140cafff8
train
function
def test_required(): """ Tests how a required Column is handled when it's not included, included and then not specified and a second column which is implicitly required isn't available. """ schema = DataFrameSchema( {"col1": Column(Int, required=False), "col2": Column(String)} ) ...
def test_required():
""" Tests how a required Column is handled when it's not included, included and then not specified and a second column which is implicitly required isn't available. """ schema = DataFrameSchema( {"col1": Column(Int, required=False), "col2": Column(String)} ) df_ok_1 = pd.DataFra...
(): """Test that an error is thrown when a dtype isn't specified and coerce is True.""" with pytest.raises(errors.SchemaInitError): DataFrameSchema({"col": Column(coerce=True)}) with pytest.raises(errors.SchemaInitError): DataFrameSchema({"col": Column()}, coerce=True) def test_required...
70
70
234
4
66
ktroutman/pandera
tests/test_schemas.py
Python
test_required
test_required
611
638
611
611
39b85f4b7d12f50e67735c5b05c65a8360dce257
bigcode/the-stack
train
140277903b4a5b13df3953a8
train
class
class SeriesGreaterCheck: # pylint: disable=too-few-public-methods """Class creating callable objects to check if series elements exceed a lower bound. """ def __init__(self, lower_bound): self.lower_bound = lower_bound def __call__(self, series: pd.Series): """Check if the ele...
class SeriesGreaterCheck: # pylint: disable=too-few-public-methods
"""Class creating callable objects to check if series elements exceed a lower bound. """ def __init__(self, lower_bound): self.lower_bound = lower_bound def __call__(self, series: pd.Series): """Check if the elements of s are > lower_bound. :returns Series with bool elemen...
( pd.Series([1, 2, 3], index=multi_index) ) assert isinstance(validated_series_multiindex, pd.Series) assert (validated_series_multiindex.index == multi_index).all() class SeriesGreaterCheck: # pylint: disable=too-few-public-methods
64
64
99
18
46
ktroutman/pandera
tests/test_schemas.py
Python
SeriesGreaterCheck
SeriesGreaterCheck
411
425
411
412
573dc459cba8ed2e7a57e089b48366bf2cc9b70e
bigcode/the-stack
train
71154fe2d3bf2c4a8333315f
train
function
@pytest.mark.parametrize("coerce", [True, False]) def test_series_schema_with_index(coerce): """Test SeriesSchema with Index and MultiIndex components.""" schema_with_index = SeriesSchema( pandas_dtype=Int, index=Index(Int, coerce=coerce), ) validated_series = schema_with_index(pd.Series...
@pytest.mark.parametrize("coerce", [True, False]) def test_series_schema_with_index(coerce):
"""Test SeriesSchema with Index and MultiIndex components.""" schema_with_index = SeriesSchema( pandas_dtype=Int, index=Index(Int, coerce=coerce), ) validated_series = schema_with_index(pd.Series([1, 2, 3], index=[1, 2, 3])) assert isinstance(validated_series, pd.Series) schema_...
50])) assert isinstance(validated_series, pd.Series) # raise error if any of the validators fails with pytest.raises(errors.SchemaError): schema.validate(pd.Series([1, 5, 20, 50])) @pytest.mark.parametrize("coerce", [True, False]) def test_series_schema_with_index(coerce):
69
70
235
21
48
ktroutman/pandera
tests/test_schemas.py
Python
test_series_schema_with_index
test_series_schema_with_index
382
408
382
383
64d2c0407ba8824c3b00999e3b7a9190af23d0c8
bigcode/the-stack
train
0ec7bada682f7d4cfee785d4
train
function
def test_lazy_dataframe_validation_nullable(): """ Test that non-nullable column failure cases are correctly processed during lazy validation. """ schema = DataFrameSchema( columns={ "int_column": Column(Int, nullable=False), "float_column": Column(Float, nullable=Fal...
def test_lazy_dataframe_validation_nullable():
""" Test that non-nullable column failure cases are correctly processed during lazy validation. """ schema = DataFrameSchema( columns={ "int_column": Column(Int, nullable=False), "float_column": Column(Float, nullable=False), "str_column": Column(String, n...
_cases.loc[ err.failure_cases.schema_context == schema_context ] for check, failure_cases in check_failure_cases.items(): assert check in err_df.check.values assert ( err_df.loc[err_df.check == check] .failur...
73
73
246
7
66
ktroutman/pandera
tests/test_schemas.py
Python
test_lazy_dataframe_validation_nullable
test_lazy_dataframe_validation_nullable
1,091
1,128
1,091
1,091
d5393aebdf94cc263d815ccb4a847de9a0cf0fcf
bigcode/the-stack
train
562e8def6baa3603857c6ae0
train
function
def test_series_schema(): """Tests that a SeriesSchema Check behaves as expected for integers and strings. Tests error cases for types, duplicates, name errors, and issues around float and integer handling of nulls""" SeriesSchema("int").validate(pd.Series([1, 2, 3])) int_schema = SeriesSchema( ...
def test_series_schema():
"""Tests that a SeriesSchema Check behaves as expected for integers and strings. Tests error cases for types, duplicates, name errors, and issues around float and integer handling of nulls""" SeriesSchema("int").validate(pd.Series([1, 2, 3])) int_schema = SeriesSchema( Int, Check(lambda x:...
b", "a"], index=pd.MultiIndex.from_arrays([[1], [2]], names=["b", "a"]), ) with pytest.raises( errors.SchemaErrors, match="A total of 2 schema errors" ): schema.validate(df, lazy=True) # test out-of-order duplicates df = pd.DataFrame( data=[[1, 2, 3, 4]], col...
173
173
579
5
168
ktroutman/pandera
tests/test_schemas.py
Python
test_series_schema
test_series_schema
272
341
272
272
937fdcff432f53fb5cafe4c46ef96f64dd570bda
bigcode/the-stack
train
9fc1c09ae514aee95e16b972
train
function
def test_no_dtype_series(): """Test how nullability is handled in SeriesSchemas where no type is specified.""" schema = SeriesSchema(nullable=False) validated_series = schema.validate(pd.Series([0, 1, 2, 3, 4, 1])) assert isinstance(validated_series, pd.Series) schema = SeriesSchema(nullable=Tr...
def test_no_dtype_series():
"""Test how nullability is handled in SeriesSchemas where no type is specified.""" schema = SeriesSchema(nullable=False) validated_series = schema.validate(pd.Series([0, 1, 2, 3, 4, 1])) assert isinstance(validated_series, pd.Series) schema = SeriesSchema(nullable=True) validated_series = s...
.0]})) assert isinstance(validated_df, pd.DataFrame) with pytest.raises(errors.SchemaError): schema = DataFrameSchema({"col": Column(nullable=False)}) schema.validate(pd.DataFrame({"col": [-123.1, None, 1.0]})) def test_no_dtype_series():
64
64
150
6
58
ktroutman/pandera
tests/test_schemas.py
Python
test_no_dtype_series
test_no_dtype_series
585
598
585
585
e39b9dc3bb8828e0d88561941f5163b2247398f4
bigcode/the-stack
train
f91dd33ae83d047e6b0ce1f0
train
function
def test_reset_index_level(schema_multiindex): """Test that resetting index correctly handles specifying level.""" test_schema = schema_multiindex.reset_index(level=["ind0"]) assert test_schema.index.name == "ind1" assert isinstance(test_schema.index, Index) test_schema = schema_multiindex.reset_in...
def test_reset_index_level(schema_multiindex):
"""Test that resetting index correctly handles specifying level.""" test_schema = schema_multiindex.reset_index(level=["ind0"]) assert test_schema.index.name == "ind1" assert isinstance(test_schema.index, Index) test_schema = schema_multiindex.reset_index(level=["ind0", "ind1"]) assert test_sch...
.columns.keys()) == ["col1", "col2"] else: assert len(test_schema.columns) == 3 assert list(test_schema.columns.keys()) == ["col1", "col2", "ind0"] assert test_schema.index is None def test_reset_index_level(schema_multiindex):
64
64
111
9
54
ktroutman/pandera
tests/test_schemas.py
Python
test_reset_index_level
test_reset_index_level
1,375
1,385
1,375
1,375
b8d6448e1656a37630ded11693abcf5dcf7768d6
bigcode/the-stack
train
9a8b41a193b4d7a91db3088b
train
function
@pytest.mark.parametrize("pandas_dtype, expected", TESTABLE_DTYPES) def test_series_schema_dtype_property(pandas_dtype, expected): """Tests every type of allowed dtype.""" assert SeriesSchema(pandas_dtype).dtype == expected
@pytest.mark.parametrize("pandas_dtype, expected", TESTABLE_DTYPES) def test_series_schema_dtype_property(pandas_dtype, expected):
"""Tests every type of allowed dtype.""" assert SeriesSchema(pandas_dtype).dtype == expected
3": ("object" if LEGACY_PANDAS else "string"), "col4": "datetime64[ns]", "col5": "uint16", } @pytest.mark.parametrize("pandas_dtype, expected", TESTABLE_DTYPES) def test_series_schema_dtype_property(pandas_dtype, expected):
64
64
48
27
37
ktroutman/pandera
tests/test_schemas.py
Python
test_series_schema_dtype_property
test_series_schema_dtype_property
750
753
750
751
4fea786631ff16d88c7f62c27074ba09bdf5c4cb
bigcode/the-stack
train
c1b288f25c8f386085674d3d
train
function
def test_sample_dataframe_schema(): """Test the sample argument of schema.validate.""" df = pd.DataFrame({"col1": range(1, 1001)}) # assert all values -1 schema = DataFrameSchema( columns={"col1": Column(Int, Check(lambda s: s == -1))} ) for seed in [11, 123456, 9000, 654]: sam...
def test_sample_dataframe_schema():
"""Test the sample argument of schema.validate.""" df = pd.DataFrame({"col1": range(1, 1001)}) # assert all values -1 schema = DataFrameSchema( columns={"col1": Column(Int, Check(lambda s: s == -1))} ) for seed in [11, 123456, 9000, 654]: sample_index = df.sample(100, random_st...
={"col1": Column(Int, Check(lambda s: s < 0))} ) # Validating with tail of 1000 should pass assert schema.validate(df, tail=1000).equals(df) with pytest.raises(errors.SchemaError): schema.validate(df) def test_sample_dataframe_schema():
64
64
133
6
58
ktroutman/pandera
tests/test_schemas.py
Python
test_sample_dataframe_schema
test_sample_dataframe_schema
696
708
696
696
4c851421e297c12020d846c3be6658bad3b14865
bigcode/the-stack
train
82b905a0bc6e9c8e04573153
train
function
@pytest.fixture def schema_simple(): """Simple schema fixture.""" schema = DataFrameSchema( columns={ "col1": Column(pandas_dtype=Int), "col2": Column(pandas_dtype=Float), }, index=Index(pandas_dtype=String, name="ind0"), ) return schema
@pytest.fixture def schema_simple():
"""Simple schema fixture.""" schema = DataFrameSchema( columns={ "col1": Column(pandas_dtype=Int), "col2": Column(pandas_dtype=Float), }, index=Index(pandas_dtype=String, name="ind0"), ) return schema
assert validated_df["column"].dtype == to_dtype if inplace: # inplace mutates original dataframe assert df["column"].dtype == to_dtype else: # not inplace preserves original dataframe type assert df["column"].dtype == from_dtype @pytest.fixture def schema_simple():
64
64
70
7
56
ktroutman/pandera
tests/test_schemas.py
Python
schema_simple
schema_simple
1,300
1,310
1,300
1,301
76cceb83729f23d174a7f2ad45ffb6eb14c459da
bigcode/the-stack
train
ebd71b14620808372e5c9240
train
function
@pytest.mark.parametrize( "columns,index", [ ( { "a": Column(Int, required=False), "b": Column(Int, required=False), }, None, ), ( None, MultiIndex( indexes=[Index(Int, name="a"), ...
@pytest.mark.parametrize( "columns,index", [ ( { "a": Column(Int, required=False), "b": Column(Int, required=False), }, None, ), ( None, MultiIndex( indexes=[Index(Int, name="a"), ...
"""Test that columns are ordered.""" schema = DataFrameSchema(columns=columns, index=index, ordered=True) df = pd.DataFrame( data=[[1, 2, 3]], columns=["a", "a", "b"], index=pd.MultiIndex.from_arrays( [[1], [2], [3]], names=["a", "a", "b"] ), ) assert isi...
resetting column name at DataFrameSchema init on named column.""" with pytest.warns(UserWarning): DataFrameSchema(columns={"new_name": Column(name="old_name")}) @pytest.mark.parametrize( "columns,index", [ ( { "a": Column(Int, required=False), "b"...
129
129
431
93
36
ktroutman/pandera
tests/test_schemas.py
Python
test_ordered_dataframe
test_ordered_dataframe
209
269
209
227
a626b917bea0aebe025e9615c043aad791512dad
bigcode/the-stack
train
b673a96a1413435bf437c060
train
function
def test_coerce_without_dtype(): """Test that an error is thrown when a dtype isn't specified and coerce is True.""" with pytest.raises(errors.SchemaInitError): DataFrameSchema({"col": Column(coerce=True)}) with pytest.raises(errors.SchemaInitError): DataFrameSchema({"col": Column()}, c...
def test_coerce_without_dtype():
"""Test that an error is thrown when a dtype isn't specified and coerce is True.""" with pytest.raises(errors.SchemaInitError): DataFrameSchema({"col": Column(coerce=True)}) with pytest.raises(errors.SchemaInitError): DataFrameSchema({"col": Column()}, coerce=True)
None, 4, 1])) assert isinstance(validated_series, pd.Series) with pytest.raises(errors.SchemaError): schema = SeriesSchema(nullable=False) schema.validate(pd.Series([0, 1, 2, None, 4, 1])) def test_coerce_without_dtype():
63
64
72
7
56
ktroutman/pandera
tests/test_schemas.py
Python
test_coerce_without_dtype
test_coerce_without_dtype
601
608
601
601
c923e2c0f6a6ec42194d2ea2dc0c521cf49eb0ba
bigcode/the-stack
train
20d4195abc5df169a1c0b11f
train
function
def test_schema_equality_operators(): """Test the usage of == for DataFrameSchema, SeriesSchema and SeriesSchemaBase.""" df_schema = DataFrameSchema( { "col1": Column(Int, Check(lambda s: s >= 0)), "col2": Column(String, Check(lambda s: s >= 2)), }, strict=Tru...
def test_schema_equality_operators():
"""Test the usage of == for DataFrameSchema, SeriesSchema and SeriesSchemaBase.""" df_schema = DataFrameSchema( { "col1": Column(Int, Check(lambda s: s >= 0)), "col2": Column(String, Check(lambda s: s >= 2)), }, strict=True, ) df_schema_columns_in_diff...
3": ("object" if LEGACY_PANDAS else "string"), "col4": "datetime64[ns]", "col5": "uint16", } @pytest.mark.parametrize("pandas_dtype, expected", TESTABLE_DTYPES) def test_series_schema_dtype_property(pandas_dtype, expected): """Tests every type of allowed dtype.""" assert SeriesSchema(panda...
93
93
313
8
84
ktroutman/pandera
tests/test_schemas.py
Python
test_schema_equality_operators
test_schema_equality_operators
756
795
756
756
095b113302435adac99b1ad065bd447904c75615
bigcode/the-stack
train
6fe935bad32c5a1128415dcf
train
function
def test_schema_transformer_deprecated(): """Using the transformer argument should raise a deprecation warning.""" with pytest.warns(DeprecationWarning): DataFrameSchema(transformer=lambda df: df)
def test_schema_transformer_deprecated():
"""Using the transformer argument should raise a deprecation warning.""" with pytest.warns(DeprecationWarning): DataFrameSchema(transformer=lambda df: df)
schema_context ] for check, failure_cases in check_failure_cases.items(): assert check in err_df.check.values assert ( err_df.loc[err_df.check == check] .failure_case.isin(failure_cases) .all() ...
64
64
43
8
56
ktroutman/pandera
tests/test_schemas.py
Python
test_schema_transformer_deprecated
test_schema_transformer_deprecated
1,263
1,266
1,263
1,263
084f72cfb2288fc5c81327b6a4dc5f666dbff3e6
bigcode/the-stack
train
77bb84c3dedbc6bc27c31df2
train
function
@pytest.mark.parametrize( "data", [ pd.DataFrame({"col": [1, 2, 3]}), pd.DataFrame({"col": ["1", "2", "3"]}), pd.DataFrame(), ], ) @pytest.mark.parametrize("required", [True, False]) def test_coerce_not_required(data, required): """Test that not required columns are not coerced."...
@pytest.mark.parametrize( "data", [ pd.DataFrame({"col": [1, 2, 3]}), pd.DataFrame({"col": ["1", "2", "3"]}), pd.DataFrame(), ], ) @pytest.mark.parametrize("required", [True, False]) def test_coerce_not_required(data, required):
"""Test that not required columns are not coerced.""" schema = DataFrameSchema( {"col": Column(int, required=required)}, coerce=True ) if required and data.empty: with pytest.raises(errors.SchemaError): schema(data) return schema(data)
@pytest.mark.parametrize( "data", [ pd.DataFrame({"col": [1, 2, 3]}), pd.DataFrame({"col": ["1", "2", "3"]}), pd.DataFrame(), ], ) @pytest.mark.parametrize("required", [True, False]) def test_coerce_not_required(data, required):
73
64
135
73
0
ktroutman/pandera
tests/test_schemas.py
Python
test_coerce_not_required
test_coerce_not_required
641
659
641
650
762d4bd42907342e69c0eb9b504729157f937033
bigcode/the-stack
train
ea5ad35287a96d3314393d82
train
function
def test_dataframe_schema(): """Tests the Checking of a DataFrame that has a wide variety of types and conditions. Tests include: when the Schema works, when a column is dropped, and when a columns values change its type. """ schema = DataFrameSchema( { "a": Column(Int, Check(lam...
def test_dataframe_schema():
"""Tests the Checking of a DataFrame that has a wide variety of types and conditions. Tests include: when the Schema works, when a column is dropped, and when a columns values change its type. """ schema = DataFrameSchema( { "a": Column(Int, Check(lambda x: x > 0, element_wise=Tr...
"""Testing creation and manipulation of DataFrameSchema objects.""" # pylint: disable=too-many-lines,redefined-outer-name import copy from functools import partial from typing import Dict import numpy as np import pandas as pd import pytest from pandera import ( STRING, Bool, Category, Check, Col...
155
178
595
5
149
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_schema
test_dataframe_schema
36
100
36
36
972257a2b805797345ee008d41aad0a220e21e14
bigcode/the-stack
train
b78308b47ad9199b87f9a47d
train
function
def test_dataframe_pandas_dtype_coerce(): """ Test that pandas dtype specified at the dataframe level overrides column data types. """ schema = DataFrameSchema( columns={f"column_{i}": Column(float) for i in range(5)}, pandas_dtype=int, coerce=True, ) df = pd.DataFra...
def test_dataframe_pandas_dtype_coerce():
""" Test that pandas dtype specified at the dataframe level overrides column data types. """ schema = DataFrameSchema( columns={f"column_{i}": Column(float) for i in range(5)}, pandas_dtype=int, coerce=True, ) df = pd.DataFrame({f"column_{i}": range(10) for i in rang...
pd.DataFrame({"foo_%d" % i: range(10) for i in range(5)}) assert isinstance(schema.validate(df), pd.DataFrame) # Raise a SchemaError if schema is strict and a regex pattern yields # no matches with pytest.raises(errors.SchemaError): schema.validate( pd.DataFrame({"bar_%d" % i: ran...
101
101
337
9
92
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_pandas_dtype_coerce
test_dataframe_pandas_dtype_coerce
132
173
132
132
580c80fedf7397f6454eb69507ffcbc5957e417d
bigcode/the-stack
train
446f18b3d446e4b3d0689beb
train
function
def test_dataframe_schema_strict_regex(): """Test that strict dataframe schema checks for regex matches.""" schema = DataFrameSchema( {"foo_*": Column(Int, regex=True)}, strict=True, ) df = pd.DataFrame({"foo_%d" % i: range(10) for i in range(5)}) assert isinstance(schema.validate(d...
def test_dataframe_schema_strict_regex():
"""Test that strict dataframe schema checks for regex matches.""" schema = DataFrameSchema( {"foo_*": Column(Int, regex=True)}, strict=True, ) df = pd.DataFrame({"foo_%d" % i: range(10) for i in range(5)}) assert isinstance(schema.validate(df), pd.DataFrame) # Raise a SchemaErr...
in the dataframe. """ schema = DataFrameSchema({"a": Column(Int, nullable=True)}, strict=True) df = pd.DataFrame({"b": [1, 2, 3]}) with pytest.raises(errors.SchemaError): schema.validate(df) def test_dataframe_schema_strict_regex():
64
64
139
8
56
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_schema_strict_regex
test_dataframe_schema_strict_regex
114
129
114
114
fe31cd13385e899b420cec77eb9813bcaf5e6c31
bigcode/the-stack
train
a0dffe0ea34faedd321cdbe9
train
function
def test_dataframe_coerce_regex(): """Test dataframe pandas dtype coercion for regex columns""" schema = DataFrameSchema( columns={"column_": Column(float, regex=True, required=False)}, pandas_dtype=int, coerce=True, ) no_match_df = pd.DataFrame({"foo": [1, 2, 3]}) match_val...
def test_dataframe_coerce_regex():
"""Test dataframe pandas dtype coercion for regex columns""" schema = DataFrameSchema( columns={"column_": Column(float, regex=True, required=False)}, pandas_dtype=int, coerce=True, ) no_match_df = pd.DataFrame({"foo": [1, 2, 3]}) match_valid_df = pd.DataFrame( { ...
.String assert (schema(df).dtypes == "object").all() # raises ValueError if _coerce_dtype is called when pandas_dtype is None schema.pandas_dtype = None with pytest.raises(ValueError): schema._coerce_dtype(df) def test_dataframe_coerce_regex():
64
64
191
7
57
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_coerce_regex
test_dataframe_coerce_regex
176
200
176
176
a2055164aa5d335c7f951ebce8a351bf144f35e2
bigcode/the-stack
train
83ae7779e2dd56b9f08e526a
train
function
def test_tail_dataframe_schema(): """Checks that validating the tail of a dataframe validates correctly.""" df = pd.DataFrame( {"col1": list(range(0, 100)) + list(range(-1, -1001, -1))} ) schema = DataFrameSchema( columns={"col1": Column(Int, Check(lambda s: s < 0))} ) # Valida...
def test_tail_dataframe_schema():
"""Checks that validating the tail of a dataframe validates correctly.""" df = pd.DataFrame( {"col1": list(range(0, 100)) + list(range(-1, -1001, -1))} ) schema = DataFrameSchema( columns={"col1": Column(Int, Check(lambda s: s < 0))} ) # Validating with tail of 1000 should pass...
columns={"col1": Column(Int, Check(lambda s: s >= 0))} ) # Validating with head of 100 should pass assert schema.validate(df, head=100).equals(df) with pytest.raises(errors.SchemaError): schema.validate(df) def test_tail_dataframe_schema():
64
64
121
6
58
ktroutman/pandera
tests/test_schemas.py
Python
test_tail_dataframe_schema
test_tail_dataframe_schema
680
693
680
680
6223082c58337a987756275875c296c6742d5089
bigcode/the-stack
train
3d0cbe2cf770403c127a8847
train
function
def test_lazy_dataframe_validation_error(): """Test exceptions on lazy dataframe validation.""" schema = DataFrameSchema( columns={ "int_col": Column(Int, Check.greater_than(5)), "int_col2": Column(Int), "float_col": Column(Float, Check.less_than(0)), "str...
def test_lazy_dataframe_validation_error():
"""Test exceptions on lazy dataframe validation.""" schema = DataFrameSchema( columns={ "int_col": Column(Int, Check.greater_than(5)), "int_col2": Column(Int), "float_col": Column(Float, Check.less_than(0)), "str_col": Column(String, Check.isin(["foo", "ba...
DataFrameSchema( columns={ ("col1", "col1a"): Column(Int), ("col1", "col1b"): Column(Int), ("col2", "col2a"): Column(Int), ("col2", "col2b"): Column(Int), } ), ), ], ) def test_select...
161
162
540
7
154
ktroutman/pandera
tests/test_schemas.py
Python
test_lazy_dataframe_validation_error
test_lazy_dataframe_validation_error
1,021
1,088
1,021
1,021
580b8fd4791d52eb550f0131176e98061a092e53
bigcode/the-stack
train
af18e97ab825e27eae30d850
train
function
@pytest.mark.parametrize("append", [True, False]) def test_set_index_append(append, schema_simple): """ Test that setting index correctly handles appending to existing index. """ test_schema = schema_simple.set_index(keys=["col1"], append=append) if append is True: assert isinstance(test_sch...
@pytest.mark.parametrize("append", [True, False]) def test_set_index_append(append, schema_simple):
""" Test that setting index correctly handles appending to existing index. """ test_schema = schema_simple.set_index(keys=["col1"], append=append) if append is True: assert isinstance(test_schema.index, MultiIndex) assert list(test_schema.index.columns.keys()) == ["ind0", "col1"] ...
else: assert len(test_schema.columns) == 2 assert list(test_schema.columns.keys()) == ["col1", "col2"] assert test_schema.index.name == "col1" @pytest.mark.parametrize("append", [True, False]) def test_set_index_append(append, schema_simple):
64
64
140
22
42
ktroutman/pandera
tests/test_schemas.py
Python
test_set_index_append
test_set_index_append
1,344
1,359
1,344
1,345
5bda0a82b282ebcaadf2b9808d96c087c58877ee
bigcode/the-stack
train
cb4184b44fb5d877cde8c207
train
function
@pytest.mark.parametrize( "data, error", [ [ pd.DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "a", "b"] ), None, ], [ pd.DataFrame( [[1, 2, 3], list("xyz"), [7, 8, 9]], columns=["a", "a", "b"] ...
@pytest.mark.parametrize( "data, error", [ [ pd.DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "a", "b"] ), None, ], [ pd.DataFrame( [[1, 2, 3], list("xyz"), [7, 8, 9]], columns=["a", "a", "b"] ...
"""Test that schema can handle dataframes with duplicated columns.""" if error is None: assert isinstance(schema(data), pd.DataFrame) else: with pytest.raises(error): schema(data)
@pytest.mark.parametrize( "data, error", [ [ pd.DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "a", "b"] ), None, ], [ pd.DataFrame( [[1, 2, 3], list("xyz"), [7, 8, 9]], columns=["a", "a", "b"] ...
200
72
242
200
0
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_duplicated_columns
test_dataframe_duplicated_columns
1,453
1,484
1,453
1,478
b9aad495d428ddfd24d695856a95ddcbf015b12a
bigcode/the-stack
train
7766d3e70339973e19dc3115
train
function
def test_update_columns(schema_simple): """ Catch-all test for update columns functionality """ # Basic function test_schema = schema_simple.update_columns({"col2": {"pandas_dtype": Int}}) assert ( schema_simple.columns["col1"].properties == test_schema.columns["col1"].properties ) ...
def test_update_columns(schema_simple):
""" Catch-all test for update columns functionality """ # Basic function test_schema = schema_simple.update_columns({"col2": {"pandas_dtype": Int}}) assert ( schema_simple.columns["col1"].properties == test_schema.columns["col1"].properties ) assert test_schema.columns["col2"].p...
.""" with pytest.raises(errors.SchemaInitError): schema_simple.set_index(["foo", "bar"]) with pytest.raises(TypeError): schema_simple.set_index() with pytest.raises(errors.SchemaInitError): schema_simple.reset_index(["foo", "bar"]) schema_simple.index = None with pytest.rais...
83
83
278
7
76
ktroutman/pandera
tests/test_schemas.py
Python
test_update_columns
test_update_columns
1,402
1,431
1,402
1,402
ef44f18c291c4a2f6d950bcd2b8c46baa5d13820
bigcode/the-stack
train
06b67bcf64aa59ed27a5e789
train
function
def test_dataframe_schema_dtype_property(): """Test that schema.dtype returns the matching Column types.""" schema = DataFrameSchema( columns={ "col1": Column(Int), "col2": Column(String), "col3": Column(STRING), "col4": Column(DateTime), "col5...
def test_dataframe_schema_dtype_property():
"""Test that schema.dtype returns the matching Column types.""" schema = DataFrameSchema( columns={ "col1": Column(Int), "col2": Column(String), "col3": Column(STRING), "col4": Column(DateTime), "col5": Column("uint16"), } ) ass...
in [schema.__str__(), schema.__repr__()]: assert isinstance(x, str) assert schema.__class__.__name__ in x for name in ["col1", "col2", "col3", "my_index"]: assert name in x def test_dataframe_schema_dtype_property():
64
64
140
7
56
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_schema_dtype_property
test_dataframe_schema_dtype_property
730
747
730
730
b198e064d8cb104d19753b849b7e4e95988fa7b5
bigcode/the-stack
train
b4d5b613aa045a5beff1f8ce
train
function
def test_head_dataframe_schema(): """Test that schema can validate head of dataframe, returns entire dataframe.""" df = pd.DataFrame( {"col1": list(range(0, 100)) + list(range(-1, -1001, -1))} ) schema = DataFrameSchema( columns={"col1": Column(Int, Check(lambda s: s >= 0))} ) ...
def test_head_dataframe_schema():
"""Test that schema can validate head of dataframe, returns entire dataframe.""" df = pd.DataFrame( {"col1": list(range(0, 100)) + list(range(-1, -1001, -1))} ) schema = DataFrameSchema( columns={"col1": Column(Int, Check(lambda s: s >= 0))} ) # Validating with head of 100...
not required columns are not coerced.""" schema = DataFrameSchema( {"col": Column(int, required=required)}, coerce=True ) if required and data.empty: with pytest.raises(errors.SchemaError): schema(data) return schema(data) def test_head_dataframe_schema():
64
64
123
6
58
ktroutman/pandera
tests/test_schemas.py
Python
test_head_dataframe_schema
test_head_dataframe_schema
662
677
662
662
5c7ad1154622d25948607eb5cc287257487a35d2
bigcode/the-stack
train
750c6918434142497246faaf
train
function
def test_series_schema_multiple_validators(): """Tests how multiple Checks on a Series Schema are handled both successfully and when errors are expected.""" schema = SeriesSchema( Int, [ Check(lambda x: 0 <= x <= 50, element_wise=True), Check(lambda s: (s == 21).any()...
def test_series_schema_multiple_validators():
"""Tests how multiple Checks on a Series Schema are handled both successfully and when errors are expected.""" schema = SeriesSchema( Int, [ Check(lambda x: 0 <= x <= 50, element_wise=True), Check(lambda s: (s == 21).any()), ], ) validated_series = sch...
_checks, ]: assert isinstance(schema.checks, list) assert len(series_schema_no_checks.checks) == 0 assert len(series_schema_one_check.checks) == 1 assert len(series_schema_multiple_checks.checks) == 2 def test_series_schema_multiple_validators():
64
64
142
8
55
ktroutman/pandera
tests/test_schemas.py
Python
test_series_schema_multiple_validators
test_series_schema_multiple_validators
364
379
364
364
76f62545b74c5c42f32af915ab2c392718569366
bigcode/the-stack
train
d689cf3ee0bd5ce92781b17b
train
function
def test_coerce_dtype_in_dataframe(): """Tests coercions of datatypes, especially regarding nullable integers.""" df = pd.DataFrame( { "column1": [10.0, 20.0, 30.0], "column2": ["2018-01-01", "2018-02-01", "2018-03-01"], "column3": [1, 2, None], "column4":...
def test_coerce_dtype_in_dataframe():
"""Tests coercions of datatypes, especially regarding nullable integers.""" df = pd.DataFrame( { "column1": [10.0, 20.0, 30.0], "column2": ["2018-01-01", "2018-02-01", "2018-03-01"], "column3": [1, 2, None], "column4": [1.0, 1.0, np.nan], } ) ...
: schema.validate(df) def test_nullable_int_in_dataframe(): """Tests handling of nullability when datatype is integers.""" df = pd.DataFrame({"column1": [5, 1, np.nan]}) null_schema = DataFrameSchema( {"column1": Column(Int, Check(lambda x: x > 0), nullable=True)} ) assert isinstan...
129
129
433
8
121
ktroutman/pandera
tests/test_schemas.py
Python
test_coerce_dtype_in_dataframe
test_coerce_dtype_in_dataframe
478
521
478
478
d15bc86dfc462770ec99e3d8d1e934d9919b5eaa
bigcode/the-stack
train
3ebc7b29af3dc157a538b7de
train
function
def test_invalid_keys(schema_simple): """Test that re/set_index raises expected exceptions.""" with pytest.raises(errors.SchemaInitError): schema_simple.set_index(["foo", "bar"]) with pytest.raises(TypeError): schema_simple.set_index() with pytest.raises(errors.SchemaInitError): ...
def test_invalid_keys(schema_simple):
"""Test that re/set_index raises expected exceptions.""" with pytest.raises(errors.SchemaInitError): schema_simple.set_index(["foo", "bar"]) with pytest.raises(TypeError): schema_simple.set_index() with pytest.raises(errors.SchemaInitError): schema_simple.reset_index(["foo", "bar...
test_schema = schema_multiindex.reset_index(level=["ind0", "ind1"]) assert test_schema.index is None assert set(list(test_schema.columns.keys())) == set( ["col1", "col2", "ind0", "ind1"] ) def test_invalid_keys(schema_simple):
64
64
93
7
57
ktroutman/pandera
tests/test_schemas.py
Python
test_invalid_keys
test_invalid_keys
1,388
1,399
1,388
1,388
5343636458a9e19f536dd9c3172099afe35958a8
bigcode/the-stack
train
72a233af3e4613934f1ea4ef
train
function
def series_greater_than_ten(series: pd.Series): """Return a bool series indicating whether the elements of s are > 10""" return series > 10
def series_greater_than_ten(series: pd.Series):
"""Return a bool series indicating whether the elements of s are > 10""" return series > 10
:returns Series with bool elements """ return series > self.lower_bound def series_greater_than_zero(series: pd.Series): """Return a bool series indicating whether the elements of s are > 0""" return series > 0 def series_greater_than_ten(series: pd.Series):
64
64
36
12
51
ktroutman/pandera
tests/test_schemas.py
Python
series_greater_than_ten
series_greater_than_ten
433
435
433
433
7c6901e4ca33ef1d5a7540e6063e33e17924405d
bigcode/the-stack
train
c8d86f6e5287140af44c0748
train
function
def series_greater_than_zero(series: pd.Series): """Return a bool series indicating whether the elements of s are > 0""" return series > 0
def series_greater_than_zero(series: pd.Series):
"""Return a bool series indicating whether the elements of s are > 0""" return series > 0
_bound): self.lower_bound = lower_bound def __call__(self, series: pd.Series): """Check if the elements of s are > lower_bound. :returns Series with bool elements """ return series > self.lower_bound def series_greater_than_zero(series: pd.Series):
64
64
35
11
52
ktroutman/pandera
tests/test_schemas.py
Python
series_greater_than_zero
series_greater_than_zero
428
430
428
428
60362f13fce99ced7f1349e6241ccd46a63724c8
bigcode/the-stack
train
3b843381d13eb9fdc0a2229e
train
function
def test_add_and_remove_columns(): """Check that adding and removing columns works as expected and doesn't modify the original underlying DataFrameSchema.""" schema1 = DataFrameSchema( { "col1": Column(Int, Check(lambda s: s >= 0)), }, strict=True, ) schema1_exac...
def test_add_and_remove_columns():
"""Check that adding and removing columns works as expected and doesn't modify the original underlying DataFrameSchema.""" schema1 = DataFrameSchema( { "col1": Column(Int, Check(lambda s: s >= 0)), }, strict=True, ) schema1_exact_copy = copy.deepcopy(schema1) ...
String, checks=[Check(lambda s: s.str.startswith("foo"))], nullable=False, allow_duplicates=True, name="my_series", ) not_equal_schema = DataFrameSchema({"col1": Column(String)}, strict=False) assert df_schema == copy.deepcopy(df_schema) assert df_schema != not_equal_sc...
131
131
437
7
123
ktroutman/pandera
tests/test_schemas.py
Python
test_add_and_remove_columns
test_add_and_remove_columns
798
857
798
798
c9f2617bc4254dec42ce1104caca139efa4d17d8
bigcode/the-stack
train
8356507d193f938420426620
train
function
@pytest.mark.parametrize( "select_columns, schema", [ ( ["col1", "col2"], DataFrameSchema( columns={ "col1": Column(Int), "col2": Column(Int), "col3": Column(Int), } ), ...
@pytest.mark.parametrize( "select_columns, schema", [ ( ["col1", "col2"], DataFrameSchema( columns={ "col1": Column(Int), "col2": Column(Int), "col3": Column(Int), } ), ...
"""Check that select_columns method correctly creates new subset schema.""" original_columns = list(schema.columns) schema_selected = schema.select_columns(select_columns) assert all(x in select_columns for x in schema_selected.columns) assert all(x in original_columns for x in schema.columns) ...
@pytest.mark.parametrize( "select_columns, schema", [ ( ["col1", "col2"], DataFrameSchema( columns={ "col1": Column(Int), "col2": Column(Int), "col3": Column(Int), } ), ...
163
72
240
163
0
ktroutman/pandera
tests/test_schemas.py
Python
test_select_columns
test_select_columns
984
1,018
984
1,010
87e6c5940e72409aab03135241c72eee5308590b
bigcode/the-stack
train
6cf248c86434ac406257f029
train
function
def test_no_dtype_dataframe(): """Test how nullability is handled in DataFrameSchemas where no type is specified.""" schema = DataFrameSchema({"col": Column(nullable=False)}) validated_df = schema.validate(pd.DataFrame({"col": [-123.1, -76.3, 1.0]})) assert isinstance(validated_df, pd.DataFrame) ...
def test_no_dtype_dataframe():
"""Test how nullability is handled in DataFrameSchemas where no type is specified.""" schema = DataFrameSchema({"col": Column(nullable=False)}) validated_df = schema.validate(pd.DataFrame({"col": [-123.1, -76.3, 1.0]})) assert isinstance(validated_df, pd.DataFrame) schema = DataFrameSchema({"co...
validated_df = schema.validate(dataframe) assert isinstance(validated_df, pd.DataFrame) for i, element in validated_df["col"].iteritems(): if i < nonnull_idx: assert isinstance(element, str) else: assert pd.isna(element) def test_no_dtype_dataframe():
64
64
170
6
58
ktroutman/pandera
tests/test_schemas.py
Python
test_no_dtype_dataframe
test_no_dtype_dataframe
569
582
569
569
d422eeee3da8912017cff46dbbc56c2997917f19
bigcode/the-stack
train
8f9389ba12cba406c5e59e3e
train
function
@pytest.fixture def schema_multiindex(): """Fixture for schema with MultiIndex.""" schema = DataFrameSchema( columns={ "col1": Column(pandas_dtype=Int), "col2": Column(pandas_dtype=Float), }, index=MultiIndex( [ Index(pandas_dtype=Strin...
@pytest.fixture def schema_multiindex():
"""Fixture for schema with MultiIndex.""" schema = DataFrameSchema( columns={ "col1": Column(pandas_dtype=Int), "col2": Column(pandas_dtype=Float), }, index=MultiIndex( [ Index(pandas_dtype=String, name="ind0"), Index(pa...
schema = DataFrameSchema( columns={ "col1": Column(pandas_dtype=Int), "col2": Column(pandas_dtype=Float), }, index=Index(pandas_dtype=String, name="ind0"), ) return schema @pytest.fixture def schema_multiindex():
64
64
97
8
55
ktroutman/pandera
tests/test_schemas.py
Python
schema_multiindex
schema_multiindex
1,313
1,328
1,313
1,314
4a7f1c8d98e5aaf404e4e456ec08d6fb9c7fc487
bigcode/the-stack
train
4cb4d018ea4503a94d1c0093
train
function
@pytest.mark.parametrize("drop", [True, False]) def test_reset_index_drop(drop, schema_simple): """Test that resetting index correctly handles dropping index levels.""" test_schema = schema_simple.reset_index(drop=drop) if drop: assert len(test_schema.columns) == 2 assert list(test_schema.co...
@pytest.mark.parametrize("drop", [True, False]) def test_reset_index_drop(drop, schema_simple):
"""Test that resetting index correctly handles dropping index levels.""" test_schema = schema_simple.reset_index(drop=drop) if drop: assert len(test_schema.columns) == 2 assert list(test_schema.columns.keys()) == ["col1", "col2"] else: assert len(test_schema.columns) == 3 ...
.columns["col1"].dtype == schema_simple.columns["col1"].dtype ) else: assert isinstance(test_schema.index, Index) assert test_schema.index.name == "col1" @pytest.mark.parametrize("drop", [True, False]) def test_reset_index_drop(drop, schema_simple):
64
64
120
21
43
ktroutman/pandera
tests/test_schemas.py
Python
test_reset_index_drop
test_reset_index_drop
1,362
1,372
1,362
1,363
9fa281778e845bef996d885ffe6c96dd602c052e
bigcode/the-stack
train
ddbead2868004fc4e0df4b97
train
function
def test_nullable_int_in_dataframe(): """Tests handling of nullability when datatype is integers.""" df = pd.DataFrame({"column1": [5, 1, np.nan]}) null_schema = DataFrameSchema( {"column1": Column(Int, Check(lambda x: x > 0), nullable=True)} ) assert isinstance(null_schema.validate(df), pd....
def test_nullable_int_in_dataframe():
"""Tests handling of nullability when datatype is integers.""" df = pd.DataFrame({"column1": [5, 1, np.nan]}) null_schema = DataFrameSchema( {"column1": Column(Int, Check(lambda x: x > 0), nullable=True)} ) assert isinstance(null_schema.validate(df), pd.DataFrame) # test case where colu...
({"a": [1, 2, 3], "b": [1.1, 2.5, 9.9]}) if should_fail: with pytest.raises(errors.SchemaError): schema.validate(df) else: schema.validate(df) def test_nullable_int_in_dataframe():
64
64
115
7
57
ktroutman/pandera
tests/test_schemas.py
Python
test_nullable_int_in_dataframe
test_nullable_int_in_dataframe
465
475
465
465
5482703c17dc4df3dcc4f1c9193a4051bfe85538
bigcode/the-stack
train
eb99801a5d1312dd1a160f6d
train
function
def test_rename_columns(): """Check that DataFrameSchema.rename_columns() method does its job""" rename_dict = {"col1": "col1_new_name", "col2": "col2_new_name"} schema_original = DataFrameSchema( columns={"col1": Column(Int), "col2": Column(Float)} ) schema_renamed = schema_original.renam...
def test_rename_columns():
"""Check that DataFrameSchema.rename_columns() method does its job""" rename_dict = {"col1": "col1_new_name", "col2": "col2_new_name"} schema_original = DataFrameSchema( columns={"col1": Column(Int), "col2": Column(Float)} ) schema_renamed = schema_original.rename_columns(rename_dict) ...
FrameSchema({"col": column}) if assertion_fn is ValueError: with pytest.raises(ValueError): schema.update_column(column_to_update, **update) return new_schema = schema.update_column(column_to_update, **update) assertion_fn(schema, new_schema) def test_rename_columns():
64
64
181
6
58
ktroutman/pandera
tests/test_schemas.py
Python
test_rename_columns
test_rename_columns
958
981
958
958
eeac7adc53249b0434c2a62906daaa85fead84c7
bigcode/the-stack
train
340f3fef4f8c32db8f58c4f4
train
function
@pytest.mark.parametrize( "check_function, should_fail", [ (lambda s: s > 0, False), (lambda s: s > 10, True), (series_greater_than_zero, False), (series_greater_than_ten, True), (SeriesGreaterCheck(lower_bound=0), False), (SeriesGreaterCheck(lower_bound=10), True...
@pytest.mark.parametrize( "check_function, should_fail", [ (lambda s: s > 0, False), (lambda s: s > 10, True), (series_greater_than_zero, False), (series_greater_than_ten, True), (SeriesGreaterCheck(lower_bound=0), False), (SeriesGreaterCheck(lower_bound=10), True...
"""Tests a DataFrameSchema against a variety of Check conditions.""" schema = DataFrameSchema( { "a": Column(Int, Check(check_function, element_wise=False)), "b": Column(Float, Check(check_function, element_wise=False)), } ) df = pd.DataFrame({"a": [1, 2, 3], "b":...
@pytest.mark.parametrize( "check_function, should_fail", [ (lambda s: s > 0, False), (lambda s: s > 10, True), (series_greater_than_zero, False), (series_greater_than_ten, True), (SeriesGreaterCheck(lower_bound=0), False), (SeriesGreaterCheck(lower_bound=10), True...
99
66
221
99
0
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_schema_check_function_types
test_dataframe_schema_check_function_types
438
462
438
449
7722e471f458952c7bf9df8f56f66a87294ccab1
bigcode/the-stack
train
1a32b92063f2eeb42c8dfbac
train
function
@pytest.mark.parametrize("pdtype", list(PandasDtype) + [None]) # type: ignore def test_series_schema_pdtype(pdtype): """Series schema pdtype property should return PandasDtype.""" if pdtype is None: series_schema = SeriesSchema(pdtype) assert series_schema.pdtype is None return for ...
@pytest.mark.parametrize("pdtype", list(PandasDtype) + [None]) # type: ignore def test_series_schema_pdtype(pdtype):
"""Series schema pdtype property should return PandasDtype.""" if pdtype is None: series_schema = SeriesSchema(pdtype) assert series_schema.pdtype is None return for pandas_dtype_input in [ pdtype, pdtype.str_alias, pdtype.value, ]: series_schema =...
name": "foo"}}) with pytest.raises(errors.SchemaInitError): schema_simple.update_columns({"ind0": {"pandas_dtype": Int}}) @pytest.mark.parametrize("pdtype", list(PandasDtype) + [None]) # type: ignore def test_series_schema_pdtype(pdtype):
63
64
153
32
32
ktroutman/pandera
tests/test_schemas.py
Python
test_series_schema_pdtype
test_series_schema_pdtype
1,434
1,450
1,434
1,435
b54802ca52420d6cf54bc2c843ccff88b392cebf
bigcode/the-stack
train
d3f9d0b633a9f9e99f3e4ad3
train
function
def test_series_schema_checks(): """Test SeriesSchema check property.""" series_schema_no_checks = SeriesSchema() series_schema_one_check = SeriesSchema(checks=Check.eq(0)) series_schema_multiple_checks = SeriesSchema( checks=[Check.gt(0), Check.lt(100)] ) for schema in [ series...
def test_series_schema_checks():
"""Test SeriesSchema check property.""" series_schema_no_checks = SeriesSchema() series_schema_one_check = SeriesSchema(checks=Check.eq(0)) series_schema_multiple_checks = SeriesSchema( checks=[Check.gt(0), Check.lt(100)] ) for schema in [ series_schema_no_checks, series...
, 5.5, np.nan]) ) # when series can't be coerced with pytest.raises( errors.SchemaError, match="Error while coercing", ): SeriesSchema(Float, coerce=True).validate(pd.Series(list("abcdefg"))) def test_series_schema_checks():
63
64
140
6
57
ktroutman/pandera
tests/test_schemas.py
Python
test_series_schema_checks
test_series_schema_checks
344
361
344
344
b8399b982e5bd4dfc78dc609b0106245c36e6e10
bigcode/the-stack
train
78429fa1c13b5afc8c1aec24
train
function
@pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "from_dtype,to_dtype", [ [float, int], [int, float], [object, int], [object, float], [int, object], [float, object], ], ) def test_schema_coerce_inplace_validation(inplace, from_dtype...
@pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "from_dtype,to_dtype", [ [float, int], [int, float], [object, int], [object, float], [int, object], [float, object], ], ) def test_schema_coerce_inplace_validation(inplace, from_dtype...
"""Test coercion logic for validation when inplace is True and False""" to_dtype = PandasDtype.from_python_type(to_dtype).str_alias from_dtype = PandasDtype.from_python_type(from_dtype).str_alias df = pd.DataFrame({"column": pd.Series([1, 2, 6], dtype=from_dtype)}) schema = DataFrameSchema({"colum...
@pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "from_dtype,to_dtype", [ [float, int], [int, float], [object, int], [object, float], [int, object], [float, object], ], ) def test_schema_coerce_inplace_validation(inplace, from_dtype...
80
72
241
80
0
ktroutman/pandera
tests/test_schemas.py
Python
test_schema_coerce_inplace_validation
test_schema_coerce_inplace_validation
1,269
1,297
1,269
1,281
c00eeaf7299348d532d359d3d2c93488e27763ad
bigcode/the-stack
train
0e53b9bd3d4331ce0c8bc406
train
function
@pytest.mark.parametrize( "column, column_to_update, update, assertion_fn", [ [ Column(Int), "col", {"pandas_dtype": String}, lambda old, new: [ old.columns["col"].pandas_dtype is Int, new.columns["col"].pandas_dtype is Stri...
@pytest.mark.parametrize( "column, column_to_update, update, assertion_fn", [ [ Column(Int), "col", {"pandas_dtype": String}, lambda old, new: [ old.columns["col"].pandas_dtype is Int, new.columns["col"].pandas_dtype is Stri...
"""Test that DataFrameSchema columns create updated copies.""" schema = DataFrameSchema({"col": column}) if assertion_fn is ValueError: with pytest.raises(ValueError): schema.update_column(column_to_update, **update) return new_schema = schema.update_column(column_to_update,...
@pytest.mark.parametrize( "column, column_to_update, update, assertion_fn", [ [ Column(Int), "col", {"pandas_dtype": String}, lambda old, new: [ old.columns["col"].pandas_dtype is Int, new.columns["col"].pandas_dtype is Stri...
248
96
322
248
0
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_schema_update_column
test_dataframe_schema_update_column
908
955
908
946
4fefdd684394632a666db479370e2f6d4170a7d3
bigcode/the-stack
train
5659b0caf525b77be0509685
train
function
def test_schema_get_dtype(): """Test that schema dtype and get_dtype methods handle regex columns.""" schema = DataFrameSchema( { "col1": Column(Int), "var*": Column(Float, regex=True), } ) data = pd.DataFrame( { "col1": [1, 2, 3], ...
def test_schema_get_dtype():
"""Test that schema dtype and get_dtype methods handle regex columns.""" schema = DataFrameSchema( { "col1": Column(Int), "var*": Column(Float, regex=True), } ) data = pd.DataFrame( { "col1": [1, 2, 3], "var1": [1.0, 1.1, 1.2], ...
_columns can remove two columns: schema4 = schema2.remove_columns(["col2", "col3"]) expected_schema_4 = DataFrameSchema( {"col1": Column(Int, Check(lambda s: s >= 0))}, strict=True ) assert schema4 == expected_schema_4 == schema1 def test_schema_get_dtype():
74
74
249
6
67
ktroutman/pandera
tests/test_schemas.py
Python
test_schema_get_dtype
test_schema_get_dtype
860
892
860
860
4381b24705b8ca0caa7361f9edb50213f870b63b
bigcode/the-stack
train
cbd35f7d226ce34d605c3c95
train
function
@pytest.mark.parametrize( "schema, data, expectation", [ [ SeriesSchema(Int, checks=Check.greater_than(0)), pd.Series(["a", "b", "c"]), { "data": pd.Series(["a", "b", "c"]), "schema_errors": { # schema object context...
@pytest.mark.parametrize( "schema, data, expectation", [ [ SeriesSchema(Int, checks=Check.greater_than(0)), pd.Series(["a", "b", "c"]), { "data": pd.Series(["a", "b", "c"]), "schema_errors": { # schema object context...
"""Test exceptions on lazy series validation.""" try: schema.validate(data, lazy=True) except errors.SchemaErrors as err: # data in the caught exception should be equal to the data # passed into validate assert err.data.equals(expectation["data"]) # make sure all exp...
@pytest.mark.parametrize( "schema, data, expectation", [ [ SeriesSchema(Int, checks=Check.greater_than(0)), pd.Series(["a", "b", "c"]), { "data": pd.Series(["a", "b", "c"]), "schema_errors": { # schema object context...
649
247
824
649
0
ktroutman/pandera
tests/test_schemas.py
Python
test_lazy_series_validation_error
test_lazy_series_validation_error
1,154
1,260
1,154
1,237
6134bc57f7b2656b96c05f84899c22b7951f821b
bigcode/the-stack
train
e574afa3ced789acc4dfe91d
train
function
@pytest.mark.parametrize("drop", [True, False]) def test_set_index_drop(drop, schema_simple): """Test that setting index correctly handles column dropping.""" test_schema = schema_simple.set_index(keys=["col1"], drop=drop) if drop is True: assert len(test_schema.columns) == 1 assert list(tes...
@pytest.mark.parametrize("drop", [True, False]) def test_set_index_drop(drop, schema_simple):
"""Test that setting index correctly handles column dropping.""" test_schema = schema_simple.set_index(keys=["col1"], drop=drop) if drop is True: assert len(test_schema.columns) == 1 assert list(test_schema.columns.keys()) == ["col2"] else: assert len(test_schema.columns) == 2 ...
index=MultiIndex( [ Index(pandas_dtype=String, name="ind0"), Index(pandas_dtype=String, name="ind1"), ] ), ) return schema @pytest.mark.parametrize("drop", [True, False]) def test_set_index_drop(drop, schema_simple):
64
64
121
21
42
ktroutman/pandera
tests/test_schemas.py
Python
test_set_index_drop
test_set_index_drop
1,331
1,341
1,331
1,332
a73d2b1b8132f2d521711560e9a06fbb7ccad6d5
bigcode/the-stack
train
b8d307508de3ecbfe1678914
train
function
def test_dataframe_schema_strict(): """ Checks if strict=True whether a schema error is raised because 'a' is not present in the dataframe. """ schema = DataFrameSchema({"a": Column(Int, nullable=True)}, strict=True) df = pd.DataFrame({"b": [1, 2, 3]}) with pytest.raises(errors.SchemaError):...
def test_dataframe_schema_strict():
""" Checks if strict=True whether a schema error is raised because 'a' is not present in the dataframe. """ schema = DataFrameSchema({"a": Column(Int, nullable=True)}, strict=True) df = pd.DataFrame({"b": [1, 2, 3]}) with pytest.raises(errors.SchemaError): schema.validate(df)
# checks if 'a' is converted to float, while schema says int, will a schema # error be thrown with pytest.raises(errors.SchemaError): schema.validate(df.assign(a=[1.7, 2.3, 3.1])) def test_dataframe_schema_strict():
63
64
85
7
56
ktroutman/pandera
tests/test_schemas.py
Python
test_dataframe_schema_strict
test_dataframe_schema_strict
103
111
103
103
511ced2cc871a713f9e92aa4c98a7ec36212da3b
bigcode/the-stack
train
ef3192d9f45554638345f29e
train
function
@pytest.mark.parametrize( "data, dtype, nonnull_idx", [ # some values are null [["foobar", "foo", "bar", "baz", np.nan, np.nan], str, 4], [["foobar", "foo", "bar", "baz", None, None], str, 4], # some values are null, non-null values are not strings [[1.0, 2.0, 3.0, 4.0, n...
@pytest.mark.parametrize( "data, dtype, nonnull_idx", [ # some values are null [["foobar", "foo", "bar", "baz", np.nan, np.nan], str, 4], [["foobar", "foo", "bar", "baz", None, None], str, 4], # some values are null, non-null values are not strings [[1.0, 2.0, 3.0, 4.0, n...
"""Tests how null values are handled with string dtypes.""" if LEGACY_PANDAS and ( dtype == "Int64" or string_type in {STRING, "string"} ): pytest.skip("Skipping data types that depend on pandas>1.0.0") dataframe = pd.DataFrame({"col": pd.Series(data, dtype=dtype)}) schema = DataFram...
@pytest.mark.parametrize( "data, dtype, nonnull_idx", [ # some values are null [["foobar", "foo", "bar", "baz", np.nan, np.nan], str, 4], [["foobar", "foo", "bar", "baz", None, None], str, 4], # some values are null, non-null values are not strings [[1.0, 2.0, 3.0, 4.0, n...
257
131
439
257
0
ktroutman/pandera
tests/test_schemas.py
Python
test_coerce_dtype_nullable_str
test_coerce_dtype_nullable_str
524
566
524
544
325ec265e6a22b0625eafe644782c44ebf2d3107
bigcode/the-stack
train
873278c70679768b5ebac642
train
class
class DummyAlgo1(AlgoBase): """Dummy Algorithm use a template for writing User-defined algorithms UDA Attributes ---------- __logger : Logger logging managed by framework gate : ArtemisGateSvc access to histograms, metadata, and stores Parameters ----------...
class DummyAlgo1(AlgoBase):
"""Dummy Algorithm use a template for writing User-defined algorithms UDA Attributes ---------- __logger : Logger logging managed by framework gate : ArtemisGateSvc access to histograms, metadata, and stores Parameters ---------- name : str ...
as represented # by the Minister of Statistics Canada, 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
169
169
564
8
160
artemis-analytics/artemis
artemis/algorithms/dummyalgo.py
Python
DummyAlgo1
DummyAlgo1
30
116
30
30
6d8ea461ab835a44d8785399bc7345f4fa3b9d10
bigcode/the-stack
train
aee8942d040c4e478b23dffc
train
class
class SmspNoMatchException(SmspException): message = 'No match found'
class SmspNoMatchException(SmspException):
message = 'No match found'
a typical example of one # error code which could have been returned by PDS in # this scenario. _SMSP_ERR_NHS_NUMBER_NOT_NEW_STYLE = 'DEMOG-0042' class SmspException(Exception): message='Unspecified exception' class SmspNoMatchException(SmspException):
64
64
19
11
53
LCBRU/identity
identity/demographics/smsp.py
Python
SmspNoMatchException
SmspNoMatchException
158
159
158
158
a1acb3462b37b0325c9372b6eaedf8ab81f9e561
bigcode/the-stack
train
aa7a0bc1add0896f91ea89bd
train
class
class SmspNhsNumberInvalidException(SmspException): message = 'NHS number not in use'
class SmspNhsNumberInvalidException(SmspException):
message = 'NHS number not in use'
message = 'No match found' class SmspMultipleMatchesException(SmspException): message = 'Multiple matches found' class SmspNhsNumberSupersededException(SmspException): message = 'NHS number superseded' class SmspNhsNumberInvalidException(SmspException):
64
64
24
13
51
LCBRU/identity
identity/demographics/smsp.py
Python
SmspNhsNumberInvalidException
SmspNhsNumberInvalidException
164
165
164
164
6fa52cb707cd70aca8e100dc58f077555fa712c9
bigcode/the-stack
train