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
1567ae15e703340b181acd2a
train
function
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None): """Runs layer normalization followed by dropout.""" output_tensor = layer_norm(input_tensor, name) output_tensor = dropout(output_tensor, dropout_prob) return output_tensor
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout.""" output_tensor = layer_norm(input_tensor, name) output_tensor = dropout(output_tensor, dropout_prob) return output_tensor
def layer_norm(input_tensor, name=None): """Run layer normalization on the last dimension of the tensor.""" return tf.contrib.layers.layer_norm( inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name) def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
64
64
50
14
50
cmacdonald/DeepCT
deepct/modeling.py
Python
layer_norm_and_dropout
layer_norm_and_dropout
369
373
369
369
49bd787c5858042f8c490802a7f88876c29ab5f4
bigcode/the-stack
train
5809aadbd0953f8ffbc35b44
train
function
def attention_layer(from_tensor, to_tensor, attention_mask=None, num_attention_heads=1, size_per_head=512, query_act=None, key_act=None, value_act=None, attenti...
def attention_layer(from_tensor, to_tensor, attention_mask=None, num_attention_heads=1, size_per_head=512, query_act=None, key_act=None, value_act=None, attenti...
"""Performs multi-headed attention from `from_tensor` to `to_tensor`. This is an implementation of multi-headed attention based on "Attention is all you Need". If `from_tensor` and `to_tensor` are the same, then this is self-attention. Each timestep in `from_tensor` attends to the corresponding sequence in `...
=2) to_seq_length = to_shape[1] to_mask = tf.cast( tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32) # We don't assume that `from_tensor` is a mask (although it could be). We # don't actually care if we attend *from* padding tokens (only *to* padding) # tokens so we create a tensor of a...
256
256
1,982
88
167
cmacdonald/DeepCT
deepct/modeling.py
Python
attention_layer
attention_layer
560
753
560
573
7f452c425bb332e96079e0211ff2e1428c514a57
bigcode/the-stack
train
171b71946d85b9b9dfb543a4
train
function
def reshape_from_matrix(output_tensor, orig_shape_list): """Reshapes a rank 2 tensor back to its original rank >= 2 tensor.""" if len(orig_shape_list) == 2: return output_tensor output_shape = get_shape_list(output_tensor) orig_dims = orig_shape_list[0:-1] width = output_shape[-1] return tf.reshape(o...
def reshape_from_matrix(output_tensor, orig_shape_list):
"""Reshapes a rank 2 tensor back to its original rank >= 2 tensor.""" if len(orig_shape_list) == 2: return output_tensor output_shape = get_shape_list(output_tensor) orig_dims = orig_shape_list[0:-1] width = output_shape[-1] return tf.reshape(output_tensor, orig_dims + [width])
Shape = %s" % (input_tensor.shape)) if ndims == 2: return input_tensor width = input_tensor.shape[-1] output_tensor = tf.reshape(input_tensor, [-1, width]) return output_tensor def reshape_from_matrix(output_tensor, orig_shape_list):
64
64
90
11
52
cmacdonald/DeepCT
deepct/modeling.py
Python
reshape_from_matrix
reshape_from_matrix
948
958
948
948
f1d063773d294b36bdecbce6de5a82d60a662b2b
bigcode/the-stack
train
723e158bf9b5005c0f0ddafa
train
function
def dropout(input_tensor, dropout_prob): """Perform dropout. Args: input_tensor: float Tensor. dropout_prob: Python float. The probability of dropping out a value (NOT of *keeping* a dimension as in `tf.nn.dropout`). Returns: A version of `input_tensor` with dropout applied. """ if dropout...
def dropout(input_tensor, dropout_prob):
"""Perform dropout. Args: input_tensor: float Tensor. dropout_prob: Python float. The probability of dropping out a value (NOT of *keeping* a dimension as in `tf.nn.dropout`). Returns: A version of `input_tensor` with dropout applied. """ if dropout_prob is None or dropout_prob == 0.0: ...
[1]) if name not in name_to_variable: continue assignment_map[name] = name initialized_variable_names[name] = 1 initialized_variable_names[name + ":0"] = 1 return (assignment_map, initialized_variable_names) def dropout(input_tensor, dropout_prob):
64
64
113
8
56
cmacdonald/DeepCT
deepct/modeling.py
Python
dropout
dropout
345
360
345
345
f2327fa7e67d9aacb151cdf5a63cb52904083efa
bigcode/the-stack
train
1f06f26ccc021699188a11cc
train
function
def gelu(input_tensor): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.erf(input_t...
def gelu(input_tensor):
"""Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.erf(input_tensor / tf.sqrt(2.0))) ...
of the embedding layer, after summing the word embeddings with the positional embeddings and the token type embeddings, then performing layer normalization. This is the input to the transformer. """ return self.embedding_output def get_embedding_table(self): return self.embedding_table def g...
64
64
107
6
57
cmacdonald/DeepCT
deepct/modeling.py
Python
gelu
gelu
265
278
265
265
e1099544b12d2baf2cac49dd63bf967ebcf2bfb8
bigcode/the-stack
train
533cee97222a0edc35ea2eab
train
function
def embedding_postprocessor(input_tensor, use_token_type=False, token_type_ids=None, token_type_vocab_size=16, token_type_embedding_name="token_type_embeddings", use_position_embed...
def embedding_postprocessor(input_tensor, use_token_type=False, token_type_ids=None, token_type_vocab_size=16, token_type_embedding_name="token_type_embeddings", use_position_embed...
"""Performs various post-processing on a word embedding tensor. Args: input_tensor: float Tensor of shape [batch_size, seq_length, embedding_size]. use_token_type: bool. Whether to add embeddings for `token_type_ids`. token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length]. ...
to [batch_size, seq_length, 1]. if input_ids.shape.ndims == 2: input_ids = tf.expand_dims(input_ids, axis=[-1]) embedding_table = tf.get_variable( name=word_embedding_name, shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range)) if use_one_hot_embeddings: ...
256
256
912
74
182
cmacdonald/DeepCT
deepct/modeling.py
Python
embedding_postprocessor
embedding_postprocessor
430
523
430
439
b03c28e0a8acd1776b174d874d51855080f509df
bigcode/the-stack
train
7ba90f8366582e57543f6242
train
function
def get_shape_list(tensor, expected_rank=None, name=None): """Returns a list of the shape of tensor, preferring static dimensions. Args: tensor: A tf.Tensor object to find the shape of. expected_rank: (optional) int. The expected rank of `tensor`. If this is specified and the `tensor` has a different...
def get_shape_list(tensor, expected_rank=None, name=None):
"""Returns a list of the shape of tensor, preferring static dimensions. Args: tensor: A tf.Tensor object to find the shape of. expected_rank: (optional) int. The expected rank of `tensor`. If this is specified and the `tensor` has a different rank, and exception will be thrown. name: Option...
: final_outputs = [] for layer_output in all_layer_outputs: final_output = reshape_from_matrix(layer_output, input_shape) final_outputs.append(final_output) return final_outputs else: final_output = reshape_from_matrix(prev_output, input_shape) return final_output def get_shape_list(te...
75
75
251
14
60
cmacdonald/DeepCT
deepct/modeling.py
Python
get_shape_list
get_shape_list
897
931
897
897
eaf27b4a9abdaf0983d3fe1c17f64dfa1f054335
bigcode/the-stack
train
1e88186c5dfe2163f436ab1a
train
function
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False): """Looks up words embeddings for id tensor. Args: ...
def embedding_lookup(input_ids, vocab_size, embedding_size=128, initializer_range=0.02, word_embedding_name="word_embeddings", use_one_hot_embeddings=False):
"""Looks up words embeddings for id tensor. Args: input_ids: int32 Tensor of shape [batch_size, seq_length] containing word ids. vocab_size: int. Size of the embedding vocabulary. embedding_size: int. Width of the word embeddings. initializer_range: float. Embedding initialization range. ...
_dropout(input_tensor, dropout_prob, name=None): """Runs layer normalization followed by dropout.""" output_tensor = layer_norm(input_tensor, name) output_tensor = dropout(output_tensor, dropout_prob) return output_tensor def create_initializer(initializer_range=0.02): """Creates a `truncated_normal_initial...
124
124
416
39
85
cmacdonald/DeepCT
deepct/modeling.py
Python
embedding_lookup
embedding_lookup
381
427
381
386
cef8bb1d044b44206a7c4fb66b4e75e3f39249fb
bigcode/the-stack
train
e1689ef506467d280f994f87
train
function
def reshape_to_matrix(input_tensor): """Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix).""" ndims = input_tensor.shape.ndims if ndims < 2: raise ValueError("Input tensor must have at least rank 2. Shape = %s" % (input_tensor.shape)) if ndims == 2: return input_tensor...
def reshape_to_matrix(input_tensor):
"""Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix).""" ndims = input_tensor.shape.ndims if ndims < 2: raise ValueError("Input tensor must have at least rank 2. Shape = %s" % (input_tensor.shape)) if ndims == 2: return input_tensor width = input_tensor.shape[-1] ...
enumerate(shape): if dim is None: non_static_indexes.append(index) if not non_static_indexes: return shape dyn_shape = tf.shape(tensor) for index in non_static_indexes: shape[index] = dyn_shape[index] return shape def reshape_to_matrix(input_tensor):
64
64
118
7
56
cmacdonald/DeepCT
deepct/modeling.py
Python
reshape_to_matrix
reshape_to_matrix
934
945
934
934
4b942d5b989831537346e247dffdb8e733272b70
bigcode/the-stack
train
9eea3c4e2c51486010c42640
train
function
def get_assignment_map_from_checkpoint(tvars, init_checkpoint): """Compute the union of the current variables and checkpoint variables.""" assignment_map = {} initialized_variable_names = {} name_to_variable = collections.OrderedDict() for var in tvars: name = var.name m = re.match("^(.*):\\d+$", nam...
def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
"""Compute the union of the current variables and checkpoint variables.""" assignment_map = {} initialized_variable_names = {} name_to_variable = collections.OrderedDict() for var in tvars: name = var.name m = re.match("^(.*):\\d+$", name) if m is not None: name = m.group(1) name_to_var...
relu": return tf.nn.relu elif act == "gelu": return gelu elif act == "tanh": return tf.tanh else: raise ValueError("Unsupported activation: %s" % act) def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
64
64
194
12
52
cmacdonald/DeepCT
deepct/modeling.py
Python
get_assignment_map_from_checkpoint
get_assignment_map_from_checkpoint
318
342
318
318
02ba327a3d7dd99a5c60564295aa4e86937b9e19
bigcode/the-stack
train
0476a10d84cf25600e267849
train
function
def get_activation(activation_string): """Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`. Args: activation_string: String name of the activation function. Returns: A Python function corresponding to the activation function. If `activation_string` is None, empty, or "linear", this w...
def get_activation(activation_string):
"""Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`. Args: activation_string: String name of the activation function. Returns: A Python function corresponding to the activation function. If `activation_string` is None, empty, or "linear", this will return None. If `activation_str...
15 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.erf(input_tensor / tf.sqrt(2.0))) return input_tensor * cdf def get_activation(activation_string):
74
74
247
7
66
cmacdonald/DeepCT
deepct/modeling.py
Python
get_activation
get_activation
281
315
281
281
94be316efce2243cf21f51907034027aa2abc603
bigcode/the-stack
train
5f2c7e22cdb8f3d3877d5fb0
train
function
def layer_norm(input_tensor, name=None): """Run layer normalization on the last dimension of the tensor.""" return tf.contrib.layers.layer_norm( inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
def layer_norm(input_tensor, name=None):
"""Run layer normalization on the last dimension of the tensor.""" return tf.contrib.layers.layer_norm( inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
A version of `input_tensor` with dropout applied. """ if dropout_prob is None or dropout_prob == 0.0: return input_tensor output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob) return output def layer_norm(input_tensor, name=None):
64
64
50
9
54
cmacdonald/DeepCT
deepct/modeling.py
Python
layer_norm
layer_norm
363
366
363
363
84e00f84bbaf7c2b3fdac2121bf9e6f239ffc29b
bigcode/the-stack
train
6b1998deb626b467f2c83ca1
train
function
def assert_rank(tensor, expected_rank, name=None): """Raises an exception if the tensor rank is not of the expected rank. Args: tensor: A tf.Tensor to check the rank of. expected_rank: Python integer or list of integers, expected rank. name: Optional name of the tensor for the error message. Raises:...
def assert_rank(tensor, expected_rank, name=None):
"""Raises an exception if the tensor rank is not of the expected rank. Args: tensor: A tf.Tensor to check the rank of. expected_rank: Python integer or list of integers, expected rank. name: Optional name of the tensor for the error message. Raises: ValueError: If the expected shape doesn't matc...
.""" if len(orig_shape_list) == 2: return output_tensor output_shape = get_shape_list(output_tensor) orig_dims = orig_shape_list[0:-1] width = output_shape[-1] return tf.reshape(output_tensor, orig_dims + [width]) def assert_rank(tensor, expected_rank, name=None):
72
72
241
12
60
cmacdonald/DeepCT
deepct/modeling.py
Python
assert_rank
assert_rank
961
988
961
961
7f49d2d2a27c4aeeb8ace9097c78c1eba12c5c8e
bigcode/the-stack
train
8e71493463ec90abf24f4909
train
class
class BertModel(object): """BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into WordPiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) input_mask = tf.constant([[1, 1, 1], [1, 1, 0]]) token_type_ids = tf.constant...
class BertModel(object):
"""BERT model ("Bidirectional Encoder Representations from Transformers"). Example usage: ```python # Already been converted into WordPiece token ids input_ids = tf.constant([[31, 51, 99], [15, 5, 0]]) input_mask = tf.constant([[1, 1, 1], [1, 1, 0]]) token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]]) ...
_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range @classmethod def from_dict(cls, json_obj...
256
256
1,363
5
251
cmacdonald/DeepCT
deepct/modeling.py
Python
BertModel
BertModel
106
262
106
106
f55b40b7a7e5743ca983e7acd85594ceb4d960e1
bigcode/the-stack
train
37cb3d8fb53b873635746809
train
function
def transformer_model(input_tensor, attention_mask=None, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, intermediate_act_fn=gelu, ...
def transformer_model(input_tensor, attention_mask=None, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, intermediate_act_fn=gelu, ...
"""Multi-headed, multi-layer Transformer from "Attention is All You Need". This is almost an exact implementation of the original Transformer encoder. See the original paper: https://arxiv.org/abs/1706.03762 Also see: https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transforme...
1, 3]) # `context_layer` = [B, N, F, H] context_layer = tf.matmul(attention_probs, value_layer) # `context_layer` = [B, F, N, H] context_layer = tf.transpose(context_layer, [0, 2, 1, 3]) if do_return_2d_tensor: # `context_layer` = [B*F, N*H] context_layer = tf.reshape( context_layer, ...
256
256
1,218
80
175
cmacdonald/DeepCT
deepct/modeling.py
Python
transformer_model
transformer_model
756
894
756
766
eb1c737e2a8a50434dce2edb5f2e2ef177ac1c12
bigcode/the-stack
train
9a73e6add73a53acc7466ee0
train
class
class ImportDescriptorsTest(BGLTestFramework): def set_test_params(self): self.num_nodes = 2 self.extra_args = [["-addresstype=legacy"], ["-addresstype=bech32", "-keypool=5"] ] self.setup_clean_chain = True self.wallet_names = [] ...
class ImportDescriptorsTest(BGLTestFramework):
def set_test_params(self): self.num_nodes = 2 self.extra_args = [["-addresstype=legacy"], ["-addresstype=bech32", "-keypool=5"] ] self.setup_clean_chain = True self.wallet_names = [] def skip_test_if_missing_module(self): ...
2019-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the importdescriptors RPC. Test importdescriptors by generating keys on node0, importing the corresponding descriptors on node1 and then...
256
256
7,681
9
247
Soptq/bitgesell
test/functional/wallet_importdescriptors.py
Python
ImportDescriptorsTest
ImportDescriptorsTest
31
468
31
31
599ba3c65c03062144cf291f815ed9d9e07deca9
bigcode/the-stack
train
16c83f882cf95efbc4c95aeb
train
class
class BulkDeleteChartCommand(BaseCommand): def __init__(self, user: User, model_ids: List[int]): self._actor = user self._model_ids = model_ids self._models: Optional[List[Slice]] = None def run(self) -> None: self.validate() try: ChartDAO.bulk_delete(self._m...
class BulkDeleteChartCommand(BaseCommand):
def __init__(self, user: User, model_ids: List[int]): self._actor = user self._model_ids = model_ids self._models: Optional[List[Slice]] = None def run(self) -> None: self.validate() try: ChartDAO.bulk_delete(self._models) except DeleteFailedError as ...
from superset.commands.base import BaseCommand from superset.commands.exceptions import DeleteFailedError from superset.exceptions import SupersetSecurityException from superset.models.slice import Slice from superset.views.base import check_ownership logger = logging.getLogger(__name__) class BulkDeleteChartCommand(...
64
64
192
8
56
thibault-ketterer/incubator-superset
superset/charts/commands/bulk_delete.py
Python
BulkDeleteChartCommand
BulkDeleteChartCommand
37
61
37
37
b81a0db414e49ecf46a39b0ccb34db8dc37861e6
bigcode/the-stack
train
b369db314efdf2ebe5a5b7c4
train
class
class RBECASServiceTest(unittest.TestCase): def testNormalizeDigest(self): digest = cas_service.RBECASService._NormalizeDigest({ 'hash': '026b992daa96202ceec74fe93e0', 'sizeBytes': '91' }) self.assertEqual(digest, { 'hash': '026b992daa96202ceec74fe93e0', 'sizeBytes': '91' ...
class RBECASServiceTest(unittest.TestCase):
def testNormalizeDigest(self): digest = cas_service.RBECASService._NormalizeDigest({ 'hash': '026b992daa96202ceec74fe93e0', 'sizeBytes': '91' }) self.assertEqual(digest, { 'hash': '026b992daa96202ceec74fe93e0', 'sizeBytes': '91' }) def testNormalizeDigest_FromProto(s...
Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest from dashboard.services import ...
79
79
264
10
68
Martijnve23/catapult
dashboard/dashboard/services/cas_service_test.py
Python
RBECASServiceTest
RBECASServiceTest
14
43
14
15
aececd8922cab9eaa197c2d0477e2948cca7b6b0
bigcode/the-stack
train
608faa6619d09852bdb78b04
train
function
def cas_iou(box,cluster): x = np.minimum(cluster[:,0],box[0]) y = np.minimum(cluster[:,1],box[1]) intersection = x * y area1 = box[0] * box[1] area2 = cluster[:,0] * cluster[:,1] iou = intersection / (area1 + area2 -intersection) return iou
def cas_iou(box,cluster):
x = np.minimum(cluster[:,0],box[0]) y = np.minimum(cluster[:,1],box[1]) intersection = x * y area1 = box[0] * box[1] area2 = cluster[:,0] * cluster[:,1] iou = intersection / (area1 + area2 -intersection) return iou
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import xml.etree.ElementTree as ET import glob import random def cas_iou(box,cluster):
44
64
87
8
35
janewen134/fyp
src/robot_learning/object_detect/scripts/kmeans_for_anchors.py
Python
cas_iou
cas_iou
8
18
8
8
568acbdda61e9d168f5866d5197c8e6b893047e6
bigcode/the-stack
train
50203edad504b5aa9416839c
train
function
def load_my_data(): labels = 'work_dir/train.txt' fr = open(labels, 'r') data = [] for line in fr: info = line.strip().split(' ') for i,m in enumerate(info): if i == 0: continue box = m.split(',') xmin = np.float64(box[0])/192...
def load_my_data():
labels = 'work_dir/train.txt' fr = open(labels, 'r') data = [] for line in fr: info = line.strip().split(' ') for i,m in enumerate(info): if i == 0: continue box = m.split(',') xmin = np.float64(box[0])/1920 ymin =...
np.float64(xmin) ymin = np.float64(ymin) xmax = np.float64(xmax) ymax = np.float64(ymax) # output width / height data.append([xmax-xmin,ymax-ymin]) return np.array(data) def load_my_data():
64
64
139
5
59
janewen134/fyp
src/robot_learning/object_detect/scripts/kmeans_for_anchors.py
Python
load_my_data
load_my_data
82
98
82
82
494f70670edae40f2235bf6ea70933b6cc2a9e8a
bigcode/the-stack
train
8046dc8239b46888d8107be3
train
function
def load_data(path): data = [] # search glob for xml_file in glob.glob('{}/*xml'.format(path)): tree = ET.parse(xml_file) height = int(tree.findtext('./size/height')) width = int(tree.findtext('./size/width')) # get width / height of each object for obj in tre...
def load_data(path):
data = [] # search glob for xml_file in glob.glob('{}/*xml'.format(path)): tree = ET.parse(xml_file) height = int(tree.findtext('./size/height')) width = int(tree.findtext('./size/width')) # get width / height of each object for obj in tree.iter('object'): ...
if (last_clu == near).all(): break # get median of each point for j in range(k): cluster[j] = np.median( box[near == j],axis=0) last_clu = near return cluster def load_data(path):
64
64
213
5
58
janewen134/fyp
src/robot_learning/object_detect/scripts/kmeans_for_anchors.py
Python
load_data
load_data
59
79
59
59
047b55deaefbf82bce0a2dffc4554319bef843ed
bigcode/the-stack
train
4e4f4efcf8bd975d4ff0643e
train
function
def kmeans(box,k): # number of boxes row = box.shape[0] # position of each bound distance = np.empty((row,k)) # the final clustering position last_clu = np.zeros((row,)) np.random.seed() # choose 5 from above cluster = box[np.random.choice(row,k,replace = Fal...
def kmeans(box,k): # number of boxes
row = box.shape[0] # position of each bound distance = np.empty((row,k)) # the final clustering position last_clu = np.zeros((row,)) np.random.seed() # choose 5 from above cluster = box[np.random.choice(row,k,replace = False)] # cluster = random.sample(row, k)...
= intersection / (area1 + area2 -intersection) return iou def avg_iou(box,cluster): return np.mean([np.max(cas_iou(box[i],cluster)) for i in range(box.shape[0])]) def kmeans(box,k): # number of boxes
63
64
209
12
51
janewen134/fyp
src/robot_learning/object_detect/scripts/kmeans_for_anchors.py
Python
kmeans
kmeans
24
57
24
25
798f05d00429663e495779f0b193c8f2dab3732f
bigcode/the-stack
train
da1790bceff135c9050795c1
train
function
def avg_iou(box,cluster): return np.mean([np.max(cas_iou(box[i],cluster)) for i in range(box.shape[0])])
def avg_iou(box,cluster):
return np.mean([np.max(cas_iou(box[i],cluster)) for i in range(box.shape[0])])
[1]) intersection = x * y area1 = box[0] * box[1] area2 = cluster[:,0] * cluster[:,1] iou = intersection / (area1 + area2 -intersection) return iou def avg_iou(box,cluster):
64
64
34
8
55
janewen134/fyp
src/robot_learning/object_detect/scripts/kmeans_for_anchors.py
Python
avg_iou
avg_iou
20
21
20
20
61b6904b85ca7f1b97ac7d1f3b504145067e9ab3
bigcode/the-stack
train
9ad66d939d130b689e94834d
train
class
class TestCap(unittest.TestCase): def test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django' result = cap.cap_text(text) self.assertEquals(result,...
class TestCap(unittest.TestCase):
def test_single_word(self): text = 'python' result = cap.cap_text(text) self.assertEquals(result, 'Python') def test_multiple_word(self): text = 'python django' result = cap.cap_text(text) self.assertEquals(result, 'Python Django')
import unittest import cap class TestCap(unittest.TestCase):
13
64
70
7
5
nil1729/python__noob
Chapter__7/unittest/test_cap.py
Python
TestCap
TestCap
4
14
4
5
149cf1eafdcf104b213f19c7127d70afc95c893a
bigcode/the-stack
train
0580ef8888255a67d6d73a33
train
class
class imdb(object): """Image database.""" def __init__(self, name, classes=None): self._name = name self._num_classes = 0 if not classes: self._classes = [] else: self._classes = classes self._image_index = [] self._obj_proposer = 'gt' self._roidb = None self._roidb_hand...
class imdb(object):
"""Image database.""" def __init__(self, name, classes=None): self._name = name self._num_classes = 0 if not classes: self._classes = [] else: self._classes = classes self._image_index = [] self._obj_proposer = 'gt' self._roidb = None self._roidb_handler = self.default_r...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ i...
132
256
2,486
4
128
kesaroid/faster-rcnn.pytorch
lib/datasets/imdb.py
Python
imdb
imdb
22
265
22
22
1d5010327f5e3cfe6a7054578243075fcd9d765d
bigcode/the-stack
train
52de9cf950ffa41dac20b25d
train
class
class SingleInlineFormsetTest(TagTestManager, TestCase): """ Test inline formset for SingleTagField relationships """ manage_models = [test_models.SimpleMixedTest] def setUpExtra(self): self.model = test_models.SimpleMixedTest self.tag_model = self.model.singletag.tag_model ...
class SingleInlineFormsetTest(TagTestManager, TestCase):
""" Test inline formset for SingleTagField relationships """ manage_models = [test_models.SimpleMixedTest] def setUpExtra(self): self.model = test_models.SimpleMixedTest self.tag_model = self.model.singletag.tag_model self.formset = test_forms.SimpleMixedSingleInline d...
[tag2.pk, tag3.pk], } ) self.assertTrue(form.is_valid()) t1 = form.save(commit=False) t1.save() form.save_m2m() # Check in-memory instance self.assertEqual(t1.name, "Test 1") self.assertEqual(t1.singletag, "purple") self.assertEqual(t...
255
256
891
13
242
jdolter/django-tagulous
tests/test_forms_mixed.py
Python
SingleInlineFormsetTest
SingleInlineFormsetTest
172
263
172
172
9e4590e20af27c6f0ed7c1fca009a179155034a7
bigcode/the-stack
train
bf835237531f5ba5b53bc61c
train
class
class FormMixedNonTagRefTest(TagTestManager, TestCase): """ Test form TagFields """ manage_models = [test_models.MixedNonTagRefTest] def setUpExtra(self): self.model = test_models.MixedNonTagRefTest self.tag_model = self.model.singletag.tag_model def test_model_form__initial_s...
class FormMixedNonTagRefTest(TagTestManager, TestCase):
""" Test form TagFields """ manage_models = [test_models.MixedNonTagRefTest] def setUpExtra(self): self.model = test_models.MixedNonTagRefTest self.tag_model = self.model.singletag.tag_model def test_model_form__initial_strings__renders_with_initial(self): form = test_...
""" Tagulous test: Forms with SingleTagField and TagFields Modules tested: tagulous.models.fields.SingleTagField tagulous.models.fields.TagField tagulous.forms.SingleTagField tagulous.forms.TagField """ from django.test import TestCase from tests.lib import TagTestManager from tests.tagulous_tests_app...
118
256
1,238
14
104
jdolter/django-tagulous
tests/test_forms_mixed.py
Python
FormMixedNonTagRefTest
FormMixedNonTagRefTest
22
164
22
22
ce60f81f0813b7a906dd4debc50bf08fb71e785c
bigcode/the-stack
train
65732158d1ccc4c730875d58
train
function
def init(cache_fn=None): """Set up the library and return the main one. Return a main library, and set a librarian for all future SongLibraries. """ s = ", ".join(formats.modules) print_d("Supported formats: %s" % s) SongFileLibrary.librarian = SongLibrary.librarian = SongLibrarian() li...
def init(cache_fn=None):
"""Set up the library and return the main one. Return a main library, and set a librarian for all future SongLibraries. """ s = ", ".join(formats.modules) print_d("Supported formats: %s" % s) SongFileLibrary.librarian = SongLibrary.librarian = SongLibrarian() library = SongFileLibrary("...
libet.formats as formats from quodlibet.const import LIBRARY_SAVE_PERIOD_SECONDS from quodlibet.library.libraries import SongFileLibrary, SongLibrary from quodlibet.library.librarians import SongLibrarian from quodlibet.util.path import mtime def init(cache_fn=None):
64
64
104
6
57
ch1huizong/Scode
stdlib2-src/dist-packages/quodlibet/library/__init__.py
Python
init
init
27
39
27
27
0688b53f7c3db20b5d4bb5e9163d46638ace4bdb
bigcode/the-stack
train
f6823f6fee530c080485927d
train
function
def save(force=False): """Save all registered libraries that have a filename and are marked dirty. If force = True save all of them blocking, else save non-blocking and only if they were last saved more than LIBRARY_SAVE_PERIOD_SECONDS ago. """ print_d("Saving all libraries...") librarian = S...
def save(force=False):
"""Save all registered libraries that have a filename and are marked dirty. If force = True save all of them blocking, else save non-blocking and only if they were last saved more than LIBRARY_SAVE_PERIOD_SECONDS ago. """ print_d("Saving all libraries...") librarian = SongFileLibrary.libraria...
ats.modules) print_d("Supported formats: %s" % s) SongFileLibrary.librarian = SongLibrary.librarian = SongLibrarian() library = SongFileLibrary("main") if cache_fn: library.load(cache_fn) return library def save(force=False):
64
64
153
5
58
ch1huizong/Scode
stdlib2-src/dist-packages/quodlibet/library/__init__.py
Python
save
save
42
64
42
42
471ff9b72c713272eb23d438bad7810e5ecb3ca6
bigcode/the-stack
train
e61b40b67607a4cd522e456e
train
function
def main(): args = parse_args() assert args.out or args.eval or args.format_only or args.show \ or args.show_dir, \ ('Please specify at least one operation (save/eval/format/show the ' 'results / save the results) with the argument "--out", "--eval"' ', "--format-only", "--sho...
def main():
args = parse_args() assert args.out or args.eval or args.format_only or args.show \ or args.show_dir, \ ('Please specify at least one operation (save/eval/format/show the ' 'results / save the results) with the argument "--out", "--eval"' ', "--format-only", "--show" or "--sho...
action=DictAction, help='custom options for evaluation, the key-value pair in xxx=yyy ' 'format will be kwargs for dataset.evaluate() function (deprecate), ' 'change to --eval-options instead.') parser.add_argument( '--eval-options', nargs='+', action=DictActi...
256
256
963
3
252
ThomasWWebb/mmdetection
tools/test.py
Python
main
main
97
202
97
97
e85e8447da5b586ae48180d4ff4b84faf02357c2
bigcode/the-stack
train
5e02e5bdee836511cde96b49
train
function
def parse_args(): parser = argparse.ArgumentParser( description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', help='output result file in pickle format') pars...
def parse_args():
parser = argparse.ArgumentParser( description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', help='output result file in pickle format') parser.add_argument( ...
import argparse import os import warnings import mmcv import torch from mmcv import Config, DictAction from mmcv.cnn import fuse_conv_bn from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import (get_dist_info, init_dist, load_checkpoint, wrap_fp16_model) fro...
119
203
679
4
114
ThomasWWebb/mmdetection
tools/test.py
Python
parse_args
parse_args
19
94
19
19
c23976f33ba140742b4d1279feaa2b4eb1292376
bigcode/the-stack
train
ccb7899e490e506e395866f3
train
function
def setup_logger(log_level): log_level = getattr(logging, log_level) logging.basicConfig( format='[%(asctime)s] %(levelname)8s %(module)6s:%(lineno)03d %(message)s', level=log_level )
def setup_logger(log_level):
log_level = getattr(logging, log_level) logging.basicConfig( format='[%(asctime)s] %(levelname)8s %(module)6s:%(lineno)03d %(message)s', level=log_level )
import asyncio import logging import uvloop from aioapns import APNs, NotificationRequest def setup_logger(log_level):
27
64
60
6
20
vitalliykashuta/aioapns
examples/client.py
Python
setup_logger
setup_logger
9
14
9
9
c961b4605e137d23d7b2570c21d1b64bac785bf4
bigcode/the-stack
train
a48c857e3acc8391beb6666e
train
class
class CmdParser(OptionParser): def error(self, msg): print('Error!提示信息如下:') self.print_help() self.exit(0) def exit(self, status=0, msg=None): exit(status)
class CmdParser(OptionParser):
def error(self, msg): print('Error!提示信息如下:') self.print_help() self.exit(0) def exit(self, status=0, msg=None): exit(status)
import os import copy import torch from optparse import OptionParser class CmdParser(OptionParser):
23
64
51
7
15
DengBoCong/nlp-paper
paper-code/pytorch_src/common/utils.py
Python
CmdParser
CmdParser
7
14
7
7
4ac03c3bf9898ac6340ba4fd30eb3755034f795d
bigcode/the-stack
train
a2a25623e087746ae2bce0a8
train
class
class BeamSearch(object): """ BeamSearch使用说明: 1.首先需要将问句编码成token向量并对齐,然后调用init_input方法进行初始化 2.对模型要求能够进行批量输入 3.BeamSearch使用实例已经集成到Chatter中,如果不进行自定义调用, 可以将聊天器继承Chatter,在满足上述两点的基础之上设计_create_predictions方法,并调用BeamSearch """ def __init__(self, beam_size, max_length, worst_score): """ ...
class BeamSearch(object):
""" BeamSearch使用说明: 1.首先需要将问句编码成token向量并对齐,然后调用init_input方法进行初始化 2.对模型要求能够进行批量输入 3.BeamSearch使用实例已经集成到Chatter中,如果不进行自定义调用, 可以将聊天器继承Chatter,在满足上述两点的基础之上设计_create_predictions方法,并调用BeamSearch """ def __init__(self, beam_size, max_length, worst_score): """ 初始化BeamSearch的序列容器...
import os import copy import torch from optparse import OptionParser class CmdParser(OptionParser): def error(self, msg): print('Error!提示信息如下:') self.print_help() self.exit(0) def exit(self, status=0, msg=None): exit(status) class BeamSearch(object):
72
256
1,055
5
67
DengBoCong/nlp-paper
paper-code/pytorch_src/common/utils.py
Python
BeamSearch
BeamSearch
17
126
17
17
15b00d28723dd40f39364efd6e450a0bde4282e5
bigcode/the-stack
train
3242e43f77f1993f91881b2d
train
class
class TestAuthentication(Base): def invalid_credentials_test(self): api = self.get_api_handle(password = 'invalid_passwd') response = api.get_card_sets() assert isinstance(response, ErrorResponse) eq_(response.http.status_code, 401) def valid_credentials_test(self...
class TestAuthentication(Base):
def invalid_credentials_test(self): api = self.get_api_handle(password = 'invalid_passwd') response = api.get_card_sets() assert isinstance(response, ErrorResponse) eq_(response.http.status_code, 401) def valid_credentials_test(self): def handler(url, *arg...
from urlparse import urlparse from mock import Mock import json from nose.tools import eq_ from memjogger.tests import Base from memjogger.api import ErrorResponse class TestAuthentication(Base):
45
64
170
5
39
zifot/memjogger-python
memjogger/tests/test_basic.py
Python
TestAuthentication
TestAuthentication
10
25
10
10
494b7a29f661c119fc478f7328439a44a01c2e1b
bigcode/the-stack
train
f6c705646b68796d857e3706
train
function
def register_opts(conf): conf.register_opts(api_opts) conf.register_opts(driver_opts) conf.register_opts(exc_log_opts) conf.register_opts(hash_opts) conf.register_opts(image_opts) conf.register_opts(img_cache_opts) conf.register_opts(netconf_opts) conf.register_opts(notification_opts) ...
def register_opts(conf):
conf.register_opts(api_opts) conf.register_opts(driver_opts) conf.register_opts(exc_log_opts) conf.register_opts(hash_opts) conf.register_opts(image_opts) conf.register_opts(img_cache_opts) conf.register_opts(netconf_opts) conf.register_opts(notification_opts) conf.register_opts(path...
to the rootwrap configuration file to use for ' 'running commands as root.')), cfg.StrOpt('tempdir', default=tempfile.gettempdir(), sample_default='/tmp', help=_('Temporary working directory, default is Python temp ' 'dir.')),...
64
64
93
5
59
JohnGarbutt/ironic
ironic/conf/default.py
Python
register_opts
register_opts
293
305
293
293
6b2f920fcc4fd12d591125fb7d54c3519acfad15
bigcode/the-stack
train
90d000812050c1279311ba8d
train
class
class mexc(Exchange): def describe(self): return self.deep_extend(super(mexc, self).describe(), { 'id': 'mexc', 'name': 'MEXC Global', 'countries': ['SC'], # Seychelles 'rateLimit': 50, # default rate limit is 20 times per second 'version': 'v2'...
class mexc(Exchange):
def describe(self): return self.deep_extend(super(mexc, self).describe(), { 'id': 'mexc', 'name': 'MEXC Global', 'countries': ['SC'], # Seychelles 'rateLimit': 50, # default rate limit is 20 times per second 'version': 'v2', 'certifie...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.async_support.base.exchange import Exchange import hashlib import math from ccxt.base.errors import ExchangeError from ccxt.base....
219
256
28,051
6
212
pcriadoperez/ccxt
python/ccxt/async_support/mexc.py
Python
mexc
mexc
26
2,968
26
27
f00ba097c995e9925bef2d4f2708509516713615
bigcode/the-stack
train
cc3141eaf784bcd8db2244a1
train
class
class ABMACDStrategyByVN(CtaTemplate): """""" author = "Xib" mswap_enable = False stoploss_enable = False sm_debug = False cancel_enable = False b_ma_window = 10 a_fast_window = 12 a_slow_window = 26 a_signal_period = 9 b_fast_window = 12 b_slow_window = 26 b_sig...
class ABMACDStrategyByVN(CtaTemplate):
"""""" author = "Xib" mswap_enable = False stoploss_enable = False sm_debug = False cancel_enable = False b_ma_window = 10 a_fast_window = 12 a_slow_window = 26 a_signal_period = 9 b_fast_window = 12 b_slow_window = 26 b_signal_period = 9 a_fast_macd0 = 0.0 ...
from vnpy_ctastrategy import ( CtaTemplate, StopOrder, ) from vnpy.trader.object import ( TickData, BarData, TradeData, OrderData, ) from vnpy.trader.constant import Direction, Offset, Status from abmacd.abmacd_v3 import ABMACDStrategy, ABMACDStrategyConfig from abmacd.strategy_model.riskctl_mo...
150
256
1,632
11
138
Xib1uvXi/tf_strategy
abmacd/abmacd_v3_vnpys.py
Python
ABMACDStrategyByVN
ABMACDStrategyByVN
21
230
21
21
e6be3dddff4b9499c83b6ae0c30ba806844e02f9
bigcode/the-stack
train
441f200abd387c897c6209d9
train
class
class Migration(migrations.Migration): dependencies = [ ('users', '0028_auto_20170207_1540'), ] operations = [ migrations.AlterField( model_name='user', name='phone', field=models.PositiveIntegerField(null=True, verbose_name='phone'), ), ...
class Migration(migrations.Migration):
dependencies = [ ('users', '0028_auto_20170207_1540'), ] operations = [ migrations.AlterField( model_name='user', name='phone', field=models.PositiveIntegerField(null=True, verbose_name='phone'), ), migrations.AlterField( model...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
31
64
165
7
23
salazarpardo/redinnovacion
users/migrations/0029_auto_20170208_1421.py
Python
Migration
Migration
7
24
7
8
9820c74c504d49a068d6f0e4cdda254c2778d122
bigcode/the-stack
train
250ca380de393b2e887f8149
train
function
def test_python_library(): with util.chdir(Path(__file__).parent / "fixtures/python_library"): template_dir = Path(__file__).parent.parent / "synthtool/gcp/templates" common = gcp.CommonTemplates(template_path=template_dir) templated_files = common.py_library() assert os.path.exists...
def test_python_library():
with util.chdir(Path(__file__).parent / "fixtures/python_library"): template_dir = Path(__file__).parent.parent / "synthtool/gcp/templates" common = gcp.CommonTemplates(template_path=template_dir) templated_files = common.py_library() assert os.path.exists(templated_files / ".kokoro...
oxfile.py.j2", **template_kwargs, ).read_text() # Validate Python syntax. result_code = compile(result, "noxfile.py", "exec") assert result_code is not None for expected in expected_text: assert expected in result def test_python_library():
64
64
99
5
58
GoogleCloudPlatform/synthtool
tests/test_python_library.py
Python
test_python_library
test_python_library
151
158
151
151
d899a5548a89c167def40dfb5ab43e53c44bd88f
bigcode/the-stack
train
9bcd7f56b7d6dd0d1c2c869b
train
function
@pytest.mark.parametrize( ["template_kwargs", "expected_text"], [ ({}, ["import nox", 'session.install("-e", ".", *constraints)']), ( {"unit_test_local_dependencies": ["../testutils", "../unitutils"]}, [ """\ UNIT_TEST_LOCAL_DEPENDENCIES = [ "../testut...
@pytest.mark.parametrize( ["template_kwargs", "expected_text"], [ ({}, ["import nox", 'session.install("-e", ".", *constraints)']), ( {"unit_test_local_dependencies": ["../testutils", "../unitutils"]}, [ """\ UNIT_TEST_LOCAL_DEPENDENCIES = [ "../testut...
t = templates.Templates(PYTHON_LIBRARY) result = t.render( "noxfile.py.j2", **template_kwargs, ).read_text() # Validate Python syntax. result_code = compile(result, "noxfile.py", "exec") assert result_code is not None for expected in expected_text: assert expected in ...
@pytest.mark.parametrize( ["template_kwargs", "expected_text"], [ ({}, ["import nox", 'session.install("-e", ".", *constraints)']), ( {"unit_test_local_dependencies": ["../testutils", "../unitutils"]}, [ """\ UNIT_TEST_LOCAL_DEPENDENCIES = [ "../testut...
567
193
646
567
0
GoogleCloudPlatform/synthtool
tests/test_python_library.py
Python
test_library_noxfile
test_library_noxfile
30
148
30
138
78f146aefaa5cafb021269782c11f7a7e1212c5f
bigcode/the-stack
train
d76acff096d20e7ca44eed3f
train
function
def test_split_system_tests(): with util.chdir(Path(__file__).parent / "fixtures/python_library"): template_dir = Path(__file__).parent.parent / "synthtool/gcp/templates" common = gcp.CommonTemplates(template_path=template_dir) templated_files = common.py_library(split_system_tests=True) ...
def test_split_system_tests():
with util.chdir(Path(__file__).parent / "fixtures/python_library"): template_dir = Path(__file__).parent.parent / "synthtool/gcp/templates" common = gcp.CommonTemplates(template_path=template_dir) templated_files = common.py_library(split_system_tests=True) with open(templated_files...
= gcp.CommonTemplates(template_path=template_dir) templated_files = common.py_library() assert os.path.exists(templated_files / ".kokoro/docs/docs-presubmit.cfg") assert os.path.exists(templated_files / ".kokoro/docker/docs/Dockerfile") def test_split_system_tests():
64
64
184
6
58
GoogleCloudPlatform/synthtool
tests/test_python_library.py
Python
test_split_system_tests
test_split_system_tests
161
175
161
161
45a7195ba80ed2301a34049802277afb1f396ae1
bigcode/the-stack
train
4c1a11c4db0a6d8af8c72e4d
train
function
@pytest.mark.parametrize( "fixtures_dir", [ Path(__file__).parent / "fixtures/python_library", # just setup.py Path(__file__).parent / "fixtures/python_library_w_version_py", # has google/cloud/texttospeech/version.py ], ) def test_configure_previous_major_version_branches(fixtures...
@pytest.mark.parametrize( "fixtures_dir", [ Path(__file__).parent / "fixtures/python_library", # just setup.py Path(__file__).parent / "fixtures/python_library_w_version_py", # has google/cloud/texttospeech/version.py ], ) def test_configure_previous_major_version_branches(fixtures...
with util.copied_fixtures_dir(fixtures_dir): t = templates.Templates(PYTHON_LIBRARY) result = t.render(".github/release-please.yml") os.makedirs(".github") shutil.copy(result, Path(".github/release-please.yml")) python.configure_previous_major_version_branches() rele...
8" in contents @pytest.mark.parametrize( "fixtures_dir", [ Path(__file__).parent / "fixtures/python_library", # just setup.py Path(__file__).parent / "fixtures/python_library_w_version_py", # has google/cloud/texttospeech/version.py ], ) def test_configure_previous_major_version_br...
78
78
260
73
4
GoogleCloudPlatform/synthtool
tests/test_python_library.py
Python
test_configure_previous_major_version_branches
test_configure_previous_major_version_branches
178
210
178
186
194151b883f7e981fc14820401f53eb7f5f6d755
bigcode/the-stack
train
7dd6cec87f3c0f7ba457c972
train
function
def get_ocr_result(videoCap, i): result = '' ocr_list = [] temp_result = [] videoCap.set(cv.CAP_PROP_POS_FRAMES, i) # i += 100; boolFrame, matFrame = videoCap.read() if boolFrame: temp_jpgframe = np.asarray(matFrame) # 截取上面0-90区域进行OCR检测 jpgframe = temp_jpgframe[0:12...
def get_ocr_result(videoCap, i):
result = '' ocr_list = [] temp_result = [] videoCap.set(cv.CAP_PROP_POS_FRAMES, i) # i += 100; boolFrame, matFrame = videoCap.read() if boolFrame: temp_jpgframe = np.asarray(matFrame) # 截取上面0-90区域进行OCR检测 jpgframe = temp_jpgframe[0:125] # 得到OCR识别结果 t...
i += 500 # print("i: {} score:{}".format(i, key)) init_candidate.clear() break return i, init_candidate, score_dic, score_record, modify_candidate, more, location, gt_y2 def get_ocr_result(videoCap, i):
64
64
158
10
53
JasonZK/Soccer_OCR
clean_ggl.py
Python
get_ocr_result
get_ocr_result
91
112
91
91
3777608711aa937e00e66e3bf57c342d6aa3468d
bigcode/the-stack
train
e5f09840a7c5ed436923080f
train
function
def evaluate_candidates(i, init_candidate, score_dic, score_record, location, temp_result, tempResult_index, modify_candidate, more, gt_y2): # 评估候选比分 for key in init_candidate.keys(): # 如果某个比分出现次数大于3 if init_candidate[key] >= 3: # 记录该比分...
def evaluate_candidates(i, init_candidate, score_dic, score_record, location, temp_result, tempResult_index, modify_candidate, more, gt_y2): # 评估候选比分
for key in init_candidate.keys(): # 如果某个比分出现次数大于3 if init_candidate[key] >= 3: # 记录该比分与对应帧数 score_dic[i] = key # 如果score_record里面暂时没有记录,就记录 if not score_record: score_record.append((i, key)) # 如果没有初始位置,就记录 ...
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' import re from paddleocr import PaddleOCR, draw_ocr import cv2 as cv import numpy as np import time from collections import defaultdict import json BASE_DIR = os.path.dirname(os.path.abspath(__file__)) keyword1 = "goal" def makedir(new_dir): if not os.path.exists(n...
202
202
674
43
158
JasonZK/Soccer_OCR
clean_ggl.py
Python
evaluate_candidates
evaluate_candidates
30
88
30
33
5e2a3a1bf33f2a4f2830c5dbf110c6ecff8b3737
bigcode/the-stack
train
df7750feb7c7ff3f127a0bcb
train
function
def get_frames(video_dir): get = 0 miss = 0 total_num = 0 more = 0 # with open('video_6_score_change.json', 'r') as fd: # Video_Score_dic = json.load(fd) SCORES = {} for root, _, files in os.walk(video_dir): for video_index in files: time1 = time.time() ...
def get_frames(video_dir):
get = 0 miss = 0 total_num = 0 more = 0 # with open('video_6_score_change.json', 'r') as fd: # Video_Score_dic = json.load(fd) SCORES = {} for root, _, files in os.walk(video_dir): for video_index in files: time1 = time.time() video_index1 = video_ind...
0][0] # x2 = temp_result[0][ii][1][0] # y1 = temp_result[0][ii][0][1] y2 = temp_result[0][ii][2][1] # 偏移量小于8则说明位置正确 # if (abs(gt_x1 - x1) + abs(gt_x2 - x2) + abs(gt_y1 - y1) + abs(gt_y2 - y2) < 8): if abs(gt_y2 - y2) < 4: ...
256
256
978
6
249
JasonZK/Soccer_OCR
clean_ggl.py
Python
get_frames
get_frames
147
244
147
147
e36c3fd35ab29c9d7ee5aec2280d69f3f177d56b
bigcode/the-stack
train
911a20182e2f33defcee5de8
train
function
def find_goal_location(temp_result, location, init_candidate, gt_y2): goal_flag = False tempResult_index = 0 for ii, [strr, ration] in enumerate(temp_result[1]): game_time = re.findall("\d:\d", strr) if game_time: num_num = game_time[0] # 如果已经记录过位置,则与记录位置进行比较 ...
def find_goal_location(temp_result, location, init_candidate, gt_y2):
goal_flag = False tempResult_index = 0 for ii, [strr, ration] in enumerate(temp_result[1]): game_time = re.findall("\d:\d", strr) if game_time: num_num = game_time[0] # 如果已经记录过位置,则与记录位置进行比较 if location: # x1 = temp_result[0][ii][0][0] ...
np.asarray(matFrame) # 截取上面0-90区域进行OCR检测 jpgframe = temp_jpgframe[0:125] # 得到OCR识别结果 temp_result = ocr(jpgframe) for mystr, ration in temp_result[1]: result += mystr ocr_list.append(mystr) result += ' ' return result, temp_result def fin...
106
106
355
16
89
JasonZK/Soccer_OCR
clean_ggl.py
Python
find_goal_location
find_goal_location
115
144
115
115
11ead2531e813458d3fdb1f8103084a02423db03
bigcode/the-stack
train
7309df35210d05479d15da84
train
function
def makedir(new_dir): if not os.path.exists(new_dir): os.makedirs(new_dir)
def makedir(new_dir):
if not os.path.exists(new_dir): os.makedirs(new_dir)
'True' import re from paddleocr import PaddleOCR, draw_ocr import cv2 as cv import numpy as np import time from collections import defaultdict import json BASE_DIR = os.path.dirname(os.path.abspath(__file__)) keyword1 = "goal" def makedir(new_dir):
64
64
21
6
58
JasonZK/Soccer_OCR
clean_ggl.py
Python
makedir
makedir
18
20
18
18
b8c0c36001fc06ad588309e16876065e1649e964
bigcode/the-stack
train
ecf08b60f9b85d217804eb17
train
class
class AuthError(RequestException): pass
class AuthError(RequestException):
pass
import requests from requests import Response, RequestException import time from .const import ( DOMAIN, DATE_FORMAT, ) from .KiaUvoApiImpl import KiaUvoApiImpl from .Token import Token _LOGGER = logging.getLogger(__name__) class AuthError(RequestException):
64
64
9
6
58
PierreLevres/kia_uvo
custom_components/kia_uvo/KiaUvoAPIUSA.py
Python
AuthError
AuthError
23
24
23
23
ddc78f05bb23e8ac83587a2a75f5e1dc9562c78d
bigcode/the-stack
train
45591226d1c74689624beb10
train
function
def request_with_active_session(func): def request_with_active_session_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except AuthError: _LOGGER.debug(f"got invalid session, attempting to repair and resend") self = args[0] token = kwargs["t...
def request_with_active_session(func):
def request_with_active_session_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except AuthError: _LOGGER.debug(f"got invalid session, attempting to repair and resend") self = args[0] token = kwargs["token"] new_token = self.log...
Exception import time from .const import ( DOMAIN, DATE_FORMAT, ) from .KiaUvoApiImpl import KiaUvoApiImpl from .Token import Token _LOGGER = logging.getLogger(__name__) class AuthError(RequestException): pass def request_with_active_session(func):
64
64
196
7
56
PierreLevres/kia_uvo
custom_components/kia_uvo/KiaUvoAPIUSA.py
Python
request_with_active_session
request_with_active_session
27
48
27
27
6581e8c5308a5c1cfe334d7d4f54c9c094d48ced
bigcode/the-stack
train
9ca286fa4e66fdb07d190085
train
function
def request_with_logging(func): def request_with_logging_wrapper(*args, **kwargs): url = kwargs["url"] json_body = kwargs.get("json_body") if json_body is not None: _LOGGER.debug(f"sending {url} request with {json_body}") else: _LOGGER.debug(f"sending {url} re...
def request_with_logging(func):
def request_with_logging_wrapper(*args, **kwargs): url = kwargs["url"] json_body = kwargs.get("json_body") if json_body is not None: _LOGGER.debug(f"sending {url} request with {json_body}") else: _LOGGER.debug(f"sending {url} request") response = func(...
json_body", None) if json_body is not None and json_body.get("vinKey", None): json_body["vinKey"] = [token.vehicle_regid] response = func(*args, **kwargs) return response return request_with_active_session_wrapper def request_with_logging(func):
64
64
211
6
57
PierreLevres/kia_uvo
custom_components/kia_uvo/KiaUvoAPIUSA.py
Python
request_with_logging
request_with_logging
51
74
51
51
453c8d14c28b2a0abfc5798f2b663894bc13a9a7
bigcode/the-stack
train
eed2df627cd2b705af252338
train
class
class KiaUvoAPIUSA(KiaUvoApiImpl): def __init__( self, username: str, password: str, region: int, brand: int, use_email_with_geocode_api: bool = False, pin: str = "", ): super().__init__( username, password, region, brand, use_email_wit...
class KiaUvoAPIUSA(KiaUvoApiImpl):
def __init__( self, username: str, password: str, region: int, brand: int, use_email_with_geocode_api: bool = False, pin: str = "", ): super().__init__( username, password, region, brand, use_email_with_geocode_api, pin ) ...
vinKey"] = [token.vehicle_regid] response = func(*args, **kwargs) return response return request_with_active_session_wrapper def request_with_logging(func): def request_with_logging_wrapper(*args, **kwargs): url = kwargs["url"] json_body = kwargs.get("json_body") ...
256
256
2,606
13
242
PierreLevres/kia_uvo
custom_components/kia_uvo/KiaUvoAPIUSA.py
Python
KiaUvoAPIUSA
KiaUvoAPIUSA
77
408
77
77
53e7ac51c746d1c8534ea4c125c0c12f35ac1c1e
bigcode/the-stack
train
380d5d33208976437431a295
train
class
class GetSort(): """ Methods for getting comments from a Reddit submission. """ def __init__(self, args, submission, url): """ Initialize variables used in later methods: self._submission: PRAW submission object Calls replace_more() method on submission object to g...
class GetSort():
""" Methods for getting comments from a Reddit submission. """ def __init__(self, args, submission, url): """ Initialize variables used in later methods: self._submission: PRAW submission object Calls replace_more() method on submission object to get nested comment...
list List containing `CommentNode`s """ forest = Forest(submission, url) seed_status = Status( "Forest has fully matured.", Fore.CYAN + Style.BRIGHT + "Seeding Forest.", "cyan" ) seed_status.start() for comment i...
114
114
380
4
109
phroiland/URS
urs/praw_scrapers/Comments.py
Python
GetSort
GetSort
226
296
226
226
9f576f8dcfbfec3169a14f4084b4bba42bd584d3
bigcode/the-stack
train
efad9f5df27935e45a045876
train
class
class Forest(): """ Methods to nurture the comment forest. """ def __init__(self, submission, url): """ Initialize the collective root. self.root: list containing CommentNodes Parameters ---------- submission: PRAW submission object url: str...
class Forest():
""" Methods to nurture the comment forest. """ def __init__(self, submission, url): """ Initialize the collective root. self.root: list containing CommentNodes Parameters ---------- submission: PRAW submission object url: str Str...
tree. """ def __init__(self, metadata): """ Set the node's comment data. self.__setattr__(key, value): set node attributes based on the `metadata` dictionary self.replies: list containing CommentNodes Parameters ---------- metad...
109
109
364
3
106
phroiland/URS
urs/praw_scrapers/Comments.py
Python
Forest
Forest
70
148
70
70
e3956783fab0b7da43c3a1cb82d3355ff5179222
bigcode/the-stack
train
16654a005887c29892c953b1
train
class
class RunComments(): """ Run the comments scraper. """ @staticmethod @LogExport.log_export @LogPRAWScraper.scraper_timer("comments") def run(args, parser, reddit): """ Run comments scraper. Calls a previously defined public method: Write.write() ...
class RunComments():
""" Run the comments scraper. """ @staticmethod @LogExport.log_export @LogPRAWScraper.scraper_timer("comments") def run(args, parser, reddit): """ Run comments scraper. Calls a previously defined public method: Write.write() Calls public method...
submission, url).get_sort(args, limit) f_name = NameFile().c_fname(args, limit, submission.title) Write._determine_export(args, data, f_name) print() Halo(color = "green", text = Style.BRIGHT + Fore.GREEN + "JSON file for '%s' comments created." % submissio...
83
83
277
4
79
phroiland/URS
urs/praw_scrapers/Comments.py
Python
RunComments
RunComments
451
500
451
451
6dbc351b1ae3473ee8afba5934f8f0809089e243
bigcode/the-stack
train
c5d37536ca3eaf568a67bf46
train
class
class SortComments(): """ Methods for sorting comments depending on which style of comments was specified (raw or structured). """ @staticmethod def sort_raw(all_comments, submission): """ Sort all comments in raw format. Calls a public method from an external module:...
class SortComments():
""" Methods for sorting comments depending on which style of comments was specified (raw or structured). """ @staticmethod def sort_raw(all_comments, submission): """ Sort all comments in raw format. Calls a public method from an external module: Objectif...
""" Insert a new CommentNode into a comment tree within the Forest. Calls previously defined private method: self._dfs_insert() Parameters ---------- new_comment: CommentNode Returns ------- None """ parent_id = new...
103
103
344
4
99
phroiland/URS
urs/praw_scrapers/Comments.py
Python
SortComments
SortComments
150
224
150
150
4129d25ecc5a1db78e4ffd76355c2d5fc48cbf52
bigcode/the-stack
train
76f60a2a52b0c7f92f8933e1
train
class
class Write(): """ Methods for writing scraped comments to CSV or JSON. """ @staticmethod def _make_json_skeleton(args, limit, submission, url): """ Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Namespace ...
class Write():
""" Methods for writing scraped comments to CSV or JSON. """ @staticmethod def _make_json_skeleton(args, limit, submission, url): """ Create a skeleton for JSON export. Include scrape details at the top. Parameters ---------- args: Namespace Name...
self._url = url more_comments_status = Status( "Finished resolving instances of MoreComments.", Fore.CYAN + Style.BRIGHT + "Resolving instances of MoreComments. This may take a while. Please wait.", "cyan" ) more_comments_status.start() self....
256
256
953
3
252
phroiland/URS
urs/praw_scrapers/Comments.py
Python
Write
Write
298
449
298
298
4c4e81e2a7a9b5978cb5279e0b5acccd260a37e3
bigcode/the-stack
train
d4a0654f0ae6ea688ef29e76
train
class
class CommentNode(): """ Defining a node object that stores comment metadata for the comments tree. """ def __init__(self, metadata): """ Set the node's comment data. self.__setattr__(key, value): set node attributes based on the `metadata` dictionary ...
class CommentNode():
""" Defining a node object that stores comment metadata for the comments tree. """ def __init__(self, metadata): """ Set the node's comment data. self.__setattr__(key, value): set node attributes based on the `metadata` dictionary self.replies: l...
.utils.Logger import ( LogError, LogExport, LogPRAWScraper ) from urs.utils.Titles import PRAWTitles ### Automate sending reset sequences to turn off color changes at the end of ### every print. init(autoreset = True) class CommentNode():
64
64
125
4
60
phroiland/URS
urs/praw_scrapers/Comments.py
Python
CommentNode
CommentNode
42
68
42
42
bf958233d3e772de92c7cec180da85d75df0476f
bigcode/the-stack
train
36a6df5df39a8403fd22784e
train
class
class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedfor...
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = nn.Linear...
memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): output = tgt intermediate = [] for layer in self.layers: output = layer(output, memory, tgt_mask=tgt_mask, ...
176
176
587
7
169
allenai/interactron
models/detr_models/transformer.py
Python
TransformerEncoderLayer
TransformerEncoderLayer
126
183
126
127
3b80a91f3bc0b5ed229dd0c0e896b89a209fc8d1
bigcode/the-stack
train
6b79253a342062766cfd269a
train
class
class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = nn.Mu...
class TransformerDecoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dr...
(src2) src = self.norm2(src) return src def forward_pre(self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None): src2 = self.norm1(src) q = k = self.with_po...
256
256
937
7
249
allenai/interactron
models/detr_models/transformer.py
Python
TransformerDecoderLayer
TransformerDecoderLayer
186
268
186
187
11cd7862ca3ac8ecf7a7cc6f49295af500081e84
bigcode/the-stack
train
40b0cb20d339ee7bb61b4faa
train
function
def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def _get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) return self.forward_post(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) def _get_clones(module, N):
64
64
25
9
55
allenai/interactron
models/detr_models/transformer.py
Python
_get_clones
_get_clones
271
272
271
271
5b705d3fe0e10b39c6159a1a13b200c5401954e8
bigcode/the-stack
train
c847cda27fa8850e631c9f0b
train
class
class TransformerEncoder(nn.Module): def __init__(self, encoder_layer, num_layers, norm=None): super().__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self, src, mask: Optional[Tensor] = N...
class TransformerEncoder(nn.Module):
def __init__(self, encoder_layer, num_layers, norm=None): super().__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self, src, mask: Optional[Tensor] = None, src_key_padding_m...
hs = self.decoder(tgt, memory, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed) return hs.transpose(1, 2), memory.permute(1, 2, 0).view(bs, c, h, w) class TransformerEncoder(nn.Module):
64
64
153
6
58
allenai/interactron
models/detr_models/transformer.py
Python
TransformerEncoder
TransformerEncoder
61
82
61
62
d660fe2b88c73bd4954e1995bdc16eb63f060ac3
bigcode/the-stack
train
b8b9aae9169e7d8a0db5231b
train
function
def build_transformer(args): return Transformer( d_model=256, dropout=0.1, nhead=8, dim_feedforward=2048, num_encoder_layers=6, num_decoder_layers=6, normalize_before=False, return_intermediate_dec=True, )
def build_transformer(args):
return Transformer( d_model=256, dropout=0.1, nhead=8, dim_feedforward=2048, num_encoder_layers=6, num_decoder_layers=6, normalize_before=False, return_intermediate_dec=True, )
return self.forward_post(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) def build_transformer(args):
63
64
65
6
57
allenai/interactron
models/detr_models/transformer.py
Python
build_transformer
build_transformer
275
285
275
275
2b131c510af22d6821bd2b086645ed19050f37a1
bigcode/the-stack
train
53b5b3c26246b818599c82dc
train
class
class TransformerDecoder(nn.Module): def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): super().__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm self.return_intermediate = return_i...
class TransformerDecoder(nn.Module):
def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): super().__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm self.return_intermediate = return_intermediate def forward(self, tgt...
src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None): output = src for layer in self.layers: output = layer(output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, pos=pos) if self.norm is not None: ...
85
85
284
6
78
allenai/interactron
models/detr_models/transformer.py
Python
TransformerDecoder
TransformerDecoder
85
123
85
86
07cba9e59ea576ed38d47db45424e3178574491d
bigcode/the-stack
train
b41718004cf6becda11302c7
train
class
class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, return_intermediate_dec=False): super().__init__() enc...
class Transformer(nn.Module):
def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, return_intermediate_dec=False): super().__init__() encoder_layer = TransformerEncoder...
# This code was copied from https://github.com/facebookresearch/detr """ DETR Transformer class. Copy-paste from torch.nn.Transformer with modifications: * positional encodings are passed in MHattention * extra LN at the end of encoder is removed * decoder returns a stack of activations from all decoding la...
102
131
437
5
96
allenai/interactron
models/detr_models/transformer.py
Python
Transformer
Transformer
17
58
17
18
a168be85f32eaa08b5e4da1c68207e6f6f0bb261
bigcode/the-stack
train
8b5366646711e7e775c4c105
train
function
def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
def _get_activation_fn(activation):
"""Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
( d_model=256, dropout=0.1, nhead=8, dim_feedforward=2048, num_encoder_layers=6, num_decoder_layers=6, normalize_before=False, return_intermediate_dec=True, ) def _get_activation_fn(activation):
64
64
77
8
56
allenai/interactron
models/detr_models/transformer.py
Python
_get_activation_fn
_get_activation_fn
288
296
288
288
b3335c84b6c4a341256ac3a5ba1865e88f2ff905
bigcode/the-stack
train
3d9637901db19c31716806ff
train
function
def expect_index_error(s, index): try: s[index] except IndexError: pass else: assert False
def expect_index_error(s, index):
try: s[index] except IndexError: pass else: assert False
s[0:-100] == '' # Start out of range assert s[100:1] == '' # Out of range both sides # This is the behaviour in cpython # assert s[-100:100] == s def expect_index_error(s, index):
64
64
30
8
55
ypyf/RustPython
tests/snippets/unicode_slicing.py
Python
expect_index_error
expect_index_error
11
17
11
11
affcdd58aa955351913f53a34ff8b2cf08e6c335
bigcode/the-stack
train
70f73a47734d4496ff1bcbc6
train
function
def test_slice_bounds(s): # End out of range assert s[0:100] == s assert s[0:-100] == '' # Start out of range assert s[100:1] == ''
def test_slice_bounds(s): # End out of range
assert s[0:100] == s assert s[0:-100] == '' # Start out of range assert s[100:1] == ''
def test_slice_bounds(s): # End out of range
13
64
52
13
0
ypyf/RustPython
tests/snippets/unicode_slicing.py
Python
test_slice_bounds
test_slice_bounds
1
6
1
2
0fe5e48dcc4f13ffd0269f8de915d50c143d950a
bigcode/the-stack
train
a5daf43b5d050182882107cb
train
class
class TestNFW(object): """ tests the Gaussian methods """ def setup(self): self.nfw = NFW() def test_function(self): x = np.array([1]) y = np.array([2]) Rs = 1. rho0 = 1 alpha_Rs = self.nfw._rho02alpha(rho0, Rs) values = self.nfw.function(x, y...
class TestNFW(object):
""" tests the Gaussian methods """ def setup(self): self.nfw = NFW() def test_function(self): x = np.array([1]) y = np.array([2]) Rs = 1. rho0 = 1 alpha_Rs = self.nfw._rho02alpha(rho0, Rs) values = self.nfw.function(x, y, Rs, alpha_Rs) ...
__author__ = 'sibirrer' from lenstronomy.LensModel.Profiles.nfw import NFW from lenstronomy.LensModel.Profiles.nfw_ellipse import NFW_ELLIPSE import numpy as np import numpy.testing as npt import pytest class TestNFW(object):
66
256
2,442
6
59
lucateo/lenstronomy
test/test_LensModel/test_Profiles/test_nfw.py
Python
TestNFW
TestNFW
12
113
12
12
8dafe6c00d81a17ebd9060836888ef5a525dfd7e
bigcode/the-stack
train
2c8f35ec3b9d979b9ae73739
train
class
class TestMassAngleConversion(object): """ test angular to mass unit conversions """ def setup(self): self.nfw = NFW() self.nfw_ellipse = NFW_ELLIPSE() def test_angle(self): x, y = 1, 0 alpha1, alpha2 = self.nfw.derivatives(x, y, alpha_Rs=1., Rs=1.) assert al...
class TestMassAngleConversion(object):
""" test angular to mass unit conversions """ def setup(self): self.nfw = NFW() self.nfw_ellipse = NFW_ELLIPSE() def test_angle(self): x, y = 1, 0 alpha1, alpha2 = self.nfw.derivatives(x, y, alpha_Rs=1., Rs=1.) assert alpha1 == 1. def test_convertAngle2r...
(values, values_interp, decimal=4) values = nfw.hessian(x, y, Rs, alpha_Rs) values_interp = nfw_interp.hessian(x, y, Rs, alpha_Rs) npt.assert_almost_equal(values, values_interp, decimal=4) class TestMassAngleConversion(object):
68
68
228
7
61
lucateo/lenstronomy
test/test_LensModel/test_Profiles/test_nfw.py
Python
TestMassAngleConversion
TestMassAngleConversion
116
138
116
116
2f6ed6e8558e5cc9a080fcf1d8414136a7346bfc
bigcode/the-stack
train
bfe76223393790c80abe3ded
train
class
class SVGCanvasDemo(GWTCanvasDemo): # override to use another canvas class def _get_canvas(self): return SVGCanvas(400,400)
class SVGCanvasDemo(GWTCanvasDemo): # override to use another canvas class
def _get_canvas(self): return SVGCanvas(400,400)
from GWTCanvasDemo import GWTCanvasDemo """* * Simple demo of the SVGCanvas Widget. This is simply using * the GWTCanvasDemo but with an SVGCanvas instead of a GWTCanvas """ class SVGCanvasDemo(GWTCanvasDemo): # override to use another canvas class
64
64
34
18
46
takipsizad/pyjs
examples/gwtcanvas/SVGCanvasDemo.py
Python
SVGCanvasDemo
SVGCanvasDemo
41
44
41
42
d10b9bf504afbddb77d77688042c7df790bd3ba6
bigcode/the-stack
train
b97920a16531bdf7aed44ffa
train
class
class Migration(migrations.Migration): dependencies = [ ('songs', '0006_auto_20170301_0736'), ] operations = [ migrations.AlterField( model_name='song', name='title', field=models.CharField(max_length=255, validators=[django.core.validators.MinLengthVali...
class Migration(migrations.Migration):
dependencies = [ ('songs', '0006_auto_20170301_0736'), ] operations = [ migrations.AlterField( model_name='song', name='title', field=models.CharField(max_length=255, validators=[django.core.validators.MinLengthValidator(2)]), ), migration...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-01 07:37 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration):
59
64
158
7
51
zaneswafford/songaday_searcher
songs/migrations/0007_auto_20170301_0737.py
Python
Migration
Migration
9
31
9
10
d64c716e0fb1df55224a23df9306737ed7233f32
bigcode/the-stack
train
dce053894559d79a02a777cd
train
function
@client.async_event def on_ready(): rfwbot.handleLogin(client.user)
@client.async_event def on_ready():
rfwbot.handleLogin(client.user)
︵', '┴─┴ ︵'))): if x != 0: msg += ' ' msg += '┳━┳ノ(°-°ノ)' await rfwbot.say(message.channel, msg) @client.async_event def on_ready():
64
64
18
9
55
eliasthompson/ZUbot
rfwbot.py
Python
on_ready
on_ready
433
435
433
434
f53effc71836691b37a9c0961f3a52715183ff5f
bigcode/the-stack
train
71eb51bdf9d857421c65c156
train
function
@client.async_event async def on_message(message): print('\033[1;34m[\033[31m' + str(message.channel) + '\033[34m]\033[36m ' + str(message.author) + '\033[33m: \033[0m' + str(message.content)) # say = input('--> ') if not rfwbot.isIgnored(message.author): if message.content.startswith(rfwbot.comman...
@client.async_event async def on_message(message):
print('\033[1;34m[\033[31m' + str(message.channel) + '\033[34m]\033[36m ' + str(message.author) + '\033[33m: \033[0m' + str(message.content)) # say = input('--> ') if not rfwbot.isIgnored(message.author): if message.content.startswith(rfwbot.commandString): command = message.content[len...
if not self.isAdmin(sender): return if cmd == 'reload': self.cReload() await self.say(channel, 'Reloaded!') if cmd == 'stop': await self.say(channel, 'Shutting down.') self.client.logout() if cmd == 'channels': await self.say...
226
226
756
11
215
eliasthompson/ZUbot
rfwbot.py
Python
on_message
on_message
389
430
389
390
a3297a3b97e67052d81b7d84fc1c96e2bd8f6ce8
bigcode/the-stack
train
02146be7285134c8ade6d759
train
class
class InvalidDieException(Exception): def __init__(self, die, error='invalid'): self.die = die self.error = error def __str__(self): if self.error == 'too many die': return "Error: Too many die. Slow your roll." if self.error == 'too many sides': return "E...
class InvalidDieException(Exception):
def __init__(self, die, error='invalid'): self.die = die self.error = error def __str__(self): if self.error == 'too many die': return "Error: Too many die. Slow your roll." if self.error == 'too many sides': return "Error: IT'S OVER 9000!!!!1!11!11!one!!1...
#!/usr/bin/env python3 import discord, configparser, random, re, requests, random from time import sleep class InvalidDieException(Exception):
32
64
111
6
25
eliasthompson/ZUbot
rfwbot.py
Python
InvalidDieException
InvalidDieException
5
15
5
5
706fc2ff67f63f92502a32b6e8a0fefefefd42d6
bigcode/the-stack
train
a81370f78c16710ae7a249de
train
class
class DiscordBot: def __init__(self, configFile): self._loadConfig(configFile) self.cReload() def _loadConfig(self, configFile): self.config = configparser.ConfigParser() self.config.read(configFile) self.commandString = self.config.get( 'settings', 'commandS...
class DiscordBot:
def __init__(self, configFile): self._loadConfig(configFile) self.cReload() def _loadConfig(self, configFile): self.config = configparser.ConfigParser() self.config.read(configFile) self.commandString = self.config.get( 'settings', 'commandString', fallback='...
#!/usr/bin/env python3 import discord, configparser, random, re, requests, random from time import sleep class InvalidDieException(Exception): def __init__(self, die, error='invalid'): self.die = die self.error = error def __str__(self): if self.error == 'too many die': retu...
141
256
2,935
4
136
eliasthompson/ZUbot
rfwbot.py
Python
DiscordBot
DiscordBot
18
382
18
18
355f668fac59fa93f616174131bccc66b2139089
bigcode/the-stack
train
30ec7c2c0b53d7f650b803e3
train
class
class Migration(migrations.Migration): dependencies = [ ('pyday_social_network', '0001_initial'), ] operations = [ migrations.AlterField( model_name='pydayuser', name='date_joined', field=models.DateTimeField(default=datetime.datetime(2016, 7, 2, 8, 29, ...
class Migration(migrations.Migration):
dependencies = [ ('pyday_social_network', '0001_initial'), ] operations = [ migrations.AlterField( model_name='pydayuser', name='date_joined', field=models.DateTimeField(default=datetime.datetime(2016, 7, 2, 8, 29, 54, 961379, tzinfo=utc)), ), ...
-*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-07-02 08:29 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration):
64
64
90
7
56
6desislava6/PyDay
pyday_social_network/migrations/0002_auto_20160702_0829.py
Python
Migration
Migration
10
22
10
11
820769c53c10617c150c095c5aac552b11d731d8
bigcode/the-stack
train
eed378242348d3877a253be0
train
function
def test_materials_property_map(): int_map = DummyPartMap([0, 1]) str_map = DummyPartMap(["part1", "part2"]) part_materials1 = {0: "InAs", 1: "GaSb"} part_materials2 = {"part1": "InAs", "part2": "Al"} mat_lib = Materials(matDict={}) mat_lib.add_material( "InAs", "semi", e...
def test_materials_property_map():
int_map = DummyPartMap([0, 1]) str_map = DummyPartMap(["part1", "part2"]) part_materials1 = {0: "InAs", 1: "GaSb"} part_materials2 = {"part1": "InAs", "part2": "Al"} mat_lib = Materials(matDict={}) mat_lib.add_material( "InAs", "semi", electronMass=0.026, directBa...
.ones((2, 3))) == "no") def test_property_map_nonuniform_types(): str_map = DummyPartMap(["part1", "part2"]) props = {"part1": 1, "part2": 1.5} prop_map = PropertyMap(str_map, lambda p: props[p]) assert prop_map((1.0, 2.0)) == 1.5 assert np.all(prop_map(np.ones((2, 3))) == 1.5) assert np.all(p...
134
134
449
7
127
merrittlosert/qmt
tests/test_property_map.py
Python
test_materials_property_map
test_materials_property_map
48
80
48
48
8f1187cf8aa743eb2245b3e153d62d5e8047b040
bigcode/the-stack
train
3dcc4a7a812988d6be84572c
train
class
class DummyPartMap: def __init__(self, part_ids): assert len(part_ids) == 2 self.partIds = part_ids def __call__(self, x): assert np.ndim(x) >= 1 x = np.asanyarray(x) if np.ndim(x) == 1: return self.partIds[x[0] > 0] else: return np.where(...
class DummyPartMap:
def __init__(self, part_ids): assert len(part_ids) == 2 self.partIds = part_ids def __call__(self, x): assert np.ndim(x) >= 1 x = np.asanyarray(x) if np.ndim(x) == 1: return self.partIds[x[0] > 0] else: return np.where(x[..., 0] > 0, self....
import numpy as np from qmt.geometry import PropertyMap, MaterialPropertyMap from qmt.materials import Materials class DummyPartMap:
30
64
114
5
24
merrittlosert/qmt
tests/test_property_map.py
Python
DummyPartMap
DummyPartMap
7
18
7
7
51efaf11750602c42215fa447cb4d4aeb03cca4e
bigcode/the-stack
train
26a9136a2145c3a38e6022e7
train
function
def test_property_map(): int_map = DummyPartMap([0, 1]) str_map = DummyPartMap(["part1", "part2"]) prop_map1 = PropertyMap(int_map, np.vectorize(lambda p: "yes" if p > 0 else "no")) assert prop_map1.get_part((1.0, 2.0)) == 1 assert np.all(prop_map1.get_part(-np.ones((2, 3))) == 0) assert prop_m...
def test_property_map():
int_map = DummyPartMap([0, 1]) str_map = DummyPartMap(["part1", "part2"]) prop_map1 = PropertyMap(int_map, np.vectorize(lambda p: "yes" if p > 0 else "no")) assert prop_map1.get_part((1.0, 2.0)) == 1 assert np.all(prop_map1.get_part(-np.ones((2, 3))) == 0) assert prop_map1((1.0, 2.0)) == "yes" ...
): assert np.ndim(x) >= 1 x = np.asanyarray(x) if np.ndim(x) == 1: return self.partIds[x[0] > 0] else: return np.where(x[..., 0] > 0, self.partIds[1], self.partIds[0]) def test_property_map():
78
78
263
5
73
merrittlosert/qmt
tests/test_property_map.py
Python
test_property_map
test_property_map
21
36
21
21
f7e6613264f3567753d6f36a8e8ecae8fe313466
bigcode/the-stack
train
7485caedb826a9c738e9d652
train
function
def test_property_map_nonuniform_types(): str_map = DummyPartMap(["part1", "part2"]) props = {"part1": 1, "part2": 1.5} prop_map = PropertyMap(str_map, lambda p: props[p]) assert prop_map((1.0, 2.0)) == 1.5 assert np.all(prop_map(np.ones((2, 3))) == 1.5) assert np.all(prop_map(-np.ones((2, 3))) ...
def test_property_map_nonuniform_types():
str_map = DummyPartMap(["part1", "part2"]) props = {"part1": 1, "part2": 1.5} prop_map = PropertyMap(str_map, lambda p: props[p]) assert prop_map((1.0, 2.0)) == 1.5 assert np.all(prop_map(np.ones((2, 3))) == 1.5) assert np.all(prop_map(-np.ones((2, 3))) == 1)
2.get_part(-np.ones((2, 3))) == "part1") assert prop_map1((1.0, 2.0)) == "yes" assert np.all(prop_map1(-np.ones((2, 3))) == "no") def test_property_map_nonuniform_types():
64
64
116
8
56
merrittlosert/qmt
tests/test_property_map.py
Python
test_property_map_nonuniform_types
test_property_map_nonuniform_types
39
45
39
39
5bddb885994f8bf44e581dee5da357425f9dbe6f
bigcode/the-stack
train
ad64d70bd9391048036bcc04
train
class
class SqlPyGenTransformer(Transformer): """Transform the parse tree for code generation.""" CNAME = str MODULE_NAME = str RTYPE_OPT = str RETURN_OPT = str def SQL_STRING(self, t): return t.strip().rstrip(";").strip() def module(self, ts): (name,) = ts return ("modu...
class SqlPyGenTransformer(Transformer):
"""Transform the parse tree for code generation.""" CNAME = str MODULE_NAME = str RTYPE_OPT = str RETURN_OPT = str def SQL_STRING(self, t): return t.strip().rstrip(";").strip() def module(self, ts): (name,) = ts return ("module", name) def pname_ptype(self, ts...
"""Generate type annotated python from SQL.""" from pprint import pprint from importlib.resources import read_text import black from lark import Lark, Transformer, UnexpectedToken from jinja2 import Template, StrictUndefined, TemplateSyntaxError class SqlPyGenTransformer(Transformer):
58
253
844
8
49
parantapa/sqlpygen
src/sqlpygen/sqlpygen.py
Python
SqlPyGenTransformer
SqlPyGenTransformer
11
139
11
11
dffd1b5995e8469574ec4abb749bd7c4cc72702d
bigcode/the-stack
train
cd835a191a521a853f9b57d0
train
function
def get_parser() -> Lark: """Return the parser.""" grammar = read_text("sqlpygen", "sqlpygen.lark") parser = Lark(grammar, parser="lalr") return parser
def get_parser() -> Lark:
"""Return the parser.""" grammar = read_text("sqlpygen", "sqlpygen.lark") parser = Lark(grammar, parser="lalr") return parser
"import_stmts": [], "schemas": [], "queries": [], } for grp, val in ts: if grp == "module": ret["module"] = val else: ret[grp].append(val) return ret def get_parser() -> Lark:
64
64
47
8
55
parantapa/sqlpygen
src/sqlpygen/sqlpygen.py
Python
get_parser
get_parser
142
146
142
142
74745a918bfdcd69e1d9b5b7e6c1e3dd9fb6438b
bigcode/the-stack
train
7cd00ab837510d3da116c7ae
train
function
def generate(text: str, verbose: bool = False) -> str: """Generate python from annotated sql.""" parser = get_parser() transformer = SqlPyGenTransformer() template = get_template() try: parse_tree = parser.parse(text) except UnexpectedToken as e: line, col = e.line - 1, e.column...
def generate(text: str, verbose: bool = False) -> str:
"""Generate python from annotated sql.""" parser = get_parser() transformer = SqlPyGenTransformer() template = get_template() try: parse_tree = parser.parse(text) except UnexpectedToken as e: line, col = e.line - 1, e.column - 1 col_m1 = max(0, col) err_line = te...
( tpl_text, trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined ) except TemplateSyntaxError as e: raise ValueError(f"Syntax error in template line {e.lineno}") from e return tpl_obj def generate(text: str, verbose: bool = False) -> str:
68
68
229
15
52
parantapa/sqlpygen
src/sqlpygen/sqlpygen.py
Python
generate
generate
161
191
161
161
5ed36b3aa2cca28e5c73322d185c36ef23cd01bd
bigcode/the-stack
train
af3aeba3eeca2fca5546dae1
train
function
def get_template() -> Template: """Return the code generation template.""" tpl_text = read_text("sqlpygen", "sqlpygen.jinja2") try: tpl_obj = Template( tpl_text, trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined ) except TemplateSyntaxError as e: raise V...
def get_template() -> Template:
"""Return the code generation template.""" tpl_text = read_text("sqlpygen", "sqlpygen.jinja2") try: tpl_obj = Template( tpl_text, trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined ) except TemplateSyntaxError as e: raise ValueError(f"Syntax error in temp...
[grp].append(val) return ret def get_parser() -> Lark: """Return the parser.""" grammar = read_text("sqlpygen", "sqlpygen.lark") parser = Lark(grammar, parser="lalr") return parser def get_template() -> Template:
64
64
95
7
56
parantapa/sqlpygen
src/sqlpygen/sqlpygen.py
Python
get_template
get_template
149
158
149
149
b23b17a0fe0bd756cbad51eecf00beb391e528dc
bigcode/the-stack
train
4820f9cbab9cbdc3cfe90eac
train
function
def get_iot_hub_resource_event_hub_consumer_group(event_hub_endpoint_name: Optional[str] = None, name: Optional[str] = None, resource_group_name: Optional[str] = None, re...
def get_iot_hub_resource_event_hub_consumer_group(event_hub_endpoint_name: Optional[str] = None, name: Optional[str] = None, resource_group_name: Optional[str] = None, re...
""" The properties of the EventHubConsumerGroupInfo object. :param str event_hub_endpoint_name: The name of the Event Hub-compatible endpoint in the IoT hub. :param str name: The name of the consumer group to retrieve. :param str resource_group_name: The name of the resource group that contains th...
HubResourceEventHubConsumerGroupResult( id=self.id, name=self.name, tags=self.tags) def get_iot_hub_resource_event_hub_consumer_group(event_hub_endpoint_name: Optional[str] = None, name: Optional[str] = None, ...
105
105
353
82
23
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/devices/v20170701/get_iot_hub_resource_event_hub_consumer_group.py
Python
get_iot_hub_resource_event_hub_consumer_group
get_iot_hub_resource_event_hub_consumer_group
69
97
69
73
c56d6987b415ecdffb3bedc5068d426541e46205
bigcode/the-stack
train
747bb3fc0cb07cc5217c9607
train
class
class AwaitableGetIotHubResourceEventHubConsumerGroupResult(GetIotHubResourceEventHubConsumerGroupResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetIotHubResourceEventHubConsumerGroupResult( id=self.id, name=sel...
class AwaitableGetIotHubResourceEventHubConsumerGroupResult(GetIotHubResourceEventHubConsumerGroupResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetIotHubResourceEventHubConsumerGroupResult( id=self.id, name=self.name, tags=self.tags)
tags(self) -> Optional[Mapping[str, str]]: """ The tags. """ return pulumi.get(self, "tags") class AwaitableGetIotHubResourceEventHubConsumerGroupResult(GetIotHubResourceEventHubConsumerGroupResult): # pylint: disable=using-constant-test
64
64
78
35
29
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/devices/v20170701/get_iot_hub_resource_event_hub_consumer_group.py
Python
AwaitableGetIotHubResourceEventHubConsumerGroupResult
AwaitableGetIotHubResourceEventHubConsumerGroupResult
58
66
58
59
5182da01f6f1342666b3b6f6d38259027753723f
bigcode/the-stack
train
011ae72222610bb442c1ec7b
train
class
@pulumi.output_type class GetIotHubResourceEventHubConsumerGroupResult: """ The properties of the EventHubConsumerGroupInfo object. """ def __init__(__self__, id=None, name=None, tags=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") ...
@pulumi.output_type class GetIotHubResourceEventHubConsumerGroupResult:
""" The properties of the EventHubConsumerGroupInfo object. """ def __init__(__self__, id=None, name=None, tags=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(na...
import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'GetIotHubResourceEventHubConsumerGroupResult', 'AwaitableGetIotHubResourceEventHubConsumerGroupResult', 'get_iot_hub_resource_event_hub_consumer_group', ] @pulumi.output_type class GetIotHubResourceEventHubCons...
87
87
290
18
69
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/devices/v20170701/get_iot_hub_resource_event_hub_consumer_group.py
Python
GetIotHubResourceEventHubConsumerGroupResult
GetIotHubResourceEventHubConsumerGroupResult
17
55
17
18
83699baa7023aebefd092edaae9c66448068f14e
bigcode/the-stack
train
88a4b169dc818d7d9cca1570
train
class
class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) # primary keys are required by SQLAlchemy email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) name = db.Column(db.String(1000))
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True) # primary keys are required by SQLAlchemy email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) name = db.Column(db.String(1000))
# models.py from flask_login import UserMixin from . import db class User(UserMixin, db.Model):
24
64
63
8
15
Pratik2587/Medical-Cost-Predictor-
models.py
Python
User
User
6
10
6
6
10b67da2e88a7b40764c99118916efa3d8c2206a
bigcode/the-stack
train
a646ed3b5bf6a1708249df2c
train
class
@pytest.mark.onlycluster class TestClusterMonitor: def test_wait_command_not_found(self, r): "Make sure the wait_for_command func works when command is not found" key = "foo" node = r.get_node_from_key(key) with r.monitor(target_node=node) as m: response = wait_for_comman...
@pytest.mark.onlycluster class TestClusterMonitor:
def test_wait_command_not_found(self, r): "Make sure the wait_for_command func works when command is not found" key = "foo" node = r.get_node_from_key(key) with r.monitor(target_node=node) as m: response = wait_for_command(r, m, "nothing", key=key) assert resp...
time.sleep(0.2) with ro.pipeline() as readonly_pipe: mock_all_nodes_resp(ro, "MOCK_OK") assert readonly_pipe.read_from_replicas is True assert readonly_pipe.get(key).get(key).execute() == ["MOCK_OK", "MOCK_OK"] slot_nodes = ro.nodes_manager.slots_cache[r...
164
164
549
10
153
Avital-Fine/redis-py
tests/test_cluster.py
Python
TestClusterMonitor
TestClusterMonitor
2,740
2,795
2,740
2,741
1c502113d24f64a41b211dde5bafda781ecce49b
bigcode/the-stack
train
340ad7a59f708280746585ec
train
function
def find_node_ip_based_on_port(cluster_client, port): for node in cluster_client.get_nodes(): if node.port == port: return node.host
def find_node_ip_based_on_port(cluster_client, port):
for node in cluster_client.get_nodes(): if node.port == port: return node.host
Mock() connection.read_response.side_effect = func node.redis_connection.connection = connection return node def mock_all_nodes_resp(rc, response): for node in rc.get_nodes(): mock_node_resp(node, response) return rc def find_node_ip_based_on_port(cluster_client, port):
64
64
33
12
51
Avital-Fine/redis-py
tests/test_cluster.py
Python
find_node_ip_based_on_port
find_node_ip_based_on_port
151
154
151
151
b6be607574c21fb04aa921571bc6c7fb3407de88
bigcode/the-stack
train
bd72f59924e07ae8ab5f5135
train
function
def mock_node_resp(node, response): connection = Mock() connection.read_response.return_value = response node.redis_connection.connection = connection return node
def mock_node_resp(node, response):
connection = Mock() connection.read_response.return_value = response node.redis_connection.connection = connection return node
readonly", "fast"], "first_key_pos": 1, "last_key_pos": 1, "step_count": 1, } } cmd_parser_initialize.side_effect = cmd_init_mock return RedisCluster(*args, **kwargs) def mock_node_resp(...
64
64
34
8
56
Avital-Fine/redis-py
tests/test_cluster.py
Python
mock_node_resp
mock_node_resp
131
135
131
131
9e45c89d1c5383cce5c29fbbbc42a9cbb9665bfa
bigcode/the-stack
train
fe4837d952a18a3b71534a02
train
function
def moved_redirection_helper(request, failover=False): """ Test that the client handles MOVED response after a failover. Redirection after a failover means that the redirection address is of a replica that was promoted to a primary. At first call it should return a MOVED ResponseError that will poi...
def moved_redirection_helper(request, failover=False):
""" Test that the client handles MOVED response after a failover. Redirection after a failover means that the redirection address is of a replica that was promoted to a primary. At first call it should return a MOVED ResponseError that will point the client to the next server it should talk to....
, **kwargs) def mock_node_resp(node, response): connection = Mock() connection.read_response.return_value = response node.redis_connection.connection = connection return node def mock_node_resp_func(node, func): connection = Mock() connection.read_response.side_effect = func node.redis_c...
146
146
487
11
134
Avital-Fine/redis-py
tests/test_cluster.py
Python
moved_redirection_helper
moved_redirection_helper
157
207
157
157
306395f88c3b87144df7cbbf8ee0b0a13bae5df1
bigcode/the-stack
train
4c32b54c64c69c7c66f33f08
train
class
@pytest.mark.onlycluster class TestReadOnlyPipeline: """ Tests for ClusterPipeline class in readonly mode """ def test_pipeline_readonly(self, r): """ On readonly mode, we supports get related stuff only. """ r.readonly(target_nodes="all") r.set("foo71", "a1") #...
@pytest.mark.onlycluster class TestReadOnlyPipeline:
""" Tests for ClusterPipeline class in readonly mode """ def test_pipeline_readonly(self, r): """ On readonly mode, we supports get related stuff only. """ r.readonly(target_nodes="all") r.set("foo71", "a1") # we assume this key is set on 127.0.0.1:7001 ...
= None for node in r.get_nodes(): if node != first_node: ask_node = node break if ask_node is None: warnings.warn("skipping this test since the cluster has only one " "node") return ask_msg = f"{r.keyslot(key)} {ask_node.host}:...
222
223
744
11
211
Avital-Fine/redis-py
tests/test_cluster.py
Python
TestReadOnlyPipeline
TestReadOnlyPipeline
2,659
2,737
2,659
2,660
63f233c3a4b35cef8cffb9dc7c97d59b400e7cbd
bigcode/the-stack
train
df85939371dc5b147eecf84d
train
class
@pytest.mark.onlycluster class TestRedisClusterObj: """ Tests for the RedisCluster class """ def test_host_port_startup_node(self): """ Test that it is possible to use host & port arguments as startup node args """ cluster = get_mocked_redis_client(host=default_h...
@pytest.mark.onlycluster class TestRedisClusterObj:
""" Tests for the RedisCluster class """ def test_host_port_startup_node(self): """ Test that it is possible to use host & port arguments as startup node args """ cluster = get_mocked_redis_client(host=default_host, port=default_port) assert cluster.get_n...
have a " "replica") return redirect_node = rc.nodes_manager.slots_cache[slot][1] else: # Use one of the primaries to be the redirected node redirect_node = rc.get_primaries()[0] r_host = redirect_node.host r_port = redirect_node.port with patch.object(Redis, "parse_r...
256
256
3,711
11
244
Avital-Fine/redis-py
tests/test_cluster.py
Python
TestRedisClusterObj
TestRedisClusterObj
210
657
210
211
bef7aef0258d1a776b937270c9d80abaf979b618
bigcode/the-stack
train
71434a76b04b4d7c6768138c
train
class
@pytest.mark.onlycluster class TestClusterPubSubObject: """ Tests for the ClusterPubSub class """ def test_init_pubsub_with_host_and_port(self, r): """ Test creation of pubsub instance with passed host and port """ node = r.get_default_node() p = r.pubsub(host=no...
@pytest.mark.onlycluster class TestClusterPubSubObject:
""" Tests for the ClusterPubSub class """ def test_init_pubsub_with_host_and_port(self, r): """ Test creation of pubsub instance with passed host and port """ node = r.get_default_node() p = r.pubsub(host=node.host, port=node.port) assert p.get_pubsub_nod...
): self.commands = { "get": { "name": "get", "arity": 2, "flags": ["readonly", "fast"], "first_key_pos": 1, "last_key_pos": 1, ...
163
163
545
12
150
Avital-Fine/redis-py
tests/test_cluster.py
Python
TestClusterPubSubObject
TestClusterPubSubObject
2,275
2,346
2,275
2,276
06037c55ae8585fe0a519a1d7ece02217d84eab6
bigcode/the-stack
train
6f783ca8a1d6cdd0a4835db2
train
function
def mock_all_nodes_resp(rc, response): for node in rc.get_nodes(): mock_node_resp(node, response) return rc
def mock_all_nodes_resp(rc, response):
for node in rc.get_nodes(): mock_node_resp(node, response) return rc
connection.read_response.return_value = response node.redis_connection.connection = connection return node def mock_node_resp_func(node, func): connection = Mock() connection.read_response.side_effect = func node.redis_connection.connection = connection return node def mock_all_nodes_resp(rc,...
64
64
29
9
54
Avital-Fine/redis-py
tests/test_cluster.py
Python
mock_all_nodes_resp
mock_all_nodes_resp
145
148
145
145
20174bf6ca9979b64a8b513639ac8031ac358adc
bigcode/the-stack
train
8a042888d187a6ad506e3752
train
function
@pytest.fixture() def slowlog(request, r): """ Set the slowlog threshold to 0, and the max length to 128. This will force every command into the slowlog and allow us to test it """ # Save old values current_config = r.config_get(target_nodes=r.get_primaries()[0]) old_slower_than_valu...
@pytest.fixture() def slowlog(request, r):
""" Set the slowlog threshold to 0, and the max length to 128. This will force every command into the slowlog and allow us to test it """ # Save old values current_config = r.config_get(target_nodes=r.get_primaries()[0]) old_slower_than_value = current_config["slowlog-log-slower-than...
, "node_3"], ], [8192, 16383, ["127.0.0.1", 7001, "node_1"], ["127.0.0.1", 7002, "node_2"]], ] @pytest.fixture() def slowlog(request, r):
64
64
202
10
54
Avital-Fine/redis-py
tests/test_cluster.py
Python
slowlog
slowlog
57
79
57
58
e51f2fc47b3070b6392dfebcf9459333c081f017
bigcode/the-stack
train
8dd6af0a89e776bcf3c2999d
train
class
@pytest.mark.onlycluster class TestClusterRedisCommands: """ Tests for RedisCluster unique commands """ def test_case_insensitive_command_names(self, r): assert ( r.cluster_response_callbacks["cluster slots"] == r.cluster_response_callbacks["CLUSTER SLOTS"] ) ...
@pytest.mark.onlycluster class TestClusterRedisCommands:
""" Tests for RedisCluster unique commands """ def test_case_insensitive_command_names(self, r): assert ( r.cluster_response_callbacks["cluster slots"] == r.cluster_response_callbacks["CLUSTER SLOTS"] ) def test_get_and_set(self, r): # get and set ca...
skip_if_redis_enterprise() def test_not_require_full_coverage_cluster_down_error(self, r): """ When require_full_coverage is set to False (default client config) and not all slots are covered, if one of the nodes has 'cluster-require_full_coverage' config set to 'yes' some key-based ...
256
256
16,050
11
244
Avital-Fine/redis-py
tests/test_cluster.py
Python
TestClusterRedisCommands
TestClusterRedisCommands
660
1,972
660
661
35fa53f92420ede7d17b2d27e8bd543770f7a95d
bigcode/the-stack
train
63fd5a59ce76f80a96604824
train
class
@pytest.mark.onlycluster class TestClusterPipeline: """ Tests for the ClusterPipeline class """ def test_blocked_methods(self, r): """ Currently some method calls on a Cluster pipeline is blocked when using in cluster mode. They maybe implemented in the future. "...
@pytest.mark.onlycluster class TestClusterPipeline:
""" Tests for the ClusterPipeline class """ def test_blocked_methods(self, r): """ Currently some method calls on a Cluster pipeline is blocked when using in cluster mode. They maybe implemented in the future. """ pipe = r.pipeline() with pytest.r...
1.1.1.1", 1111) with pytest.raises(RedisClusterException): r.pubsub(node) def test_init_pubsub_with_a_non_existent_host_port(self, r): """ Test creation of pubsub instance with host and port that don't belong to a node in the cluster. RedisClusterException should...
256
256
2,056
10
245
Avital-Fine/redis-py
tests/test_cluster.py
Python
TestClusterPipeline
TestClusterPipeline
2,349
2,656
2,349
2,350
8246221b4f99dc7d33863cc18c75d8b294481a15
bigcode/the-stack
train