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
1ab36c7c0aaf4ec5308fdfa0
train
function
async def test_zeroconf_no_data(hass): """Test a failed zeroconf discovery because of no data.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={} ) assert result["type"] == "abort" assert result["reason"] == "not_...
async def test_zeroconf_no_data(hass):
"""Test a failed zeroconf discovery because of no data.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={} ) assert result["type"] == "abort" assert result["reason"] == "not_xiaomi_miio"
iaomi-miio-device", ZEROCONF_PROP: {ZEROCONF_MAC: TEST_MAC}, }, ) assert result["type"] == "abort" assert result["reason"] == "not_xiaomi_miio" async def test_zeroconf_no_data(hass):
64
64
85
12
52
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_zeroconf_no_data
test_zeroconf_no_data
158
165
158
158
9a907bcedb677e1b606188b0b331c0f9bd1163d4
bigcode/the-stack
train
268a43635e20447e5f077782
train
function
async def test_config_flow_step_unknown_device(hass): """Test config flow, unknown device error.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id"] == "device" ass...
async def test_config_flow_step_unknown_device(hass):
"""Test config flow, unknown device error.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id"] == "device" assert result["errors"] == {} mock_info = get_mock_i...
"], {CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN}, ) assert result["type"] == "form" assert result["step_id"] == "device" assert result["errors"] == {"base": "cannot_connect"} async def test_config_flow_step_unknown_device(hass):
63
64
185
11
52
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_config_flow_step_unknown_device
test_config_flow_step_unknown_device
204
227
204
204
366b723c40b0fc1bfe4e2c6134ee9daa97eef2be
bigcode/the-stack
train
a1a539b70bcc432e251dc016
train
function
async def test_zeroconf_unknown_device(hass): """Test a failed zeroconf discovery because of a unknown device.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={ CONF_HOST: TEST_HOST, ZER...
async def test_zeroconf_unknown_device(hass):
"""Test a failed zeroconf discovery because of a unknown device.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={ CONF_HOST: TEST_HOST, ZEROCONF_NAME: "not-a-xiaomi-miio-device", ...
["data"] == { const.CONF_FLOW_TYPE: const.CONF_GATEWAY, CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN, const.CONF_MODEL: TEST_MODEL, const.CONF_MAC: TEST_MAC, } async def test_zeroconf_unknown_device(hass):
64
64
132
12
52
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_zeroconf_unknown_device
test_zeroconf_unknown_device
142
155
142
142
5b69c2bf7c5326a8517f3eeb0b700c35c1342a04
bigcode/the-stack
train
256bad2b04cd6ec321d4ae20
train
function
async def test_import_flow_success(hass): """Test a successful import form yaml for a device.""" mock_info = get_mock_info(model=const.MODELS_SWITCH[0]) with patch( "homeassistant.components.xiaomi_miio.device.Device.info", return_value=mock_info, ), patch( "homeassistant.compon...
async def test_import_flow_success(hass):
"""Test a successful import form yaml for a device.""" mock_info = get_mock_info(model=const.MODELS_SWITCH[0]) with patch( "homeassistant.components.xiaomi_miio.device.Device.info", return_value=mock_info, ), patch( "homeassistant.components.xiaomi_miio.async_setup_entry", retur...
flow_id"], {CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN}, ) assert result["type"] == "form" assert result["step_id"] == "device" assert result["errors"] == {"base": "unknown_device"} async def test_import_flow_success(hass):
63
64
215
9
54
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_import_flow_success
test_import_flow_success
230
254
230
230
a9a17878735940e4170c721faf9a0286ac69f4d9
bigcode/the-stack
train
0c2d0b497293c09ff4d2737b
train
function
async def test_config_flow_step_device_manual_model_succes(hass): """Test config flow, device connection error, manual model.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["...
async def test_config_flow_step_device_manual_model_succes(hass):
"""Test config flow, device connection error, manual model.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id"] == "device" assert result["errors"] == {} with ...
: TEST_HOST, CONF_TOKEN: TEST_TOKEN}, ) assert result["type"] == "create_entry" assert result["title"] == TEST_NAME assert result["data"] == { const.CONF_FLOW_TYPE: const.CONF_DEVICE, CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN, const.CONF_MODEL: const.MODELS_SWITCH...
106
106
356
15
91
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_config_flow_step_device_manual_model_succes
test_config_flow_step_device_manual_model_succes
257
301
257
257
73acfaaca8ed20f8a1dd48d25a94cbe24dffe788
bigcode/the-stack
train
ce2b3034309434865f46a38c
train
function
async def test_zeroconf_vacuum_success(hass): """Test a successful zeroconf discovery of a vacuum.""" test_vacuum_model = const.MODELS_VACUUM[0] test_zeroconf_name = const.MODELS_VACUUM[0].replace(".", "-") await zeroconf_device_success(hass, test_zeroconf_name, test_vacuum_model)
async def test_zeroconf_vacuum_success(hass):
"""Test a successful zeroconf discovery of a vacuum.""" test_vacuum_model = const.MODELS_VACUUM[0] test_zeroconf_name = const.MODELS_VACUUM[0].replace(".", "-") await zeroconf_device_success(hass, test_zeroconf_name, test_vacuum_model)
_vacuum_success(hass): """Test a successful config flow for a vacuum.""" test_vacuum_model = const.MODELS_VACUUM[0] await config_flow_device_success(hass, test_vacuum_model) async def test_zeroconf_vacuum_success(hass):
64
64
89
14
50
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_zeroconf_vacuum_success
test_zeroconf_vacuum_success
397
401
397
397
9ee571a32f8256f94731b52533abfb266ff3f688
bigcode/the-stack
train
48684c93b12abe28f8860046
train
function
async def test_zeroconf_gateway_success(hass): """Test a successful zeroconf discovery of a gateway.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={ CONF_HOST: TEST_HOST, ZEROCONF_NAME...
async def test_zeroconf_gateway_success(hass):
"""Test a successful zeroconf discovery of a gateway.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={ CONF_HOST: TEST_HOST, ZEROCONF_NAME: TEST_ZEROCONF_NAME, ZEROCONF_PROP...
result["type"] == "create_entry" assert result["title"] == DEFAULT_GATEWAY_NAME assert result["data"] == { const.CONF_FLOW_TYPE: const.CONF_GATEWAY, CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN, const.CONF_MODEL: TEST_MODEL, const.CONF_MAC: TEST_MAC, } async def test...
88
88
296
12
76
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_zeroconf_gateway_success
test_zeroconf_gateway_success
102
139
102
102
81d5f507118e30344ac888356e21b0fffff0e6e9
bigcode/the-stack
train
b6918c615141e854c0797723
train
function
async def zeroconf_device_success(hass, zeroconf_name_to_test, model_to_test): """Test a successful zeroconf discovery of a device (base class).""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={ CO...
async def zeroconf_device_success(hass, zeroconf_name_to_test, model_to_test):
"""Test a successful zeroconf discovery of a device (base class).""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data={ CONF_HOST: TEST_HOST, ZEROCONF_NAME: zeroconf_name_to_test, ...
["type"] == "create_entry" assert result["title"] == model_to_test assert result["data"] == { const.CONF_FLOW_TYPE: const.CONF_DEVICE, CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN, const.CONF_MODEL: model_to_test, const.CONF_MAC: TEST_MAC, } async def zeroconf_device_...
95
95
318
21
74
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
zeroconf_device_success
zeroconf_device_success
338
375
338
338
ce7507e4a6824b8e8986ef6a5ad25101a5bd25a3
bigcode/the-stack
train
ce42a6df04f022a0adc99f3c
train
function
async def config_flow_device_success(hass, model_to_test): """Test a successful config flow for a device (base class).""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id...
async def config_flow_device_success(hass, model_to_test):
"""Test a successful config flow for a device (base class).""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id"] == "device" assert result["errors"] == {} mock_...
" assert result["title"] == overwrite_model assert result["data"] == { const.CONF_FLOW_TYPE: const.CONF_DEVICE, CONF_HOST: TEST_HOST, CONF_TOKEN: TEST_TOKEN, const.CONF_MODEL: overwrite_model, const.CONF_MAC: None, } async def config_flow_device_success(hass, model_to...
77
77
257
13
64
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
config_flow_device_success
config_flow_device_success
304
335
304
304
8534ea4c6e08055d7c74142d29e8462bbefb954b
bigcode/the-stack
train
e39f72c38c8f0ccab274bd40
train
function
async def test_zeroconf_plug_success(hass): """Test a successful zeroconf discovery of a plug.""" test_plug_model = const.MODELS_SWITCH[0] test_zeroconf_name = const.MODELS_SWITCH[0].replace(".", "-") await zeroconf_device_success(hass, test_zeroconf_name, test_plug_model)
async def test_zeroconf_plug_success(hass):
"""Test a successful zeroconf discovery of a plug.""" test_plug_model = const.MODELS_SWITCH[0] test_zeroconf_name = const.MODELS_SWITCH[0].replace(".", "-") await zeroconf_device_success(hass, test_zeroconf_name, test_plug_model)
} async def test_config_flow_plug_success(hass): """Test a successful config flow for a plug.""" test_plug_model = const.MODELS_SWITCH[0] await config_flow_device_success(hass, test_plug_model) async def test_zeroconf_plug_success(hass):
64
64
80
13
51
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_zeroconf_plug_success
test_zeroconf_plug_success
384
388
384
384
942d44754ed69a91727b8018b6d7362c7b272f05
bigcode/the-stack
train
4e57dd49bb2679fd49f87fc5
train
function
async def test_config_flow_step_device_connect_error(hass): """Test config flow, device connection error.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id"] == "device...
async def test_config_flow_step_device_connect_error(hass):
"""Test config flow, device connection error.""" result = await hass.config_entries.flow.async_init( const.DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["step_id"] == "device" assert result["errors"] == {} with patch( ...
}, data={CONF_HOST: TEST_HOST, ZEROCONF_NAME: TEST_ZEROCONF_NAME}, ) assert result["type"] == "abort" assert result["reason"] == "not_xiaomi_miio" async def test_config_flow_step_device_connect_error(hass):
64
64
176
12
52
mikan-megane/core
tests/components/xiaomi_miio/test_config_flow.py
Python
test_config_flow_step_device_connect_error
test_config_flow_step_device_connect_error
180
201
180
180
d57940ffe616fec8482cf1567a720dc5ea128130
bigcode/the-stack
train
3a1ff7bcc814bd28c44897ca
train
class
class FenwickTree: def __init__(self, n): self.ft = [0 for i in range(n+1)] def rsq_util(self, b): # return RSQ(1, b) s = 0 while b > 0: s += self.ft[b] b -= LSOne(b) return s def rsq(self, a, b): return self.rsq_util(b) - (0 if a == 1 else s...
class FenwickTree:
def __init__(self, n): self.ft = [0 for i in range(n+1)] def rsq_util(self, b): # return RSQ(1, b) s = 0 while b > 0: s += self.ft[b] b -= LSOne(b) return s def rsq(self, a, b): return self.rsq_util(b) - (0 if a == 1 else self.rsq_util(a-1)) ...
from sys import stdin, stdout LSOne = lambda b: b&(-b) class FenwickTree:
23
64
145
5
18
neemiasbsilva/advanced-topics-computer-science
fenwick-tree/need_math_fenwick.py
Python
FenwickTree
FenwickTree
5
23
5
6
d2baaa3b6b0b933ead5ec81a7b2dad0832fec625
bigcode/the-stack
train
3aabd6ebaa39de1c2073ebf5
train
class
class IDMMOBILVehicleMerge(IDMMOBILVehicle): def __init__(self, id, lane_id, glob_x, speed, aggressiveness=None): super().__init__(id, lane_id, glob_x, speed, aggressiveness) with open('./src/envs/config.json', 'rb') as handle: config = json.load(handle) self.act_long_c = ...
class IDMMOBILVehicleMerge(IDMMOBILVehicle):
def __init__(self, id, lane_id, glob_x, speed, aggressiveness=None): super().__init__(id, lane_id, glob_x, speed, aggressiveness) with open('./src/envs/config.json', 'rb') as handle: config = json.load(handle) self.act_long_c = None # current action self.act_long_p...
from importlib import reload from vehicles import idmmobil_vehicle reload(idmmobil_vehicle) from vehicles.idmmobil_vehicle import IDMMOBILVehicle import json class IDMMOBILVehicleMerge(IDMMOBILVehicle):
49
256
1,929
13
35
saArbabi/PlanToMerge
src/vehicles/idmmobil_merge_vehicle.py
Python
IDMMOBILVehicleMerge
IDMMOBILVehicleMerge
7
209
7
7
5c3d8980f722576406bcc10945bd16c290533af5
bigcode/the-stack
train
a662d8eaeceac3b4db389a79
train
class
class Role(db.Document, RoleMixin): name = db.StringField(max_length=80, unique=True) description = db.StringField(max_length=255)
class Role(db.Document, RoleMixin):
name = db.StringField(max_length=80, unique=True) description = db.StringField(max_length=255)
from flask_security import RoleMixin from app import config db = config.db class Role(db.Document, RoleMixin):
25
64
33
8
16
smartcities-livinglab-udg/APP-SmartCheckIn
app/models/Role.py
Python
Role
Role
7
9
7
7
68380f6bba26c289b4b90b5a6c94ad37d37a35ad
bigcode/the-stack
train
7ad7dcd95e1a4bd742db0701
train
function
def execute(args, parser): config = Config(args.config, verbose=False) with config.trialscontext() as session: q = (session.query(Trial) .filter(Trial.status == 'SUCCEEDED') .order_by(Trial.started)) data = [curr.to_dict() for curr in q.all()] bk.output_file(args.f...
def execute(args, parser):
config = Config(args.config, verbose=False) with config.trialscontext() as session: q = (session.query(Trial) .filter(Trial.status == 'SUCCEEDED') .order_by(Trial.started)) data = [curr.to_dict() for curr in q.all()] bk.output_file(args.filename, title='osprey') ...
' 'version >=0.10.0.\n\n $ conda install bokeh # (recommended)\n' 'or\n $ pip install bokeh') PLOTS = [plot_4, plot_1, plot_2, plot_3] def execute(args, parser):
64
64
161
6
58
msultan/osprey
osprey/execute_plot.py
Python
execute
execute
19
41
19
19
5c8b0d9c3cc8cf24be3ed6510ad0e17d57ddfb27
bigcode/the-stack
train
4fd8294be961bf12e157bb2f
train
class
class MRPCTask(GlueTask): """The MRPC task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['0', '1'] metric = CompositeEvalMetric() metric.add(F1()) metric.add(Accuracy()) super(MRPCTask, self).__init__(class_labels, metric, is_pair) d...
class MRPCTask(GlueTask):
"""The MRPC task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['0', '1'] metric = CompositeEvalMetric() metric.add(F1()) metric.add(Accuracy()) super(MRPCTask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segme...
"""Get the test segment of the dataset for the task. Returns ------- tuple of (str, TSVDataset), or list of tuple : the segment name, and the dataset. """ return 'test', self.get_dataset(segment='test') class MRPCTask(GlueTask):
64
64
187
9
55
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
MRPCTask
MRPCTask
129
150
129
129
bf8371d265d107e834adac384a3cdf4b08bf1720
bigcode/the-stack
train
d8346579de38024eeb109fcd
train
class
class CoLATask(GlueTask): """The Warstdadt acceptability task on GlueBenchmark.""" def __init__(self): is_pair = False class_labels = ['0', '1'] metric = MCC(average='micro') super(CoLATask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train',...
class CoLATask(GlueTask):
"""The Warstdadt acceptability task on GlueBenchmark.""" def __init__(self): is_pair = False class_labels = ['0', '1'] metric = MCC(average='micro') super(CoLATask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', root=...
'train' Dataset segments. Options are 'train', 'dev', 'test'. root : str, default $GLUE_DIR/STS-B Path to the folder which stores the dataset. """ return GlueSTSB(segment=segment, root=root) class CoLATask(GlueTask):
64
64
179
8
56
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
CoLATask
CoLATask
239
258
239
239
94851c699edb2d2ea91d505118cb753571506447
bigcode/the-stack
train
750a2992b7e511e9fa7588da
train
class
class XNLITask(GlueTask): """The XNLI task using the dataset released from Baidu <https://github.com/PaddlePaddle/LARK/tree/develop/ERNIE>. """ def __init__(self): is_pair = True class_labels = ['neutral', 'entailment', 'contradiction'] metric = Accuracy() super(XNLITas...
class XNLITask(GlueTask):
"""The XNLI task using the dataset released from Baidu <https://github.com/PaddlePaddle/LARK/tree/develop/ERNIE>. """ def __init__(self): is_pair = True class_labels = ['neutral', 'entailment', 'contradiction'] metric = Accuracy() super(XNLITask, self).__init__(class_la...
the task. Returns ------- list of TSVDataset : the dataset of the test segment. """ return [('test_matched', self.get_dataset(segment='test_matched')), ('test_mismatched', self.get_dataset(segment='test_mismatched'))] class XNLITask(GlueTask):
67
67
225
9
58
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
XNLITask
XNLITask
344
368
344
344
84acc9a152c79b07ac39f3e84e264f3c8fe32955
bigcode/the-stack
train
8d23d38c3f95f39012ea53db
train
class
class STSBTask(GlueTask): """The Sentence Textual Similarity Benchmark task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = None metric = PearsonCorrelation() super(STSBTask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='...
class STSBTask(GlueTask):
"""The Sentence Textual Similarity Benchmark task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = None metric = PearsonCorrelation() super(STSBTask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', ...
'train' Dataset segments. Options are 'train', 'dev', 'test'. root : str, default $GLUE_DIR/QNLI Path to the folder which stores the dataset. """ return GlueQNLI(segment=segment, root=root) class STSBTask(GlueTask):
64
64
173
8
56
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
STSBTask
STSBTask
218
237
218
218
bc481345bc90e02698f4b48f210739446f9b9bcb
bigcode/the-stack
train
fc0f2b765271695c866a7aad
train
class
class SSTTask(GlueTask): """The Stanford Sentiment Treebank task on GlueBenchmark.""" def __init__(self): is_pair = False class_labels = ['0', '1'] metric = Accuracy() super(SSTTask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', ...
class SSTTask(GlueTask):
"""The Stanford Sentiment Treebank task on GlueBenchmark.""" def __init__(self): is_pair = False class_labels = ['0', '1'] metric = Accuracy() super(SSTTask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', root=os.path...
default 'train' Dataset segments. Options are 'train', 'dev', 'test'. root : str, default $GLUE_DIR/CoLA Path to the folder which stores the dataset. """ return GlueCoLA(segment=segment, root=root) class SSTTask(GlueTask):
64
64
173
7
57
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
SSTTask
SSTTask
260
279
260
260
f1347444f4457e37ae9b773ce289bd006c91a715
bigcode/the-stack
train
49bbd33688519faf4bcded94
train
class
class QQPTask(GlueTask): """The Quora Question Pairs task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['0', '1'] metric = CompositeEvalMetric() metric.add(F1()) metric.add(Accuracy()) super(QQPTask, self).__init__(class_labels, metric, i...
class QQPTask(GlueTask):
"""The Quora Question Pairs task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['0', '1'] metric = CompositeEvalMetric() metric.add(F1()) metric.add(Accuracy()) super(QQPTask, self).__init__(class_labels, metric, is_pair) def get_data...
default 'train' Dataset segments. Options are 'train', 'dev', 'test'. root : str, default $GLUE_DIR/MRPC Path to the folder which stores the dataset. """ return MRPCDataset(segment=segment, root=root) class QQPTask(GlueTask):
64
64
189
8
56
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
QQPTask
QQPTask
152
173
152
152
ea6bad81a58fcc887cf85150209739af162b10e2
bigcode/the-stack
train
cf5fcef1c5e2c55245b23825
train
class
class RTETask(GlueTask): """The Recognizing Textual Entailment task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['not_entailment', 'entailment'] metric = Accuracy() super(RTETask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, ...
class RTETask(GlueTask):
"""The Recognizing Textual Entailment task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['not_entailment', 'entailment'] metric = Accuracy() super(RTETask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', ...
'train' Dataset segments. Options are 'train', 'dev', 'test'. root : str, default $GLUE_DIR/QQP Path to the folder which stores the dataset. """ return GlueQQP(segment=segment, root=root) class RTETask(GlueTask):
64
64
182
8
56
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
RTETask
RTETask
176
195
176
176
56f94ee3da9b73f886f711802ed2642b753b0bd5
bigcode/the-stack
train
c5b783c6aa0575c1e4cad75d
train
class
class MNLITask(GlueTask): """The Multi-Genre Natural Language Inference task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['neutral', 'entailment', 'contradiction'] metric = Accuracy() super(MNLITask, self).__init__(class_labels, metric, is_pair) de...
class MNLITask(GlueTask):
"""The Multi-Genre Natural Language Inference task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['neutral', 'entailment', 'contradiction'] metric = Accuracy() super(MNLITask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segmen...
.path.join(os.getenv('GLUE_DIR', 'glue_data'), 'WNLI')): """Get the corresponding dataset for WNLI Parameters ---------- segment : str, default 'train' Dataset segments. Options are 'dev', 'test', 'train' root : str, default $GLUE_DIR/WNLI Path to the fol...
105
105
351
9
96
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
MNLITask
MNLITask
302
342
302
302
7374cd86cade512244075ff6eb1166140e61f10f
bigcode/the-stack
train
507a0c7e69ab57cd4e33636d
train
class
class QNLITask(GlueTask): """The SQuAD NLI task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['not_entailment', 'entailment'] metric = Accuracy() super(QNLITask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', ...
class QNLITask(GlueTask):
"""The SQuAD NLI task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['not_entailment', 'entailment'] metric = Accuracy() super(QNLITask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', root=os....
'train' Dataset segments. Options are 'train', 'dev', 'test'. root : str, default $GLUE_DIR/RTE Path to the folder which stores the dataset. """ return GlueRTE(segment=segment, root=root) class QNLITask(GlueTask):
64
64
183
9
55
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
QNLITask
QNLITask
197
216
197
197
1bc136c91d79281e126ff620300de3468731f81e
bigcode/the-stack
train
3463962f679dce0e95d08fe4
train
class
class WNLITask(GlueTask): """The Winograd NLI task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['0', '1'] metric = Accuracy() super(WNLITask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', r...
class WNLITask(GlueTask):
"""The Winograd NLI task on GlueBenchmark.""" def __init__(self): is_pair = True class_labels = ['0', '1'] metric = Accuracy() super(WNLITask, self).__init__(class_labels, metric, is_pair) def get_dataset(self, segment='train', root=os.path.join(os.getenv...
train' Dataset segments. Options are 'train', 'dev', 'test'. root : str, default $GLUE_DIR/SST Path to the folder which stores the dataset. """ return GlueSST2(segment=segment, root=root) class WNLITask(GlueTask):
64
64
177
9
55
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
WNLITask
WNLITask
281
300
281
281
1824ad716db245384a5226005aefc802987e6816
bigcode/the-stack
train
42f5158718729f603ec5fb04
train
class
class GlueTask(object): """Abstract GLUE task class. Parameters ---------- class_labels : list of str, or None Classification labels of the task. Set to None for regression tasks with continuous real values. metrics : list of EValMetric Evaluation metrics of the task. is...
class GlueTask(object):
"""Abstract GLUE task class. Parameters ---------- class_labels : list of str, or None Classification labels of the task. Set to None for regression tasks with continuous real values. metrics : list of EValMetric Evaluation metrics of the task. is_pair : bool Whe...
('GLUE_DIR', 'glue_data'), 'MRPC')): assert segment in ['train', 'dev', 'test'], 'Unsupported segment: %s' % segment path = os.path.join(root, '%s.tsv' % segment) A_IDX, B_IDX, LABEL_IDX = 3, 4, 0 if segment == 'test': fields = [A_IDX, B_IDX] else: fields ...
134
134
449
5
129
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
GlueTask
GlueTask
62
127
62
62
2ad0135fa5813c7e489135954e7f1f9160edf3b6
bigcode/the-stack
train
fbc8b92058fddd35864692da
train
class
@register(segment=['train', 'dev', 'test']) class MRPCDataset(TSVDataset): """The Microsoft Research Paraphrase Corpus dataset. Parameters ---------- segment : str, default 'train' Dataset segment. Options are 'train', 'dev', 'test'. root : str, default '$GLUE_DIR/MRPC' Path to the ...
@register(segment=['train', 'dev', 'test']) class MRPCDataset(TSVDataset):
"""The Microsoft Research Paraphrase Corpus dataset. Parameters ---------- segment : str, default 'train' Dataset segment. Options are 'train', 'dev', 'test'. root : str, default '$GLUE_DIR/MRPC' Path to the folder which stores the MRPC dataset. The datset can be downloaded ...
TE, GlueMNLI, GlueQNLI, GlueWNLI from gluonnlp.data.registry import register try: from .baidu_ernie_data import BaiduErnieXNLI except ImportError: from baidu_ernie_data import BaiduErnieXNLI @register(segment=['train', 'dev', 'test']) class MRPCDataset(TSVDataset):
83
83
278
21
61
basicv8vc/gluon-nlp
scripts/bert/data/classification.py
Python
MRPCDataset
MRPCDataset
35
59
35
36
8bd914df5fd8c5069ccfd6afeb1140e261251da9
bigcode/the-stack
train
4fbb548e591e97502500a468
train
class
@pytest.mark.SUITE_main @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase): def test_C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC(self, request, workspace, editor, launcher_platform): ...
@pytest.mark.SUITE_main @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase):
def test_C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC(self, request, workspace, editor, launcher_platform): from .collider import C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC as test_module self._run_test(request, workspace, editor, test_module) @revert_physics_con...
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ # This suite consists of all test cases that are passing and have been verified. import pytest import os impo...
196
256
886
36
160
fromasmtodisasm/o3de
AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py
Python
TestAutomation
TestAutomation
26
86
26
30
def4ddc1e2c18c742cafd359c1781b021820dcae
bigcode/the-stack
train
1df6207888a208602e11f1fa
train
function
def test_error_bad_arg2(): from vmad.core.error import BadArgument with Builder() as m: a = m.input('a') with pytest.raises(BadArgument): add(1, x1=1, x2=2)
def test_error_bad_arg2():
from vmad.core.error import BadArgument with Builder() as m: a = m.input('a') with pytest.raises(BadArgument): add(1, x1=1, x2=2)
=a, x2=b) def test_error_bad_arg1(): from vmad.core.error import BadArgument with Builder() as m: a = m.input('a') with pytest.raises(BadArgument): add(1, 1, 1) def test_error_bad_arg2():
64
64
55
7
57
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_bad_arg2
test_error_bad_arg2
22
27
22
22
0cd877e8cadf1c4703794d2f740ef355b6cb3582
bigcode/the-stack
train
098d4a312fd8baa1cb7276ca
train
function
def test_error_missing(): from vmad.core.error import MissingArgument with Builder() as m: a = m.input('a') with pytest.raises(MissingArgument): add(x2=1)
def test_error_missing():
from vmad.core.error import MissingArgument with Builder() as m: a = m.input('a') with pytest.raises(MissingArgument): add(x2=1)
, 1) def test_error_bad_arg2(): from vmad.core.error import BadArgument with Builder() as m: a = m.input('a') with pytest.raises(BadArgument): add(1, x1=1, x2=2) def test_error_missing():
64
64
45
5
59
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_missing
test_error_missing
29
34
29
29
cb6d87bb0aa817004d5ea5cfcfa1595453e258a6
bigcode/the-stack
train
57c24f950701821c732c1f10
train
function
def test_error_bad_arg1(): from vmad.core.error import BadArgument with Builder() as m: a = m.input('a') with pytest.raises(BadArgument): add(1, 1, 1)
def test_error_bad_arg1():
from vmad.core.error import BadArgument with Builder() as m: a = m.input('a') with pytest.raises(BadArgument): add(1, 1, 1)
.error import InferError with Builder() as m: with Builder() as m2: a = m.input('a') b = m2.input('b') with pytest.raises(InferError): c = add(x1=a, x2=b) def test_error_bad_arg1():
64
64
51
7
57
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_bad_arg1
test_error_bad_arg1
15
20
15
15
1559b3528f1921b9e67e69175083d5c944d514c4
bigcode/the-stack
train
fc7643c82fa5d18dcb260774
train
function
def test_error_overwrite(): from vmad.core.error import OverwritePrecaution with Builder() as m: a = m.input('a') with pytest.raises(OverwritePrecaution): add(x1=a, x2=a, y=a)
def test_error_overwrite():
from vmad.core.error import OverwritePrecaution with Builder() as m: a = m.input('a') with pytest.raises(OverwritePrecaution): add(x1=a, x2=a, y=a)
(1, x1=1, x2=2) def test_error_missing(): from vmad.core.error import MissingArgument with Builder() as m: a = m.input('a') with pytest.raises(MissingArgument): add(x2=1) def test_error_overwrite():
64
64
55
6
58
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_overwrite
test_error_overwrite
36
41
36
36
9a19eff900feb20308d0b06676b18381863ab2c5
bigcode/the-stack
train
673e67f2d1c6ce5bee630c23
train
function
def test_error_unexpected_output(): from vmad.core.error import ResolveError with Builder() as m: a = m.input('a') m.output(a=a) with pytest.raises(ResolveError): m.compute(vout='a', init={})
def test_error_unexpected_output():
from vmad.core.error import ResolveError with Builder() as m: a = m.input('a') m.output(a=a) with pytest.raises(ResolveError): m.compute(vout='a', init={})
(): from vmad.core.error import UnexpectedOutput with Builder() as m: a = m.input('a') m.output(a=a) with pytest.raises(UnexpectredOutput): m.compute(vout='b', init=dict(a=1.0)) def test_error_unexpected_output():
64
64
57
7
57
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_unexpected_output
test_error_unexpected_output
61
68
61
61
06adafb9698fb7120dc80a78256d069e0e153437
bigcode/the-stack
train
469f8b28d070e3eb97091a5b
train
function
def test_error_infer(): from vmad.core.error import InferError with Builder() as m: with Builder() as m2: a = m.input('a') b = m2.input('b') with pytest.raises(InferError): c = add(x1=a, x2=b)
def test_error_infer():
from vmad.core.error import InferError with Builder() as m: with Builder() as m2: a = m.input('a') b = m2.input('b') with pytest.raises(InferError): c = add(x1=a, x2=b)
from vmad.core.model import Builder from vmad.core.stdlib import add import pytest def test_error_infer():
26
64
68
6
19
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_infer
test_error_infer
6
13
6
6
8a6cf73a39daf5d592edd432e3c459028a802a54
bigcode/the-stack
train
c849adf51659e01f44e85e9d
train
function
def test_error_many_output(): from vmad.core.error import DuplicatedOutput with Builder() as m: a = m.input('a') with pytest.raises(DuplicatedOutput): m.output(a=a) m.output(a=a)
def test_error_many_output():
from vmad.core.error import DuplicatedOutput with Builder() as m: a = m.input('a') with pytest.raises(DuplicatedOutput): m.output(a=a) m.output(a=a)
=1) def test_error_overwrite(): from vmad.core.error import OverwritePrecaution with Builder() as m: a = m.input('a') with pytest.raises(OverwritePrecaution): add(x1=a, x2=a, y=a) def test_error_many_output():
64
64
54
6
58
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_many_output
test_error_many_output
43
49
43
43
27eae514316246672fb01a90163212452413da09
bigcode/the-stack
train
5711c6eb97b34d93f0f2b832
train
function
def test_error_unexpected_output(): from vmad.core.error import UnexpectedOutput with Builder() as m: a = m.input('a') m.output(a=a) with pytest.raises(UnexpectredOutput): m.compute(vout='b', init=dict(a=1.0))
def test_error_unexpected_output():
from vmad.core.error import UnexpectedOutput with Builder() as m: a = m.input('a') m.output(a=a) with pytest.raises(UnexpectredOutput): m.compute(vout='b', init=dict(a=1.0))
y=a) def test_error_many_output(): from vmad.core.error import DuplicatedOutput with Builder() as m: a = m.input('a') with pytest.raises(DuplicatedOutput): m.output(a=a) m.output(a=a) def test_error_unexpected_output():
64
64
63
7
57
Maxelee/vmad
vmad/core/tests/test_error.py
Python
test_error_unexpected_output
test_error_unexpected_output
52
59
52
52
3872dfd5a51f179068227ca3a286870a98c2d368
bigcode/the-stack
train
70d3035e28731921b98d34e4
train
class
class WiX: name = "wix" full_name = "WiX" def __init__(self, command, wix_home=None, bin_install=False): """Create a wrapper around a WiX install. :param command: The command using the wrapper. :param wix_home: The path of the WiX installation. :param bin_install: Is the in...
class WiX:
name = "wix" full_name = "WiX" def __init__(self, command, wix_home=None, bin_install=False): """Create a wrapper around a WiX install. :param command: The command using the wrapper. :param wix_home: The path of the WiX installation. :param bin_install: Is the install a bin...
import os import shutil from pathlib import Path from requests import exceptions as requests_exceptions from briefcase.exceptions import ( BriefcaseCommandError, MissingToolError, NetworkFailure, NonManagedToolError, ) WIX_DOWNLOAD_URL = "https://github.com/wixtoolset/wix3/releases/download/wix3112rt...
85
256
1,037
4
81
pybee/briefcase
src/briefcase/integrations/wix.py
Python
WiX
WiX
17
163
17
17
1a61a72c333c29d6b36f342e1066c687d8c0baa3
bigcode/the-stack
train
1c45f96d573bd794ef71018f
train
function
def get_context(context): context.brand_html = "It Management"
def get_context(context):
context.brand_html = "It Management"
source_link = "https://github.com/[org_name]/it_management" # docs_base_url = "https://[org_name].github.io/it_management" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context):
64
64
13
5
59
umindo/it_management
it_management/config/docs.py
Python
get_context
get_context
10
11
10
10
0e161b656217944e1d6e856a92029f8900d4ea17
bigcode/the-stack
train
7d3123ec7cfe693cbf4c5d4a
train
function
def solve_fifteen(): return sum(int(x) for x in str(2 ** 1000))
def solve_fifteen():
return sum(int(x) for x in str(2 ** 1000))
#!/usr/bin/env python """ 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ def solve_fifteen():
58
64
23
6
52
marshallhumble/Project_Euler
Project-Euler/python/16.py
Python
solve_fifteen
solve_fifteen
13
14
13
13
2e43821637ad64a8073d82d3f8db10141d08f29a
bigcode/the-stack
train
ae6735b1f2bacbd5e53466db
train
function
def test_function(): assert solve_fifteen() == 1366
def test_function():
assert solve_fifteen() == 1366
of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ def solve_fifteen(): return sum(int(x) for x in str(2 ** 1000)) def test_function():
64
64
16
4
60
marshallhumble/Project_Euler
Project-Euler/python/16.py
Python
test_function
test_function
17
18
17
17
ee603b76ec4ad62dac55096b9d550167b2dc61bf
bigcode/the-stack
train
58cd344b0d8ee171f1a80838
train
class
class Path(object): def __init__(self): super(Path, self).__init__() self.bases = [] self.destinations = [] self.now = 0 self.future_base = None self.speed = 100 self.capacity = 8 # 以下三个必须对应起来 # 保留该路线所有信息,经过的也保留起来 self.path = [] ...
class Path(object):
def __init__(self): super(Path, self).__init__() self.bases = [] self.destinations = [] self.now = 0 self.future_base = None self.speed = 100 self.capacity = 8 # 以下三个必须对应起来 # 保留该路线所有信息,经过的也保留起来 self.path = [] self.orders = [] ...
.append(order) else: for order in temp_order_list: if order.destination == position.d_id: temp_order_list.remove(order) if temp_order_list: log.error("there some order not arrive destination") return sys.maxint if truck.status == Truck_stat...
256
256
1,278
4
251
liuxiaokaiA/truck_scheduling
model/base_model/base_/path.py
Python
Path
Path
52
211
52
52
72b8936b9c84dceee845e356289b589fcd0f06fe
bigcode/the-stack
train
7c794464dd2d0d17357858c2
train
function
def calculate_cost_by_path(truck_id, position_list, order_list): truck = Trucks[truck_id] cost = 0 temp_order_list = [] for index, position in enumerate(position_list): if index > 0: cost += position_list[index - 1].calculate_ditance(position) * truck.truck_cost(len(temp_order_list))...
def calculate_cost_by_path(truck_id, position_list, order_list):
truck = Trucks[truck_id] cost = 0 temp_order_list = [] for index, position in enumerate(position_list): if index > 0: cost += position_list[index - 1].calculate_ditance(position) * truck.truck_cost(len(temp_order_list)) if isinstance(position, Base): for order in ...
# -*- encoding: utf-8 -*- import sys from itertools import permutations from global_data import Orders, Destinations, Trucks, Bases from model.base_model.base import Base import logging from model.base_model.base_.type import Truck_status from model.base_model.destination import Destination log = logging.getLogger("...
82
110
367
15
67
liuxiaokaiA/truck_scheduling
model/base_model/base_/path.py
Python
calculate_cost_by_path
calculate_cost_by_path
15
49
15
15
34c758ffbba50b5a38c636e875a0e7ee97cd2ce5
bigcode/the-stack
train
a5a767ff2a9d9f72e5e609be
train
function
def test_actor(): a = A(None) b = B(a) a._o = b b.start() a.start() b._p.join() a._p.join()
def test_actor():
a = A(None) b = B(a) a._o = b b.start() a.start() b._p.join() a._p.join()
self._o = other self.count = 3 def tick(self): self._o.send("ping") self.recv() self.count -= 1 if self.count == 0: raise RuntimeError("Fatal exception: FOO is BARed") def test_actor():
64
64
43
4
60
pbs/thespian
src/thespian/_tests/test_actor.py
Python
test_actor
test_actor
50
57
50
50
ee7acdb8ae640a46f0db577d4ab561abdc389fac
bigcode/the-stack
train
6c2adbfab7060aab8206ad70
train
class
class B(LActor): def __init__(self, other): super(B, self).__init__() self._o = other self.count = 10 def tick(self): self._o.send("ping") self.recv() self.count -= 1 if self.count == 0: return self.STOP
class B(LActor):
def __init__(self, other): super(B, self).__init__() self._o = other self.count = 10 def tick(self): self._o.send("ping") self.recv() self.count -= 1 if self.count == 0: return self.STOP
super(A, self).__init__() self._o = other self.count = 10 def tick(self): self.recv() self._o.send("pong") self.count -= 1 if self.count == 0: return self.STOP class B(LActor):
64
64
74
5
58
pbs/thespian
src/thespian/_tests/test_actor.py
Python
B
B
22
33
22
22
518e66a1d58b64332b5632e5a086d0100b3bd612
bigcode/the-stack
train
28f2c0600364cdc5fc179be7
train
function
def test_dead_actor(): a = A(None) dead = DeadActor(a) a._o = dead dead.start() a.start() a.check_alive() with pytest.raises(DeadActorException): for _ in xrange(20): # this happens asyncronosly; wait for up to 2 seconds dead.check_alive() time.sle...
def test_dead_actor():
a = A(None) dead = DeadActor(a) a._o = dead dead.start() a.start() a.check_alive() with pytest.raises(DeadActorException): for _ in xrange(20): # this happens asyncronosly; wait for up to 2 seconds dead.check_alive() time.sleep(.1)
= A(None) b = B(a) a._o = b b.start() a.start() b._p.join() a._p.join() # if this dind't deadlock, we're happy campers # TODO: enhance the assertions def test_dead_actor():
64
64
84
5
58
pbs/thespian
src/thespian/_tests/test_actor.py
Python
test_dead_actor
test_dead_actor
62
73
62
62
b3dab1c1b0e63abafbf68d2b51f20f227538e7d3
bigcode/the-stack
train
6de5f438e9264ec1936d07b8
train
class
class DeadActor(LActor): def __init__(self, other): super(DeadActor, self).__init__() self._o = other self.count = 3 def tick(self): self._o.send("ping") self.recv() self.count -= 1 if self.count == 0: raise RuntimeError("Fatal exception: FOO ...
class DeadActor(LActor):
def __init__(self, other): super(DeadActor, self).__init__() self._o = other self.count = 3 def tick(self): self._o.send("ping") self.recv() self.count -= 1 if self.count == 0: raise RuntimeError("Fatal exception: FOO is BARed")
(B, self).__init__() self._o = other self.count = 10 def tick(self): self._o.send("ping") self.recv() self.count -= 1 if self.count == 0: return self.STOP class DeadActor(LActor):
64
64
85
6
57
pbs/thespian
src/thespian/_tests/test_actor.py
Python
DeadActor
DeadActor
36
47
36
36
1712e8a5933217b004da424b8f7a97b0126e6150
bigcode/the-stack
train
92c87d52a44687711e91f436
train
class
class A(LActor): def __init__(self, other): super(A, self).__init__() self._o = other self.count = 10 def tick(self): self.recv() self._o.send("pong") self.count -= 1 if self.count == 0: return self.STOP
class A(LActor):
def __init__(self, other): super(A, self).__init__() self._o = other self.count = 10 def tick(self): self.recv() self._o.send("pong") self.count -= 1 if self.count == 0: return self.STOP
import time import pytest from thespian.actor import LActor, DeadActorException class A(LActor):
24
64
74
5
18
pbs/thespian
src/thespian/_tests/test_actor.py
Python
A
A
8
19
8
8
9469a3f7ab5f3c7473fbd4928cfbd43098b6dea4
bigcode/the-stack
train
a80f1ac49e4f0bd49feff78b
train
function
def get_positions_to_recover(fake_genome_mapping_filename, mpileup_filename, genome_snp, min_cov=40): """ Return a list of genomic positions that isophase should call SNPs for. Must be: 1. covered (based on ccs.mpileup) with at least MIN_COVERAGE (default: 40) 2. is a SNP (based on genome VCF) ...
def get_positions_to_recover(fake_genome_mapping_filename, mpileup_filename, genome_snp, min_cov=40):
""" Return a list of genomic positions that isophase should call SNPs for. Must be: 1. covered (based on ccs.mpileup) with at least MIN_COVERAGE (default: 40) 2. is a SNP (based on genome VCF) """ fake_map = read_fake_mapping(fake_genome_mapping_filename) good_positions = [] cov_at_...
_map = {} with open(fake_genome_mapping_filename) as (f): for line in f: fake_pos, ref_chr, ref_pos = line.strip().split(',') fake_map[int(fake_pos)] = (ref_chr, int(ref_pos)) return fake_map def get_positions_to_recover(fake_genome_mapping_filename, mpileup_filename, genome_snp...
84
84
280
26
57
ArthurDondi/cDNA_Cupcake
phasing/utils/evaluate_snp_with_genome.py
Python
get_positions_to_recover
get_positions_to_recover
24
44
24
24
b95d39086a4328a4febe3f51bf8ae892fbbaff7e
bigcode/the-stack
train
1e33e531adb2e3d7bcb03ac2
train
function
def read_fake_mapping(fake_genome_mapping_filename): """ :param fake_genome_mapping_filename: fake genome mapping file :return: dict of fake position -> (chr, ref position) """ fake_map = {} with open(fake_genome_mapping_filename) as (f): for line in f: fake_pos, ref_chr, ref...
def read_fake_mapping(fake_genome_mapping_filename):
""" :param fake_genome_mapping_filename: fake genome mapping file :return: dict of fake position -> (chr, ref position) """ fake_map = {} with open(fake_genome_mapping_filename) as (f): for line in f: fake_pos, ref_chr, ref_pos = line.strip().split(',') fake_map[i...
= 'etseng@pacb.com' import os, sys, glob from collections import defaultdict from csv import DictReader, DictWriter from bx.intervals import IntervalTree import vcf import phasing.io.SAMMPileUpReader as sp def read_fake_mapping(fake_genome_mapping_filename):
64
64
103
10
53
ArthurDondi/cDNA_Cupcake
phasing/utils/evaluate_snp_with_genome.py
Python
read_fake_mapping
read_fake_mapping
10
21
10
10
0ce5cad6500475481b37984ec5eb0cc2661ffbb7
bigcode/the-stack
train
26e927e2ea0cda331a946c03
train
function
def main_brangus(vcf_filename, out_filename, unzip_snps=None): if unzip_snps is None: unzip_snps = defaultdict(lambda : {}) for r in vcf.VCFReader(open(vcf_filename)): unzip_snps[r.CHROM][r.POS] = r print('Finished reading ' + vcf_filename, file=sys.stderr) out_f = open(out_file...
def main_brangus(vcf_filename, out_filename, unzip_snps=None):
if unzip_snps is None: unzip_snps = defaultdict(lambda : {}) for r in vcf.VCFReader(open(vcf_filename)): unzip_snps[r.CHROM][r.POS] = r print('Finished reading ' + vcf_filename, file=sys.stderr) out_f = open(out_filename, 'w') FIELDS = ['dir', 'chrom', 'pos', 'strand', 'ref'...
': 'Y', 'in_PB': 'N', 'cov_Short': 'NA', 'cov_PB': cov_at_pos[chrom,pos-1], 'genomic_HP': 'Y' if (chrom in repeat_by_chrom and len(repeat_by_chrom[chrom].find(pos,pos))>0) else 'N' } try: out['cov_Short'] = shortread_cov[chro...
135
135
453
17
118
ArthurDondi/cDNA_Cupcake
phasing/utils/evaluate_snp_with_genome.py
Python
main_brangus
main_brangus
105
137
105
105
12bbc751638141d952a255c75d3cf85fc0400859
bigcode/the-stack
train
11ce044532146a83c5fedd54
train
function
def main_maize(ki11_snps=None, dirs=None): if ki11_snps is None: ki11_snps = defaultdict(lambda : {}) # chrom -> pos -> VCF record debug_count = 0 for r in vcf.VCFReader(open('B73Ki11.q20.vcf')): ki11_snps[r.CHROM][r.POS] = r #if debug_count > 100000: break ...
def main_maize(ki11_snps=None, dirs=None):
if ki11_snps is None: ki11_snps = defaultdict(lambda : {}) # chrom -> pos -> VCF record debug_count = 0 for r in vcf.VCFReader(open('B73Ki11.q20.vcf')): ki11_snps[r.CHROM][r.POS] = r #if debug_count > 100000: break debug_count += 1 print('Finished rea...
1, 'phased.partial.NO_SNPS_FOUND') if not os.path.exists(vcffile): assert os.path.exists(nosnp) print(('Skipping {0} because no SNPs found.').format(d1), file=sys.stderr) else: print(('Evaluating {0}.').format(d1), file=sys.stderr) strand = 'NA' ...
213
213
711
14
198
ArthurDondi/cDNA_Cupcake
phasing/utils/evaluate_snp_with_genome.py
Python
main_maize
main_maize
139
191
139
139
58f3f5c3edc3fac6982b1daf23a351c12dfdc692
bigcode/the-stack
train
c279cd4340ce48cbfd729831
train
function
def eval_isophase(isophase_vcf, genome_snp, good_positions, cov_at_pos, repeat_by_chrom, shortread_cov, writer_f, name='NA', strand='NA'): for r in vcf.VCFReader(open(isophase_vcf)): out = {'dir': name, 'chrom': 'NA', 'pos': r.POS, 'strand': strand, ...
def eval_isophase(isophase_vcf, genome_snp, good_positions, cov_at_pos, repeat_by_chrom, shortread_cov, writer_f, name='NA', strand='NA'):
for r in vcf.VCFReader(open(isophase_vcf)): out = {'dir': name, 'chrom': 'NA', 'pos': r.POS, 'strand': strand, 'ref': r.REF, 'alt_Short': 'NA', 'alt_PB': 'NA', 'in_Short': 'NA', 'in_PB': '...
used for reports later for rec in sp.MPileUpReader(mpileup_filename): if rec is None: # means coverage zero, ignore continue genome_chr, genome_pos = fake_map[rec.pos] cov_at_pos[(genome_chr,genome_pos)] = rec.nCov if rec.nCov >= min_cov: genome_chr = genome_...
186
186
621
42
143
ArthurDondi/cDNA_Cupcake
phasing/utils/evaluate_snp_with_genome.py
Python
eval_isophase
eval_isophase
47
102
47
47
2f1cbeaa1039e65f224cbbe7933a79945ef90f70
bigcode/the-stack
train
e5265d8bfcf4feefc2fe13d7
train
class
class VAE(nn.Module): def __init__(self, sample_dim=784, hidden_dim=400, z_dim=20): super(VAE, self).__init__() self.encode = Encoder(input_dim=sample_dim, hidden_dim=hidden_dim, output_dim=z_dim) self.decode = Decoder(input_dim=z_dim, hidden_dim=hidden_dim, output_dim=sample_dim) def r...
class VAE(nn.Module):
def __init__(self, sample_dim=784, hidden_dim=400, z_dim=20): super(VAE, self).__init__() self.encode = Encoder(input_dim=sample_dim, hidden_dim=hidden_dim, output_dim=z_dim) self.decode = Decoder(input_dim=z_dim, hidden_dim=hidden_dim, output_dim=sample_dim) def reparameterize(self, mu...
= nn.Linear(input_dim, hidden_dim) self.fc4 = nn.Linear(hidden_dim, output_dim) def forward(self, z): h3 = F.relu(self.fc3(z)) h4 = torch.sigmoid(self.fc4(h3)) return h4 class VAE(nn.Module):
64
64
167
6
57
czhongyu/generative-models
vae.py
Python
VAE
VAE
42
57
42
42
f1db43298495a6714d77f1d757bf50cb5a780db8
bigcode/the-stack
train
32ce3b4dcacafc7fed51dc4e
train
function
def main(): epochs = int(config['vae']['epochs']) for epoch in range(1, epochs + 1): train(epoch) dev(epoch) # generate result every epoch with torch.no_grad(): sample = torch.randn(64, z_dim).to(device) sample = model.decode(sample).cpu() save...
def main():
epochs = int(config['vae']['epochs']) for epoch in range(1, epochs + 1): train(epoch) dev(epoch) # generate result every epoch with torch.no_grad(): sample = torch.randn(64, z_dim).to(device) sample = model.decode(sample).cpu() save_image(sampl...
_image(comparison.cpu(), config['vae']['result_path'] + 'reconstruction_test.png', nrow=n) test_loss /= len(test_loader.dataset) writer.add_scalar('test_loss', test_loss) print('====> Test set loss: {:.4f}'.format(test_loss)) def main():
64
64
161
3
61
czhongyu/generative-models
vae.py
Python
main
main
151
166
151
151
f071e1fc113774e6a5984888cc3e8abcb6052399
bigcode/the-stack
train
fe9843cbce81940da21e46fd
train
function
def test(): model.eval() test_loss = 0 with torch.no_grad(): for i, (data, _) in enumerate(test_loader): data = data.to(device) recon_batch, mu, logvar = model(data) test_loss += loss_function(recon_batch, data, mu, logvar).item() # comparison between ...
def test():
model.eval() test_loss = 0 with torch.no_grad(): for i, (data, _) in enumerate(test_loader): data = data.to(device) recon_batch, mu, logvar = model(data) test_loss += loss_function(recon_batch, data, mu, logvar).item() # comparison between original dat...
4f}'.format(dev_loss)) # save model if dev_loss < best_loss: print('Better loss! Saving model!') torch.save(model.state_dict(), config['vae']['model_path'] + 'vae.pth') best_epoch, best_loss = epoch, dev_loss def test():
64
64
192
3
60
czhongyu/generative-models
vae.py
Python
test
test
130
148
130
130
5781c18191332c5ac2102682b87ef7d671c974d2
bigcode/the-stack
train
dae62743a7e02957a0a927ae
train
function
def loss_function(recon_x, x, mu, logvar): # ELBO # Reconstruction + KL divergence losses summed over all elements and batch BCE = F.binary_cross_entropy(recon_x, x.view(-1, sample_dim), reduction='sum') # see Appendix B from VAE paper: # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2...
def loss_function(recon_x, x, mu, logvar): # ELBO # Reconstruction + KL divergence losses summed over all elements and batch
BCE = F.binary_cross_entropy(recon_x, x.view(-1, sample_dim), reduction='sum') # see Appendix B from VAE paper: # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014 # https://arxiv.org/abs/1312.6114 # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2) KLD = 0.5 * torch.sum(1 + logvar - m...
.encode(x) z = self.reparameterize(mu, logvar) output = self.decode(z) return output, mu, logvar def loss_function(recon_x, x, mu, logvar): # ELBO # Reconstruction + KL divergence losses summed over all elements and batch
64
64
164
33
30
czhongyu/generative-models
vae.py
Python
loss_function
loss_function
60
71
60
62
3ff2ef54d510cbd5e2affe71516b707f56574c5c
bigcode/the-stack
train
dc2b1adf6078b44f412c7e61
train
class
class Decoder(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(Decoder, self).__init__() self.fc3 = nn.Linear(input_dim, hidden_dim) self.fc4 = nn.Linear(hidden_dim, output_dim) def forward(self, z): h3 = F.relu(self.fc3(z)) h4 = torch.sigmoid(sel...
class Decoder(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim): super(Decoder, self).__init__() self.fc3 = nn.Linear(input_dim, hidden_dim) self.fc4 = nn.Linear(hidden_dim, output_dim) def forward(self, z): h3 = F.relu(self.fc3(z)) h4 = torch.sigmoid(self.fc4(h3)) return ...
, output_dim) def forward(self, x): x = x.view(-1, self.input_dim) h1 = F.relu(self.fc1(x)) mu, logvar = self.fc21(h1), self.fc22(h1) return mu, logvar class Decoder(nn.Module):
64
64
92
5
58
czhongyu/generative-models
vae.py
Python
Decoder
Decoder
30
39
30
30
0f59f4da8802949e87f585b46fb16e5ce8746b40
bigcode/the-stack
train
695075d34b157dd441604c8a
train
function
def dev(epoch): global best_epoch, best_loss model.eval() dev_loss = 0 with torch.no_grad(): for i, (data, _) in enumerate(dev_loader): data = data.to(device) recon_batch, mu, logvar = model(data) dev_loss += loss_function(recon_batch, data, mu, logvar).item()...
def dev(epoch):
global best_epoch, best_loss model.eval() dev_loss = 0 with torch.no_grad(): for i, (data, _) in enumerate(dev_loader): data = data.to(device) recon_batch, mu, logvar = model(data) dev_loss += loss_function(recon_batch, data, mu, logvar).item() # c...
() / len(data))) train_loss /= len(train_loader.dataset) writer.add_scalar('train_epoch_loss', train_loss, epoch) print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, train_loss)) # save model # torch.save(model.state_dict(), config['vae']['model_path'] + 'vae.pth') def dev(epoch):
79
79
264
4
75
czhongyu/generative-models
vae.py
Python
dev
dev
102
127
102
102
851a310e8f085bd22e0d09510309487c01e293a3
bigcode/the-stack
train
a1022b1a7d74fd2e9d46b44e
train
function
def train(epoch): model.train() train_loss = 0 for batch_idx, (data, _) in enumerate(train_loader): data = data.to(device) optimizer.zero_grad() recon_batch, mu, logvar = model(data) loss = loss_function(recon_batch, data, mu, logvar) loss.backward() train_los...
def train(epoch):
model.train() train_loss = 0 for batch_idx, (data, _) in enumerate(train_loader): data = data.to(device) optimizer.zero_grad() recon_batch, mu, logvar = model(data) loss = loss_function(recon_batch, data, mu, logvar) loss.backward() train_loss += loss.item() ...
/abs/1312.6114 # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2) KLD = 0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return BCE - KLD def train(epoch):
73
73
244
4
68
czhongyu/generative-models
vae.py
Python
train
train
74
96
74
74
e051c7a310ea70f71327bf417335308526c6f553
bigcode/the-stack
train
7f34e5909f74697e2e86e3de
train
class
class Encoder(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(Encoder, self).__init__() self.input_dim = input_dim self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc21 = nn.Linear(hidden_dim, output_dim) self.fc22 = nn.Linear(hidden_dim, output_dim) ...
class Encoder(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim): super(Encoder, self).__init__() self.input_dim = input_dim self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc21 = nn.Linear(hidden_dim, output_dim) self.fc22 = nn.Linear(hidden_dim, output_dim) def forward(self, x):...
configparser import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image import numpy as np from tensorboardX import SummaryWriter import random import os class Encoder(nn.Module):
64
64
132
5
58
czhongyu/generative-models
vae.py
Python
Encoder
Encoder
15
27
15
15
24e6398101306b66972a724b98eb207e9000196b
bigcode/the-stack
train
3b560ce403ce461c1cc45fdf
train
class
class MultiRNNCell(MultiRNNCellBase): def __init__(self, cells, state_is_tuple=True): super(MultiRNNCell, self).__init__(cells, state_is_tuple) self.old_outputs = [] self.old_states = [] self.new_outputs = [] def call(self, inputs, state): cur_state_pos = 0 cur_inp = inputs ...
class MultiRNNCell(MultiRNNCellBase):
def __init__(self, cells, state_is_tuple=True): super(MultiRNNCell, self).__init__(cells, state_is_tuple) self.old_outputs = [] self.old_states = [] self.new_outputs = [] def call(self, inputs, state): cur_state_pos = 0 cur_inp = inputs new_states = [] old_states = [] ...
from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import variable_scope as vs from tensorflow.python.training.checkpointable import base as checkpointable from tensorflow.python.util import nest from tensorflow.python.ops.array_ops import zeros, zero...
173
230
768
13
160
IBM/ostl
Scripts/MultiRNNCell.py
Python
MultiRNNCell
MultiRNNCell
17
103
17
18
c79c257849008c7bfc546c8f9174858f61d61a09
bigcode/the-stack
train
68f630292ab7deb28f884234
train
function
def test_cast_int(env): res = env.int('unparsed_int') assert res == -2, "casting unparsed_int failed" assert env.clear('unparsed_int') is True, "expecting True when unparsed_int popped"
def test_cast_int(env):
res = env.int('unparsed_int') assert res == -2, "casting unparsed_int failed" assert env.clear('unparsed_int') is True, "expecting True when unparsed_int popped"
_bool(env): res = env.bool('unparsed_bool') assert res is True, "casting unparsed_bool failed" assert env.clear('unparsed_bool') is True, "expecting True when unparsed_bool popped" # cannot retrieve anymore or throws an error def test_cast_int(env):
64
64
52
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_int
test_cast_int
52
55
52
52
3e0febfc570f8249c0ab2cb5a42e356fec8793ae
bigcode/the-stack
train
bb831740253d81ba538a8622
train
function
def test_set_value_2(env): env.set('my_key', '1234') res = env('my_key') assert res == '1234', "testing setting custom string my_key failed" assert env.clear('my_key') is True, "expecting True when mode popped"
def test_set_value_2(env):
env.set('my_key', '1234') res = env('my_key') assert res == '1234', "testing setting custom string my_key failed" assert env.clear('my_key') is True, "expecting True when mode popped"
') assert res == json.dumps({"mmm": 12}), "casting unparsed_unparsed_json failed" assert env.clear('unparsed_json') is True, "expecting True when unparsed_unparsed_json popped" # cannot retrieve anymore or throws an error def test_set_value_2(env):
64
64
63
8
55
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_set_value_2
test_set_value_2
138
142
138
138
82181b2d0447331477b76bf332cf1eb241b5aec0
bigcode/the-stack
train
f27461a503b32646f8b12f8f
train
function
def test_cast_date(env): res = env.date('unparsed_date') assert type(res) is type( datetime.strptime('09-19-2018', '%m-%d-%Y').date()), "casting unparsed_date failed" assert env.clear('unparsed_date') is True, "expecting True when unparsed_date popped"
def test_cast_date(env):
res = env.date('unparsed_date') assert type(res) is type( datetime.strptime('09-19-2018', '%m-%d-%Y').date()), "casting unparsed_date failed" assert env.clear('unparsed_date') is True, "expecting True when unparsed_date popped"
13:55:26', '%m/%d/%y %H:%M:%S')), "casting unparsed_datetime failed" assert env.clear('unparsed_datetime') is True, "expecting True when unparsed_datetime popped" # cannot retrieve anymore or throws an error def test_cast_date(env):
64
64
73
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_date
test_cast_date
74
78
74
74
c7bdd175543fd199135759f972d9eb8432ffbf60
bigcode/the-stack
train
bf3d82c29fb8105237b61966
train
function
def test_set_value(env): env.set('my_key', 1234) res = env.int('my_key') assert res == 1234, "testing setting custom string my_key failed" assert env.clear('my_key') is True, "expecting True when mode popped"
def test_set_value(env):
env.set('my_key', 1234) res = env.int('my_key') assert res == 1234, "testing setting custom string my_key failed" assert env.clear('my_key') is True, "expecting True when mode popped"
envmanager.tests.data import envloader_config_casts config = envloader_config_casts """ Tests castings """ @pytest.fixture def env(): @env_loader(config) def inner(): from envmanager.core import Env return Env(config) return inner() def test_set_value(env):
64
64
62
6
58
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_set_value
test_set_value
30
34
30
30
b1a48e0534fc4d2f06b93d95d349f6738774655e
bigcode/the-stack
train
972f45aa0cc4cec57ec1ed44
train
function
def test_cast_dict(env): res = env.dict('unparsed_dict') assert res == {"a": 1}, "casting unparsed_dict failed" assert env.clear('unparsed_dict') is True, "expecting True when unparsed_dict popped"
def test_cast_dict(env):
res = env.dict('unparsed_dict') assert res == {"a": 1}, "casting unparsed_dict failed" assert env.clear('unparsed_dict') is True, "expecting True when unparsed_dict popped"
= env.float('unparsed_float') assert res == 12345678.0, "casting unparsed_float failed" assert env.clear('unparsed_float') is True, "expecting True when unparsed_float popped" # cannot retrieve anymore or throws an error def test_cast_dict(env):
64
64
55
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_dict
test_cast_dict
117
120
117
117
0733eb30b7c9147155b2d97319e5c1b58bdb57cd
bigcode/the-stack
train
bb3f9c447246360e19d08bab
train
function
def test_set_value_3(env): env.set('my_key_2', '2020-10-10') res = env('my_key_2') assert res == '2020-10-10', "testing setting custom string my_key_2 failed" assert env.clear('my_key_2') is True, "expecting True when mode popped"
def test_set_value_3(env):
env.set('my_key_2', '2020-10-10') res = env('my_key_2') assert res == '2020-10-10', "testing setting custom string my_key_2 failed" assert env.clear('my_key_2') is True, "expecting True when mode popped"
4') res = env('my_key') assert res == '1234', "testing setting custom string my_key failed" assert env.clear('my_key') is True, "expecting True when mode popped" # cannot retrieve anymore or throws an error def test_set_value_3(env):
64
64
80
8
55
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_set_value_3
test_set_value_3
146
150
146
146
21870f58e9afc0508c4eda38e17e5ee5a93c426c
bigcode/the-stack
train
8b5f1c19ea8bed3fbf52793e
train
function
@pytest.fixture def env(): @env_loader(config) def inner(): from envmanager.core import Env return Env(config) return inner()
@pytest.fixture def env(): @env_loader(config)
def inner(): from envmanager.core import Env return Env(config) return inner()
import Decimal from urllib.parse import urlparse from uuid import UUID import pytest from envmanager.decorators import env_loader from envmanager.tests.data import envloader_config_casts config = envloader_config_casts """ Tests castings """ @pytest.fixture def env(): @env_loader(config)
64
64
33
12
52
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
env
env
20
27
20
22
7d4c360a0853597a8e3e10eb9483a7ff5a552050
bigcode/the-stack
train
09f3eec7d672fef2250a0b3c
train
function
def test_cast_bool(env): res = env.bool('unparsed_bool') assert res is True, "casting unparsed_bool failed" assert env.clear('unparsed_bool') is True, "expecting True when unparsed_bool popped"
def test_cast_bool(env):
res = env.bool('unparsed_bool') assert res is True, "casting unparsed_bool failed" assert env.clear('unparsed_bool') is True, "expecting True when unparsed_bool popped"
): res = env.str('unparsed_str') assert res == '1234', "casting unparsed_str failed" assert env.clear('unparsed_str') is True, "expecting True when unparsed_str popped" # cannot retrieve anymore or throws an error def test_cast_bool(env):
64
64
51
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_bool
test_cast_bool
45
48
45
45
003bfc2c5024574e84d4096d7d7a1b10caef0d3a
bigcode/the-stack
train
e163831ffffea34718a025f8
train
function
def test_cast_str(env): res = env.str('unparsed_str') assert res == '1234', "casting unparsed_str failed" assert env.clear('unparsed_str') is True, "expecting True when unparsed_str popped"
def test_cast_str(env):
res = env.str('unparsed_str') assert res == '1234', "casting unparsed_str failed" assert env.clear('unparsed_str') is True, "expecting True when unparsed_str popped"
1234) res = env.int('my_key') assert res == 1234, "testing setting custom string my_key failed" assert env.clear('my_key') is True, "expecting True when mode popped" # cannot retrieve anymore or throws an error def test_cast_str(env):
64
64
53
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_str
test_cast_str
38
41
38
38
4ef47ca34f6b584dfa7e8e3945ddec4fc6e95750
bigcode/the-stack
train
6d70afd1a096928673d83786
train
function
def test_cast_decimal(env): res = env.decimal('unparsed_decimal') assert res == Decimal('12.2'), "casting unparsed_decimal failed" assert env.clear('unparsed_decimal') is True, "expecting True when unparsed_decimal popped"
def test_cast_decimal(env):
res = env.decimal('unparsed_decimal') assert res == Decimal('12.2'), "casting unparsed_decimal failed" assert env.clear('unparsed_decimal') is True, "expecting True when unparsed_decimal popped"
res = env.dict('unparsed_dict') assert res == {"a": 1}, "casting unparsed_dict failed" assert env.clear('unparsed_dict') is True, "expecting True when unparsed_dict popped" # cannot retrieve anymore or throws an error def test_cast_decimal(env):
64
64
57
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_decimal
test_cast_decimal
124
127
124
124
ac29416dbb59d30a03fe57f03e4f2c61b77e94e0
bigcode/the-stack
train
816fb1224c4a86331cddade3
train
function
def test_cast_log_level(env): res = env.log_level_as_str('unparsed_log_int') assert res == "DEBUG", "casting unparsed_log failed" assert env.clear('unparsed_log') is True, "expecting True when unparsed_log popped"
def test_cast_log_level(env):
res = env.log_level_as_str('unparsed_log_int') assert res == "DEBUG", "casting unparsed_log failed" assert env.clear('unparsed_log') is True, "expecting True when unparsed_log popped"
_as_int('unparsed_log') assert res == logging.getLevelName("DEBUG"), "casting unparsed_log failed" assert env.clear('unparsed_log') is True, "expecting True when unparsed_log popped" # cannot retrieve anymore or throws an error def test_cast_log_level(env):
64
64
57
7
56
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_log_level
test_cast_log_level
103
106
103
103
9e5f8c18d7672e459c5def2281c23c51c09f78e9
bigcode/the-stack
train
d55e24f7d09e90990f093749
train
function
def test_cast_json(env): res = env.json('unparsed_json') assert res == json.dumps({"mmm": 12}), "casting unparsed_unparsed_json failed" assert env.clear('unparsed_json') is True, "expecting True when unparsed_unparsed_json popped"
def test_cast_json(env):
res = env.json('unparsed_json') assert res == json.dumps({"mmm": 12}), "casting unparsed_unparsed_json failed" assert env.clear('unparsed_json') is True, "expecting True when unparsed_unparsed_json popped"
env.decimal('unparsed_decimal') assert res == Decimal('12.2'), "casting unparsed_decimal failed" assert env.clear('unparsed_decimal') is True, "expecting True when unparsed_decimal popped" # cannot retrieve anymore or throws an error def test_cast_json(env):
64
64
61
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_json
test_cast_json
131
134
131
131
7d68495daae5941c2c4e06f8cfe5587a66799866
bigcode/the-stack
train
e71ad76bdec9976f95fa3d51
train
function
def test_uuid(env): res = env.uuid('unparsed_uuid') assert res == UUID('12345678-1234-5678-1234-567812345678'), "casting unparsed_uuid failed" assert env.clear('unparsed_uuid') is True, "expecting True when unparsed_uuid popped"
def test_uuid(env):
res = env.uuid('unparsed_uuid') assert res == UUID('12345678-1234-5678-1234-567812345678'), "casting unparsed_uuid failed" assert env.clear('unparsed_uuid') is True, "expecting True when unparsed_uuid popped"
parsed_url') assert res.hostname == urlparse('https://stackoverflow.com/questions/').hostname, "casting unparsed_url failed" assert env.clear('unparsed_url') is True, "expecting True when unparsed_url popped" # cannot retrieve anymore or throws an error def test_uuid(env):
64
64
68
5
58
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_uuid
test_uuid
89
92
89
89
1f19e27e63a64c606a85cd43479f06fddff9fe48
bigcode/the-stack
train
a679f07a6bc6706190478378
train
function
def test_cast_list(env): res = env.list('unparsed_list') assert res == [1, 2, 3, 'string'], "casting unparsed_int failed" assert env.clear('unparsed_list') is True, "expecting True when unparsed_list popped"
def test_cast_list(env):
res = env.list('unparsed_list') assert res == [1, 2, 3, 'string'], "casting unparsed_int failed" assert env.clear('unparsed_list') is True, "expecting True when unparsed_list popped"
(env): res = env.int('unparsed_int') assert res == -2, "casting unparsed_int failed" assert env.clear('unparsed_int') is True, "expecting True when unparsed_int popped" # cannot retrieve anymore or throws an error def test_cast_list(env):
64
64
61
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_list
test_cast_list
59
62
59
59
b576d95929d52983a8c5d35acb9fb75a7d872e39
bigcode/the-stack
train
60a94aaccfec5118fc773e0a
train
function
def test_url(env): res = env.url('unparsed_url') assert res.hostname == urlparse('https://stackoverflow.com/questions/').hostname, "casting unparsed_url failed" assert env.clear('unparsed_url') is True, "expecting True when unparsed_url popped"
def test_url(env):
res = env.url('unparsed_url') assert res.hostname == urlparse('https://stackoverflow.com/questions/').hostname, "casting unparsed_url failed" assert env.clear('unparsed_url') is True, "expecting True when unparsed_url popped"
datetime.strptime('09-19-2018', '%m-%d-%Y').date()), "casting unparsed_date failed" assert env.clear('unparsed_date') is True, "expecting True when unparsed_date popped" # cannot retrieve anymore or throws an error def test_url(env):
64
64
61
5
58
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_url
test_url
82
85
82
82
c272ce2ca4582a399d151c66e25616e949a1d052
bigcode/the-stack
train
008bd1b6564581ee411339f5
train
function
def test_cast_float(env): res = env.float('unparsed_float') assert res == 12345678.0, "casting unparsed_float failed" assert env.clear('unparsed_float') is True, "expecting True when unparsed_float popped"
def test_cast_float(env):
res = env.float('unparsed_float') assert res == 12345678.0, "casting unparsed_float failed" assert env.clear('unparsed_float') is True, "expecting True when unparsed_float popped"
= env.log_level_as_str('unparsed_log_int') assert res == "DEBUG", "casting unparsed_log failed" assert env.clear('unparsed_log') is True, "expecting True when unparsed_log popped" # cannot retrieve anymore or throws an error def test_cast_float(env):
64
64
56
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_float
test_cast_float
110
113
110
110
1e6cd337fcd53f0542f5fef9c603d27391ec1b74
bigcode/the-stack
train
97a32a74de1ceeb38589c183
train
function
def test_cast_datetime(env): res = env.datetime('unparsed_datetime') assert type(res) is type( datetime.strptime('09/19/18 13:55:26', '%m/%d/%y %H:%M:%S')), "casting unparsed_datetime failed" assert env.clear('unparsed_datetime') is True, "expecting True when unparsed_datetime popped"
def test_cast_datetime(env):
res = env.datetime('unparsed_datetime') assert type(res) is type( datetime.strptime('09/19/18 13:55:26', '%m/%d/%y %H:%M:%S')), "casting unparsed_datetime failed" assert env.clear('unparsed_datetime') is True, "expecting True when unparsed_datetime popped"
parsed_list') assert res == [1, 2, 3, 'string'], "casting unparsed_int failed" assert env.clear('unparsed_list') is True, "expecting True when unparsed_list popped" # cannot retrieve anymore or throws an error def test_cast_datetime(env):
64
64
82
6
57
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_datetime
test_cast_datetime
66
70
66
66
6de28a0f575834d3f1114d16ec0a156745eaf3a2
bigcode/the-stack
train
0c20fab02d5ccdbec00cf930
train
function
def test_cast_log_level(env): res = env.log_level_as_int('unparsed_log') assert res == logging.getLevelName("DEBUG"), "casting unparsed_log failed" assert env.clear('unparsed_log') is True, "expecting True when unparsed_log popped"
def test_cast_log_level(env):
res = env.log_level_as_int('unparsed_log') assert res == logging.getLevelName("DEBUG"), "casting unparsed_log failed" assert env.clear('unparsed_log') is True, "expecting True when unparsed_log popped"
12345678-1234-5678-1234-567812345678'), "casting unparsed_uuid failed" assert env.clear('unparsed_uuid') is True, "expecting True when unparsed_uuid popped" # cannot retrieve anymore or throws an error def test_cast_log_level(env):
64
64
60
7
56
arianseyedi/python-envmanager
envmanager/tests/test_casting_funcs.py
Python
test_cast_log_level
test_cast_log_level
96
99
96
96
9809fb672f8c0d62cd470bc86b05b0a1e6986d37
bigcode/the-stack
train
8b217353f79a11b0231860c5
train
function
def convert_readme(): try: call(["pandoc", "-f", "markdown_github", "-t", "rst", "-o", "README.txt", "README.markdown"]) except OSError: pass return open('README.txt').read()
def convert_readme():
try: call(["pandoc", "-f", "markdown_github", "-t", "rst", "-o", "README.txt", "README.markdown"]) except OSError: pass return open('README.txt').read()
#!/usr/bin/env python from setuptools import setup from subprocess import call def convert_readme():
21
64
59
5
15
Telmediq/django-genericadmin
setup.py
Python
convert_readme
convert_readme
6
11
6
6
45500de6133e82e57241cc10f621e188007fc1ff
bigcode/the-stack
train
49da9d9d01286e4c603d8d14
train
class
class F5BigIpLtmMonitorRpc(F5BigIpNamedObject): def _set_crud_methods(self): self._methods = { 'create': self._api.tm.ltm.monitor.rpcs.rpc.create, 'read': self._api.tm.ltm.monitor.rpcs.rpc.load, 'update': self._api.tm.ltm.monitor.rpcs.rpc.update, 'delete': sel...
class F5BigIpLtmMonitorRpc(F5BigIpNamedObject):
def _set_crud_methods(self): self._methods = { 'create': self._api.tm.ltm.monitor.rpcs.rpc.create, 'read': self._api.tm.ltm.monitor.rpcs.rpc.load, 'update': self._api.tm.ltm.monitor.rpcs.rpc.update, 'delete': self._api.tm.ltm.monitor.rpcs.rpc.delete, ...
=dict(type='int') ) argument_spec.update(F5_PROVIDER_ARGS) argument_spec.update(F5_NAMED_OBJ_ARGS) return argument_spec @property def supports_check_mode(self): return True class F5BigIpLtmMonitorRpc(F5BigIpNamedObject):
64
64
113
16
47
GabrielFortin/ansible-module-f5bigip
library/f5bigip_ltm_monitor_rpc.py
Python
F5BigIpLtmMonitorRpc
F5BigIpLtmMonitorRpc
157
165
157
157
205d8071d42ddfa3b046fa81a77d5e66baabc415
bigcode/the-stack
train
54e9a64042205b12d7b2ebd1
train
class
class ModuleParams(object): @property def argument_spec(self): argument_spec = dict( app_service=dict(type='str'), debug=dict(type='str', choices=F5_POLAR_CHOICES), defaults_from=dict(type='str'), description=dict(type='str'), destination=dict(...
class ModuleParams(object): @property
def argument_spec(self): argument_spec = dict( app_service=dict(type='str'), debug=dict(type='str', choices=F5_POLAR_CHOICES), defaults_from=dict(type='str'), description=dict(type='str'), destination=dict(type='str'), interval=dict(typ...
5.base import F5_NAMED_OBJ_ARGS from ansible_common_f5.base import F5_POLAR_CHOICES from ansible_common_f5.base import F5_PROVIDER_ARGS from ansible_common_f5.bigip import F5BigIpNamedObject class ModuleParams(object): @property
64
64
189
9
54
GabrielFortin/ansible-module-f5bigip
library/f5bigip_ltm_monitor_rpc.py
Python
ModuleParams
ModuleParams
130
154
130
131
3eaf3a308e104253d7180b8c253f3da311d8be14
bigcode/the-stack
train
77ed717291182d75967e846e
train
function
def main(): params = ModuleParams() module = AnsibleModule(argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode) try: obj = F5BigIpLtmMonitorRpc(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except Ex...
def main():
params = ModuleParams() module = AnsibleModule(argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode) try: obj = F5BigIpLtmMonitorRpc(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except Exception as e...
._api.tm.ltm.monitor.rpcs.rpc.load, 'update': self._api.tm.ltm.monitor.rpcs.rpc.update, 'delete': self._api.tm.ltm.monitor.rpcs.rpc.delete, 'exists': self._api.tm.ltm.monitor.rpcs.rpc.exists } def main():
64
64
82
3
61
GabrielFortin/ansible-module-f5bigip
library/f5bigip_ltm_monitor_rpc.py
Python
main
main
168
177
168
168
4685d9850e9770c6428e57a3dd119da177f56a82
bigcode/the-stack
train
1b531436c67ffc405c98bd92
train
class
class Mount(AbstractMount): """Mount class for a simulator. Use this when you don't actually have a mount attached. """ def __init__(self, location, commands=dict(), *args, **kwargs ): super().__init__(location, *args, **kwargs) ...
class Mount(AbstractMount):
"""Mount class for a simulator. Use this when you don't actually have a mount attached. """ def __init__(self, location, commands=dict(), *args, **kwargs ): super().__init__(location, *args, **kwargs) self.logger.info('\t...
import time from astropy import units as u from pocs.utils import current_time from pocs.mount import AbstractMount class Mount(AbstractMount):
32
256
1,295
5
26
kmeagle1515/POCS
pocs/mount/simulator.py
Python
Mount
Mount
9
226
9
10
a5295ab3036c1bacf9b38123d0701da69a3ea257
bigcode/the-stack
train
09c2c7dda5c8acb6b047e539
train
class
class UpdateNameTestCase(BaseTestCase): def setUp(self): super(UpdateNameTestCase, self).setUp() self.check = Check.objects.create(project=self.project) self.url = "/checks/%s/name/" % self.check.code self.redirect_url = "/projects/%s/checks/" % self.project.code def test_it_wo...
class UpdateNameTestCase(BaseTestCase):
def setUp(self): super(UpdateNameTestCase, self).setUp() self.check = Check.objects.create(project=self.project) self.url = "/checks/%s/name/" % self.check.code self.redirect_url = "/projects/%s/checks/" % self.project.code def test_it_works(self): self.client.login(use...
from hc.api.models import Check from hc.test import BaseTestCase class UpdateNameTestCase(BaseTestCase):
24
188
628
9
14
s1s5/healthchecks
hc/front/tests/test_update_name.py
Python
UpdateNameTestCase
UpdateNameTestCase
5
73
5
5
364b608f1c7f61e511b00b251fa9fe1a6f4cc446
bigcode/the-stack
train
a3e7473a8f89349ca4d66039
train
class
class LogCheckerMixin(object): """Mixing for test cases that want to check logs.""" # TODO: Make this a helper. def parse_iso_format(self, iso_string): dt_string, _sep, micro_string = iso_string.partition(".") dt = datetime.datetime.strptime(dt_string, "%Y-%m-%dT%H:%M:%S") microsecon...
class LogCheckerMixin(object):
"""Mixing for test cases that want to check logs.""" # TODO: Make this a helper. def parse_iso_format(self, iso_string): dt_string, _sep, micro_string = iso_string.partition(".") dt = datetime.datetime.strptime(dt_string, "%Y-%m-%dT%H:%M:%S") microsecond = int(micro_string or '0') ...
import json import logging import datetime import re from mock import Mock from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_sandbox import ( ResourceTestCaseBase, DummyAppWorker) from vumi.tests.helpers import VumiTestCase, PersistenceHelper from vumi.tests.utils import LogCatch...
89
89
299
6
82
lynnUg/vumi-go
go/apps/jsbox/tests/test_log.py
Python
LogCheckerMixin
LogCheckerMixin
19
44
19
19
d6f7dac5f0305e0eb5adcc9c1230e0514bae7d77
bigcode/the-stack
train
bda4a8ded1a475f03c217083
train
class
class TestTxLogManager(VumiTestCase, LogCheckerMixin): @inlineCallbacks def setUp(self): self.persistence_helper = self.add_helper(PersistenceHelper()) self.parent_redis = yield self.persistence_helper.get_redis_manager() self.redis = self.parent_redis.sub_manager( LogManager...
class TestTxLogManager(VumiTestCase, LogCheckerMixin): @inlineCallbacks
def setUp(self): self.persistence_helper = self.add_helper(PersistenceHelper()) self.parent_redis = yield self.persistence_helper.get_redis_manager() self.redis = self.parent_redis.sub_manager( LogManager.DEFAULT_SUB_STORE) def log_manager(self, max_logs=None): retur...
for msg, (expected_level, expected_msg) in zip(actual, expected): match = log_re.match(msg) self.assertTrue(match is not None, "Expected formatted log message but got %r" % (msg,)) self.assertEqual(match.group('msg'), expected_...
129
129
431
19
110
lynnUg/vumi-go
go/apps/jsbox/tests/test_log.py
Python
TestTxLogManager
TestTxLogManager
47
87
47
48
f163fb48838f58b9c6f5030fd3918c79d3726de7
bigcode/the-stack
train
9bf872d954821249ff1c95d9
train
class
class TestGoLoggingResource(ResourceTestCaseBase, LogCheckerMixin): app_worker_cls = StubbedAppWorker resource_cls = GoLoggingResource @inlineCallbacks def setUp(self): super(TestGoLoggingResource, self).setUp() self.persistence_helper = self.add_helper(PersistenceHelper()) self...
class TestGoLoggingResource(ResourceTestCaseBase, LogCheckerMixin):
app_worker_cls = StubbedAppWorker resource_cls = GoLoggingResource @inlineCallbacks def setUp(self): super(TestGoLoggingResource, self).setUp() self.persistence_helper = self.add_helper(PersistenceHelper()) self.parent_redis = yield self.persistence_helper.get_redis_manager() ...
d" % i) for i in range(1, 11) ]) @inlineCallbacks def test_get_logs(self): lm = self.log_manager() for i in range(3): yield self.redis.lpush("campaign-1:conv-1", str(i)) logs = yield lm.get_logs("campaign-1", "conv-1") self.assertEqual(logs, ['2', '1', '0']) ...
177
177
592
14
162
lynnUg/vumi-go
go/apps/jsbox/tests/test_log.py
Python
TestGoLoggingResource
TestGoLoggingResource
103
172
103
103
ece21382ec27996f0bb5345f11a05e8085c34e3d
bigcode/the-stack
train
0e1516446cc268bdf00ed9a1
train
class
class StubbedAppWorker(DummyAppWorker): def __init__(self): super(StubbedAppWorker, self).__init__() self.conversation = None def conversation_for_api(self, api): return self.conversation
class StubbedAppWorker(DummyAppWorker):
def __init__(self): super(StubbedAppWorker, self).__init__() self.conversation = None def conversation_for_api(self, api): return self.conversation
", str(i)) logs = yield lm.get_logs("campaign-1", "conv-1") self.assertEqual(logs, ['2', '1', '0']) class TestLogManager(TestTxLogManager): sync_persistence = True class StubbedAppWorker(DummyAppWorker):
64
64
51
10
53
lynnUg/vumi-go
go/apps/jsbox/tests/test_log.py
Python
StubbedAppWorker
StubbedAppWorker
94
100
94
94
5165270dbaa4c31f83c8b0c9d623d9ed88e8622e
bigcode/the-stack
train
7d44b528dc70a8dc434b393b
train
class
class TestLogManager(TestTxLogManager): sync_persistence = True
class TestLogManager(TestTxLogManager):
sync_persistence = True
(3): yield self.redis.lpush("campaign-1:conv-1", str(i)) logs = yield lm.get_logs("campaign-1", "conv-1") self.assertEqual(logs, ['2', '1', '0']) class TestLogManager(TestTxLogManager):
63
64
16
9
54
lynnUg/vumi-go
go/apps/jsbox/tests/test_log.py
Python
TestLogManager
TestLogManager
90
91
90
90
93a1a9491f106368d0fb09858d4248733de8e79f
bigcode/the-stack
train
117beca073c8eb81870e7c3a
train
function
def fibd(lastmonth, livemonth, young): rabbits = np.zeros(([lastmonth, livemonth]), dtype='uint64') # 初始化第一个月数据,lastmonth = 5 # 初始兔子young对,1:livemonth-1都为0 rabbits[0, 0] = young rabbits[0, 1:livemonth] = 0 # print(rabbits[0]) for i in range(1, lastmonth): # young等于上个月除young之外所有兔子之和 ...
def fibd(lastmonth, livemonth, young):
rabbits = np.zeros(([lastmonth, livemonth]), dtype='uint64') # 初始化第一个月数据,lastmonth = 5 # 初始兔子young对,1:livemonth-1都为0 rabbits[0, 0] = young rabbits[0, 1:livemonth] = 0 # print(rabbits[0]) for i in range(1, lastmonth): # young等于上个月除young之外所有兔子之和 rabbits[i, 0] = rabbits[i - 1, ...
python3 # -*- coding: utf-8 -*- # @File : fibd.py # @Date : 2019-02-16 # @Author : luyang(luyang@novogene.com) import numpy as np def fibd(lastmonth, livemonth, young):
64
64
205
12
51
luyang93/ROSALIND
fibd.py
Python
fibd
fibd
11
25
11
11
75fa5d93c1ed436afd0cd9f0f05e5bc78ef6cd85
bigcode/the-stack
train
a12da62b35e5a5303699b986
train
function
def main(): file = 'input/rosalind_fibd.txt' with open(file) as f: lines = f.readlines() for line in lines: young = 1 last_month = int(line.split()[0]) live_month = int(line.split()[1]) rabbit = fibd(last_month, live_month, young) d = i...
def main():
file = 'input/rosalind_fibd.txt' with open(file) as f: lines = f.readlines() for line in lines: young = 1 last_month = int(line.split()[0]) live_month = int(line.split()[1]) rabbit = fibd(last_month, live_month, young) d = int(rabbit[la...
emonth].sum() # 次月数据等于上月数据享有偏移1 rabbits[i, 1:livemonth] = rabbits[i - 1, 0:livemonth - 1] # print(rabbits[i]) return rabbits def main():
64
64
96
3
60
luyang93/ROSALIND
fibd.py
Python
main
main
28
38
28
28
15155e1eaed4b06a27dea4567d5f36ae43f13070
bigcode/the-stack
train
090a8198c047cab2d035a1b2
train
function
def evenly_spaced_trees(trees: List[int]) -> int: gap = reduce(gcd, [trees[i + 1] - trees[i] for i in range(len(trees) - 1)]) return (trees[-1] - trees[0]) // gap + 1 - len(trees)
def evenly_spaced_trees(trees: List[int]) -> int:
gap = reduce(gcd, [trees[i + 1] - trees[i] for i in range(len(trees) - 1)]) return (trees[-1] - trees[0]) // gap + 1 - len(trees)
from typing import List from math import gcd from functools import reduce def evenly_spaced_trees(trees: List[int]) -> int:
30
64
67
15
14
NigrumAquila/py_checkio
github/evenly_spaced_trees.py
Python
evenly_spaced_trees
evenly_spaced_trees
5
7
5
5
ec78137ce17e6a72bca174aa42138489d0bda477
bigcode/the-stack
train
cd965b85f1686e2870bd11a6
train
function
def run(args): print("御灵 自动挂机脚本运行...") while(True): challenge()
def run(args):
print("御灵 自动挂机脚本运行...") while(True): challenge()
_SIFT_CONTINUE, timeout = 120) touch_pos(random_pos(pos, 50, 100, 0, 1), 2) time.sleep(4) touch_pos(random_pos(pos, 50, 100, 0, 1), 2) def run(args):
64
64
22
4
60
github-alvin/yys
script/yuling.py
Python
run
run
25
28
25
25
7fb078de2edf58c3270461e6b3dd37a6a190edea
bigcode/the-stack
train
527641c4db849640f1c07149
train
function
def challenge(): touch(wait(step1, timeout=60)) pos = wait(GLOBAL_SIFT_CONTINUE, timeout = 120) touch_pos(random_pos(pos, 50, 100, 0, 1), 2) time.sleep(4) touch_pos(random_pos(pos, 50, 100, 0, 1), 2)
def challenge():
touch(wait(step1, timeout=60)) pos = wait(GLOBAL_SIFT_CONTINUE, timeout = 120) touch_pos(random_pos(pos, 50, 100, 0, 1), 2) time.sleep(4) touch_pos(random_pos(pos, 50, 100, 0, 1), 2)
_CONTINUE from common.utils import random_pos, touch_pos, image auto_setup(__file__) # 挑战 按钮 step1 = image("yeyuanhuo_chi_challenge.png", (1.059, 0.296), (1152, 679)) def challenge():
64
64
80
3
61
github-alvin/yys
script/yuling.py
Python
challenge
challenge
17
22
17
17
af1260a0cd9b0e1de6d4c84531882accaca145bc
bigcode/the-stack
train
6ab569ee7a72c0fd26f9b2e2
train
class
class TestEnhancedECBehaviour(unittest.TestCase): """Test case to verify all enhanced EC interpretation tasks.""" def setUp(self): """Setup the test harness.""" # Setup logging with a timestamp, the module, and the log level. logging.basicConfig(level=logging.DEBUG, format=('%(as...
class TestEnhancedECBehaviour(unittest.TestCase):
"""Test case to verify all enhanced EC interpretation tasks.""" def setUp(self): """Setup the test harness.""" # Setup logging with a timestamp, the module, and the log level. logging.basicConfig(level=logging.DEBUG, format=('%(asctime)s - %(module)s -' ...
#!/usr/bin/env python2 # Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for the EC-3PO interpreter.""" from __future__ import print_function # pylint: disable=cros-logging-import import l...
104
256
2,358
9
94
mirrexagon/chrome-ec
util/ec3po/interpreter_unittest.py
Python
TestEnhancedECBehaviour
TestEnhancedECBehaviour
19
252
19
19
344299e495e3b3fe5ab52c1b8a6b8117a4098bf8
bigcode/the-stack
train
76dc75a1b5f658a49716abb9
train
class
class TestUARTDisconnection(unittest.TestCase): """Test case to verify interpreter disconnection/reconnection.""" def setUp(self): """Setup the test harness.""" # Setup logging with a timestamp, the module, and the log level. logging.basicConfig(level=logging.DEBUG, format=('%(as...
class TestUARTDisconnection(unittest.TestCase):
"""Test case to verify interpreter disconnection/reconnection.""" def setUp(self): """Setup the test harness.""" # Setup logging with a timestamp, the module, and the log level. logging.basicConfig(level=logging.DEBUG, format=('%(asctime)s - %(module)s -' ...
be ' 'False')) self.assertTrue(self.itpr.enhanced_ec, msg='enhanced_ec sholud be True') # Now let's perform another interrogation, but pretend that the EC ignores # it. self.cmd_pipe_user.send(interpreter.EC_SYN) self.itpr.HandleUserData() # ...
255
256
1,065
9
246
mirrexagon/chrome-ec
util/ec3po/interpreter_unittest.py
Python
TestUARTDisconnection
TestUARTDisconnection
255
362
255
255
2f23834ac92c4b46793ca7d59b9984e43729852c
bigcode/the-stack
train
0e7f3650d564b2e2027721a8
train
function
def generateSpamBody(emailBody: str) -> str: global SPAM_WORDLIST SPAM_WORD_AFTER_N_WORDS = 10 words = emailBody.split() for i in range(0, len(words), SPAM_WORD_AFTER_N_WORDS): words[i] = choice(SPAM_WORDLIST) return ' '.join(words)
def generateSpamBody(emailBody: str) -> str:
global SPAM_WORDLIST SPAM_WORD_AFTER_N_WORDS = 10 words = emailBody.split() for i in range(0, len(words), SPAM_WORD_AFTER_N_WORDS): words[i] = choice(SPAM_WORDLIST) return ' '.join(words)
""" Helper that return a timestamp, with additional seconds if provided The returned timestamp is in ms (10^-3s) """ shift_after_seconds = 10**precision_after_second return int(time() * shift_after_seconds) def generateSpamBody(emailBody: str) -> str:
64
64
76
12
52
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
generateSpamBody
generateSpamBody
61
69
61
61
e4cf2c5699055aa114c5f8f87b3b82f5324d56aa
bigcode/the-stack
train
795e2dc71c8c03fb842aed62
train
function
def generateSimpleEmail(emailAdresses: List[EmailAddress], spammerAdresses=[], spam_rate=0.0, from_sender='', with_body=False) -> Email: """" Generate a fake email from a list of email address, a custom sender and body message can be provided (for flood) """ sender = choice(emailAdresses) if not from_sender els...
def generateSimpleEmail(emailAdresses: List[EmailAddress], spammerAdresses=[], spam_rate=0.0, from_sender='', with_body=False) -> Email:
"""" Generate a fake email from a list of email address, a custom sender and body message can be provided (for flood) """ sender = choice(emailAdresses) if not from_sender else from_sender receiver = choice(emailAdresses) timestamp = getTimestamp() subject = FAKE.sentence(nb_words=5) body = gene...
(words), SPAM_WORD_AFTER_N_WORDS): words[i] = choice(SPAM_WORDLIST) return ' '.join(words) def generateSimpleEmail(emailAdresses: List[EmailAddress], spammerAdresses=[], spam_rate=0.0, from_sender='', with_body=False) -> Email:
64
64
166
35
29
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
generateSimpleEmail
generateSimpleEmail
72
83
72
72
fef9b9bb7747968755e995af6080ace1de79b153
bigcode/the-stack
train
5b9ab26a5e37dc8c9dfd246c
train
class
@dataclass class Email: """ Structure of an email """ sender: EmailAddress receiver: EmailAddress timestamp: int subject: str body: str
@dataclass class Email:
""" Structure of an email """ sender: EmailAddress receiver: EmailAddress timestamp: int subject: str body: str
AM_WORDLIST_SOURCE = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'Spam_Keywords.txt') SPAM_WORDLIST = [word.strip() for word in open(_SPAM_WORDLIST_SOURCE)] EmailAddress = NewType('EmailAdress', str) @dataclass class Email:
64
64
40
6
58
johannchopin/htw-m1-softwarearchitecture
src/entry/fakeEmails.py
Python
Email
Email
21
28
21
22
50dad4c45a7865d967f24ffab83f71c0375a0e18
bigcode/the-stack
train