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
e0e5d0895875366e45f4932d
train
function
def image_loader(pkl_file, model ='vgg', dtype='float32'): with open(pkl_file, 'rb') as f: data = pkl.load(f) f.close() for im, target in tqdm.tqdm(zip(data['data'], data['target']), total=50000): im = cv2.imdecode(np.fromstring(im, np.uint8), cv2.IMREAD_COLOR) im = cv2.cvtColor(im, ...
def image_loader(pkl_file, model ='vgg', dtype='float32'):
with open(pkl_file, 'rb') as f: data = pkl.load(f) f.close() for im, target in tqdm.tqdm(zip(data['data'], data['target']), total=50000): im = cv2.imdecode(np.fromstring(im, np.uint8), cv2.IMREAD_COLOR) im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) im = im.astype(dtype) im...
] for weight_name in g.attrs['weight_names']: weight_value = g[weight_name].value name = str(weight_name).split("'")[1] weights[name] = weight_value return weights def image_loader(pkl_file, model ='vgg', dtype='float32'):
64
64
171
17
46
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
image_loader
image_loader
243
256
243
243
42bf3323c72a5180b2751b216882831d87221c09
bigcode/the-stack
train
c7ccd46d8392a5a114b9f9d8
train
function
def top5_acc(pred, k=5): Inf = 0. results = [] for i in range(k): results.append(pred.index(max(pred))) pred[pred.index(max(pred))] = Inf return results
def top5_acc(pred, k=5):
Inf = 0. results = [] for i in range(k): results.append(pred.index(max(pred))) pred[pred.index(max(pred))] = Inf return results
(im, axis=0) im[..., 0] -= 103.939 im[..., 1] -= 116.779 im[..., 2] -= 123.68 label = int(target) yield im, label def top5_acc(pred, k=5):
64
64
51
10
53
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
top5_acc
top5_acc
258
264
258
258
09d46507f5587e07e46c267553f567fa10bf8054
bigcode/the-stack
train
3e5ec8be0e06c9bd5b7823ae
train
function
def quantize_conv_weights(weights,conv_quant): if conv_quant == 'per_channel': s = [] for i in range(weights.shape[-1]): abs_weights = np.abs(weights[:,:,:,i]) vmax = np.max(abs_weights) scale = vmax/127. s.append(scale) scales = ...
def quantize_conv_weights(weights,conv_quant):
if conv_quant == 'per_channel': s = [] for i in range(weights.shape[-1]): abs_weights = np.abs(weights[:,:,:,i]) vmax = np.max(abs_weights) scale = vmax/127. s.append(scale) scales = np.array(s) qweights = np.divide(weights,sca...
.constant(weights[weight_name], dtype=tf.float32) s = 1.0 try: b = tf.constant(weights[bias_name], dtype=tf.float32) except: b = None return w, b, s def quantize_conv_weights(weights,conv_quant):
64
64
181
11
52
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
quantize_conv_weights
quantize_conv_weights
95
118
95
96
52da4356336ce29f3934d4e19b537402c5df2443
bigcode/the-stack
train
32526d54d78ef87520bdc91b
train
function
def avgpool_2d(x, k=2, s=1, padding='VALID'): return tf.nn.avg_pool(x, ksize=[1, k, k, 1], strides=[1, s, s,1],padding=padding)
def avgpool_2d(x, k=2, s=1, padding='VALID'):
return tf.nn.avg_pool(x, ksize=[1, k, k, 1], strides=[1, s, s,1],padding=padding)
, s=2, padding='VALID'): return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, s, s, 1],padding=padding) def avgpool_2d(x, k=2, s=1, padding='VALID'):
64
64
54
20
44
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
avgpool_2d
avgpool_2d
67
68
67
67
21dcdc5945ce06bef1fa47eb73f339e277d2c03f
bigcode/the-stack
train
789afbb601b1935147665c07
train
function
def collect_stats(all_global_max,all_global_min,max_x, min_x): all_global_max.append(max_x) all_global_min.append(min_x) return all_global_max, all_global_min
def collect_stats(all_global_max,all_global_min,max_x, min_x):
all_global_max.append(max_x) all_global_min.append(min_x) return all_global_max, all_global_min
def generate_global_max_min(): global_max, global_min = [],[] for i in range(16): global_max.append(float("-inf")) global_min.append(float("inf")) return global_max,global_min def collect_stats(all_global_max,all_global_min,max_x, min_x):
64
64
44
17
46
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
collect_stats
collect_stats
273
278
273
274
38f2d66d773deb31491bf040f3f26964dc84eb51
bigcode/the-stack
train
8fbd53acdaba49d1cbeb5dde
train
function
def get_scales(global_max, global_min, threshold): scales = [] for i in range(global_max.size): abs_value = max(threshold*(np.abs(global_max[i])),threshold*(np.abs(global_min[i]))) s = np.divide(abs_value, 127.) scales.append(s) return scales
def get_scales(global_max, global_min, threshold):
scales = [] for i in range(global_max.size): abs_value = max(threshold*(np.abs(global_max[i])),threshold*(np.abs(global_min[i]))) s = np.divide(abs_value, 127.) scales.append(s) return scales
.array(all_global_max[i]) min_sum = min_sum + np.array(all_global_min[i]) global_max, global_min = max_sum/(i+1), min_sum/(i+1) return global_max,global_min def get_scales(global_max, global_min, threshold):
64
64
67
12
51
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
get_scales
get_scales
313
319
313
313
4084aae8c1c9620db7bc98703f1cfa5f463e58e2
bigcode/the-stack
train
f2576b4716272277d6869e45
train
function
def weight_loader(weight_file): weights = {} f = h5py.File(weight_file, mode='r') try: layers = f.attrs['layer_names'] except: raise ValueError("weights file must contain attribution: 'layer_names'") for layer_name in layers: g = f[layer_name] for weight_name in g.att...
def weight_loader(weight_file):
weights = {} f = h5py.File(weight_file, mode='r') try: layers = f.attrs['layer_names'] except: raise ValueError("weights file must contain attribution: 'layer_names'") for layer_name in layers: g = f[layer_name] for weight_name in g.attrs['weight_names']: ...
,x_min = denselayer(x, w, quant,calibrate,x_max,x_min,s,activation_scales[15]) x = bias_and_activation(x,b, activation = '') if calibrate: return x_max,x_min else: return x def weight_loader(weight_file):
64
64
114
6
57
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
weight_loader
weight_loader
228
241
228
228
21b682264bc2b2a7f07644a962a50bf3e38c0c1d
bigcode/the-stack
train
92dcb31020d0e81c467c1021
train
function
def quantize_tensor(x,s): x = tf.divide(x, s) x = tf.rint(x) x = tf.clip_by_value(x,-128.0,127.0) return x,s
def quantize_tensor(x,s):
x = tf.divide(x, s) x = tf.rint(x) x = tf.clip_by_value(x,-128.0,127.0) return x,s
import sys import numpy as np import pickle as pkl import cv2 import math import tqdm import os config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.33 def quantize_tensor(x,s):
64
64
46
7
56
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
quantize_tensor
quantize_tensor
16
20
16
16
8ed2f886c36fa4245efce381b38fca1a7b71d764
bigcode/the-stack
train
61b873b3151d7ffb1ea9a3ba
train
function
def maxpool_2d(x, k=2, s=2, padding='VALID'): return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, s, s, 1],padding=padding)
def maxpool_2d(x, k=2, s=2, padding='VALID'):
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, s, s, 1],padding=padding)
= tf.cast(x, dtype=tf.float32) x = tf.matmul(x, w) s = sx * weight_scale x = x * s return x, x_max, x_min def maxpool_2d(x, k=2, s=2, padding='VALID'):
64
64
55
20
43
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
maxpool_2d
maxpool_2d
64
65
64
64
3af4c9b9b7a387970b5143d56b54798dbaaad61d
bigcode/the-stack
train
f6bce45e90b503b0098e56dc
train
function
def generate_global_max_min(): global_max, global_min = [],[] for i in range(16): global_max.append(float("-inf")) global_min.append(float("inf")) return global_max,global_min
def generate_global_max_min():
global_max, global_min = [],[] for i in range(16): global_max.append(float("-inf")) global_min.append(float("inf")) return global_max,global_min
) yield im, label def top5_acc(pred, k=5): Inf = 0. results = [] for i in range(k): results.append(pred.index(max(pred))) pred[pred.index(max(pred))] = Inf return results def generate_global_max_min():
64
64
47
6
57
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
generate_global_max_min
generate_global_max_min
266
271
266
266
054765d071a08fe51e6c200398d234baac111a10
bigcode/the-stack
train
34daf65ef36a7cadbaf744c6
train
function
def get_weights_biases(weights, weight_name, bias_name='bbb', quant=True): w = weights[weight_name] if quant: w, s = quantize_weights(w) w = tf.constant(w, dtype=tf.float32) else: w = tf.constant(weights[weight_name], dtype=tf.float32) s = 1.0 try: b = tf.constant...
def get_weights_biases(weights, weight_name, bias_name='bbb', quant=True):
w = weights[weight_name] if quant: w, s = quantize_weights(w) w = tf.constant(w, dtype=tf.float32) else: w = tf.constant(weights[weight_name], dtype=tf.float32) s = 1.0 try: b = tf.constant(weights[bias_name], dtype=tf.float32) except: b = None ret...
(abs_weights) s = vmax / 127. qweights = weights / s qweights = np.round(qweights) qweights = qweights.astype(np.int8) return qweights, s def get_weights_biases(weights, weight_name, bias_name='bbb', quant=True):
64
64
112
18
45
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
get_weights_biases
get_weights_biases
80
92
80
80
63e94bbacad5a0eea1ff2824d7c4a2b5e41d6e29
bigcode/the-stack
train
26a29045c9e93c04fa4b14aa
train
function
def conv_2d(x, w,quant, calibrate, x_max = [], x_min= [], weight_scale=0., activation_scale=1, strides=1, padding='SAME', dilations=[1,1,1,1]): if calibrate: x_max.append(tf.reduce_max(x)) x_min.append(tf.reduce_min(x)) x = tf.nn.conv2d(x, w, strides=[1, strides, strides, 1...
def conv_2d(x, w,quant, calibrate, x_max = [], x_min= [], weight_scale=0., activation_scale=1, strides=1, padding='SAME', dilations=[1,1,1,1]):
if calibrate: x_max.append(tf.reduce_max(x)) x_min.append(tf.reduce_min(x)) x = tf.nn.conv2d(x, w, strides=[1, strides, strides, 1], padding=padding, dilations=dilations) if quant: x, sx = quantize_tensor(x,activation_scale) x = tf.cast(x, dtype=tf.float32) ...
127.0) return x,s def conv_2d(x, w,quant, calibrate, x_max = [], x_min= [], weight_scale=0., activation_scale=1, strides=1, padding='SAME', dilations=[1,1,1,1]):
64
64
199
55
8
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
conv_2d
conv_2d
22
37
22
24
c86f0a585479a1d541108d95ec9f8d68021609be
bigcode/the-stack
train
9ced891631bdd244f5d54550
train
function
def get_conv_weights_biases(weights, conv_quant,weight_name, bias_name='bbb', quant=True): w = weights[weight_name] if quant: w, s = quantize_conv_weights(w,conv_quant) w = tf.constant(w, dtype=tf.float32) else: w = tf.constant(weights[weight_name], dtype=tf.float32) s = 1.0 ...
def get_conv_weights_biases(weights, conv_quant,weight_name, bias_name='bbb', quant=True):
w = weights[weight_name] if quant: w, s = quantize_conv_weights(w,conv_quant) w = tf.constant(w, dtype=tf.float32) else: w = tf.constant(weights[weight_name], dtype=tf.float32) s = 1.0 try: b = tf.constant(weights[bias_name], dtype=tf.float32) except: ...
s = vmax / 127. qweights = weights / s qweights = np.round(qweights) qweights = qweights.astype(np.int8) return qweights, s def get_conv_weights_biases(weights, conv_quant,weight_name, bias_name='bbb', quant=True):
64
64
120
22
41
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
get_conv_weights_biases
get_conv_weights_biases
121
133
121
121
a490db772a75df420f664d7ebc7ce13b0d51143e
bigcode/the-stack
train
a81979e06d5b427ae376ca49
train
function
def get_final_max_and_min(all_global_max, all_global_min, method= 'absolute'): if method == 'absolute': global_max, global_min = [], [] d_max = np.array([float("-inf") for i in all_global_max[0]]) d_min = np.array([float("inf") for i in all_global_min[0]]) for j in range(len(...
def get_final_max_and_min(all_global_max, all_global_min, method= 'absolute'):
if method == 'absolute': global_max, global_min = [], [] d_max = np.array([float("-inf") for i in all_global_max[0]]) d_min = np.array([float("inf") for i in all_global_min[0]]) for j in range(len(all_global_max[0])): for i in range(len(all_global_max)): ...
")) global_min.append(float("inf")) return global_max,global_min def collect_stats(all_global_max,all_global_min,max_x, min_x): all_global_max.append(max_x) all_global_min.append(min_x) return all_global_max, all_global_min def get_final_max_and_min(all_global_max, all_global_min, me...
81
81
271
20
60
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
get_final_max_and_min
get_final_max_and_min
281
310
281
282
ca79cfc09a00062ea7c9f3467c92ac7ef29b8e24
bigcode/the-stack
train
fe2f0c2a60012e331c961f66
train
function
def VGG16(x, weights, quant, calibrate, activation_scales,conv_quant): x_max,x_min = [],[] x = tf.reshape(x, shape=[-1, 224, 224, 3]) # block 1 w, b, s = get_conv_weights_biases(weights,conv_quant, 'block1_conv1_W_1:0', 'block1_conv1_b_1:0', quant) x,x_max,x_min = conv_2d(x, w,qu...
def VGG16(x, weights, quant, calibrate, activation_scales,conv_quant):
x_max,x_min = [],[] x = tf.reshape(x, shape=[-1, 224, 224, 3]) # block 1 w, b, s = get_conv_weights_biases(weights,conv_quant, 'block1_conv1_W_1:0', 'block1_conv1_b_1:0', quant) x,x_max,x_min = conv_2d(x, w,quant,calibrate, x_max,x_min,s,activation_scales[0]) x = bias_and_activati...
scales = np.array(s) qweights = np.divide(weights,scales) qweights = np.round(qweights) qweights = qweights.astype(np.int8) return qweights,scales if conv_quant == 'per_layer': abs_weights = np.abs(weights) vmax = np.max(abs_weights) s =...
256
256
1,576
21
234
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
VGG16
VGG16
136
226
136
137
8beebbeba1c85efde7456766c1e32a9c0059a602
bigcode/the-stack
train
3efff3327b050733be91c64b
train
function
def quantize_weights(weights): abs_weights = np.abs(weights) vmax = np.max(abs_weights) s = vmax / 127. qweights = weights / s qweights = np.round(qweights) qweights = qweights.astype(np.int8) return qweights, s
def quantize_weights(weights):
abs_weights = np.abs(weights) vmax = np.max(abs_weights) s = vmax / 127. qweights = weights / s qweights = np.round(qweights) qweights = qweights.astype(np.int8) return qweights, s
padding=padding) def avgpool_2d(x, k=2, s=1, padding='VALID'): return tf.nn.avg_pool(x, ksize=[1, k, k, 1], strides=[1, s, s,1],padding=padding) def quantize_weights(weights):
64
64
65
6
58
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
quantize_weights
quantize_weights
70
77
70
70
f69604eccaf555ae5067d986be36759040d4615b
bigcode/the-stack
train
7372febc1a22d67a715d6efc
train
function
def denselayer(x,w,quant,calibrate,x_max=[],x_min=[],weight_scale=0.,activation_scale=1.): if calibrate: x_max.append(tf.reduce_max(x)) x_min.append(tf.reduce_min(x)) x = tf.matmul(x, w) if quant: x, sx = quantize_tensor(x,activation_scale) x = tf.cast(x, dtype=t...
def denselayer(x,w,quant,calibrate,x_max=[],x_min=[],weight_scale=0.,activation_scale=1.):
if calibrate: x_max.append(tf.reduce_max(x)) x_min.append(tf.reduce_min(x)) x = tf.matmul(x, w) if quant: x, sx = quantize_tensor(x,activation_scale) x = tf.cast(x, dtype=tf.float32) x = tf.matmul(x, w) s = sx * weight_scale x = x * s ...
if b is not None: x = tf.nn.bias_add(x, b) if activation == 'relu': x = tf.nn.relu(x) return x def denselayer(x,w,quant,calibrate,x_max=[],x_min=[],weight_scale=0.,activation_scale=1.):
64
64
124
28
35
krishnateja95/Quantization-Test_bed
Vgg16.py
Python
denselayer
denselayer
48
61
48
48
8ee9a2b15f7eff85d2101b6c991879cf880da723
bigcode/the-stack
train
932a20402761eedecb2d18d0
train
class
class OsJsonFile(_FileBasic): @classmethod def read(cls, fileString, encoding=None): if cls.MTD_os_path.isfile(fileString): with open(fileString) as j: raw = cls.MOD_json.load(j, encoding=encoding) j.close() return raw @classmethod def...
class OsJsonFile(_FileBasic): @classmethod
def read(cls, fileString, encoding=None): if cls.MTD_os_path.isfile(fileString): with open(fileString) as j: raw = cls.MOD_json.load(j, encoding=encoding) j.close() return raw @classmethod def write(cls, fileString, raw, indent=4, ensure_a...
lines(cls, fileString): if bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString): with cls.MOD_gzip.GzipFile( mode=u'rb', fileobj=open(fileString, u'rb') ) as g: raw = g.readlines() g.close() return ra...
84
84
283
12
71
no7hings/Lynxi
workspace/module/python-2.7/LxBasic/bscMethods/_bscMtdFile.py
Python
OsJsonFile
OsJsonFile
349
392
349
350
3385f1220fabd9002692b9dad901387a47d7bc2a
bigcode/the-stack
train
5a6a12d6249dd0032b8e404f
train
class
class OsImage(_FileBasic): module_fullpath_name = 'PIL.Image' @classmethod def _toPImage(cls, fileString): module = bscMtdCore.Mtd_BscUtility._bsc_mtd__set_python_module_load_(cls.module_fullpath_name) if module: if bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString): ...
class OsImage(_FileBasic):
module_fullpath_name = 'PIL.Image' @classmethod def _toPImage(cls, fileString): module = bscMtdCore.Mtd_BscUtility._bsc_mtd__set_python_module_load_(cls.module_fullpath_name) if module: if bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString): return module.open(fi...
cls.MOD_json.dump( raw, g, indent=indent, ensure_ascii=ensure_ascii ) # g.close() # bscMtdCore.Mtd_BscUtility._setOsFileCopy(temporaryName, fileString) class OsImage(_FileBasic):
64
64
163
7
57
no7hings/Lynxi
workspace/module/python-2.7/LxBasic/bscMethods/_bscMtdFile.py
Python
OsImage
OsImage
428
447
428
428
71f669b8cf97fa726d5579949670d1393c10c086
bigcode/the-stack
train
cbd8e3d9e8280e382292977c
train
class
class OsJsonGzip(_FileBasic): @classmethod def read(cls, fileString, encoding=None): if bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString): with cls.MOD_gzip.GzipFile( mode=u'rb', fileobj=open(fileString, u'rb') ) as g: ra...
class OsJsonGzip(_FileBasic): @classmethod
def read(cls, fileString, encoding=None): if bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString): with cls.MOD_gzip.GzipFile( mode=u'rb', fileobj=open(fileString, u'rb') ) as g: raw = cls.MOD_json.load(g, encoding=encoding) ...
for k, v in dic.items(): dic_[k] = v # cls.write(fileString, dic) @classmethod def load(cls, raw): return cls.MOD_json.loads(raw) @classmethod def dump(cls, raw): return cls.MOD_json.dumps(raw) class OsJsonGzip(_FileBasic): @classmethod
77
77
259
13
64
no7hings/Lynxi
workspace/module/python-2.7/LxBasic/bscMethods/_bscMtdFile.py
Python
OsJsonGzip
OsJsonGzip
395
425
395
396
81a306387f565aedd864af0972941dca126cc2a0
bigcode/the-stack
train
b46697f1672e0b55bc3d2b5f
train
class
class OsFileGzip(_FileBasic): @classmethod def write(cls, fileString, raw): bscMtdCore.Mtd_BscUtility._bsc_mtd__os_path__set_file_directory_create_(fileString) # osFileBasename = bscMtdCore.Mtd_BscUtility._getOsFileBasename(fileString) # with cls.MOD_gzip.GzipFile( ...
class OsFileGzip(_FileBasic): @classmethod
def write(cls, fileString, raw): bscMtdCore.Mtd_BscUtility._bsc_mtd__os_path__set_file_directory_create_(fileString) # osFileBasename = bscMtdCore.Mtd_BscUtility._getOsFileBasename(fileString) # with cls.MOD_gzip.GzipFile( filename=osFileBasename, ...
raw = f.read() f.close() return raw @classmethod def readlines(cls, fileString): if bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString): with open(fileString, u'rb') as f: raw = f.readlines() f.close() ...
87
87
291
13
73
no7hings/Lynxi
workspace/module/python-2.7/LxBasic/bscMethods/_bscMtdFile.py
Python
OsFileGzip
OsFileGzip
310
346
310
311
fe49ce429992e8a81316dd1fb02bc29873a27836
bigcode/the-stack
train
891d379308bd7a700015efb9
train
class
class OsMultifile(bscMtdCore.Mtd_BscBasic): DEF_placeholder_multifile_list = ['<udim>', '%04d', '<f>', '####'] VAR_padding_multifile = 4 @classmethod def _getOsFileFrame(cls, fileString, paddingValue): lis = cls.MOD_re.findall( '[0-9]'*paddingValue, bscMtdCore.Mtd_BscUti...
class OsMultifile(bscMtdCore.Mtd_BscBasic):
DEF_placeholder_multifile_list = ['<udim>', '%04d', '<f>', '####'] VAR_padding_multifile = 4 @classmethod def _getOsFileFrame(cls, fileString, paddingValue): lis = cls.MOD_re.findall( '[0-9]'*paddingValue, bscMtdCore.Mtd_BscUtility._getOsFileBasename(fileString) ...
=9, fileobj=open(temporaryName, u'wb') ) as g: cls.MOD_json.dump( raw, g, indent=indent, ensure_ascii=ensure_ascii ) # g.close() # bscMtdCore.Mtd_BscUtility._setOsFileC...
256
256
1,280
16
239
no7hings/Lynxi
workspace/module/python-2.7/LxBasic/bscMethods/_bscMtdFile.py
Python
OsMultifile
OsMultifile
450
565
450
450
25be9b2a719ae058c865e98cf75535e08e125d20
bigcode/the-stack
train
9822152dd65e1132de90b7ca
train
class
class _FileBasic(bscMtdCore.Mtd_BscBasic): @classmethod def isExist(cls, fileString): return bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString) @classmethod def createDirectory(cls, fileString): bscMtdCore.Mtd_BscUtility._bsc_mtd__os_path__set_file_directory_create_(fileString) @...
class _FileBasic(bscMtdCore.Mtd_BscBasic): @classmethod
def isExist(cls, fileString): return bscMtdCore.Mtd_BscUtility._isOsFileExist(fileString) @classmethod def createDirectory(cls, fileString): bscMtdCore.Mtd_BscUtility._bsc_mtd__os_path__set_file_directory_create_(fileString) @classmethod def name(cls, fileString): return bs...
# coding:utf-8 from LxBasic import bscMtdCore class _FileBasic(bscMtdCore.Mtd_BscBasic): @classmethod
36
256
2,812
19
16
no7hings/Lynxi
workspace/module/python-2.7/LxBasic/bscMethods/_bscMtdFile.py
Python
_FileBasic
_FileBasic
5
278
5
6
36cc1c77f3c3d6ae8a5b0013d0e4a023f1e19a39
bigcode/the-stack
train
a4540283f656758b72e35559
train
class
class OsFile(_FileBasic): @classmethod def write(cls, fileString, raw): bscMtdCore.Mtd_BscUtility._bsc_mtd__os_path__set_file_directory_create_(fileString) with open(fileString, u'wb') as f: if isinstance(raw, (str, unicode)): f.write(raw) elif isinstance(...
class OsFile(_FileBasic): @classmethod
def write(cls, fileString, raw): bscMtdCore.Mtd_BscUtility._bsc_mtd__os_path__set_file_directory_create_(fileString) with open(fileString, u'wb') as f: if isinstance(raw, (str, unicode)): f.write(raw) elif isinstance(raw, (tuple, list)): f.writ...
._setOsJsonWrite( osVersionFile, { bscMtdCore.Mtd_BscUtility._getSystemActiveTimestamp(): bscMtdCore.Mtd_BscUtility._getOsFileBasename(targetFileString) } ) class OsFile(_FileBasic): @classmethod
65
65
217
11
54
no7hings/Lynxi
workspace/module/python-2.7/LxBasic/bscMethods/_bscMtdFile.py
Python
OsFile
OsFile
281
307
281
282
674b0d5c485fdc5b7c712d79bc4bcf168b019392
bigcode/the-stack
train
a7e9164e8340d1a2fd9f2b09
train
class
class StreamPause: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.pause = False self._pause_generator = None self._pause_cr = None def set_pause_generator(self, generator=None): if self._pause_cr is not None: self._pause_cr.kill(...
class StreamPause:
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.pause = False self._pause_generator = None self._pause_cr = None def set_pause_generator(self, generator=None): if self._pause_cr is not None: self._pause_cr.kill() self....
(): self.idle_event.set() else: self.log.info("Reset de-asserted") if self._run_cr is None: self._run_cr = cocotb.start_soon(self._run()) async def _run(self): raise NotImplementedError() class StreamPause:
64
64
172
4
60
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
StreamPause
StreamPause
162
188
162
162
7c93b0fd9470ad1f6674c5c387d37bc13d87b098
bigcode/the-stack
train
26b334e5c68b7ad3d47eba31
train
function
def define_stream(name, signals, optional_signals=None, valid_signal=None, ready_signal=None, signal_widths=None): all_signals = signals.copy() if optional_signals is None: optional_signals = [] else: all_signals += optional_signals if valid_signal is None: for s in all_signals...
def define_stream(name, signals, optional_signals=None, valid_signal=None, ready_signal=None, signal_widths=None):
all_signals = signals.copy() if optional_signals is None: optional_signals = [] else: all_signals += optional_signals if valid_signal is None: for s in all_signals: if s.lower().endswith('valid'): valid_signal = s if valid_signal not in all_signa...
clock_edge_event = RisingEdge(self.clock) while True: await clock_edge_event # read handshake signals ready_sample = self.ready is None or self.ready.value valid_sample = self.valid is None or self.valid.value if ready_sample and valid_sample: ...
135
135
452
25
110
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
define_stream
define_stream
350
411
350
350
4dd2e09a7e0398a2d6a632ac35617d45a9daafe2
bigcode/the-stack
train
607909bfbb6c3144b9f11fe1
train
class
class StreamMonitor(StreamBase): _init_x = False _valid_init = None _ready_init = None def _recv(self, item): if self.queue.empty(): self.active_event.clear() return item async def recv(self): item = await self.queue.get() return self._recv(item) ...
class StreamMonitor(StreamBase):
_init_x = False _valid_init = None _ready_init = None def _recv(self, item): if self.queue.empty(): self.active_event.clear() return item async def recv(self): item = await self.queue.get() return self._recv(item) def recv_nowait(self): ite...
_event.set() if self.valid is not None: self.valid.value = 1 self.active = True else: if self.valid is not None: self.valid.value = 0 self.active = not self.queue.empty() ...
72
72
241
6
66
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
StreamMonitor
StreamMonitor
260
302
260
261
bf9f31ea40363d3d98649a86dbd4c29483a0de3a
bigcode/the-stack
train
99fd52c4b1aadf6abdb0ecc3
train
class
class StreamTransaction: _signals = ["data"] def __init__(self, *args, **kwargs): for sig in self._signals: if sig in kwargs: setattr(self, sig, kwargs[sig]) del kwargs[sig] else: setattr(self, sig, 0) super().__init__(*a...
class StreamTransaction:
_signals = ["data"] def __init__(self, *args, **kwargs): for sig in self._signals: if sig in kwargs: setattr(self, sig, kwargs[sig]) del kwargs[sig] else: setattr(self, sig, 0) super().__init__(*args, **kwargs) def __...
als=self._optional_signals, **kwargs) @classmethod def from_entity(cls, entity, **kwargs): return cls(entity, **kwargs) @classmethod def from_prefix(cls, entity, prefix, **kwargs): return cls(entity, prefix, **kwargs) class StreamTransaction:
64
64
119
4
60
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
StreamTransaction
StreamTransaction
52
67
52
53
c521f9cab1108aea09bd208adc9d4b86e279ae06
bigcode/the-stack
train
0aca18ccd1574e155b381c35
train
class
class StreamBus(Bus): _signals = ["data"] _optional_signals = [] def __init__(self, entity=None, prefix=None, **kwargs): super().__init__(entity, prefix, self._signals, optional_signals=self._optional_signals, **kwargs) @classmethod def from_entity(cls, entity, **kwargs): return c...
class StreamBus(Bus):
_signals = ["data"] _optional_signals = [] def __init__(self, entity=None, prefix=None, **kwargs): super().__init__(entity, prefix, self._signals, optional_signals=self._optional_signals, **kwargs) @classmethod def from_entity(cls, entity, **kwargs): return cls(entity, **kwargs) ...
OTHER DEALINGS IN THE SOFTWARE. """ import logging import cocotb from cocotb.queue import Queue, QueueFull from cocotb.triggers import RisingEdge, Event, First, Timer from cocotb_bus.bus import Bus from .reset import Reset class StreamBus(Bus):
64
64
111
6
57
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
StreamBus
StreamBus
35
49
35
36
31fa31bcc6c663d5985d7ad2bddc0ae6e3290d58
bigcode/the-stack
train
2d8ce0567ebb6d99f27b7c12
train
class
class StreamBase(Reset): _signals = ["data", "valid", "ready"] _optional_signals = [] _signal_widths = {"valid": 1, "ready": 1} _init_x = False _valid_signal = "valid" _valid_init = None _ready_signal = "ready" _ready_init = None _transaction_obj = StreamTransaction _bus_obj...
class StreamBase(Reset):
_signals = ["data", "valid", "ready"] _optional_signals = [] _signal_widths = {"valid": 1, "ready": 1} _init_x = False _valid_signal = "valid" _valid_init = None _ready_signal = "ready" _ready_init = None _transaction_obj = StreamTransaction _bus_obj = StreamBus def __in...
self._signals, optional_signals=self._optional_signals, **kwargs) @classmethod def from_entity(cls, entity, **kwargs): return cls(entity, **kwargs) @classmethod def from_prefix(cls, entity, prefix, **kwargs): return cls(entity, prefix, **kwargs) class StreamTransaction: _signal...
191
191
638
6
185
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
StreamBase
StreamBase
70
159
70
71
ba112f7a056dd8c3d9dcb713365a17791c33aa6c
bigcode/the-stack
train
2ba7a2decaae7e723b811faa
train
class
class StreamSource(StreamBase, StreamPause): _init_x = True _valid_init = 0 _ready_init = None def __init__(self, bus, clock, reset=None, reset_active_level=True, *args, **kwargs): super().__init__(bus, clock, reset, reset_active_level, *args, **kwargs) self.queue_occupancy_limit = -...
class StreamSource(StreamBase, StreamPause):
_init_x = True _valid_init = 0 _ready_init = None def __init__(self, bus, clock, reset=None, reset_active_level=True, *args, **kwargs): super().__init__(bus, clock, reset, reset_active_level, *args, **kwargs) self.queue_occupancy_limit = -1 async def send(self, obj): whil...
_pause_generator(self, generator=None): if self._pause_cr is not None: self._pause_cr.kill() self._pause_cr = None self._pause_generator = generator if self._pause_generator is not None: self._pause_cr = cocotb.start_soon(self._run_pause()) def clear_pa...
129
129
432
9
119
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
StreamSource
StreamSource
191
257
191
192
90fc93cdfa31422913abadd8374339ad15571ee2
bigcode/the-stack
train
f984b0990e45472687bbd0ac
train
class
class StreamSink(StreamMonitor, StreamPause): _init_x = False _valid_init = None _ready_init = 0 def __init__(self, bus, clock, reset=None, reset_active_level=True, *args, **kwargs): super().__init__(bus, clock, reset, reset_active_level, *args, **kwargs) self.queue_occupancy_limit =...
class StreamSink(StreamMonitor, StreamPause):
_init_x = False _valid_init = None _ready_init = 0 def __init__(self, bus, clock, reset=None, reset_active_level=True, *args, **kwargs): super().__init__(bus, clock, reset, reset_active_level, *args, **kwargs) self.queue_occupancy_limit = -1 def full(self): if self.queue_...
: await clock_edge_event # read handshake signals ready_sample = self.ready is None or self.ready.value valid_sample = self.valid is None or self.valid.value if ready_sample and valid_sample: obj = self._transaction_obj() self...
84
84
282
9
75
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
Python
StreamSink
StreamSink
305
347
305
306
7eee70e67089a45c644ed3f53af9bf7366e18100
bigcode/the-stack
train
902dc1331211fa5f83450015
train
function
def xirr(cashflows, guess=0.1): """ calculate the Internal Rate of Return of a series of cashflows at irregular intervals. :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash...
def xirr(cashflows, guess=0.1):
""" calculate the Internal Rate of Return of a series of cashflows at irregular intervals. :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investments) are repr...
: x[0]) t0 = chron_order[0][0] return sum([cf / (1 + rate) ** ((t - t0).days / 365.0) for (t, cf) in chron_order]) def xirr(cashflows, guess=0.1):
64
64
161
13
51
Rico358097990/xalpha
xalpha/cons.py
Python
xirr
xirr
502
514
502
502
1b0474d3158b7fa42fe7dbc4d2d53bf86ac565db
bigcode/the-stack
train
02d62345f96fc82b15e48c82
train
function
def myround(num, label=1): """ correct implementation of round with round half up, round to 2 decimals :param num: the floating number, to be rounded :param label: integer 1 or 2, 1 for round half up while 2 for always round down :returns: the float number after rounding, with two decimals """ ...
def myround(num, label=1):
""" correct implementation of round with round half up, round to 2 decimals :param num: the floating number, to be rounded :param label: integer 1 or 2, 1 for round half up while 2 for always round down :returns: the float number after rounding, with two decimals """ if label == 1: ...
a guess at the xirr rate solution to be used as a starting point for the numerical solution :returns: the IRR as a single floating number """ return optimize.newton(lambda r: xnpv(r, cashflows), guess) def myround(num, label=1):
64
64
174
9
55
Rico358097990/xalpha
xalpha/cons.py
Python
myround
myround
517
533
517
517
fef3fa800af698b4032d01421ed176f865e5958a
bigcode/the-stack
train
76faa9afef70b502d77e2a59
train
function
def today_obj(): """ today obj in beijing timezone with no tzinfo :return: datetime.datetime """ now = dt.datetime.now(tz=tz_bj) return now.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None)
def today_obj():
""" today obj in beijing timezone with no tzinfo :return: datetime.datetime """ now = dt.datetime.now(tz=tz_bj) return now.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None)
VisualMapOpts, ) from scipy import optimize from xalpha import __path__ logger = logging.getLogger(__name__) # date obj of today # today = lambda: dt.datetime.combine(dt.date.today(), dt.time.min) tz_bj = dt.timezone(dt.timedelta(hours=8)) def today_obj():
64
64
67
4
60
Rico358097990/xalpha
xalpha/cons.py
Python
today_obj
today_obj
36
43
36
36
6195703bc7660cf56fbf2b13c887ee8e32e40a57
bigcode/the-stack
train
063b6ecc207f181e0a56484b
train
function
def next_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj += dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj += dt.timedelta(1) return dtobj
def next_onday(dtobj):
dtobj = _date_check(dtobj, check=True) dtobj += dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj += dt.timedelta(1) return dtobj
if check and (dtobj.year > dt.datetime.now().year or dtobj.year < 1991): raise ValueError( "date goes beyond market range: %s" % dtobj.strftime("%Y-%m-%d") ) return dtobj def next_onday(dtobj):
64
64
62
7
56
Rico358097990/xalpha
xalpha/cons.py
Python
next_onday
next_onday
559
564
559
559
3e0431a7888fe30dfdb477c5596f687af1d958b0
bigcode/the-stack
train
ee6bb9bb64008c3bfd9efb16
train
function
@reconnect() def rpost_json(*args, **kws): r = requests.post(*args, **kws) return r.json()
@reconnect() def rpost_json(*args, **kws):
r = requests.post(*args, **kws) return r.json()
rget = reconnect()(requests.get) rpost = reconnect()(requests.post) @reconnect() def rget_json(*args, **kws): r = requests.get(*args, **kws) return r.json() @reconnect() def rpost_json(*args, **kws):
64
64
32
15
49
Rico358097990/xalpha
xalpha/cons.py
Python
rpost_json
rpost_json
665
668
665
666
26055c7fc283dcd8b1ee5c20556a33573d4da6c0
bigcode/the-stack
train
f35f1a79396d9cc8d126082e
train
function
def scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None): t = sum([v for _, v in d.items()]) if t * scale > ulimit: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d
def scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None):
t = sum([v for _, v in d.items()]) if t * scale > ulimit: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d
) dtobj -= dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate: dtobj -= dt.timedelta(1) return dtobj def scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None):
64
64
102
22
41
Rico358097990/xalpha
xalpha/cons.py
Python
scale_dict
scale_dict
575
585
575
575
f847a7240f7f6765cb0b02c0cc831dac764b6ebb
bigcode/the-stack
train
f4afd4048f7baaf3ff0a2139
train
function
def convert_date(date): """ convert date into datetime object :param date: string of form '2017-01-01' or datetime object :returns: corresponding datetime object """ if isinstance(date, str): return pd.Timestamp(date) else: return date
def convert_date(date):
""" convert date into datetime object :param date: string of form '2017-01-01' or datetime object :returns: corresponding datetime object """ if isinstance(date, str): return pd.Timestamp(date) else: return date
) elif ( label == 2 ): # for jingshunchangcheng... who just omit the overflow share behind 2 decimal res = float(Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_DOWN")) return res def convert_date(date):
64
64
64
5
58
Rico358097990/xalpha
xalpha/cons.py
Python
convert_date
convert_date
536
546
536
536
853450c7925df3e79fb9793ef7af20c7727d4302
bigcode/the-stack
train
c5c6b4bf9af7ee26136eeee7
train
function
def _date_check(dtobj, check=False): if not isinstance(dtobj, dt.datetime): dtobj = dt.datetime.strptime(dtobj.replace("/", "").replace("-", ""), "%Y%m%d") if check and (dtobj.year > dt.datetime.now().year or dtobj.year < 1991): raise ValueError( "date goes beyond market range: %s" %...
def _date_check(dtobj, check=False):
if not isinstance(dtobj, dt.datetime): dtobj = dt.datetime.strptime(dtobj.replace("/", "").replace("-", ""), "%Y%m%d") if check and (dtobj.year > dt.datetime.now().year or dtobj.year < 1991): raise ValueError( "date goes beyond market range: %s" % dtobj.strftime("%Y-%m-%d") )...
into datetime object :param date: string of form '2017-01-01' or datetime object :returns: corresponding datetime object """ if isinstance(date, str): return pd.Timestamp(date) else: return date def _date_check(dtobj, check=False):
64
64
97
10
53
Rico358097990/xalpha
xalpha/cons.py
Python
_date_check
_date_check
549
556
549
549
12ab29f4ea8657e2ca7ae6ae8d28e79db68f36b2
bigcode/the-stack
train
f2017a777f167848b0880ba3
train
function
def last_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj -= dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate: dtobj -= dt.timedelta(1) return dtobj
def last_onday(dtobj):
dtobj = _date_check(dtobj, check=True) dtobj -= dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate: dtobj -= dt.timedelta(1) return dtobj
obj): dtobj = _date_check(dtobj, check=True) dtobj += dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj += dt.timedelta(1) return dtobj def last_onday(dtobj):
64
64
61
7
56
Rico358097990/xalpha
xalpha/cons.py
Python
last_onday
last_onday
567
572
567
567
0d0620f9e45c0ccc9f142fb41a97e167a23817a1
bigcode/the-stack
train
ef7b4e9f220e6618367e9473
train
function
@reconnect() def rget_json(*args, **kws): r = requests.get(*args, **kws) return r.json()
@reconnect() def rget_json(*args, **kws):
r = requests.get(*args, **kws) return r.json()
to %s" % e.args[0]) raise e time.sleep(0.5 * count) return wrapper return robustify rget = reconnect()(requests.get) rpost = reconnect()(requests.post) @reconnect() def rget_json(*args, **kws):
64
64
32
15
49
Rico358097990/xalpha
xalpha/cons.py
Python
rget_json
rget_json
659
662
659
660
dd32861426acab03012a0a17ce22fd47035d3581
bigcode/the-stack
train
cb730a063465c32bae21eb69
train
function
def xnpv(rate, cashflows): """ give the current cash value based on future cashflows :param rate: float, the preset year rate :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. ...
def xnpv(rate, cashflows):
""" give the current cash value based on future cashflows :param rate: float, the preset year rate :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investmen...
Opts(type_="time"), "datazoom_opts": [DataZoomOpts(range_start=60, range_end=100)], "tooltip_opts": TooltipOpts(trigger_on="mousemove", trigger="item"), "legend_opts": LegendOpts(pos_top="top"), } def xnpv(rate, cashflows):
64
64
185
9
55
Rico358097990/xalpha
xalpha/cons.py
Python
xnpv
xnpv
486
499
486
486
f6e1320138c229c51feb541ca33bf68488e0d9f8
bigcode/the-stack
train
d798ac0cd4aac2e0e8e2ba30
train
function
def _float(n): try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): ...
def _float(n):
try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): n = ...
: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d def _float(n):
64
64
209
5
58
Rico358097990/xalpha
xalpha/cons.py
Python
_float
_float
588
608
588
588
a907b9108701ab24d21d6179058c0eea6d8052f4
bigcode/the-stack
train
aa1fb8393cf018faa029c8fa
train
function
def calendar_selfcheck(): # 国内链接 githubusercontent.com 大概率存在问题,因此设计成联网自动更新日历大概率无用。 # 也许之后考虑一些较稳定的第三方资源托管服务 current_year = dt.datetime.now().year if str(current_year) != opendate[-1][:4]: logger.warning( "Please update xalpha via `pip install -U xalpha` to keep the trade calendar up-t...
def calendar_selfcheck(): # 国内链接 githubusercontent.com 大概率存在问题,因此设计成联网自动更新日历大概率无用。 # 也许之后考虑一些较稳定的第三方资源托管服务
current_year = dt.datetime.now().year if str(current_year) != opendate[-1][:4]: logger.warning( "Please update xalpha via `pip install -U xalpha` to keep the trade calendar up-to-date" ) print("请更新 xalpha 版本以更新最新年份的 A 股交易日历, 否则将可能无法正确获取和处理最新的基金净值")
["003318", "000311", "000601", "009989"] def calendar_selfcheck(): # 国内链接 githubusercontent.com 大概率存在问题,因此设计成联网自动更新日历大概率无用。 # 也许之后考虑一些较稳定的第三方资源托管服务
63
64
138
47
16
Rico358097990/xalpha
xalpha/cons.py
Python
calendar_selfcheck
calendar_selfcheck
66
74
66
68
d709ae29367423d19457c686d16b892add9f8991
bigcode/the-stack
train
34f542dce673c1e265daf252
train
function
def reconnect(tries=5, timeout=12): def robustify(f): @wraps(f) def wrapper(*args, **kws): import xalpha.provider as xp if getattr(xp, "proxy", None): kws["proxies"] = {"http": xp.proxy, "https": xp.proxy} kws["timeout"] = timeout ...
def reconnect(tries=5, timeout=12):
def robustify(f): @wraps(f) def wrapper(*args, **kws): import xalpha.provider as xp if getattr(xp, "proxy", None): kws["proxies"] = {"http": xp.proxy, "https": xp.proxy} kws["timeout"] = timeout logger.debug("Using proxy %s" % ...
"-": logger.info("_float met -, taken as 0") return 0 elif n.endswith("%"): logger.info("_float met with %% as %s" % n) return float(n[:-1]) / 100 except AttributeError: pass if not n: logger.info("_float met with None as input arguments")...
99
99
332
11
88
Rico358097990/xalpha
xalpha/cons.py
Python
reconnect
reconnect
611
652
611
611
bcfed018c9d8265e170b2a872bf43f8dda8db81a
bigcode/the-stack
train
64b656d3e6d97dd25a7306f5
train
class
class Sutha: """This class holds all control for the Hero Sutha's Deck""" def __init__(self): self.deck = deque( [Card("Divine Inspiration2",0,0,2,0,0,True), Card("Banishing Smite2",0,0,0,1,0,True), Card("Divine Smite2",3,0,1,0,0,False), Card("Fighting Words2",2,0...
class Sutha:
"""This class holds all control for the Hero Sutha's Deck""" def __init__(self): self.deck = deque( [Card("Divine Inspiration2",0,0,2,0,0,True), Card("Banishing Smite2",0,0,0,1,0,True), Card("Divine Smite2",3,0,1,0,0,False), Card("Fighting Words2",2,0,1,0,0,False)...
,2,False)] ) def lias_special(self, Opponent): pass def shuffle(self): #tic = time.perf_counter() temp_list = list(self.deck) random.shuffle(temp_list) self.deck = deque(temp_list) #toc = time.perf_counter() #print(f"Shuffled the deck in ...
121
121
405
4
117
luisdsantiago/dungeon-cardgame
heroes.py
Python
Sutha
Sutha
45
80
45
45
cca61294159e67b4018104219ce9df6118652c1b
bigcode/the-stack
train
d68225612bc38817a772e007
train
class
class Lia: """This class holds all control for the Hero Lia's Deck""" def __init__(self): self.deck = deque( [Card("Divine Inspiration",0,0,2,0,0,True), Card("Banishing Smite",0,0,0,1,0,True), Card("Divine Smite",3,0,1,0,0,False), Card("Fighting Words",2,0,1,0,0,F...
class Lia:
"""This class holds all control for the Hero Lia's Deck""" def __init__(self): self.deck = deque( [Card("Divine Inspiration",0,0,2,0,0,True), Card("Banishing Smite",0,0,0,1,0,True), Card("Divine Smite",3,0,1,0,0,False), Card("Fighting Words",2,0,1,0,0,False), ...
import random from collections import deque from dungeon_cardgame import Card class Lia:
18
116
389
3
14
luisdsantiago/dungeon-cardgame
heroes.py
Python
Lia
Lia
5
40
5
5
2b678da0e6b8bfd93f42c54683dd0eb1d6fb191b
bigcode/the-stack
train
dbfc80a02d1982131cc9850a
train
function
async def hello(): async with websockets.connect('ws://localhost:8765') as websocket: name = input("What's your name? ") await websocket.send(name) print(f'>{name}') greeting = await websocket.recv() print(f'< {greeting}')
async def hello():
async with websockets.connect('ws://localhost:8765') as websocket: name = input("What's your name? ") await websocket.send(name) print(f'>{name}') greeting = await websocket.recv() print(f'< {greeting}')
import asyncio import websockets async def hello():
11
64
58
4
6
syth0le/python-websockets
basic_usage/client.py
Python
hello
hello
5
13
5
5
9040a5c277cbe1a7c39e8c73e244d40fada8d7a8
bigcode/the-stack
train
7b15508f9d08cf0b0f9f15c9
train
class
class AQRemoveViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'base.html' self.view = views.AQRemoveView.as_view() ...
class AQRemoveViewTest(TestCase):
def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'base.html' self.view = views.AQRemoveView.as_view() self.request = HttpRequest() ...
_csrf(response.content.decode('utf-8')) self.assertEqual(response, rendered) def test_post_when_no_aq_project(self): AirQualityProject.objects.get(pk=self.aq_project.id).delete() self.request.user = self.superuser self.request.method = 'POST' self.request.POST = { ...
211
211
704
8
203
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQRemoveViewTest
AQRemoveViewTest
725
827
725
726
c4b848093caf00bc7ff80cf3ec80d1ffa8a2048e
bigcode/the-stack
train
459f3f069d88b092195a93e3
train
class
class AQProjectsAPIViewTest(TestCase): def setUp(self): self.contributor = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.url = '/api/airquality/projects/' self.factory = APIRequestFactory() self.request_get = self.factory....
class AQProjectsAPIViewTest(TestCase):
def setUp(self): self.contributor = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.url = '/api/airquality/projects/' self.factory = APIRequestFactory() self.request_get = self.factory.get(self.url) self.view = views....
.request_get, user=self.anonym) response = self.view(self.request_get).render() self.assertEqual(response.status_code, 403) def test_get_with_user(self): force_authenticate(self.request_get, user=self.user) response = self.view(self.request_get).render() self.assertEqual(...
146
146
488
8
138
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQProjectsAPIViewTest
AQProjectsAPIViewTest
1,121
1,190
1,121
1,122
ad5fd55506c15bbf0dc8667b8be44caabeec75d5
bigcode/the-stack
train
4a1e2a82b9ce770c641484fa
train
class
class AQSheetAPIViewTest(TestCase): def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.url = '/api/airquality/sheet/' self.factory = APIRequestFactory() self.request_get = self.factory.get(self.u...
class AQSheetAPIViewTest(TestCase):
def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.url = '/api/airquality/sheet/' self.factory = APIRequestFactory() self.request_get = self.factory.get(self.url) self.view = views.AQSheet...
_code, 404) def test_get_when_no_category(self): Category.objects.get(pk=self.category.id).delete() force_authenticate(self.request_get, user=self.superuser) response = self.view( self.request_get, project_id=self.project.id, category_id=self.category.id...
98
98
327
8
90
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQSheetAPIViewTest
AQSheetAPIViewTest
1,067
1,118
1,067
1,068
3640cb98b12581531b2d5f50a8db4c6003278df5
bigcode/the-stack
train
5f0320000e6ea2cfa9ed196f
train
class
class AQExportViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.view = views.AQExportView.as_view() self.request = HttpRequest() ...
class AQExportViewTest(TestCase):
def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.view = views.AQExportView.as_view() self.request = HttpRequest() self.request.method = 'GET' ...
'total_locations': 0, 'total_measurements': 0 } ) self.assertEqual(response.status_code, 200) response = render_helpers.remove_csrf(response.content.decode('utf-8')) self.assertEqual(response, rendered) class AQExportViewTest(TestCase):
64
64
204
8
56
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQExportViewTest
AQExportViewTest
126
157
126
127
f913910f8eb4a83c52f83b672706f06f1515a94a
bigcode/the-stack
train
98a8c46e0eeb71cc5f5f4cda
train
class
class AQLocationsSingleAPIViewTest(TestCase): def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.location = AirQualityLocationFactory.create(creator=self.creator) self.url = '/api/airquality/locations/%...
class AQLocationsSingleAPIViewTest(TestCase):
def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.location = AirQualityLocationFactory.create(creator=self.creator) self.url = '/api/airquality/locations/%s/' % self.location.id self.data = { ...
']), 0) def test_get_together_with_measurements(self): AirQualityMeasurementFactory.create( location=self.location_1, creator=self.location_1.creator ) AirQualityMeasurementFactory.create( location=self.location_2, creator=self.location_2.cre...
256
256
918
10
246
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQLocationsSingleAPIViewTest
AQLocationsSingleAPIViewTest
1,292
1,442
1,292
1,293
bd038d24179603f7426d81a25f6ddb2436b44628
bigcode/the-stack
train
6d191766f91be2295f3e1ecc
train
class
class AQMeasurementsAPIViewTest(TestCase): def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.location = AirQualityLocationFactory.create( creator=self.creator, properties={ ...
class AQMeasurementsAPIViewTest(TestCase):
def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.location = AirQualityLocationFactory.create( creator=self.creator, properties={ 'height': 2, 'distance': ...
() self.assertEqual(response.status_code, 204) self.assertEqual( AirQualityLocation.objects.filter(pk=self.location.id).exists(), False ) def test_delete_when_there_are_measurements(self): self.measurement_1 = AirQualityMeasurementFactory.create( ...
256
256
1,481
8
248
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQMeasurementsAPIViewTest
AQMeasurementsAPIViewTest
1,445
1,647
1,445
1,446
b69deddc9e5db7689901d82df6ce0ab84f5ed832
bigcode/the-stack
train
60c8d313a5fd7aa0b3ed061a
train
class
class AQProjectsSingleAjaxViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.creator = UserFactory.create(**{'is_superuser': False}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() ...
class AQProjectsSingleAjaxViewTest(TestCase):
def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.creator = UserFactory.create(**{'is_superuser': False}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.project = ProjectFactory.create(add_contr...
) self.assertEqual(response.status_code, 302) self.assertIn('/admin/airquality/', response['location']) self.assertEqual(AirQualityProject.objects.count(), 1) self.assertEqual(AirQualityCategory.objects.count(), 1) self.assertEqual(AirQualityField.objects.count(), 1) def t...
174
174
580
10
164
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQProjectsSingleAjaxViewTest
AQProjectsSingleAjaxViewTest
834
926
834
835
cff12f386205fdad609d821686e14b5d70c794f0
bigcode/the-stack
train
7e1e31eb7fc440d124f75ede
train
class
class AQLocationsAPIViewTest(TestCase): def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.url = '/api/airquality/locations/' self.data = { 'type': 'Feature', 'geometry': { ...
class AQLocationsAPIViewTest(TestCase):
def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.url = '/api/airquality/locations/' self.data = { 'type': 'Feature', 'geometry': { 'type': 'Point', ...
tributor(self): force_authenticate(self.request_get, user=self.contributor) response = self.view(self.request_get).render() projects = json.loads(response.content) self.assertEqual(response.status_code, 200) self.assertEqual(len(projects), 1) self.assertEqual(projects[0...
191
191
638
9
182
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQLocationsAPIViewTest
AQLocationsAPIViewTest
1,193
1,289
1,193
1,194
6dada032d5d30565077edc8e1ad3dbb11d603d8c
bigcode/the-stack
train
89b7c587d698cb6e209ddfc8
train
class
class AQAddViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'aq_add.html' self.view = views.AQAddView.as_view() ...
class AQAddViewTest(TestCase):
def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'aq_add.html' self.view = views.AQAddView.as_view() self.request = HttpRequest() ...
ments': 0 } ) self.assertEqual(response.status_code, 200) response = render_helpers.remove_csrf(response.content.decode('utf-8')) self.assertEqual(response, rendered) class AQExportViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is...
256
256
1,505
8
248
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQAddViewTest
AQAddViewTest
160
383
160
161
2e9e4cdf731d3154d801a942476a58ea98aba9ed
bigcode/the-stack
train
089ccff83a59f67fbfd14c7d
train
class
class AQCategoriesSingleAjaxViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.creator = UserFactory.create(**{'is_superuser': False}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() ...
class AQCategoriesSingleAjaxViewTest(TestCase):
def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.creator = UserFactory.create(**{'is_superuser': False}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.project = ProjectFactory.create(add_contr...
) self.assertEqual(response.status_code, 200) self.assertEqual(project['id'], self.project.id) def test_get_when_project_marked_as_inactive(self): self.project.status = 'inactive' self.project.save() force_authenticate(self.request_get, user=self.superuser) respons...
243
243
813
10
233
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQCategoriesSingleAjaxViewTest
AQCategoriesSingleAjaxViewTest
929
1,060
929
930
a1e9a8a6d2ea64cfb5ef097a7d543536e47f29ad
bigcode/the-stack
train
3b2b0397841dbdd281c0e3e6
train
class
class AQProjectViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'aq_project.html' self.view = views.AQProjectView.as_vi...
class AQProjectViewTest(TestCase):
def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'aq_project.html' self.view = views.AQProjectView.as_view() self.request = HttpRequ...
.request) } ) self.assertEqual(response.status_code, 200) response = render_helpers.remove_csrf(response.content.decode('utf-8')) self.assertEqual(response, rendered) self.assertEqual( Project.objects.get(pk=self.project.id).islocked, False ...
256
256
2,238
8
248
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQProjectViewTest
AQProjectViewTest
386
722
386
387
ac78f6a737f0246841929954810588778811ee27
bigcode/the-stack
train
5920eb5e3da8e83ec4a13ccc
train
class
class AQMeasurementsSingleAPIViewTest(TestCase): def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.location_1 = AirQualityLocationFactory.create( creator=self.creator, properties={ ...
class AQMeasurementsSingleAPIViewTest(TestCase):
def setUp(self): self.creator = UserFactory.create() self.user = UserFactory.create() self.anonym = AnonymousUser() self.location_1 = AirQualityLocationFactory.create( creator=self.creator, properties={ 'additional_details': 'Heavy traffic.' ...
Equal(Location.objects.count(), 0) self.assertEqual(Observation.objects.count(), 0) def test_post_when_submitting(self): self.data['finished'] = timezone.now().isoformat() self.data['project'] = self.project.id self.data['properties'] = {'results': 48.05} self.request_post...
256
256
2,278
9
247
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQMeasurementsSingleAPIViewTest
AQMeasurementsSingleAPIViewTest
1,650
1,971
1,650
1,651
bfd42bb3ee95ee87a49faa8d005b4f1745743d6c
bigcode/the-stack
train
41dbed786219ea9c4ac00758
train
class
class AQIndexViewTest(TestCase): def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'aq_index.html' self.view = views.AQIndexView.as_view() ...
class AQIndexViewTest(TestCase):
def setUp(self): self.superuser = UserFactory.create(**{'is_superuser': True}) self.user = UserFactory.create(**{'is_superuser': False}) self.anonym = AnonymousUser() self.template = 'aq_index.html' self.view = views.AQIndexView.as_view() self.request = HttpRequest(...
) from geokey.contributions.models import Location, Observation from geokey_airquality import views from geokey_airquality.models import ( AirQualityProject, AirQualityCategory, AirQualityField, AirQualityLocation, AirQualityMeasurement ) from geokey_airquality.tests.model_factories import ( Ai...
136
136
454
8
128
ExCiteS/geokey-airquality
geokey_airquality/tests/test_views.py
Python
AQIndexViewTest
AQIndexViewTest
57
123
57
58
98abb92865ba1cd45c7b4a9f0fe3ad76444d6330
bigcode/the-stack
train
2cf380725319fb3fe626ce10
train
function
def register(parser): add_output_dir(parser)
def register(parser):
add_output_dir(parser)
""" Map ISO codes to the list of all Glottolog languages and dialects subsumed "under" it. """ from csvw.dsv import UnicodeWriter from pyglottolog.cli_util import add_output_dir def register(parser):
49
64
10
4
44
SimonGreenhill/pyglottolog
src/pyglottolog/commands/iso2codes.py
Python
register
register
9
10
9
9
a4e2b9d6f0db0fb348e91420aca4ec4b05e8cff8
bigcode/the-stack
train
33312387fbef4c5d4f03b4c6
train
function
def run(args): nodes = list(args.repos.languoids()) res = {} for node in nodes: if node.iso: res[node.id] = (node.iso, set()) for node in nodes: if node.level == args.repos.languoid_levels.family or node.id in res: continue for nid in res: ma...
def run(args):
nodes = list(args.repos.languoids()) res = {} for node in nodes: if node.iso: res[node.id] = (node.iso, set()) for node in nodes: if node.level == args.repos.languoid_levels.family or node.id in res: continue for nid in res: matched = False ...
""" Map ISO codes to the list of all Glottolog languages and dialects subsumed "under" it. """ from csvw.dsv import UnicodeWriter from pyglottolog.cli_util import add_output_dir def register(parser): add_output_dir(parser) def run(args):
59
64
187
4
55
SimonGreenhill/pyglottolog
src/pyglottolog/commands/iso2codes.py
Python
run
run
13
37
13
13
3f417d421709499c271bc60379dc6a6290cec8e5
bigcode/the-stack
train
350a1fbb1c1f06aee73f6a71
train
class
@Gtk.Template(resource_path='/org/dithernet/aspinwall/launcher/ui/launcherwidget.ui') class LauncherWidget(Gtk.Box): """ Box containing a widget, alongside with its header. This class is used in the launcher to display widgets. For information on creating widgets, see docs/widgets/creating-widgets.md. """ __gtyp...
@Gtk.Template(resource_path='/org/dithernet/aspinwall/launcher/ui/launcherwidget.ui') class LauncherWidget(Gtk.Box):
""" Box containing a widget, alongside with its header. This class is used in the launcher to display widgets. For information on creating widgets, see docs/widgets/creating-widgets.md. """ __gtype_name__ = 'LauncherWidget' container = Gtk.Template.Child() container_overlay = Gtk.Template.Child() widget_head...
_sensitive(True) self._aspwidget._widgetbox.chooser_button_revealer.set_sensitive(True) self.get_parent().set_reveal_child(False) self._aspwidget._widgetbox.edit_mode = False else: self._aspwidget._widgetbox.exit_management_mode() @Gtk.Template.Callback() def show_widget_settings(self, *args): """Sho...
256
256
1,292
28
228
aspinwall-ui/aspinwall
src/launcher/widgets.py
Python
LauncherWidget
LauncherWidget
96
250
96
97
8aa143a5563e376ef5bb15d36a42eb6d547123fe
bigcode/the-stack
train
209e4f41f7f3d4ab2551e6b4
train
class
@Gtk.Template(resource_path='/org/dithernet/aspinwall/launcher/ui/widgetheader.ui') class LauncherWidgetHeader(Gtk.Box): """Header for LauncherWidget.""" __gtype_name__ = 'LauncherWidgetHeader' icon = Gtk.Template.Child('widget_header_icon') title = Gtk.Template.Child('widget_header_title') widget_settings_butto...
@Gtk.Template(resource_path='/org/dithernet/aspinwall/launcher/ui/widgetheader.ui') class LauncherWidgetHeader(Gtk.Box):
"""Header for LauncherWidget.""" __gtype_name__ = 'LauncherWidgetHeader' icon = Gtk.Template.Child('widget_header_icon') title = Gtk.Template.Child('widget_header_title') widget_settings_button = Gtk.Template.Child() move_up_button = Gtk.Template.Child('widget_header_move_up') move_down_button = Gtk.Template.C...
# coding: utf-8 """ Contains basic code for the launcher's widget handling. """ from gi.repository import Gtk, Gdk, GObject @Gtk.Template(resource_path='/org/dithernet/aspinwall/launcher/ui/widgetheader.ui') class LauncherWidgetHeader(Gtk.Box):
59
209
699
28
30
aspinwall-ui/aspinwall
src/launcher/widgets.py
Python
LauncherWidgetHeader
LauncherWidgetHeader
7
94
7
8
eac591639b2be7b86538ed0a6a5e5264ef77cb79
bigcode/the-stack
train
eeb5401b317cebe949b874c0
train
function
def get_android_out_dir(env): return os.path.join( Dir("#platform/android/java/lib/libs").abspath, "release" if env["target"] == "release" else "debug", android_arch_dirs[env["android_arch"]], )
def get_android_out_dir(env):
return os.path.join( Dir("#platform/android/java/lib/libs").abspath, "release" if env["target"] == "release" else "debug", android_arch_dirs[env["android_arch"]], )
mono_reg_utils as monoreg android_arch_dirs = {"armv7": "armeabi-v7a", "arm64v8": "arm64-v8a", "x86": "x86", "x86_64": "x86_64"} def get_android_out_dir(env):
63
64
54
7
56
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
get_android_out_dir
get_android_out_dir
15
20
15
15
cfb63bc178929017896d794af88ddffd1a4b99eb
bigcode/the-stack
train
43e66ccdf0fae12418cc660d
train
function
def copy_mono_shared_libs(env, mono_root, target_mono_root_dir): from shutil import copy def copy_if_exists(src, dst): if os.path.isfile(src): copy(src, dst) platform = env["platform"] if platform == "windows": src_mono_bin_dir = os.path.join(mono_root, "bin") targ...
def copy_mono_shared_libs(env, mono_root, target_mono_root_dir):
from shutil import copy def copy_if_exists(src, dst): if os.path.isfile(src): copy(src, dst) platform = env["platform"] if platform == "windows": src_mono_bin_dir = os.path.join(mono_root, "bin") target_mono_bin_dir = os.path.join(target_mono_root_dir, "bin") ...
"2.0")) copy_tree(os.path.join(mono_etc_dir, "4.0"), os.path.join(target_mono_config_dir, "4.0")) copy_tree(os.path.join(mono_etc_dir, "4.5"), os.path.join(target_mono_config_dir, "4.5")) if os.path.isdir(os.path.join(mono_etc_dir, "mconfig")): copy_tree(os.path.join(mono_etc_dir, "mconfig"), os.pa...
167
167
558
18
149
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
copy_mono_shared_libs
copy_mono_shared_libs
512
574
512
512
74b2a68ecf42c6995fd0b1566251c44bb5c1858b
bigcode/the-stack
train
66ef1bf7c7c25338c6d2e8a7
train
function
def find_wasm_src_dir(mono_root): hint_dirs = [ os.path.join(mono_root, "src"), os.path.join(mono_root, "../src"), ] for hint_dir in hint_dirs: if os.path.isfile(os.path.join(hint_dir, "driver.c")): return hint_dir return ""
def find_wasm_src_dir(mono_root):
hint_dirs = [ os.path.join(mono_root, "src"), os.path.join(mono_root, "../src"), ] for hint_dir in hint_dirs: if os.path.isfile(os.path.join(hint_dir, "driver.c")): return hint_dir return ""
_unix_like(platform): return platform in ["osx", "x11", "server", "android", "haiku", "iphone"] def module_supports_tools_on(platform): return platform not in ["android", "javascript", "iphone"] def find_wasm_src_dir(mono_root):
63
64
72
10
53
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
find_wasm_src_dir
find_wasm_src_dir
73
81
73
73
6eae7d42a8216a43f23561730ee1d90dd82bb792
bigcode/the-stack
train
503fe37e298339125a01ae3d
train
function
def is_unix_like(platform): return platform in ["osx", "x11", "server", "android", "haiku", "iphone"]
def is_unix_like(platform):
return platform in ["osx", "x11", "server", "android", "haiku", "iphone"]
copy(src_path, os.path.join(dst_dir, dst_name)) else: copy(src_path, dst_dir) def is_desktop(platform): return platform in ["windows", "osx", "x11", "server", "uwp", "haiku"] def is_unix_like(platform):
63
64
32
7
56
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
is_unix_like
is_unix_like
65
66
65
65
08dc906f8a0a52d82d1afc548c80c86bd64f423c
bigcode/the-stack
train
53349aec53521f13c1eaca73
train
function
def make_template_dir(env, mono_root): from shutil import rmtree platform = env["platform"] target = env["target"] template_dir_name = "" assert is_desktop(platform) template_dir_name = "data.mono.%s.%s.%s" % (platform, env["bits"], target) output_dir = Dir("#bin").abspath template_...
def make_template_dir(env, mono_root):
from shutil import rmtree platform = env["platform"] target = env["target"] template_dir_name = "" assert is_desktop(platform) template_dir_name = "data.mono.%s.%s.%s" % (platform, env["bits"], target) output_dir = Dir("#bin").abspath template_dir = os.path.join(output_dir, template...
mono_root = subprocess.check_output(["pkg-config", "mono-2", "--variable=prefix"]).decode("utf8").strip() if tools_enabled: # Only supported for editor builds. copy_mono_root_files(env, mono_root, mono_bcl) def make_template_dir(env, mono_root):
64
64
209
9
55
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
make_template_dir
make_template_dir
406
433
406
406
b0a4b7b21239ee1e7fe19255e6a9a7aa4731a4df
bigcode/the-stack
train
ed90dc34c55d314270897396
train
function
def copy_mono_root_files(env, mono_root, mono_bcl): from glob import glob from shutil import copy from shutil import rmtree if not mono_root: raise RuntimeError("Mono installation directory not found") output_dir = Dir("#bin").abspath editor_mono_root_dir = os.path.join(output_dir, "Go...
def copy_mono_root_files(env, mono_root, mono_bcl):
from glob import glob from shutil import copy from shutil import rmtree if not mono_root: raise RuntimeError("Mono installation directory not found") output_dir = Dir("#bin").abspath editor_mono_root_dir = os.path.join(output_dir, "GodotSharp", "Mono") if os.path.isdir(editor_mono...
"Mono") if os.path.isdir(template_mono_root_dir): rmtree(template_mono_root_dir) # Clean first # Copy etc/mono/ template_mono_config_dir = os.path.join(template_mono_root_dir, "etc", "mono") copy_mono_etc_dir(mono_root, template_mono_config_dir, platform) # Copy the required shared lib...
117
117
391
15
102
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
copy_mono_root_files
copy_mono_root_files
436
475
436
436
abfa0f12ae9f2f681806bd6d6c801d6f004fe978
bigcode/the-stack
train
01371c5117e4a239e58d9548
train
function
def copy_file(src_dir, dst_dir, src_name, dst_name=""): from shutil import copy src_path = os.path.join(Dir(src_dir).abspath, src_name) dst_dir = Dir(dst_dir).abspath if not os.path.isdir(dst_dir): os.makedirs(dst_dir) if dst_name: copy(src_path, os.path.join(dst_dir, dst_name)) ...
def copy_file(src_dir, dst_dir, src_name, dst_name=""):
from shutil import copy src_path = os.path.join(Dir(src_dir).abspath, src_name) dst_dir = Dir(dst_dir).abspath if not os.path.isdir(dst_dir): os.makedirs(dst_dir) if dst_name: copy(src_path, os.path.join(dst_dir, dst_name)) else: copy(src_path, dst_dir)
= "." + extension for prefix in prefixes: for curname in names: filename = prefix + curname + extension if os.path.isfile(os.path.join(directory, filename)): return filename return "" def copy_file(src_dir, dst_dir, src_name, dst_name=""):
63
64
96
16
47
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
copy_file
copy_file
46
58
46
46
98e16a60777671250a9dd5a5d981a3d13c3e94c2
bigcode/the-stack
train
61cd09ae6bf9f87c21e0a1ea
train
function
def is_desktop(platform): return platform in ["windows", "osx", "x11", "server", "uwp", "haiku"]
def is_desktop(platform):
return platform in ["windows", "osx", "x11", "server", "uwp", "haiku"]
_name) dst_dir = Dir(dst_dir).abspath if not os.path.isdir(dst_dir): os.makedirs(dst_dir) if dst_name: copy(src_path, os.path.join(dst_dir, dst_name)) else: copy(src_path, dst_dir) def is_desktop(platform):
64
64
32
6
58
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
is_desktop
is_desktop
61
62
61
61
5d2b6c1b95cbdf82d8d29d3f2efb8e1c5db245ad
bigcode/the-stack
train
ce6b2d0d669f75e63c96729f
train
function
def module_supports_tools_on(platform): return platform not in ["android", "javascript", "iphone"]
def module_supports_tools_on(platform):
return platform not in ["android", "javascript", "iphone"]
["windows", "osx", "x11", "server", "uwp", "haiku"] def is_unix_like(platform): return platform in ["osx", "x11", "server", "android", "haiku", "iphone"] def module_supports_tools_on(platform):
63
64
22
8
55
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
module_supports_tools_on
module_supports_tools_on
69
70
69
69
6d650a974271391f0b0dee8e1e6a7110613b4acb
bigcode/the-stack
train
e7b46727cb4197cc2af9c50f
train
function
def find_name_in_dir_files(directory, names, prefixes=[""], extensions=[""]): for extension in extensions: if extension and not extension.startswith("."): extension = "." + extension for prefix in prefixes: for curname in names: if os.path.isfile(os.path.join(...
def find_name_in_dir_files(directory, names, prefixes=[""], extensions=[""]):
for extension in extensions: if extension and not extension.startswith("."): extension = "." + extension for prefix in prefixes: for curname in names: if os.path.isfile(os.path.join(directory, prefix + curname + extension)): return curname ...
return os.path.join( Dir("#platform/android/java/lib/libs").abspath, "release" if env["target"] == "release" else "debug", android_arch_dirs[env["android_arch"]], ) def find_name_in_dir_files(directory, names, prefixes=[""], extensions=[""]):
64
64
77
17
47
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
find_name_in_dir_files
find_name_in_dir_files
23
31
23
23
c66b7d01588924c54ea1236907a931f04e981b41
bigcode/the-stack
train
64ff1f3ac560d5e935566657
train
function
def find_file_in_dir(directory, names, prefixes=[""], extensions=[""]): for extension in extensions: if extension and not extension.startswith("."): extension = "." + extension for prefix in prefixes: for curname in names: filename = prefix + curname + extensi...
def find_file_in_dir(directory, names, prefixes=[""], extensions=[""]):
for extension in extensions: if extension and not extension.startswith("."): extension = "." + extension for prefix in prefixes: for curname in names: filename = prefix + curname + extension if os.path.isfile(os.path.join(directory, filename)):...
("."): extension = "." + extension for prefix in prefixes: for curname in names: if os.path.isfile(os.path.join(directory, prefix + curname + extension)): return curname return "" def find_file_in_dir(directory, names, prefixes=[""], extensions=[""...
63
64
80
16
47
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
find_file_in_dir
find_file_in_dir
34
43
34
34
7e8b189572c40b63f486c7f5ec173deb478256db
bigcode/the-stack
train
5c9c2416240f6959df728a27
train
function
def copy_mono_etc_dir(mono_root, target_mono_config_dir, platform): from distutils.dir_util import copy_tree from glob import glob from shutil import copy if not os.path.isdir(target_mono_config_dir): os.makedirs(target_mono_config_dir) mono_etc_dir = os.path.join(mono_root, "etc", "mono")...
def copy_mono_etc_dir(mono_root, target_mono_config_dir, platform):
from distutils.dir_util import copy_tree from glob import glob from shutil import copy if not os.path.isdir(target_mono_config_dir): os.makedirs(target_mono_config_dir) mono_etc_dir = os.path.join(mono_root, "etc", "mono") if not os.path.isdir(mono_etc_dir): mono_etc_dir = "" ...
ono_framework_dir): os.makedirs(editor_mono_framework_dir) if not os.path.isdir(editor_mono_framework_facades_dir): os.makedirs(editor_mono_framework_facades_dir) for assembly in glob(os.path.join(mono_framework_dir, "*.dll")): copy(assembly, editor_mono_framework_dir) for assembly ...
117
117
391
19
98
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
copy_mono_etc_dir
copy_mono_etc_dir
478
509
478
478
874eaa109d4301711ab4779eff43717dd34f6224
bigcode/the-stack
train
53d565fcd922b48c07a886d4
train
function
def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext): tmpenv = Environment() tmpenv.AppendENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH")) tmpenv.ParseConfig("pkg-config monosgen-2 --libs-only-L") for hint_dir in tmpenv["LIBPATH"]: name_found = find_name_in_dir_files(hint_dir,...
def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext):
tmpenv = Environment() tmpenv.AppendENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH")) tmpenv.ParseConfig("pkg-config monosgen-2 --libs-only-L") for hint_dir in tmpenv["LIBPATH"]: name_found = find_name_in_dir_files(hint_dir, mono_lib_names, prefixes=["lib"], extensions=[sharedlib_ext]) ...
iler-log", "libMonoSupportW", ] ] for lib_file_name in lib_file_names: copy_if_exists(os.path.join(src_mono_lib_dir, lib_file_name), target_mono_lib_dir) def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext):
64
64
140
17
47
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
pkgconfig_try_find_mono_root
pkgconfig_try_find_mono_root
577
585
577
577
1242c3dcc1d91acdfda670c72f538b87241a903e
bigcode/the-stack
train
86db3fe6f0d86b62df75f1e2
train
function
def configure(env, env_mono): bits = env["bits"] is_android = env["platform"] == "android" is_javascript = env["platform"] == "javascript" is_ios = env["platform"] == "iphone" is_ios_sim = is_ios and env["ios_simulator"] tools_enabled = env["tools"] mono_static = env["mono_static"] copy...
def configure(env, env_mono):
bits = env["bits"] is_android = env["platform"] == "android" is_javascript = env["platform"] == "javascript" is_ios = env["platform"] == "iphone" is_ios_sim = is_ios and env["ios_simulator"] tools_enabled = env["tools"] mono_static = env["mono_static"] copy_mono_root = env["copy_mono_ro...
_name, dst_name=""): from shutil import copy src_path = os.path.join(Dir(src_dir).abspath, src_name) dst_dir = Dir(dst_dir).abspath if not os.path.isdir(dst_dir): os.makedirs(dst_dir) if dst_name: copy(src_path, os.path.join(dst_dir, dst_name)) else: copy(src_path, dst...
255
256
2,937
8
247
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
Python
configure
configure
84
403
84
84
4cd775061a4ac3ca8fb2e8cf6bcc3fa4ce73f658
bigcode/the-stack
train
c3774f693745c1ddf052a054
train
class
class PoolingConnection(Connection): """ Base connection class for connections that use libraries without thread safety and no capacity for connection pooling. To use this just implement a ``_make_connection`` method that constructs a new connection and returns it. """ def __init__(self, *a...
class PoolingConnection(Connection):
""" Base connection class for connections that use libraries without thread safety and no capacity for connection pooling. To use this just implement a ``_make_connection`` method that constructs a new connection and returns it. """ def __init__(self, *args, **kwargs): self._free_co...
OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. try: import queue except ImportError: import Queue as queue from .base import Connection class PoolingConnection(Connection):
64
64
160
6
57
shub1095/elasticsearch-py
elasticsearch/connection/pooling.py
Python
PoolingConnection
PoolingConnection
25
50
25
25
7acbcd967bdc7ff718179540ba52084f49fa60f5
bigcode/the-stack
train
c81412c06f9c9019c3c7a156
train
function
def model_config(name: str) -> ml_collections.ConfigDict: """Get the ConfigDict of a CASP14 model.""" if name not in CONFIG_DIFFS: raise ValueError(f'Invalid model name {name}.') cfg = copy.deepcopy(CONFIG) cfg.update_from_flattened_dict(CONFIG_DIFFS[name]) return cfg
def model_config(name: str) -> ml_collections.ConfigDict:
"""Get the ConfigDict of a CASP14 model.""" if name not in CONFIG_DIFFS: raise ValueError(f'Invalid model name {name}.') cfg = copy.deepcopy(CONFIG) cfg.update_from_flattened_dict(CONFIG_DIFFS[name]) return cfg
"""Model config.""" import copy import ml_collections NUM_RES = 'num residues placeholder' NUM_MSA_SEQ = 'msa placeholder' NUM_EXTRA_SEQ = 'extra msa placeholder' NUM_TEMPLATES = 'num templates placeholder' def model_config(name: str) -> ml_collections.ConfigDict:
62
64
73
14
48
mindspore-ai/mindscience
MindSPONGE/mindsponge/fold/eval/config/config.py
Python
model_config
model_config
13
20
13
13
39b1a8f8e70b8a07359bceac182b833d4a631041
bigcode/the-stack
train
8268d7b008e500ac63c39345
train
function
def prepare_labels_for_insertion(file_path: str): """ Read the file and creates a union insertion graph Args: file_path: path to a file (3 columns: a label type e.g. "@@decimal_delimiter@@", a label e.g. "целого", and a weight e.g. "0.1"). Returns dictionary mapping from label type to ...
def prepare_labels_for_insertion(file_path: str):
""" Read the file and creates a union insertion graph Args: file_path: path to a file (3 columns: a label type e.g. "@@decimal_delimiter@@", a label e.g. "целого", and a weight e.g. "0.1"). Returns dictionary mapping from label type to an fst that inserts the labels with the specified ...
_SPACE, GraphFst, insert_space from nemo_text_processing.text_normalization.en.utils import load_labels from nemo_text_processing.text_normalization.ru.utils import get_abs_path from pynini.lib import pynutil delete_space = pynutil.delete(" ") def prepare_labels_for_insertion(file_path: str):
63
64
181
11
52
lifefeel/NeMo
nemo_text_processing/text_normalization/ru/taggers/decimals.py
Python
prepare_labels_for_insertion
prepare_labels_for_insertion
26
47
26
26
5691a0799fb48c1fc63b9c21d329b8496f70e6b1
bigcode/the-stack
train
7db5695b0f2f530d0e2f0833
train
class
class DecimalFst(GraphFst): """ Finite state transducer for classifying decimal, e.g. "1,08" -> tokens { decimal { integer_part: "одно целая" fractional_part: "восемь сотых} } Args: cardinal: CardinalFst deterministic: if True will provide a single transduction option, ...
class DecimalFst(GraphFst):
""" Finite state transducer for classifying decimal, e.g. "1,08" -> tokens { decimal { integer_part: "одно целая" fractional_part: "восемь сотых} } Args: cardinal: CardinalFst deterministic: if True will provide a single transduction option, for False multiple trans...
def prepare_labels_for_insertion(file_path: str): """ Read the file and creates a union insertion graph Args: file_path: path to a file (3 columns: a label type e.g. "@@decimal_delimiter@@", a label e.g. "целого", and a weight e.g. "0.1"). Returns dictionary mapping from label type to ...
189
189
631
8
180
lifefeel/NeMo
nemo_text_processing/text_normalization/ru/taggers/decimals.py
Python
DecimalFst
DecimalFst
50
107
50
50
5d24e9610f7a5600f3ab1fc8d4f58b1e58236e2e
bigcode/the-stack
train
df15f053fa03f9e962729b65
train
function
def main(mytimer: func.TimerRequest) -> None: utc_timestamp = datetime.datetime.utcnow().replace( tzinfo=datetime.timezone.utc).isoformat() if mytimer.past_due: logging.info("The timer is past due!") logging.info("Python timer trigger function ran at %s", utc_timestamp) logging.inf...
def main(mytimer: func.TimerRequest) -> None:
utc_timestamp = datetime.datetime.utcnow().replace( tzinfo=datetime.timezone.utc).isoformat() if mytimer.past_due: logging.info("The timer is past due!") logging.info("Python timer trigger function ran at %s", utc_timestamp) logging.info("Starting program") SO = SOne() se...
(chunk_count)) self.success_processed = self.success_processed + chunk_count else: logging.info("Error during sending events to Azure Sentinel. Response code:{}".format(response.status_code)) self.fail_processed = self.fail_processed + chunk_count def main(mytimer: func.T...
64
64
213
13
50
johnbilliris/Azure-Sentinel
DataConnectors/SentinelOne/SentinelOneSentinelConnector/__init__.py
Python
main
main
168
186
168
168
c134ba7db3627778048de83e5303790d9deac90f
bigcode/the-stack
train
953addc1092701ef7a35dda9
train
class
class SOne(): def __init__(self): self.domain = domain self.header = { 'Authorization': 'ApiToken {}'.format(token), 'Content-Type': 'application/json', } self.from_date, self.to_date = self.generate_date() self.results_array = [] ...
class SOne():
def __init__(self): self.domain = domain self.header = { 'Authorization': 'ApiToken {}'.format(token), 'Content-Type': 'application/json', } self.from_date, self.to_date = self.generate_date() self.results_array = [] def generate_date...
import azure.functions as func import datetime import json import base64 import hashlib import hmac import requests import re import os import logging from .state_manager import StateManager token = os.environ['SentinelOneAPIToken'] domain = os.environ['SentinelOneUrl'] table_name = "SentinelOne" chun...
223
256
906
5
218
johnbilliris/Azure-Sentinel
DataConnectors/SentinelOne/SentinelOneSentinelConnector/__init__.py
Python
SOne
SOne
31
107
31
32
5ba0b15012b00f4f9308f2e2a87d40f3d343ed84
bigcode/the-stack
train
c81eae5bcce19ee654ca933b
train
class
class Sentinel: def __init__(self): self.logAnalyticsUri = logAnalyticsUri self.success_processed = 0 self.fail_processed = 0 self.table_name = table_name self.chunksize = chunksize def gen_chunks_to_object(self, data, chunksize=100): chunk = [] ...
class Sentinel:
def __init__(self): self.logAnalyticsUri = logAnalyticsUri self.success_processed = 0 self.fail_processed = 0 self.table_name = table_name self.chunksize = chunksize def gen_chunks_to_object(self, data, chunksize=100): chunk = [] for index, line in...
{ "limit": 1000, "createdAt__gt": self.from_date, "createdAt__lt": self.to_date } elif "updated_events" in api_req_id: api_req_params = { "limit": 200, "updatedAt__gt"...
174
174
582
3
171
johnbilliris/Azure-Sentinel
DataConnectors/SentinelOne/SentinelOneSentinelConnector/__init__.py
Python
Sentinel
Sentinel
109
166
109
110
e1445682caa00693414c799b546c840b07c1b324
bigcode/the-stack
train
c40187b8da9434bcbb8e391c
train
function
def get_can_signals(CP): # this function generates lists for signal, messages and initial values signals = [ ("XMISSION_SPEED", "ENGINE_DATA", 0), ("WHEEL_SPEED_FL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_FR", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RR", "WHEE...
def get_can_signals(CP): # this function generates lists for signal, messages and initial values
signals = [ ("XMISSION_SPEED", "ENGINE_DATA", 0), ("WHEEL_SPEED_FL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_FR", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RR", "WHEEL_SPEEDS", 0), ("STEER_ANGLE", "STEERING_SENSORS", 0), ("STEER_ANGLE_RATE", "STEERING...
0), ("PARM_10", "ADJ_LANE_LEFT_2", 0), ] checks = [ ("CUR_LANE_LEFT_1", 15), ("CUR_LANE_LEFT_2", 15), ("CUR_LANE_RIGHT_1", 15), ("CUR_LANE_RIGHT_2", 15), ("CUR_LANE_LEFT_1", 15), ("CUR_LANE_LEFT_2", 15), ("CUR_LANE_RIGHT_1", 15), ("CUR_LANE_RIGHT_2", 15), ...
256
256
1,694
21
234
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
Python
get_can_signals
get_can_signals
115
251
115
116
275b9fad2c1cf942d6dca12ae49a82c251c4c22f
bigcode/the-stack
train
da63865bb444d0c4d0a71701
train
function
def get_cam_can_signals(): signals = [ ("FRAME_ID", "CUR_LANE_LEFT_1", 0), ("FRAME_ID", "CUR_LANE_LEFT_2", 0), ("FRAME_ID", "CUR_LANE_RIGHT_1", 0), ("FRAME_ID", "CUR_LANE_RIGHT_2", 0), ("FRAME_ID", "ADJ_LANE_LEFT_1", 0), ("FRAME_ID", "ADJ_LANE_LEFT_2", 0), ("FRAME_ID", "ADJ_L...
def get_cam_can_signals():
signals = [ ("FRAME_ID", "CUR_LANE_LEFT_1", 0), ("FRAME_ID", "CUR_LANE_LEFT_2", 0), ("FRAME_ID", "CUR_LANE_RIGHT_1", 0), ("FRAME_ID", "CUR_LANE_RIGHT_2", 0), ("FRAME_ID", "ADJ_LANE_LEFT_1", 0), ("FRAME_ID", "ADJ_LANE_LEFT_2", 0), ("FRAME_ID", "ADJ_LANE_RIGHT_1", 0), ("F...
_to_capnp = {'P': 'park', 'R': 'reverse', 'N': 'neutral', 'D': 'drive', 'D': 'drive', 'D': 'drive'} # 'S': 'sport', 'L': 'low'} try: return val_to_capnp[vals[gear]] except KeyError: return "unknown" def calc_cruise_offset(offset, speed): # euristic formula so that speed is controlled ...
256
256
1,291
7
249
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
Python
get_cam_can_signals
get_cam_can_signals
31
113
31
31
7ed79b586a3b5bcdf29a22258b0452bd53f8e8c2
bigcode/the-stack
train
1a69a7eb3b9503e688ba20ad
train
function
def get_can_parser(CP): signals, checks = get_can_signals(CP) bus_pt = 1 if CP.isPandaBlack and CP.carFingerprint in HONDA_BOSCH else 0 return CANParser(DBC[CP.carFingerprint]['pt'], signals, checks, bus_pt)
def get_can_parser(CP):
signals, checks = get_can_signals(CP) bus_pt = 1 if CP.isPandaBlack and CP.carFingerprint in HONDA_BOSCH else 0 return CANParser(DBC[CP.carFingerprint]['pt'], signals, checks, bus_pt)
GasInterceptor: signals.append(("INTERCEPTOR_GAS", "GAS_SENSOR", 0)) signals.append(("INTERCEPTOR_GAS2", "GAS_SENSOR", 0)) checks.append(("GAS_SENSOR", 50)) return signals, checks def get_can_parser(CP):
64
64
65
7
56
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
Python
get_can_parser
get_can_parser
254
258
254
254
e1497f408aa2524b368a7bc806cb6dd0cb9cc8a0
bigcode/the-stack
train
0826110f8cfcc50ef5d6446a
train
function
def calc_cruise_offset(offset, speed): # euristic formula so that speed is controlled to ~ 0.3m/s below pid_speed # constraints to solve for _K0, _K1, _K2 are: # - speed = 0m/s, out = -0.3 # - speed = 34m/s, offset = 20, out = -0.25 # - speed = 34m/s, offset = -2.5, out = -1.8 _K0 = -0.3 _K1 = -0.01879 ...
def calc_cruise_offset(offset, speed): # euristic formula so that speed is controlled to ~ 0.3m/s below pid_speed # constraints to solve for _K0, _K1, _K2 are: # - speed = 0m/s, out = -0.3 # - speed = 34m/s, offset = 20, out = -0.25 # - speed = 34m/s, offset = -2.5, out = -1.8
_K0 = -0.3 _K1 = -0.01879 _K2 = 0.01013 return min(_K0 + _K1 * speed + _K2 * speed * offset, 0.)
def calc_cruise_offset(offset, speed): # euristic formula so that speed is controlled to ~ 0.3m/s below pid_speed # constraints to solve for _K0, _K1, _K2 are: # - speed = 0m/s, out = -0.3 # - speed = 34m/s, offset = 20, out = -0.25 # - speed = 34m/s, offset = -2.5, out = -1.8
114
64
170
114
0
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
Python
calc_cruise_offset
calc_cruise_offset
20
29
20
25
e1aacc5ca75e1ea7251456ae8b6f6542afc0c9ed
bigcode/the-stack
train
639d41a662a15ae7ee34aad2
train
class
class CarState(): def __init__(self, CP): #self.kegman = kegman_conf() #self.trMode = int(self.kegman.conf['lastTrMode']) # default to last distance interval on startup #self.trMode = 1 self.lkMode = True self.read_distance_lines_prev = 4 self.CP = CP self.can_define = CANDefine(DBC[CP...
class CarState():
def __init__(self, CP): #self.kegman = kegman_conf() #self.trMode = int(self.kegman.conf['lastTrMode']) # default to last distance interval on startup #self.trMode = 1 self.lkMode = True self.read_distance_lines_prev = 4 self.CP = CP self.can_define = CANDefine(DBC[CP.carFingerprint]['...
elif CP.carFingerprint == CAR.ODYSSEY_CHN: signals += [("MAIN_ON", "SCM_BUTTONS", 0), ("EPB_STATE", "EPB_STATUS", 0)] checks += [("EPB_STATUS", 50)] # add gas interceptor reading if we are using it if CP.enableGasInterceptor: signals.append(("INTERCEPTOR_GAS", "GAS_SENSOR", 0)) si...
256
256
4,089
4
252
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
Python
CarState
CarState
268
521
268
268
d7d199df0424dbd73c07d1f47fad26de06de6c31
bigcode/the-stack
train
451f3ab93257f649937549c1
train
function
def get_cam_can_parser(isPandaBlack): signals, checks = get_cam_can_signals() checks = [] bus_cam = 1 if not isPandaBlack else 2 return CANParser("bosch_camera", signals, checks, bus_cam)
def get_cam_can_parser(isPandaBlack):
signals, checks = get_cam_can_signals() checks = [] bus_cam = 1 if not isPandaBlack else 2 return CANParser("bosch_camera", signals, checks, bus_cam)
= get_can_signals(CP) bus_pt = 1 if CP.isPandaBlack and CP.carFingerprint in HONDA_BOSCH else 0 return CANParser(DBC[CP.carFingerprint]['pt'], signals, checks, bus_pt) def get_cam_can_parser(isPandaBlack):
64
64
56
10
54
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
Python
get_cam_can_parser
get_cam_can_parser
261
266
261
261
6dea2e604cd8b9c519468a40b6d3477d8dbf2c77
bigcode/the-stack
train
a89c202a6579758c67d9372e
train
function
def parse_gear_shifter(gear, vals): val_to_capnp = {'P': 'park', 'R': 'reverse', 'N': 'neutral', 'D': 'drive', 'D': 'drive', 'D': 'drive'} # 'S': 'sport', 'L': 'low'} try: return val_to_capnp[vals[gear]] except KeyError: return "unknown"
def parse_gear_shifter(gear, vals):
val_to_capnp = {'P': 'park', 'R': 'reverse', 'N': 'neutral', 'D': 'drive', 'D': 'drive', 'D': 'drive'} # 'S': 'sport', 'L': 'low'} try: return val_to_capnp[vals[gear]] except KeyError: return "unknown"
.parser import CANParser from selfdrive.config import Conversions as CV from selfdrive.car.honda.values import CAR, DBC, STEER_THRESHOLD, SPEED_FACTOR, HONDA_BOSCH from selfdrive.kegman_conf import kegman_conf def parse_gear_shifter(gear, vals):
64
64
92
11
52
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
Python
parse_gear_shifter
parse_gear_shifter
10
17
10
11
b78b39485709177a17b534e5986eb82d1570dfb7
bigcode/the-stack
train
1a65c9fb27fc77a0bd405a7b
train
function
def startDialog(event): _order = { "room": '', "date": '', "startTime": '', "duration": '' } res = {"version": "1.0", "sessionAttributes": _order, "shouldEndSession": False, "response": { "directives": [ { ...
def startDialog(event):
_order = { "room": '', "date": '', "startTime": '', "duration": '' } res = {"version": "1.0", "sessionAttributes": _order, "shouldEndSession": False, "response": { "directives": [ { "typ...
"canFulfill": "YES" } }, "shouldEndSession": False, } def launchRequest(event): return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Welcome..." } } ...
76
76
256
5
71
p-sk/AlexaMeetingRoomBooking
main-back.py
Python
startDialog
startDialog
309
354
309
309
665acd3be4e976f52acdb7d47c330d9b27309939
bigcode/the-stack
train
57257c342554f5b9947423b1
train
function
def defaultFunction(event): return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Sorry I cannot understand that can you please try again" }, "shouldEndSession": False, } }
def defaultFunction(event):
return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Sorry I cannot understand that can you please try again" }, "shouldEndSession": False, } }
Wrong" } } } def sessionEndedRequest(event): return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Bye.." } } } def defaultFunction(event):
64
64
66
5
59
p-sk/AlexaMeetingRoomBooking
main-back.py
Python
defaultFunction
defaultFunction
271
281
271
271
6f61bf52c03d16a271fcea3c89e9ccd341a0f347
bigcode/the-stack
train
797ee83ac413a4ade76df304
train
function
def canFulfilled(event): if event["request"]["intent"]["name"] == "BookRoom": return { "version": "1.0", "response": { "canFulfillIntent": { "canFulfill": "YES" } }, "shouldEndSession": False, }
def canFulfilled(event):
if event["request"]["intent"]["name"] == "BookRoom": return { "version": "1.0", "response": { "canFulfillIntent": { "canFulfill": "YES" } }, "shouldEndSession": False, }
"version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Sorry I cannot understand that can you please try again" }, "shouldEndSession": False, } } def canFulfilled(event):
64
64
69
6
58
p-sk/AlexaMeetingRoomBooking
main-back.py
Python
canFulfilled
canFulfilled
284
294
284
284
bc2c0ce19a847de6362de7933e6c12323b6a6e1b
bigcode/the-stack
train
4d278a65d0f55650a66dda3f
train
function
def sessionEndedRequest(event): return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Bye.." } } }
def sessionEndedRequest(event):
return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Bye.." } } }
improve readability." } } } else: return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Something Went Wrong" } } } def ...
64
64
51
6
58
p-sk/AlexaMeetingRoomBooking
main-back.py
Python
sessionEndedRequest
sessionEndedRequest
259
268
259
259
cd801c855c10db11597215b09322a2aed431290b
bigcode/the-stack
train
f8f5c3511111030ffd073626
train
function
def bookRoom(event, order): order = bookSlot(order) if order["status"] == "COMPLETED": msg = "Book Request For room: "+event["request"]["intent"]["slots"]["room"]["value"] +\ "From:"+event["request"]["intent"]["slots"]["date"]["value"]+" "+event["request"]["intent"]["slots"]["time"]["value"]...
def bookRoom(event, order):
order = bookSlot(order) if order["status"] == "COMPLETED": msg = "Book Request For room: "+event["request"]["intent"]["slots"]["room"]["value"] +\ "From:"+event["request"]["intent"]["slots"]["date"]["value"]+" "+event["request"]["intent"]["slots"]["time"]["value"]+" " +\ "Duratio...
"] = '' return askAgain("You requested booking for older date time. Kindly try future date time.", "time", order) else: return askAgain('What time you want to book', 'time', order) else: return askAgain('When is this meeting', 'date', order) else: ...
92
92
308
7
85
p-sk/AlexaMeetingRoomBooking
main-back.py
Python
bookRoom
bookRoom
224
256
224
224
0ba7a18c86d2acd66c9d591020ea23582dabf6b8
bigcode/the-stack
train
f9d190fb4561b22bcb395cbc
train
function
def launchRequest(event): return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Welcome..." } } }
def launchRequest(event):
return { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Welcome..." } } }
request"]["intent"]["name"] == "BookRoom": return { "version": "1.0", "response": { "canFulfillIntent": { "canFulfill": "YES" } }, "shouldEndSession": False, } def launchRequest(event):
64
64
49
5
59
p-sk/AlexaMeetingRoomBooking
main-back.py
Python
launchRequest
launchRequest
297
306
297
297
419efe5e7e98f6e9fd1ea6891a8d095f6aa43999
bigcode/the-stack
train