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
694cb0a48cb5111a09881d20
train
function
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term): leq = msat_make_leq(menv, arg0, arg1) return msat_make_not(menv, leq)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1) return msat_make_not(menv, leq)
q(menv: msat_env, arg0: msat_term, arg1: msat_term): return msat_make_leq(menv, arg1, arg0) def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
64
64
56
26
38
EnricoMagnago/F3
benchmarks/ltl_maxplus/f3/maxplus_40_87.py
Python
msat_make_gt
msat_make_gt
53
55
53
53
6ebfbc8ba8c3ffb3ba712af6009f476ff9bc91f6
bigcode/the-stack
train
f4b0a984dbf2b6df354254b3
train
function
def msat_make_or(menv: msat_env, *args): if len(args) == 0: return msat_make_false(menv) if len(args) == 1: return args[0] res = _msat_make_or(menv, args[0], args[1]) for arg in args[2:]: res = _msat_make_or(menv, res, arg) return res
def msat_make_or(menv: msat_env, *args):
if len(args) == 0: return msat_make_false(menv) if len(args) == 1: return args[0] res = _msat_make_or(menv, args[0], args[1]) for arg in args[2:]: res = _msat_make_or(menv, res, arg) return res
0] res = _msat_make_and(menv, args[0], args[1]) for arg in args[2:]: res = _msat_make_and(menv, res, arg) return res def msat_make_or(menv: msat_env, *args):
64
64
95
15
48
EnricoMagnago/F3
benchmarks/ltl_maxplus/f3/maxplus_40_87.py
Python
msat_make_or
msat_make_or
27
35
27
27
f438b06f87101c1408a80c618388aa43127fb698
bigcode/the-stack
train
bc7587e036509c7e3114ef0a
train
class
class TestCodeResourceTrigger(TestCase): @patch.multiple(CodeResourceTrigger, __abstractmethods__=set()) @patch("samcli.lib.utils.resource_trigger.get_resource_by_id") def test_init(self, get_resource_by_id_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock = MagicMock() ...
class TestCodeResourceTrigger(TestCase): @patch.multiple(CodeResourceTrigger, __abstractmethods__=set()) @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
def test_init(self, get_resource_by_id_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock = MagicMock() trigger = CodeResourceTrigger(ResourceIdentifier("A"), stacks, on_code_change_mock) self.assertEqual(trigger._resource, get_resource_by_id_mock.return_value) se...
", on_template_change_mock) trigger._validator_wrapper(event_mock) on_template_change_mock.assert_called_once_with(event_mock) class TestCodeResourceTrigger(TestCase): @patch.multiple(CodeResourceTrigger, __abstractmethods__=set()) @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
65
65
218
39
26
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestCodeResourceTrigger
TestCodeResourceTrigger
88
106
88
90
fce54b891ae9e8541665a70d5d7798db0b82f70c
bigcode/the-stack
train
66136a7059a90551cf2817b2
train
class
class TestTemplateTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.DefinitionValidator") @patch("samcli.lib.utils.resource_trigger.Path") @patch("samcli.lib.utils.resource_trigger.ResourceTrigger.get_single_file_path_handler") def test_get_path_handler(self, single_file_handler_mock, path_mo...
class TestTemplateTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.DefinitionValidator") @patch("samcli.lib.utils.resource_trigger.Path") @patch("samcli.lib.utils.resource_trigger.ResourceTrigger.get_single_file_path_handler")
def test_get_path_handler(self, single_file_handler_mock, path_mock, validator_mock): trigger = TemplateTrigger("template.yaml", MagicMock()) result = trigger.get_path_handlers() self.assertEqual(result, [single_file_handler_mock.return_value]) self.assertEqual(single_file_handler_mo...
_handler=handler_mock.return_value, recursive=True, static_folder=True ) class TestTemplateTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.DefinitionValidator") @patch("samcli.lib.utils.resource_trigger.Path") @patch("samcli.lib.utils.resource_trigger.ResourceTrigger.get_single_file_pat...
67
67
225
51
16
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestTemplateTrigger
TestTemplateTrigger
67
85
67
70
7661603fb5d5123c9d987b9f31ce710b91a5047c
bigcode/the-stack
train
9713c9e44039209ca6e8db6b
train
class
class TestLambdaLayerCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamLayerProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id") def test_init(self, get_resource_by_id_mock, layer_provider_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock =...
class TestLambdaLayerCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamLayerProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
def test_init(self, get_resource_by_id_mock, layer_provider_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock = MagicMock() layer_mock = layer_provider_mock.return_value.get.return_value trigger = LambdaLayerCodeTrigger(ResourceIdentifier("A"), stacks, on_code_change_mo...
_mock = MagicMock() function_mock = function_provider_mock.return_value.get.return_value trigger = LambdaImageCodeTrigger(ResourceIdentifier("A"), stacks, on_code_change_mock) result = trigger._get_code_uri() self.assertEqual(result, function_mock.metadata.get.return_value) class TestLam...
98
98
329
39
59
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestLambdaLayerCodeTrigger
TestLambdaLayerCodeTrigger
187
216
187
189
07f615eb313929427cfb40108e24c0059dde6e1d
bigcode/the-stack
train
cb508fd576acd20c945fcf7b
train
class
class TestLambdaFunctionCodeTrigger(TestCase): @patch.multiple(LambdaFunctionCodeTrigger, __abstractmethods__=set()) @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id") def test_init(self, get_resource_by_id_mock, function_provid...
class TestLambdaFunctionCodeTrigger(TestCase): @patch.multiple(LambdaFunctionCodeTrigger, __abstractmethods__=set()) @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
def test_init(self, get_resource_by_id_mock, function_provider_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock = MagicMock() function_mock = function_provider_mock.return_value.get.return_value code_uri_mock = MagicMock() LambdaFunctionCodeTrigger._get_code_ur...
._on_code_change, on_code_change_mock) @patch.multiple(CodeResourceTrigger, __abstractmethods__=set()) @patch("samcli.lib.utils.resource_trigger.get_resource_by_id") def test_init_invalid(self, get_resource_by_id_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock = MagicMock() ...
166
166
554
57
109
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestLambdaFunctionCodeTrigger
TestLambdaFunctionCodeTrigger
109
160
109
112
853f665d8dbac9b19e4cab245e886440720a3feb
bigcode/the-stack
train
f69063dd4487252c1b3c3f05
train
class
class TestLambdaImageCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id") def test_get_code_uri(self, get_resource_by_id_mock, function_provider_mock): stacks = [MagicMock(), MagicMock()] on_code...
class TestLambdaImageCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
def test_get_code_uri(self, get_resource_by_id_mock, function_provider_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock = MagicMock() function_mock = function_provider_mock.return_value.get.return_value trigger = LambdaImageCodeTrigger(ResourceIdentifier("A"), stacks, o...
on_code_change_mock) result = trigger._get_code_uri() self.assertEqual(result, function_mock.codeuri) class TestLambdaImageCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
64
64
130
39
25
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestLambdaImageCodeTrigger
TestLambdaImageCodeTrigger
175
184
175
177
f1154b5d20c7935caad7321b20f063599fa829f1
bigcode/the-stack
train
4a00480ec6eef7a69948a45c
train
class
class TestLambdaZipCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id") def test_get_code_uri(self, get_resource_by_id_mock, function_provider_mock): stacks = [MagicMock(), MagicMock()] on_code_c...
class TestLambdaZipCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
def test_get_code_uri(self, get_resource_by_id_mock, function_provider_mock): stacks = [MagicMock(), MagicMock()] on_code_change_mock = MagicMock() function_mock = function_provider_mock.return_value.get.return_value trigger = LambdaZipCodeTrigger(ResourceIdentifier("A"), stacks, on_...
(bundle.self_delete, on_code_change_mock) self.assertEqual(bundle.event_handler.on_any_event, on_code_change_mock) class TestLambdaZipCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.SamFunctionProvider") @patch("samcli.lib.utils.resource_trigger.get_resource_by_id")
64
64
128
39
25
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestLambdaZipCodeTrigger
TestLambdaZipCodeTrigger
163
172
163
165
d9e843582c8149f47163410e98d1ffaf1e3b64bd
bigcode/the-stack
train
60f6ec390ee3bf5746c6121d
train
class
class TestDefinitionCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.DefinitionValidator") @patch("samcli.lib.utils.resource_trigger.Path") @patch("samcli.lib.utils.resource_trigger.ResourceTrigger.get_single_file_path_handler") @patch("samcli.lib.utils.resource_trigger.get_resource_by_i...
class TestDefinitionCodeTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.DefinitionValidator") @patch("samcli.lib.utils.resource_trigger.Path") @patch("samcli.lib.utils.resource_trigger.ResourceTrigger.get_single_file_path_handler") @patch("samcli.lib.utils.resource_trigger.get_resource_by_i...
def test_get_path_handler(self, get_resource_by_id_mock, single_file_handler_mock, path_mock, validator_mock): stacks = [MagicMock(), MagicMock()] resource = {"Properties": {"DefinitionUri": "abc"}} get_resource_by_id_mock.return_value = resource trigger = DefinitionCodeTrigger("Test...
get_dir_path_handler_mock.return_value = bundle trigger = LambdaLayerCodeTrigger(ResourceIdentifier("A"), stacks, on_code_change_mock) result = trigger.get_path_handlers() self.assertEqual(result, [bundle]) self.assertEqual(bundle.self_create, on_code_change_mock) self.assertE...
155
155
517
67
88
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestDefinitionCodeTrigger
TestDefinitionCodeTrigger
219
258
219
223
6c90710d14205826a211ebc74ebeddcdf1c96f29
bigcode/the-stack
train
e6b8b1dc3131bb773ed32d32
train
class
class TestResourceTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.PathHandler") @patch("samcli.lib.utils.resource_trigger.RegexMatchingEventHandler") @patch("samcli.lib.utils.resource_trigger.Path") def test_single_file_path_handler(self, path_mock, handler_mock, bundle_mock): path ...
class TestResourceTrigger(TestCase): @patch("samcli.lib.utils.resource_trigger.PathHandler") @patch("samcli.lib.utils.resource_trigger.RegexMatchingEventHandler") @patch("samcli.lib.utils.resource_trigger.Path")
def test_single_file_path_handler(self, path_mock, handler_mock, bundle_mock): path = MagicMock() path_mock.return_value = path file_path = MagicMock() file_path.__str__.return_value = "/parent/file" parent_path = MagicMock() parent_path.__str__.return_value = "/pare...
, DefinitionCodeTrigger, LambdaFunctionCodeTrigger, LambdaImageCodeTrigger, LambdaLayerCodeTrigger, LambdaZipCodeTrigger, ResourceTrigger, TemplateTrigger, ) from samcli.local.lambdafn.exceptions import FunctionNotFound, ResourceNotFound from samcli.lib.providers.exceptions import MissingLoc...
125
125
417
47
77
awilkins/aws-sam-cli
tests/unit/lib/utils/test_resource_trigger.py
Python
TestResourceTrigger
TestResourceTrigger
20
64
20
23
d9cf1e18aa8fe0a0709762c95fbdc1ac87fad81b
bigcode/the-stack
train
92581ed1a24f97e3185f9f2d
train
function
def im2adc_550_mb( frame ): ''' This undos Mark B's reshape function in /software/p2/dev.py:convertImage (real code is burried in assembly) ''' if frame.ndim == 3: return np.array( [ im2adc_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (3,4) ) #b...
def im2adc_550_mb( frame ):
''' This undos Mark B's reshape function in /software/p2/dev.py:convertImage (real code is burried in assembly) ''' if frame.ndim == 3: return np.array( [ im2adc_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (3,4) ) #blocks1 = blocks[:,:,(0,4,1,6...
frame, (2,6) ) blocks1 = blocks[:,:,(0,2,4,5,1,8,3,10,6,7,9,11)] return unreshape( blocks1, (3,4) ) def im2adc_550_mb( frame ):
64
64
179
10
54
iontorrent/TS
plugin/CustomerSupportArchive/Lane_Diagnostics/tools/adc.py
Python
im2adc_550_mb
im2adc_550_mb
38
45
38
38
01c86b8257d7609ab7b35d5a523194febcb54a89
bigcode/the-stack
train
b874f64cea183b9cfcb4bf6e
train
function
def unreshape( data, blocksize ): ''' Reverses the output of block_reshape ''' numR, numC, els = data.shape rows = numR*blocksize[0] cols = numC*blocksize[1] return data.transpose((1,0,2)).reshape( numC, rows, -1 ).transpose((1,0,2)).reshape( rows, cols )
def unreshape( data, blocksize ):
''' Reverses the output of block_reshape ''' numR, numC, els = data.shape rows = numR*blocksize[0] cols = numC*blocksize[1] return data.transpose((1,0,2)).reshape( numC, rows, -1 ).transpose((1,0,2)).reshape( rows, cols )
numR = rows/blocksize[0] numC = cols/blocksize[1] return data.reshape(rows , numC , -1 ).transpose((1,0,2)).reshape(numC,numR,-1).transpose((1,0,2)) def unreshape( data, blocksize ):
64
64
90
9
55
iontorrent/TS
plugin/CustomerSupportArchive/Lane_Diagnostics/tools/adc.py
Python
unreshape
unreshape
14
19
14
14
59ca8a469f811a539608963ea9f56eecbb3ed4db
bigcode/the-stack
train
a70f7e636ee05f4ba3e7b9c1
train
function
def adc2im_550( frame ): ''' Converts a 550 "ADC" image (pixel layout) to a "datacollect" image (well laout) ''' if frame.ndim == 3: return np.array( [ adc2im_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (2,6) ) blocks1 = blocks[:,:,(0,2,4,5,1,8...
def adc2im_550( frame ):
''' Converts a 550 "ADC" image (pixel layout) to a "datacollect" image (well laout) ''' if frame.ndim == 3: return np.array( [ adc2im_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (2,6) ) blocks1 = blocks[:,:,(0,2,4,5,1,8,3,10,6,7,9,11)] retu...
( frame, (3,4) ) blocks1 = blocks[:,:,(0,4,1,6,2,3,8,9,5,10,7,11)] return unreshape( blocks1, (2,6) ) def adc2im_550( frame ):
64
64
143
9
55
iontorrent/TS
plugin/CustomerSupportArchive/Lane_Diagnostics/tools/adc.py
Python
adc2im_550
adc2im_550
30
36
30
30
ef67b273155bde4b0c341c934b5d3408c4c6e85e
bigcode/the-stack
train
b1e88d3dcc50a3b593df3d94
train
function
def adc2im_550_mb( frame ): ''' THis mimics Mark B's reshape function ''' if frame.ndim == 3: return np.array( [ adc2im_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (2,6) ) #blocks1 = blocks[:,:,(0,2,4,5,1,8,3,10,6,7,9,11)] #blocks1 = blocks...
def adc2im_550_mb( frame ):
''' THis mimics Mark B's reshape function ''' if frame.ndim == 3: return np.array( [ adc2im_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (2,6) ) #blocks1 = blocks[:,:,(0,2,4,5,1,8,3,10,6,7,9,11)] #blocks1 = blocks[:,:,(1,2,4,5,0,8,3,10,6,7,9...
5,10,7,11)] blocks1 = blocks[:,:,(4,0,1,2,6,3,8,9,5,10,7,11)] return unreshape( blocks1, (2,6) ) def adc2im_550_mb( frame ):
64
64
194
10
54
iontorrent/TS
plugin/CustomerSupportArchive/Lane_Diagnostics/tools/adc.py
Python
adc2im_550_mb
adc2im_550_mb
47
55
47
47
97ab9929f51ef3fbf3ca7a07e69fad1505e6b9ae
bigcode/the-stack
train
a6fa76f5c2f41f9e87e49ba1
train
function
def block_reshape( data, blocksize ): ''' Reshapes the 2D data into 3D data, with the 3rd dimension being adjacent pixels ''' rows, cols = data.shape numR = rows/blocksize[0] numC = cols/blocksize[1] return data.reshape(rows , numC , -1 ).transpose((1,0,2)).reshape(numC,numR,-1).transpose((1,0,2))
def block_reshape( data, blocksize ):
''' Reshapes the 2D data into 3D data, with the 3rd dimension being adjacent pixels ''' rows, cols = data.shape numR = rows/blocksize[0] numC = cols/blocksize[1] return data.reshape(rows , numC , -1 ).transpose((1,0,2)).reshape(numC,numR,-1).transpose((1,0,2))
""" Contains helpful functions to unravel or ravel chip data between physical columns and per-adc quasi-columns. """ import numpy as np def block_reshape( data, blocksize ):
37
64
100
10
26
iontorrent/TS
plugin/CustomerSupportArchive/Lane_Diagnostics/tools/adc.py
Python
block_reshape
block_reshape
7
12
7
7
189dbc76d6335028a566a3171b58032fa985cc3f
bigcode/the-stack
train
2c0baa28f6d4a154693905bf
train
function
def im2adc_550( frame ): ''' Converts a 550 "datacollect" image (well layout) to an "ADC" image (pixel layout)''' if frame.ndim == 3: return np.array( [ im2adc_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (3,4) ) blocks1 = blocks[:,:,(0,4,1,6,2,...
def im2adc_550( frame ):
''' Converts a 550 "datacollect" image (well layout) to an "ADC" image (pixel layout)''' if frame.ndim == 3: return np.array( [ im2adc_550(f) for f in frame.transpose((2,0,1)) ] ).transpose((1,2,0)) blocks = block_reshape( frame, (3,4) ) blocks1 = blocks[:,:,(0,4,1,6,2,3,8,9,5,10,7,11)] ret...
= numR*blocksize[0] cols = numC*blocksize[1] return data.transpose((1,0,2)).reshape( numC, rows, -1 ).transpose((1,0,2)).reshape( rows, cols ) def im2adc_550( frame ):
64
64
142
9
55
iontorrent/TS
plugin/CustomerSupportArchive/Lane_Diagnostics/tools/adc.py
Python
im2adc_550
im2adc_550
22
28
22
22
ba16a639d7b08dd6aa192bf778ce20455c2aca3c
bigcode/the-stack
train
4f9336bbe58c0ea53ee871c1
train
class
class TestEntry(unittest.TestCase): """Entry unit test stubs""" def setUp(self): pass def tearDown(self): pass def testEntry(self): """Test Entry""" # FIXME: construct object with mandatory attributes with example values # model = Entry() # noqa: E501 ...
class TestEntry(unittest.TestCase):
"""Entry unit test stubs""" def setUp(self): pass def tearDown(self): pass def testEntry(self): """Test Entry""" # FIXME: construct object with mandatory attributes with example values # model = Entry() # noqa: E501 pass
BrowserUpProxyClient from BrowserUpProxyClient.model.entry_request import EntryRequest from BrowserUpProxyClient.model.entry_response import EntryResponse globals()['EntryRequest'] = EntryRequest globals()['EntryResponse'] = EntryResponse from BrowserUpProxyClient.model.entry import Entry class TestEntry(unittest.Test...
64
64
73
7
56
580/mitmproxy
out/production/mitmproxynew/clients/python/test/test_entry.py
Python
TestEntry
TestEntry
22
35
22
22
02f6e3efc06f5ff0dfa112316101c7f3cdd7eb93
bigcode/the-stack
train
5f0ace548e4d4004e27bc747
train
class
class agilent8590B(agilentBase8590A): "Agilent 8590B IVI spectrum analyzer driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'HP8590B') super(agilent8590B, self).__init__(*args, **kwargs) self._input_impedance = 50 self._frequency_low = 9e...
class agilent8590B(agilentBase8590A):
"Agilent 8590B IVI spectrum analyzer driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'HP8590B') super(agilent8590B, self).__init__(*args, **kwargs) self._input_impedance = 50 self._frequency_low = 9e3 self._frequency_high = 1.8e9...
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .agilentBase8590A import * class agilent8590B(agilentBase8590A):
64
64
110
14
50
elopezga/ErrorRate
ivi/agilent/agilent8590B.py
Python
agilent8590B
agilent8590B
29
39
29
29
1c4721799156a9cad8c00608091a0e30a67a494a
bigcode/the-stack
train
a373ed519918f22940e2222a
train
function
def dist_normal_diag_sample_ad_set_dim_func(head, x, mean, scale): """ Lookup the dist_normal_diag_ad_set_dim_map and return hash_value and hash_key """ key = [] key.append(tuple(head.shape)) key.append(tuple(x.shape)) key.append(tuple(mean.shape)) key.append(tuple(scale.shape)) key....
def dist_normal_diag_sample_ad_set_dim_func(head, x, mean, scale):
""" Lookup the dist_normal_diag_ad_set_dim_map and return hash_value and hash_key """ key = [] key.append(tuple(head.shape)) key.append(tuple(x.shape)) key.append(tuple(mean.shape)) key.append(tuple(scale.shape)) key.append(x.dtype) hash_key = str(tuple(key)) if hash_key in ...
fuction: distr_normal_diag_sample_ad""" import akg from test_op.prob_program.distribution import normal_diag from akg.utils import custom_tiling as ct_util dist_normal_diag_ad_set_dim_map = { } def dist_normal_diag_sample_ad_set_dim_func(head, x, mean, scale):
64
64
125
17
47
laekov/akg
tests/common/test_op/prob_program/distr_normal_diag_sample_ad.py
Python
dist_normal_diag_sample_ad_set_dim_func
dist_normal_diag_sample_ad_set_dim_func
25
39
25
25
f0352f74d8fceae322b4e5c5e802475860b9c6e6
bigcode/the-stack
train
3cdcf1ddf87a38de0eb51391
train
function
@ct_util.reg_set_dim_func(dist_normal_diag_sample_ad_set_dim_func) def normal_diag_sample_ad(head, mean, scale, eps): """ An example of differentiating normal_diag.sample in all inputs and paramters Args: head: The adjoint of the output, in other words, some tensors, by which the Jacobians ...
@ct_util.reg_set_dim_func(dist_normal_diag_sample_ad_set_dim_func) def normal_diag_sample_ad(head, mean, scale, eps):
""" An example of differentiating normal_diag.sample in all inputs and paramters Args: head: The adjoint of the output, in other words, some tensors, by which the Jacobians will be multiplied x: input mean: vector of means of MVN scale: vector of sigma of MVN wit...
dist_normal_diag_ad_set_dim_map.keys(): return ct_util.set_dims(dist_normal_diag_ad_set_dim_map[hash_key]), hash_key return "", hash_key @ct_util.reg_set_dim_func(dist_normal_diag_sample_ad_set_dim_func) def normal_diag_sample_ad(head, mean, scale, eps):
64
64
152
29
34
laekov/akg
tests/common/test_op/prob_program/distr_normal_diag_sample_ad.py
Python
normal_diag_sample_ad
normal_diag_sample_ad
41
56
41
42
484f8636505692a0a1992735fde997349f527460
bigcode/the-stack
train
e700ab4447c7bb8424d06fc7
train
class
class TxnMallTest(BitcoinTestFramework): def add_options(self, parser): parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true", help="Test double-spend of 1-confirmed transaction") def setup_network(self): # Start with split network: ...
class TxnMallTest(BitcoinTestFramework):
def add_options(self, parser): parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true", help="Test double-spend of 1-confirmed transaction") def setup_network(self): # Start with split network: return super(TxnMallTest, self).setu...
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2017-2018 The LitecoinZ developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test proper accounting with malleable transactions # f...
114
256
1,002
10
103
newtl/litecoinz
qa/rpc-tests/txn_doublespend.py
Python
TxnMallTest
TxnMallTest
16
104
16
17
73a57e98f41a4cd05b450b04db810a5e92251c3b
bigcode/the-stack
train
81fa7162e451d70dacb770b7
train
function
def resize_image(image, shape=(224,224)): target_width = shape[0] target_height = shape[1] initial_width = tf.shape(image)[0] initial_height = tf.shape(image)[1] im = image ratio = 0 if(initial_width < initial_height): ratio = tf.cast(256 / initial_width, tf.float32) h = tf.c...
def resize_image(image, shape=(224,224)):
target_width = shape[0] target_height = shape[1] initial_width = tf.shape(image)[0] initial_height = tf.shape(image)[1] im = image ratio = 0 if(initial_width < initial_height): ratio = tf.cast(256 / initial_width, tf.float32) h = tf.cast(initial_height, tf.float32) * ratio ...
tf.data.Dataset.from_tensor_slices((img_path, label)) dataset = dataset.map(_data_generator, num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size) dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) return dataset def resize_image(image, shape=(224,224)...
72
72
240
11
60
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
resize_image
resize_image
99
119
99
99
9268a1bc3d952d5c425722ad98100de3d39dfcc8
bigcode/the-stack
train
19037dd3ca30e46e04227759
train
function
def main(): # Prepare dataset # Training data train_path = np.load(BASE_DIR + TRAIN_DATA_DIR) train_label = np.load(BASE_DIR + TRAIN_LABEL_DIR) assert len(train_path) == len(train_label) # Evaluation data eval_path = np.load(BASE_DIR + EVAL_DATA_DIR) eval_label = np.load(BASE_DIR + EVAL...
def main(): # Prepare dataset # Training data
train_path = np.load(BASE_DIR + TRAIN_DATA_DIR) train_label = np.load(BASE_DIR + TRAIN_LABEL_DIR) assert len(train_path) == len(train_label) # Evaluation data eval_path = np.load(BASE_DIR + EVAL_DATA_DIR) eval_label = np.load(BASE_DIR + EVAL_LABEL_DIR) assert len(eval_path) == len(eval_labe...
im = tf.image.crop_to_bounding_box(im, startx, starty, target_width, target_height) return im def scale19(image): i = resize_image(image, (224,224)) return (i) def ResNet152V2(): IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3) resnet152v2 = tf.keras.applications.ResNet152V2(include_top=True, ...
163
163
544
13
150
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
main
main
138
194
138
140
de1c0b8e7f1ac2004219ee6f5935b9b602fe919d
bigcode/the-stack
train
b1f191f8396bc9997016e251
train
function
@tf.function def test_step(model, metric, images, labels): predictions = model(images) metric.update_state(labels, predictions)
@tf.function def test_step(model, metric, images, labels):
predictions = model(images) metric.update_state(labels, predictions)
resnet152v2 = tf.keras.applications.ResNet152V2(include_top=True, weights='imagenet', input_shape=IMG_SHAPE, classes=1000) return resnet152v2 @tf.function ...
64
64
29
15
48
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
test_step
test_step
133
136
133
134
402ac6cf4bb32dd4097554cedcb0529341adf258
bigcode/the-stack
train
a3a6e7123ecb1d3a8b003351
train
function
def _attacking_data_generator(image_path, label): # Read image img = tf.io.read_file(image_path) img = tf.image.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) img.set_shape([None, None, 3]) # Resize initial_width = tf.shape(img)[0] initial_height =...
def _attacking_data_generator(image_path, label): # Read image
img = tf.io.read_file(image_path) img = tf.image.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) img.set_shape([None, None, 3]) # Resize initial_width = tf.shape(img)[0] initial_height = tf.shape(img)[1] ratio = 0 if(initial_width < initial...
.config.experimental.list_logical_devices('GPU') print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs") except RuntimeError as e: # Memory growth must be set before GPUs have been initialized print(e) def _attacking_data_generator(image_path, label): # Read image
69
69
232
16
53
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
_attacking_data_generator
_attacking_data_generator
58
80
58
59
1a268228ef871026368f9d172388f7fd05e691cb
bigcode/the-stack
train
bdb6a7d8b327f34bb484771a
train
function
def scale19(image): i = resize_image(image, (224,224)) return (i)
def scale19(image):
i = resize_image(image, (224,224)) return (i)
)[1] startx = width//2 - (target_width//2) starty = height//2 - (target_height//2) im = tf.image.crop_to_bounding_box(im, startx, starty, target_width, target_height) return im def scale19(image):
64
64
22
5
58
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
scale19
scale19
121
123
121
121
ea03f7bbe4d094b66e440e05be64329322633aab
bigcode/the-stack
train
f7da28731f8217ab390630b8
train
function
def _testing_data_generator(image_path, label): # Read image img = tf.io.read_file(image_path) img = tf.image.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) img.set_shape([None, None, 3]) img = scale19(img) return img, label
def _testing_data_generator(image_path, label): # Read image
img = tf.io.read_file(image_path) img = tf.image.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) img.set_shape([None, None, 3]) img = scale19(img) return img, label
* ratio img = tf.image.resize(img, (w, 256), method="bicubic") img = tf.image.random_crop(img, size=(IMG_SIZE, IMG_SIZE, 3)) return img, label def _testing_data_generator(image_path, label): # Read image
64
64
77
15
48
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
_testing_data_generator
_testing_data_generator
82
89
82
83
917522a925ce50d6869e42942d00da9f051705a0
bigcode/the-stack
train
975a06a6a98749860fba632d
train
function
def ResNet152V2(): IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3) resnet152v2 = tf.keras.applications.ResNet152V2(include_top=True, weights='imagenet', input_shape=IMG_SHAPE, ...
def ResNet152V2():
IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3) resnet152v2 = tf.keras.applications.ResNet152V2(include_top=True, weights='imagenet', input_shape=IMG_SHAPE, classes=10...
- (target_height//2) im = tf.image.crop_to_bounding_box(im, startx, starty, target_width, target_height) return im def scale19(image): i = resize_image(image, (224,224)) return (i) def ResNet152V2():
64
64
71
7
57
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
ResNet152V2
ResNet152V2
125
131
125
125
245b6826c676b52c065dd02becde854cbe11e5e6
bigcode/the-stack
train
b3ca3db5686504ff6e121645
train
function
def testing_dataset_generator(img_path, label, _data_generator, batch_size): assert img_path.shape[0] == label.shape[0] dataset = tf.data.Dataset.from_tensor_slices((img_path, label)) dataset = dataset.map(_data_generator, num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_s...
def testing_dataset_generator(img_path, label, _data_generator, batch_size):
assert img_path.shape[0] == label.shape[0] dataset = tf.data.Dataset.from_tensor_slices((img_path, label)) dataset = dataset.map(_data_generator, num_parallel_calls=tf.data.experimental.AUTOTUNE) dataset = dataset.batch(batch_size) dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE...
.image.decode_image(img, channels=3) img = tf.image.convert_image_dtype(img, tf.float32) img.set_shape([None, None, 3]) img = scale19(img) return img, label def testing_dataset_generator(img_path, label, _data_generator, batch_size):
64
64
94
16
47
nthu-datalab/Runtime-Masking-and-Cleansing
prepare/augment_dataset.py
Python
testing_dataset_generator
testing_dataset_generator
91
97
91
91
771cb973d53d873e489377dbc06f9b72fd337311
bigcode/the-stack
train
24ed1cdf534f4eca42b32628
train
class
class Roadm(_JsonThing): default_values = { 'target_pch_out_db': -17, 'add_drop_osnr': 100, 'pmd': 0, 'restrictions': { 'preamp_variety_list': [], 'booster_variety_list': [] } } def __init__(self, **kwargs): self.update_attr(self.defau...
class Roadm(_JsonThing):
default_values = { 'target_pch_out_db': -17, 'add_drop_osnr': 100, 'pmd': 0, 'restrictions': { 'preamp_variety_list': [], 'booster_variety_list': [] } } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Roadm...
, 'padding': 10, 'EOL': 0, 'con_in': 0, 'con_out': 0 } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Span') class Roadm(_JsonThing):
64
64
93
7
57
odd22/gnpy
gnpy/tools/json_io.py
Python
Roadm
Roadm
92
104
92
92
c7204f31bbafd215c1245780b5a4fac4b1e714af
bigcode/the-stack
train
acd3bf45b980c86339ebf39f
train
class
class RamanFiber(_JsonThing): default_values = { 'type_variety': '', 'dispersion': None, 'gamma': 0, 'pmd_coef': 0, 'raman_efficiency': None } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'RamanFiber') for param in ('cr'...
class RamanFiber(_JsonThing):
default_values = { 'type_variety': '', 'dispersion': None, 'gamma': 0, 'pmd_coef': 0, 'raman_efficiency': None } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'RamanFiber') for param in ('cr', 'frequency_offset'): ...
= { 'type_variety': '', 'dispersion': None, 'gamma': 0, 'pmd_coef': 0 } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Fiber') class RamanFiber(_JsonThing):
64
64
163
7
57
odd22/gnpy
gnpy/tools/json_io.py
Python
RamanFiber
RamanFiber
130
145
130
130
6de66b7a6dc70f71486fac374214364299d5771e
bigcode/the-stack
train
84a3afab6ce87a9f8b9fcd98
train
class
class Amp(_JsonThing): default_values = { 'f_min': 191.35e12, 'f_max': 196.1e12, 'type_variety': '', 'type_def': '', 'gain_flatmax': None, 'gain_min': None, 'p_max': None, 'nf_model': None, 'dual_stage_model': None, 'nf_fit_coeff': None...
class Amp(_JsonThing):
default_values = { 'f_min': 191.35e12, 'f_max': 196.1e12, 'type_variety': '', 'type_def': '', 'gain_flatmax': None, 'gain_min': None, 'p_max': None, 'nf_model': None, 'dual_stage_model': None, 'nf_fit_coeff': None, 'nf_ripple': ...
**kwargs): self.update_attr(self.default_values, kwargs, 'Transceiver') class Fiber(_JsonThing): default_values = { 'type_variety': '', 'dispersion': None, 'gamma': 0, 'pmd_coef': 0 } def __init__(self, **kwargs): self.update_attr(self.default_values, kwar...
252
252
840
6
246
odd22/gnpy
gnpy/tools/json_io.py
Python
Amp
Amp
148
229
148
148
ec336ed9871a028f5ea8699f61ae70f81773e3ea
bigcode/the-stack
train
b7779fc2602458f16f4828b6
train
function
def convert_service_sheet( input_filename, eqpt, network, network_filename=None, output_filename='', bidir=False): if output_filename == '': output_filename = f'{str(input_filename)[0:len(str(input_filename))-len(str(input_filename.suffixes[0]))]}_services.jso...
def convert_service_sheet( input_filename, eqpt, network, network_filename=None, output_filename='', bidir=False):
if output_filename == '': output_filename = f'{str(input_filename)[0:len(str(input_filename))-len(str(input_filename.suffixes[0]))]}_services.json' data = read_service_sheet(input_filename, eqpt, network, network_filename, bidir) save_json(data, output_filename) return data
s_req'] = snc['svec']['request-id-number'] disjunctions_list.append(Disjunction(**params)) return disjunctions_list def convert_service_sheet( input_filename, eqpt, network, network_filename=None, output_filename='', bidir=False):
64
64
101
31
32
odd22/gnpy
gnpy/tools/json_io.py
Python
convert_service_sheet
convert_service_sheet
555
566
555
561
143a93e0f24426afadfa78126a7e77f1cbcff2ff
bigcode/the-stack
train
c16a75766a6d672ad7adfc4a
train
class
class Transceiver(_JsonThing): default_values = { 'type_variety': None, 'frequency': None, 'mode': {} } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Transceiver')
class Transceiver(_JsonThing):
default_values = { 'type_variety': None, 'frequency': None, 'mode': {} } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Transceiver')
md': 0, 'restrictions': { 'preamp_variety_list': [], 'booster_variety_list': [] } } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Roadm') class Transceiver(_JsonThing):
64
64
57
7
57
odd22/gnpy
gnpy/tools/json_io.py
Python
Transceiver
Transceiver
107
115
107
107
bc265542fb3628e6e8795287b98c4eae92a7604c
bigcode/the-stack
train
00ac860265226aaeb964199b
train
class
class SI(_JsonThing): default_values = { "f_min": 191.35e12, "f_max": 196.1e12, "baud_rate": 32e9, "spacing": 50e9, "power_dbm": 0, "power_range_db": [0, 0, 0.5], "roll_off": 0.15, "tx_osnr": 45, "sys_margins": 0 } def __init__(self, *...
class SI(_JsonThing):
default_values = { "f_min": 191.35e12, "f_max": 196.1e12, "baud_rate": 32e9, "spacing": 50e9, "power_dbm": 0, "power_range_db": [0, 0, 0.5], "roll_off": 0.15, "tx_osnr": 45, "sys_margins": 0 } def __init__(self, **kwargs): self...
_kwargs and name != 'Amp': print(ansi_escapes.red + f'\n WARNING missing {k} attribute in eqpt_config.json[{name}]' + f'\n default value is {k} = {v}' + ansi_escapes.reset) class SI(_JsonThing):
64
64
134
6
58
odd22/gnpy
gnpy/tools/json_io.py
Python
SI
SI
56
70
56
56
f988df897a6a9d77b931b2bb5800a76d6572345d
bigcode/the-stack
train
6855704723579312d84902b2
train
class
class Model_openroadm_booster: pass
class Model_openroadm_booster:
pass
_coef') Model_hybrid = namedtuple('Model_hybrid', 'nf_ram gain_ram edfa_variety') Model_dual_stage = namedtuple('Model_dual_stage', 'preamp_variety booster_variety') class Model_openroadm_preamp: pass class Model_openroadm_booster:
64
64
11
8
55
odd22/gnpy
gnpy/tools/json_io.py
Python
Model_openroadm_booster
Model_openroadm_booster
40
41
40
40
37bda734d45114ee8f90c6dd165bd707bf0ac73c
bigcode/the-stack
train
558a0cbe7514ef7ea4b78b85
train
class
class Span(_JsonThing): default_values = { 'power_mode': True, 'delta_power_range_db': None, 'max_fiber_lineic_loss_for_raman': 0.25, 'target_extended_gain': 2.5, 'max_length': 150, 'length_units': 'km', 'max_loss': None, 'padding': 10, 'EOL': ...
class Span(_JsonThing):
default_values = { 'power_mode': True, 'delta_power_range_db': None, 'max_fiber_lineic_loss_for_raman': 0.25, 'target_extended_gain': 2.5, 'max_length': 150, 'length_units': 'km', 'max_loss': None, 'padding': 10, 'EOL': 0, 'con_in': 0, ...
0.5], "roll_off": 0.15, "tx_osnr": 45, "sys_margins": 0 } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'SI') class Span(_JsonThing):
64
64
134
6
58
odd22/gnpy
gnpy/tools/json_io.py
Python
Span
Span
73
89
73
73
d27c6e2f2b87dd2b4769d4b91ab247622da1e0e0
bigcode/the-stack
train
e76a55925c8ec43589c6e552
train
function
def _roadm_restrictions_sanity_check(equipment): """ verifies that booster and preamp restrictions specified in roadm equipment are listed in the edfa. """ restrictions = equipment['Roadm']['default'].restrictions['booster_variety_list'] + \ equipment['Roadm']['default'].restrictions['preamp_var...
def _roadm_restrictions_sanity_check(equipment):
""" verifies that booster and preamp restrictions specified in roadm equipment are listed in the edfa. """ restrictions = equipment['Roadm']['default'].restrictions['booster_variety_list'] + \ equipment['Roadm']['default'].restrictions['preamp_variety_list'] for amp_name in restrictions: ...
ain_flatmax if edfa.gain_min < edfa_preamp.gain_min: raise EquipmentConfigError(f'Dual stage {edfa.type_variety} minimal gain is lower than its preamp minimal gain') return equipment def _roadm_restrictions_sanity_check(equipment):
64
64
118
13
50
odd22/gnpy
gnpy/tools/json_io.py
Python
_roadm_restrictions_sanity_check
_roadm_restrictions_sanity_check
264
272
264
264
8dae476ada634f08eb8ac92a5026f4ec6c1f9b82
bigcode/the-stack
train
b2c131f774d7b18cec798043
train
class
class _JsonThing: def update_attr(self, default_values, kwargs, name): clean_kwargs = {k: v for k, v in kwargs.items() if v != ''} for k, v in default_values.items(): setattr(self, k, clean_kwargs.get(k, v)) if k not in clean_kwargs and name != 'Amp': print(an...
class _JsonThing:
def update_attr(self, default_values, kwargs, name): clean_kwargs = {k: v for k, v in kwargs.items() if v != ''} for k, v in default_values.items(): setattr(self, k, clean_kwargs.get(k, v)) if k not in clean_kwargs and name != 'Amp': print(ansi_escapes.red + ...
('Model_hybrid', 'nf_ram gain_ram edfa_variety') Model_dual_stage = namedtuple('Model_dual_stage', 'preamp_variety booster_variety') class Model_openroadm_preamp: pass class Model_openroadm_booster: pass class _JsonThing:
64
64
125
5
58
odd22/gnpy
gnpy/tools/json_io.py
Python
_JsonThing
_JsonThing
44
53
44
44
b02aa4cc594170f2bf30b90bc236bfeea52831ce
bigcode/the-stack
train
e9def71ff723f6bcfa65dd7b
train
function
def requests_from_json(json_data, equipment): """Extract list of requests from data parsed from JSON""" requests_list = [] for req in json_data['path-request']: # init all params from request params = {} params['request_id'] = req['request-id'] params['source'] = req['source...
def requests_from_json(json_data, equipment):
"""Extract list of requests from data parsed from JSON""" requests_list = [] for req in json_data['path-request']: # init all params from request params = {} params['request_id'] = req['request-id'] params['source'] = req['source'] params['bidir'] = req['bidirectiona...
: data = json.load(f) return data def save_json(obj, filename): with open(filename, 'w', encoding='utf-8') as f: json.dump(obj, f, indent=2, ensure_ascii=False) def load_requests(filename, eqpt, bidir, network, network_filename): """ loads the requests from a json or an excel file into a...
194
194
648
9
185
odd22/gnpy
gnpy/tools/json_io.py
Python
requests_from_json
requests_from_json
441
495
441
441
53827c7ea52a4bba7a7b86a09b98f2d3746e8132
bigcode/the-stack
train
4187531f8ff16e2bc5da0a0f
train
class
class Fiber(_JsonThing): default_values = { 'type_variety': '', 'dispersion': None, 'gamma': 0, 'pmd_coef': 0 } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Fiber')
class Fiber(_JsonThing):
default_values = { 'type_variety': '', 'dispersion': None, 'gamma': 0, 'pmd_coef': 0 } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Fiber')
') class Transceiver(_JsonThing): default_values = { 'type_variety': None, 'frequency': None, 'mode': {} } def __init__(self, **kwargs): self.update_attr(self.default_values, kwargs, 'Transceiver') class Fiber(_JsonThing):
64
64
66
6
58
odd22/gnpy
gnpy/tools/json_io.py
Python
Fiber
Fiber
118
127
118
118
c2120973eb74964dd0aace74492cdff011bcc08d
bigcode/the-stack
train
eab2e6413d364dd873f63b31
train
function
def network_to_json(network): data = { 'elements': [n.to_json for n in network] } connections = { 'connections': [{"from_node": n.uid, "to_node": next_n.uid} for n in network for next_n in network.successors(n) if next_...
def network_to_json(network):
data = { 'elements': [n.to_json for n in network] } connections = { 'connections': [{"from_node": n.uid, "to_node": next_n.uid} for n in network for next_n in network.successors(n) if next_n is not None] } data....
edge_length = 0.01 g.add_edge(nodes[from_node], nodes[to_node], weight=edge_length) except KeyError: raise NetworkTopologyError(f'can not find {from_node} or {to_node} defined in {cx}') return g def network_to_json(network):
64
64
84
6
57
odd22/gnpy
gnpy/tools/json_io.py
Python
network_to_json
network_to_json
402
413
402
402
41faaccea0edc86a7f439e5a535521b4364a7e69
bigcode/the-stack
train
a118d086da984abaddec5c6a
train
function
def load_equipment(filename): json_data = load_json(filename) return _equipment_from_json(json_data, filename)
def load_equipment(filename):
json_data = load_json(filename) return _equipment_from_json(json_data, filename)
62.5e9), (67e9, 75e9), (92e9, 100e9)] return min((s[1] for s in spacing_list if s[0] > baud_rate), default=baud_rate * 1.2) def load_equipment(filename):
64
64
25
6
58
odd22/gnpy
gnpy/tools/json_io.py
Python
load_equipment
load_equipment
240
242
240
240
5cbc58c583750df346e0c96476e7144cc008fa68
bigcode/the-stack
train
ed20b424755b63f3c2afacc8
train
function
def save_json(obj, filename): with open(filename, 'w', encoding='utf-8') as f: json.dump(obj, f, indent=2, ensure_ascii=False)
def save_json(obj, filename):
with open(filename, 'w', encoding='utf-8') as f: json.dump(obj, f, indent=2, ensure_ascii=False)
network.successors(n) if next_n is not None] } data.update(connections) return data def load_json(filename): with open(filename, 'r', encoding='utf-8') as f: data = json.load(f) return data def save_json(obj, filename):
64
64
39
7
56
odd22/gnpy
gnpy/tools/json_io.py
Python
save_json
save_json
422
424
422
422
2cbe6faa3e7995549b90a57244987f2e52d03a66
bigcode/the-stack
train
ab15f88d27edba1c79d77540
train
function
def load_network(filename, equipment): if filename.suffix.lower() in ('.xls', '.xlsx'): json_data = xls_to_json_data(filename) elif filename.suffix.lower() == '.json': json_data = load_json(filename) else: raise ValueError(f'unsupported topology filename extension {filename.suffix.lo...
def load_network(filename, equipment):
if filename.suffix.lower() in ('.xls', '.xlsx'): json_data = xls_to_json_data(filename) elif filename.suffix.lower() == '.json': json_data = load_json(filename) else: raise ValueError(f'unsupported topology filename extension {filename.suffix.lower()}') return network_from_json(j...
raise EquipmentConfigError(f'Unrecognized network element type "{key}"') _check_fiber_vs_raman_fiber(equipment) equipment = _update_dual_stage(equipment) _roadm_restrictions_sanity_check(equipment) return equipment def load_network(filename, equipment):
64
64
82
7
56
odd22/gnpy
gnpy/tools/json_io.py
Python
load_network
load_network
326
333
326
326
d286d82b7106f4cbd128281d5aad0748b1d62195
bigcode/the-stack
train
df9a77108bcfee1abd343c66
train
function
def save_network(network: DiGraph, filename: str): '''Dump the network into a JSON file :param network: network to work on :param filename: file to write to ''' save_json(network_to_json(network), filename)
def save_network(network: DiGraph, filename: str):
'''Dump the network into a JSON file :param network: network to work on :param filename: file to write to ''' save_json(network_to_json(network), filename)
_data(filename) elif filename.suffix.lower() == '.json': json_data = load_json(filename) else: raise ValueError(f'unsupported topology filename extension {filename.suffix.lower()}') return network_from_json(json_data, equipment) def save_network(network: DiGraph, filename: str):
64
64
54
12
52
odd22/gnpy
gnpy/tools/json_io.py
Python
save_network
save_network
336
342
336
336
2a170d094a2e4a27e560711b64cc7ba38c490112
bigcode/the-stack
train
be07f014d5378c126f772682
train
function
def _check_one_request(params, f_max_from_si): """Checks that the requested parameters are consistant (spacing vs nb channel vs transponder mode...)""" f_min = params['f_min'] f_max = params['f_max'] max_recommanded_nb_channels = automatic_nch(f_min, f_max, params['spacing']) if params['baud_rate'] ...
def _check_one_request(params, f_max_from_si):
"""Checks that the requested parameters are consistant (spacing vs nb channel vs transponder mode...)""" f_min = params['f_min'] f_max = params['f_max'] max_recommanded_nb_channels = automatic_nch(f_min, f_max, params['spacing']) if params['baud_rate'] is not None: # implicitly means that a ...
params['f_max'] = automatic_fmax(f_min, spacing, nch) else: params['nb_channel'] = automatic_nch(f_min, f_max_from_si, params['spacing']) except KeyError: params['nb_channel'] = automatic_nch(f_min, f_max_from_si, params['spacing']) params['effective_freq_slot'] ...
169
169
565
12
156
odd22/gnpy
gnpy/tools/json_io.py
Python
_check_one_request
_check_one_request
498
534
498
498
1c7c2d3ef6408c04573789d9abdf239c25611935
bigcode/the-stack
train
acf8b8a7aeedfc2499ef6dca
train
function
def _check_fiber_vs_raman_fiber(equipment): """Ensure that Fiber and RamanFiber with the same name define common properties equally""" if 'RamanFiber' not in equipment: return for fiber_type in set(equipment['Fiber'].keys()) & set(equipment['RamanFiber'].keys()): for attr in ('dispersion', '...
def _check_fiber_vs_raman_fiber(equipment):
"""Ensure that Fiber and RamanFiber with the same name define common properties equally""" if 'RamanFiber' not in equipment: return for fiber_type in set(equipment['Fiber'].keys()) & set(equipment['RamanFiber'].keys()): for attr in ('dispersion', 'dispersion-slope', 'gamma', 'pmd-coefficient...
restrictions['preamp_variety_list'] for amp_name in restrictions: if amp_name not in equipment['Edfa']: raise EquipmentConfigError(f'ROADM restriction {amp_name} does not refer to a defined EDFA name') def _check_fiber_vs_raman_fiber(equipment):
64
64
180
13
51
odd22/gnpy
gnpy/tools/json_io.py
Python
_check_fiber_vs_raman_fiber
_check_fiber_vs_raman_fiber
275
287
275
275
92027ab4c6c51006d65e3998099b0c93895af802
bigcode/the-stack
train
f28021f1ee3949849a1ee2c3
train
function
def _update_dual_stage(equipment): edfa_dict = equipment['Edfa'] for edfa in edfa_dict.values(): if edfa.type_def == 'dual_stage': edfa_preamp = edfa_dict[edfa.dual_stage_model.preamp_variety] edfa_booster = edfa_dict[edfa.dual_stage_model.booster_variety] for key, va...
def _update_dual_stage(equipment):
edfa_dict = equipment['Edfa'] for edfa in edfa_dict.values(): if edfa.type_def == 'dual_stage': edfa_preamp = edfa_dict[edfa.dual_stage_model.preamp_variety] edfa_booster = edfa_dict[edfa.dual_stage_model.booster_variety] for key, value in edfa_preamp.__dict__.items()...
, 100e9)] return min((s[1] for s in spacing_list if s[0] > baud_rate), default=baud_rate * 1.2) def load_equipment(filename): json_data = load_json(filename) return _equipment_from_json(json_data, filename) def _update_dual_stage(equipment):
72
72
240
9
63
odd22/gnpy
gnpy/tools/json_io.py
Python
_update_dual_stage
_update_dual_stage
245
261
245
245
395ffca4ba22407409d0979f70447db85d1298ff
bigcode/the-stack
train
754d8c72b459b8a4100311ce
train
class
class Model_openroadm_preamp: pass
class Model_openroadm_preamp:
pass
tuple('Model_openroadm_ila', 'nf_coef') Model_hybrid = namedtuple('Model_hybrid', 'nf_ram gain_ram edfa_variety') Model_dual_stage = namedtuple('Model_dual_stage', 'preamp_variety booster_variety') class Model_openroadm_preamp:
64
64
11
8
56
odd22/gnpy
gnpy/tools/json_io.py
Python
Model_openroadm_preamp
Model_openroadm_preamp
36
37
36
36
5cf5363560e3d9bfa3f0dcf62f6ac66de48ffb4f
bigcode/the-stack
train
558112d43379e00e29d26e24
train
function
def disjunctions_from_json(json_data): """ reads the disjunction requests from the json dict and create the list of requested disjunctions for this set of requests """ disjunctions_list = [] if 'synchronization' in json_data: for snc in json_data['synchronization']: params = ...
def disjunctions_from_json(json_data):
""" reads the disjunction requests from the json dict and create the list of requested disjunctions for this set of requests """ disjunctions_list = [] if 'synchronization' in json_data: for snc in json_data['synchronization']: params = {} params['disjunction_id']...
_m} to support request' +\ f'{params["path_bandwidth"] * 1e-9} Gbit/s with {params["trx_type"]} {params["trx_mode"]}' _logger.critical(msg) raise ServiceError(msg) def disjunctions_from_json(json_data):
64
64
189
9
55
odd22/gnpy
gnpy/tools/json_io.py
Python
disjunctions_from_json
disjunctions_from_json
537
552
537
537
813f42fa2fadf125d5c9789c24aadbbef9b72e9f
bigcode/the-stack
train
c1592e795a1c21d5a8233a0e
train
function
def network_from_json(json_data, equipment): # NOTE|dutc: we could use the following, but it would tie our data format # too closely to the graph library # from networkx import node_link_graph g = DiGraph() for el_config in json_data['elements']: typ = el_config.pop('type') ...
def network_from_json(json_data, equipment): # NOTE|dutc: we could use the following, but it would tie our data format # too closely to the graph library # from networkx import node_link_graph
g = DiGraph() for el_config in json_data['elements']: typ = el_config.pop('type') variety = el_config.pop('type_variety', 'default') cls = _cls_for(typ) if typ == 'Fused': # well, there's no variety for the 'Fused' node type pass elif variety in eq...
return elements.Roadm elif equipment_type == 'Transceiver': return elements.Transceiver elif equipment_type == 'Fiber': return elements.Fiber elif equipment_type == 'RamanFiber': return elements.RamanFiber else: raise ConfigurationError(f'Unknown network equipment...
120
120
401
50
70
odd22/gnpy
gnpy/tools/json_io.py
Python
network_from_json
network_from_json
362
399
362
365
0a88401c501ad855be7776cbb38d2f5bc66d975d
bigcode/the-stack
train
2e534e4ee88f80e0a04689e8
train
function
def _equipment_from_json(json_data, filename): """build global dictionnary eqpt_library that stores all eqpt characteristics: edfa type type_variety, fiber type_variety from the eqpt_config.json (filename parameter) also read advanced_config_from_json file parameters for edfa if they are available: ...
def _equipment_from_json(json_data, filename):
"""build global dictionnary eqpt_library that stores all eqpt characteristics: edfa type type_variety, fiber type_variety from the eqpt_config.json (filename parameter) also read advanced_config_from_json file parameters for edfa if they are available: typically nf_ripple, dfg gain ripple, dgt and n...
', 'gamma', 'pmd-coefficient'): fiber = equipment['Fiber'][fiber_type] raman = equipment['RamanFiber'][fiber_type] a = getattr(fiber, attr, None) b = getattr(raman, attr, None) if a != b: raise EquipmentConfigError(f'WARNING: Fiber and RamanFib...
109
110
367
10
99
odd22/gnpy
gnpy/tools/json_io.py
Python
_equipment_from_json
_equipment_from_json
290
323
290
290
ef3bf4193efcaff4b3799bf9731fdff33f55e9cd
bigcode/the-stack
train
843fad68d67442cb4b567c0a
train
function
def _cls_for(equipment_type): if equipment_type == 'Edfa': return elements.Edfa if equipment_type == 'Fused': return elements.Fused elif equipment_type == 'Roadm': return elements.Roadm elif equipment_type == 'Transceiver': return elements.Transceiver elif equipment_t...
def _cls_for(equipment_type):
if equipment_type == 'Edfa': return elements.Edfa if equipment_type == 'Fused': return elements.Fused elif equipment_type == 'Roadm': return elements.Roadm elif equipment_type == 'Transceiver': return elements.Transceiver elif equipment_type == 'Fiber': return...
equipment) def save_network(network: DiGraph, filename: str): '''Dump the network into a JSON file :param network: network to work on :param filename: file to write to ''' save_json(network_to_json(network), filename) def _cls_for(equipment_type):
64
64
117
8
56
odd22/gnpy
gnpy/tools/json_io.py
Python
_cls_for
_cls_for
345
359
345
345
923026bf7998b13d0a52474063681634f120f6e3
bigcode/the-stack
train
2030ad11350847da132d3d38
train
function
def load_requests(filename, eqpt, bidir, network, network_filename): """ loads the requests from a json or an excel file into a data string """ if filename.suffix.lower() in ('.xls', '.xlsx'): _logger.info('Automatically converting requests from XLS to JSON') try: return convert_...
def load_requests(filename, eqpt, bidir, network, network_filename):
""" loads the requests from a json or an excel file into a data string """ if filename.suffix.lower() in ('.xls', '.xlsx'): _logger.info('Automatically converting requests from XLS to JSON') try: return convert_service_sheet(filename, eqpt, network, network_filename=network_filen...
= json.load(f) return data def save_json(obj, filename): with open(filename, 'w', encoding='utf-8') as f: json.dump(obj, f, indent=2, ensure_ascii=False) def load_requests(filename, eqpt, bidir, network, network_filename):
64
64
134
16
48
odd22/gnpy
gnpy/tools/json_io.py
Python
load_requests
load_requests
427
438
427
427
b7782b84097007087d04aa113c4ab285c24c1767
bigcode/the-stack
train
b5d1a28c88f419e9165fdcc1
train
function
def load_json(filename): with open(filename, 'r', encoding='utf-8') as f: data = json.load(f) return data
def load_json(filename):
with open(filename, 'r', encoding='utf-8') as f: data = json.load(f) return data
connections = { 'connections': [{"from_node": n.uid, "to_node": next_n.uid} for n in network for next_n in network.successors(n) if next_n is not None] } data.update(connections) return data def load_json(filename):
64
64
33
5
58
odd22/gnpy
gnpy/tools/json_io.py
Python
load_json
load_json
416
419
416
416
afb51491649856c4c21b484e860c613a882932d2
bigcode/the-stack
train
603e4becf5dfd2fafa2057ad
train
function
def _automatic_spacing(baud_rate): """return the min possible channel spacing for a given baud rate""" # TODO : this should parametrized in a cfg file # list of possible tuples [(max_baud_rate, spacing_for_this_baud_rate)] spacing_list = [(33e9, 37.5e9), (38e9, 50e9), (50e9, 62.5e9), (67e9, 75e9), (92e9...
def _automatic_spacing(baud_rate):
"""return the min possible channel spacing for a given baud rate""" # TODO : this should parametrized in a cfg file # list of possible tuples [(max_baud_rate, spacing_for_this_baud_rate)] spacing_list = [(33e9, 37.5e9), (38e9, 50e9), (50e9, 62.5e9), (67e9, 75e9), (92e9, 100e9)] return min((s[1] for ...
: raise EquipmentConfigError(f'Edfa type_def {type_def} does not exist') json_data = load_json(config) return cls(**{**kwargs, **json_data, 'nf_model': nf_def, 'dual_stage_model': dual_stage_def}) def _automatic_spacing(baud_rate):
64
64
144
8
56
odd22/gnpy
gnpy/tools/json_io.py
Python
_automatic_spacing
_automatic_spacing
232
237
232
232
e40189a764caaf48b789a0467abddfff4a350486
bigcode/the-stack
train
3832ca4625c36e2ab61b6119
train
class
class TestSubsequentSiblingQuirks(TestSubsequentSibling): """Test subsequent sibling combinator with quirks.""" def setUp(self): """Setup.""" self.purge() self.quirks = True
class TestSubsequentSiblingQuirks(TestSubsequentSibling):
"""Test subsequent sibling combinator with quirks.""" def setUp(self): """Setup.""" self.purge() self.quirks = True
">Child 2</span> <span id="6">Child 3</span> </pre> </div> """, "p ~ span", ["3"], flags=util.HTML ) class TestSubsequentSiblingQuirks(TestSubsequentSibling):
64
64
49
15
49
Guillaume-Fernandez/phishfinder
venv/lib/python3.6/site-packages/tests/test_level3/test_subsequent_sibling.py
Python
TestSubsequentSiblingQuirks
TestSubsequentSiblingQuirks
31
38
31
31
3cb84a3197347ed2e27bfc16b2ccbec64ae15691
bigcode/the-stack
train
5ad8b9d9558e92eadf73cc76
train
class
class TestSubsequentSibling(util.TestCase): """Test subsequent sibling combinator.""" def test_subsequent_sibling(self): """Test subsequent sibling.""" self.assert_selector( """ <div> <p id="0">Some text <span id="1"> in a paragraph</span>.</p> <...
class TestSubsequentSibling(util.TestCase):
"""Test subsequent sibling combinator.""" def test_subsequent_sibling(self): """Test subsequent sibling.""" self.assert_selector( """ <div> <p id="0">Some text <span id="1"> in a paragraph</span>.</p> <a id="2" href="http://google.com">Link</a> ...
"""Test subsequent sibling combinator.""" from __future__ import unicode_literals from .. import util class TestSubsequentSibling(util.TestCase):
30
64
170
10
19
Guillaume-Fernandez/phishfinder
venv/lib/python3.6/site-packages/tests/test_level3/test_subsequent_sibling.py
Python
TestSubsequentSibling
TestSubsequentSibling
6
28
6
6
471b757543edb69550aac3c78f9de71bbe50f02a
bigcode/the-stack
train
69f43e7fda12b870aa498d5e
train
function
def create_new_smart_contract(template_name='PollutionTracker', metrics=[]): with open(os.path.join(os.getcwd(), template_name + '.sol'), 'w', encoding='utf-8') as out_file, open( os.path.join(os.getcwd(), 'smartpollution', 'static', 'smartcontracts', 'simple_template_smartcontr...
def create_new_smart_contract(template_name='PollutionTracker', metrics=[]):
with open(os.path.join(os.getcwd(), template_name + '.sol'), 'w', encoding='utf-8') as out_file, open( os.path.join(os.getcwd(), 'smartpollution', 'static', 'smartcontracts', 'simple_template_smartcontract.sol'), 'r', encoding='utf-8') as template_f: for lin in template_...
in.replace('@ContractName@', str(template_name).replace('-', ''))) if "@MetricName@" in lin: out_file.write(lin.replace('@MetricName@', str(r'"' + metric_name + r'"').replace('-', ''))) if "@LowerTrigger@" in lin: out_file.write(lin.replace('@Lower...
134
134
448
16
118
SandroLuck/SCGenerator
mysite/smartpollution/generate_smartcontract.py
Python
create_new_smart_contract
create_new_smart_contract
25
59
25
25
64d598db3a0aee7da0d319d9104a93a99524de1d
bigcode/the-stack
train
6a745df9fde0bac71fd67075
train
function
def create_new_smart_contract_with_thresholds(template_name='PollutionTracker', thresholds=[]): print('Creating thresholds contract.') with open(os.path.join(os.getcwd(), template_name + '.sol'), 'w', encoding='utf-8') as out_file, open( os.path.join(os.getcwd(), 'smartpollution', 'static', 'smartco...
def create_new_smart_contract_with_thresholds(template_name='PollutionTracker', thresholds=[]):
print('Creating thresholds contract.') with open(os.path.join(os.getcwd(), template_name + '.sol'), 'w', encoding='utf-8') as out_file, open( os.path.join(os.getcwd(), 'smartpollution', 'static', 'smartcontracts', 'simple_template_smartcontract_with_thresholds.sol'), 'r', en...
out_file.write('\t\tfunction alarm' + str(met) + '(' + 'int16 _val' + str( met) + ',' + 'string _id) onlyOwner{' + str(met) + '(' + '_val' + str( met) + ', ' + '_id);}\n') if "@paramsAlarmAll@" in lin: out_file.write('\t\t\t') ...
256
256
1,482
19
237
SandroLuck/SCGenerator
mysite/smartpollution/generate_smartcontract.py
Python
create_new_smart_contract_with_thresholds
create_new_smart_contract_with_thresholds
62
171
62
62
4a2ba54b37d915682c001d6868597ed2b3a3b06e
bigcode/the-stack
train
e33f97e9e883042803782de3
train
function
def create_new_smart_contract1(template_name='PollutionTracker', metric_name='DefaultMetricName', lower_trigger=-6666, upper_trigger=6666): with open(os.path.join(os.getcwd(), template_name + '.sol'), 'w', encoding='utf-8') as out_file, open( os.path.join(os.getcwd(), 'sma...
def create_new_smart_contract1(template_name='PollutionTracker', metric_name='DefaultMetricName', lower_trigger=-6666, upper_trigger=6666):
with open(os.path.join(os.getcwd(), template_name + '.sol'), 'w', encoding='utf-8') as out_file, open( os.path.join(os.getcwd(), 'smartpollution', 'static', 'smartcontracts', 'template_smartcontract.sol'), 'r', encoding='utf-8') as template_f: for lin in template_f: if no...
import os from .models import * def create_new_smart_contract1(template_name='PollutionTracker', metric_name='DefaultMetricName', lower_trigger=-6666, upper_trigger=6666):
42
78
261
34
8
SandroLuck/SCGenerator
mysite/smartpollution/generate_smartcontract.py
Python
create_new_smart_contract1
create_new_smart_contract1
5
22
5
6
c741497c6f91056ef435dfe1a67612fc8d85fd4f
bigcode/the-stack
train
dd8fbb890aa865e223d27d3e
train
class
@Label.model @bi_sync @workflow @on_delete_check(check=[("phone.PhoneRange", "supplier"), ("sa.Service", "supplier")]) class Supplier(Document): meta = { "collection": "noc.suppliers", "indexes": ["name"], "strict": False, "auto_create_index": False, } name = StringField() ...
@Label.model @bi_sync @workflow @on_delete_check(check=[("phone.PhoneRange", "supplier"), ("sa.Service", "supplier")]) class Supplier(Document):
meta = { "collection": "noc.suppliers", "indexes": ["name"], "strict": False, "auto_create_index": False, } name = StringField() description = StringField() is_affilated = BooleanField(default=False) profile = PlainReferenceField(SupplierProfile) state = Plai...
Field from noc.wf.models.state import State from noc.project.models.project import Project from noc.core.wf.decorator import workflow from noc.core.bi.decorator import bi_sync from noc.core.model.decorator import on_delete_check id_lock = Lock() @Label.model @bi_sync @workflow @on_delete_check(check=[("phone.PhoneRang...
92
92
308
37
55
prorevizor/noc
crm/models/supplier.py
Python
Supplier
Supplier
31
72
31
35
433537354184a682ea03c4e9261cd70d8cade17a
bigcode/the-stack
train
3b90b6c0c3a276bc398ecb98
train
class
class TapiCommonGetserviceinterfacepointlistOutput(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, sip=None): # noqa: E501 """TapiCommonGetserviceinterfacepointlistOutput - a model defi...
class TapiCommonGetserviceinterfacepointlistOutput(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, sip=None): # noqa: E501 """TapiCommonGetserviceinterfacepointlistOutput - a model defined in OpenAPI :param sip: The sip of this TapiCom...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from tapi_server.models.base_model_ import Model from tapi_server.models.tapi_common_getserviceinterfacepointlist_output_sip import TapiCommonGetserviceinterfacepointli...
102
128
427
11
90
arthurMll/TAPI
RI/flask_server/tapi_server/models/tapi_common_getserviceinterfacepointlist_output.py
Python
TapiCommonGetserviceinterfacepointlistOutput
TapiCommonGetserviceinterfacepointlistOutput
13
67
13
13
778053e16d9447b8b4df2215b531c6e9fd7fd9ea
bigcode/the-stack
train
01a349e90cccd3d026a4acf2
train
function
def expval(op): r"""Expectation value of the supplied observable. Args: op (Observable): a quantum observable object Raises: QuantumFunctionError: `op` is not an instance of :class:`~.Observable` """ if not isinstance(op, Observable): raise QuantumFunctionError( ...
def expval(op):
r"""Expectation value of the supplied observable. Args: op (Observable): a quantum observable object Raises: QuantumFunctionError: `op` is not an instance of :class:`~.Observable` """ if not isinstance(op, Observable): raise QuantumFunctionError( "{} is not an o...
, Expectation, Tensor from .qnodes import QuantumFunctionError def _remove_if_in_queue(op): r"""Helper function to handle removing ops from the QNode queue""" if op in qml._current_context.queue: qml._current_context.queue.remove(op) def expval(op):
64
64
199
5
59
jwoehr/pennylane
pennylane/measure.py
Python
expval
expval
31
60
31
31
0f0eec8068ad4bba97c4351e2369df1714dba754
bigcode/the-stack
train
4fee30437cb312912604edc5
train
function
def _remove_if_in_queue(op): r"""Helper function to handle removing ops from the QNode queue""" if op in qml._current_context.queue: qml._current_context.queue.remove(op)
def _remove_if_in_queue(op):
r"""Helper function to handle removing ops from the QNode queue""" if op in qml._current_context.queue: qml._current_context.queue.remove(op)
of measurement outcomes from quantum observables - expectation values, variances of expectations, and measurement samples. """ import pennylane as qml from .operation import Observable, Sample, Variance, Expectation, Tensor from .qnodes import QuantumFunctionError def _remove_if_in_queue(op):
64
64
44
8
55
jwoehr/pennylane
pennylane/measure.py
Python
_remove_if_in_queue
_remove_if_in_queue
25
28
25
25
8367b5cf5e966fe25dfb4b52dfec300522c6dafa
bigcode/the-stack
train
f919a524851a12f67013d7a9
train
function
def sample(op): r"""Sample from the supplied observable, with the number of shots determined from the ``dev.shots`` attribute of the corresponding device. Args: op (Observable): a quantum observable object Raises: QuantumFunctionError: `op` is not an instance of :class:`~.Observable` ...
def sample(op):
r"""Sample from the supplied observable, with the number of shots determined from the ``dev.shots`` attribute of the corresponding device. Args: op (Observable): a quantum observable object Raises: QuantumFunctionError: `op` is not an instance of :class:`~.Observable` """ if no...
current_context.queue.remove(op) # set return type to be a variance op.return_type = Variance if qml._current_context is not None: # add observable to QNode observable queue qml._current_context._append_op(op) return op def sample(op):
64
64
215
4
59
jwoehr/pennylane
pennylane/measure.py
Python
sample
sample
95
125
95
95
d7a2ec31f0d017f4224555bae5b925ad32ff2653
bigcode/the-stack
train
188191faea60b19737caa502
train
function
def var(op): r"""Variance of the supplied observable. Args: op (Observable): a quantum observable object Raises: QuantumFunctionError: `op` is not an instance of :class:`~.Observable` """ if not isinstance(op, Observable): raise QuantumFunctionError( "{} is not ...
def var(op):
r"""Variance of the supplied observable. Args: op (Observable): a quantum observable object Raises: QuantumFunctionError: `op` is not an instance of :class:`~.Observable` """ if not isinstance(op, Observable): raise QuantumFunctionError( "{} is not an observable...
_if_in_queue(op) # set return type to be an expectation value op.return_type = Expectation if qml._current_context is not None: # add observable to QNode observable queue qml._current_context._append_op(op) return op def var(op):
64
64
195
4
59
jwoehr/pennylane
pennylane/measure.py
Python
var
var
63
92
63
63
fd675bc5cf6e9cef5bc2869ce985fa0f0f32c64f
bigcode/the-stack
train
00d41a592aa4010d2d30b20a
train
class
class Migration(migrations.Migration): dependencies = [ ('web', '0010_auto_20160203_1406'), ] operations = [ migrations.RenameField( model_name='resource', old_name='event_date', new_name='event_time', ), ]
class Migration(migrations.Migration):
dependencies = [ ('web', '0010_auto_20160203_1406'), ] operations = [ migrations.RenameField( model_name='resource', old_name='event_date', new_name='event_time', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-02-03 14:10 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
52
64
63
7
44
ocwc/oerweekapi
web/migrations/0011_auto_20160203_1410.py
Python
Migration
Migration
8
20
8
9
4e0ace0454612200f64efc8a457d9622b106bcfb
bigcode/the-stack
train
9389e325d0f976e9c6645020
train
class
class DecisionTreeExplainableModel(BaseExplainableModel): available_explanations = [Extension.GLOBAL, Extension.LOCAL] explainer_type = Extension.GLASSBOX """Decision Tree explainable model. :param multiclass: Set to true to generate a multiclass model. :type multiclass: bool :param random_sta...
class DecisionTreeExplainableModel(BaseExplainableModel):
available_explanations = [Extension.GLOBAL, Extension.LOCAL] explainer_type = Extension.GLASSBOX """Decision Tree explainable model. :param multiclass: Set to true to generate a multiclass model. :type multiclass: bool :param random_state: Int to seed the model. :type random_state: int ...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- """Defines an explainable tree model.""" from ...common.constants import ShapValuesOutput, ExplainableModelType, Extension from .explainab...
160
256
1,581
11
148
bethz/interpret-community
python/interpret_community/mimic/models/tree_model.py
Python
DecisionTreeExplainableModel
DecisionTreeExplainableModel
23
184
23
23
55b918cc9e548481fa85f5513512d6ccaec7e562
bigcode/the-stack
train
8b46b46571ca8e4779b8ebaf
train
class
class FallbackPolicy(Policy): """Policy which predicts fallback actions. A fallback can be triggered by a low confidence score on a NLU prediction or by a low confidence score on an action prediction. """ @staticmethod def _standard_featurizer(): return None def __init__(self, ...
class FallbackPolicy(Policy):
"""Policy which predicts fallback actions. A fallback can be triggered by a low confidence score on a NLU prediction or by a low confidence score on an action prediction. """ @staticmethod def _standard_featurizer(): return None def __init__(self, nlu_threshold: f...
import json import logging import os from typing import Any, List, Text from rasa_core import utils from rasa_core.constants import FALLBACK_SCORE from rasa_core.domain import Domain from rasa_core.policies.policy import Policy from rasa_core.trackers import DialogueStateTracker logger = logging.getLogger(__name__) c...
74
256
939
7
67
Beeketing/rasa_core
rasa_core/policies/fallback.py
Python
FallbackPolicy
FallbackPolicy
15
133
15
15
1a717b1aaa2dced3bb8d2ed74350e37b78583133
bigcode/the-stack
train
1ec9025028d0386dea503c24
train
function
@pytest.mark.skip("Test fails on Jenkins - Investigate why") @pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190101S0051.fits"]) def test_add_oiwfs_warns_when_wfs_if_not_in_field(caplog, filename): """ Test that the primitive does not run if the input file does not have a DQ plan....
@pytest.mark.skip("Test fails on Jenkins - Investigate why") @pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190101S0051.fits"]) def test_add_oiwfs_warns_when_wfs_if_not_in_field(caplog, filename):
""" Test that the primitive does not run if the input file does not have a DQ plan. Parameters ---------- caplog : fixture filename : str """ caplog.set_level(logging.DEBUG) file_path = download_from_archive(filename) ad = astrodata.open(file_path) p = GMOSImage([ad]) ...
assert n == ext_num @pytest.mark.skip("Test fails on Jenkins - Investigate why") @pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190101S0051.fits"]) def test_add_oiwfs_warns_when_wfs_if_not_in_field(caplog, filename):
64
64
216
58
5
DBerke/DRAGONS
geminidr/gmos/tests/image/test_add_oiwfs_to_dq.py
Python
test_add_oiwfs_warns_when_wfs_if_not_in_field
test_add_oiwfs_warns_when_wfs_if_not_in_field
102
129
102
105
03597fa93ac06f60ad939b67291badde8f32b690
bigcode/the-stack
train
0d073a879540e005691410d1
train
function
def plot(ad): """ Displays the tiled arrays with the DQ mask for analysing the data. Parameters ---------- ad : multi-extension data """ from astropy.visualization import ImageNormalize, ZScaleInterval from copy import deepcopy import numpy as np import matplotlib.pyplot as plt ...
def plot(ad):
""" Displays the tiled arrays with the DQ mask for analysing the data. Parameters ---------- ad : multi-extension data """ from astropy.visualization import ImageNormalize, ZScaleInterval from copy import deepcopy import numpy as np import matplotlib.pyplot as plt p = GMOSI...
p.addOIWFSToDQ() # plot(p.streams['main'][0]) print(caplog.records) assert any("No good rows in" in r.message for r in caplog.records) assert any("Cannot distinguish probe region from sky for" in r.message for r in caplog.records) # -- Helper functions ----------------------------...
78
78
263
4
74
DBerke/DRAGONS
geminidr/gmos/tests/image/test_add_oiwfs_to_dq.py
Python
plot
plot
133
166
133
133
3bb67b05490d8d4adf64a8b8934d82cd3458ac98
bigcode/the-stack
train
721a672e048c81bb555a49f5
train
function
@pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190101S0051.fits"]) def test_warn_if_dq_does_not_exist(caplog, filename): """ Test that the primitive does not run if the input file does not have a DQ plan. Parameters ---------- caplog : fixture filename : str ...
@pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190101S0051.fits"]) def test_warn_if_dq_does_not_exist(caplog, filename):
""" Test that the primitive does not run if the input file does not have a DQ plan. Parameters ---------- caplog : fixture filename : str """ caplog.set_level(logging.DEBUG) file_path = download_from_archive(filename) ad = astrodata.open(file_path) p = GMOSImage([ad]) ...
0 assert any("OIWFS not used for image" in r.message for r in caplog.records) @pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190101S0051.fits"]) def test_warn_if_dq_does_not_exist(caplog, filename):
64
64
156
39
25
DBerke/DRAGONS
geminidr/gmos/tests/image/test_add_oiwfs_to_dq.py
Python
test_warn_if_dq_does_not_exist
test_warn_if_dq_does_not_exist
39
59
39
41
b6b24d4fd1e6a248df9587c16afe50bcc26ede3f
bigcode/the-stack
train
38d1a2664dfe21562e9e3f4b
train
function
@pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190102S0162.fits"]) def test_oiwfs_not_used_in_observation(caplog, filename): """ Test that nothing happens when the input file does not use the OIWFS. Parameters ---------- caplog : fixture filename : str """ ca...
@pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190102S0162.fits"]) def test_oiwfs_not_used_in_observation(caplog, filename):
""" Test that nothing happens when the input file does not use the OIWFS. Parameters ---------- caplog : fixture filename : str """ caplog.set_level(logging.DEBUG) file_path = download_from_archive(filename) ad = astrodata.open(file_path) p = GMOSImage([ad]) p.addOIWFST...
from geminidr.gmos.primitives_gmos_image import GMOSImage from gempy.utils import logutils @pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename", ["N20190102S0162.fits"]) def test_oiwfs_not_used_in_observation(caplog, filename):
64
64
160
40
23
DBerke/DRAGONS
geminidr/gmos/tests/image/test_add_oiwfs_to_dq.py
Python
test_oiwfs_not_used_in_observation
test_oiwfs_not_used_in_observation
16
36
16
18
f25bfe21b4bbaa0312c6aed0a9020e832f5f0df2
bigcode/the-stack
train
bb67c2913c055f5029e49ccc
train
function
@pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename, x0, y0, ext_num", [("S20190105S0168.fits", 130, 483, 9)]) def test_add_oiwfs_runs_normally(caplog, ext_num, filename, x0, y0): """ Test that the primitive does not run if the input file does not have a DQ plan. ...
@pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename, x0, y0, ext_num", [("S20190105S0168.fits", 130, 483, 9)]) def test_add_oiwfs_runs_normally(caplog, ext_num, filename, x0, y0):
""" Test that the primitive does not run if the input file does not have a DQ plan. Parameters ---------- caplog : fixture filename : str """ caplog.set_level(logging.DEBUG) file_path = download_from_archive(filename) ad = astrodata.open(file_path) p = GMOSImage([ad]) ...
.records) > 0 assert any("No DQ plane for" in r.message for r in caplog.records) @pytest.mark.dragons_remote_data @pytest.mark.parametrize("filename, x0, y0, ext_num", [("S20190105S0168.fits", 130, 483, 9)]) def test_add_oiwfs_runs_normally(caplog, ext_num, filename, x0, y0):
94
94
315
68
26
DBerke/DRAGONS
geminidr/gmos/tests/image/test_add_oiwfs_to_dq.py
Python
test_add_oiwfs_runs_normally
test_add_oiwfs_runs_normally
62
99
62
65
9af508253063d237f158fddf168506dd5e8f20f1
bigcode/the-stack
train
0d2d68870ff90f35af20dae7
train
class
class DirectionsTest(_test.TestCase): def setUp(self): self.key = 'AIzaasdf' self.client = googlemaps.Client(self.key) @responses.activate def test_simple_directions(self): responses.add(responses.GET, 'https://maps.googleapis.com/maps/api/directions/json', ...
class DirectionsTest(_test.TestCase):
def setUp(self): self.key = 'AIzaasdf' self.client = googlemaps.Client(self.key) @responses.activate def test_simple_directions(self): responses.add(responses.GET, 'https://maps.googleapis.com/maps/api/directions/json', body='{"status":"OK...
# # Copyright 2014 Google Inc. All rights reserved. # # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
182
256
2,215
8
173
davidrobles/google-maps-services-python
googlemaps/test/test_directions.py
Python
DirectionsTest
DirectionsTest
30
277
30
31
800ebbbf5fdd1ef2253abafee685669f8c82273d
bigcode/the-stack
train
e31b2bc1062dd0ba87201984
train
function
def now(): """Return a timezone-aware datetime.datetime object in rfc3339.UTC_TZ timezone, representing the current moment (time.time()). Useful as a replacement for the (timezone-unaware) datetime.datetime.now() method.""" return utcfromtimestamp(time.time())
def now():
"""Return a timezone-aware datetime.datetime object in rfc3339.UTC_TZ timezone, representing the current moment (time.time()). Useful as a replacement for the (timezone-unaware) datetime.datetime.now() method.""" return utcfromtimestamp(time.time())
frac_sec, wholetz, tzsign, tzhour, tzmin) return datetime.datetime( int(y), int(m), int(d), hour, min, sec, microsec, tz) else: raise ValueError('Invalid RFC 3339 datetime string', s) def now():
64
64
60
3
61
tonyg/python-rfc3339
rfc3339.py
Python
now
now
393
398
393
393
46f8a3bab004bc61251e25d6f3621eb8397d8d18
bigcode/the-stack
train
f267f193afcc446c74a0ddeb
train
function
def timestamptostr(ts): """Return a RFC3339 date-time string corresponding to the given Unix-epoch timestamp.""" return datetimetostr(utcfromtimestamp(ts))
def timestamptostr(ts):
"""Return a RFC3339 date-time string corresponding to the given Unix-epoch timestamp.""" return datetimetostr(utcfromtimestamp(ts))
' """ if dt.utcoffset() is None: return "%sZ" % dt.isoformat() if dt.utcoffset() == ZERO: return "%sZ" % dt.replace(tzinfo=None).isoformat() return dt.isoformat() def timestamptostr(ts):
64
64
40
7
57
tonyg/python-rfc3339
rfc3339.py
Python
timestamptostr
timestamptostr
456
459
456
456
2ad60a46113cca88594913c9d6d2f79d7d778075
bigcode/the-stack
train
b7fad8d069897d2e4e02d2b3
train
function
def datetimetostr(dt): """ Return a RFC3339 date-time string corresponding to the given datetime object. Special-case both absent timezone and timezone offset zero to use 'Z' instead of '+00:00'. >>> datetimetostr(datetime.datetime(2008, 8, 24, 0, 0, tzinfo=UTC_TZ)) '2008-08-24T00:00:00Z' >...
def datetimetostr(dt):
""" Return a RFC3339 date-time string corresponding to the given datetime object. Special-case both absent timezone and timezone offset zero to use 'Z' instead of '+00:00'. >>> datetimetostr(datetime.datetime(2008, 8, 24, 0, 0, tzinfo=UTC_TZ)) '2008-08-24T00:00:00Z' >>> datetimetostr(dateti...
11, 250000, tzinfo=tzinfo(-83, '-01:23'))) '00:00:11.250000-01:23' """ if t.utcoffset() is not None: if t.utcoffset() != ZERO: return t.isoformat() else: t = t.replace(tzinfo=None) return "%sZ" % t.isoformat() def datetimetostr(dt):
94
94
315
7
87
tonyg/python-rfc3339
rfc3339.py
Python
datetimetostr
datetimetostr
433
454
433
433
711a805571b0f577fcf4fd48c0d2b9e7365e8c63
bigcode/the-stack
train
f365fa87f0e715c71ede183d
train
function
def parse_time(s): """ Given a string matching the 'full-time' production above, returns a datetime.time instance. Any deviation from the allowed format will produce a raised ValueError. >>> parse_time("00:00:00Z") datetime.time(0, 0, tzinfo=rfc3339.UTC_TZ) >>> parse_time(" 00:00:00Z ") ...
def parse_time(s):
""" Given a string matching the 'full-time' production above, returns a datetime.time instance. Any deviation from the allowed format will produce a raised ValueError. >>> parse_time("00:00:00Z") datetime.time(0, 0, tzinfo=rfc3339.UTC_TZ) >>> parse_time(" 00:00:00Z ") datetime.time(0,...
z == 'Z': tz = UTC_TZ else: tzhour = int(tzhour) tzmin = int(tzmin) offset = tzhour * 60 + tzmin if offset == 0: tz = UTC_TZ else: if tzhour > 24 or tzmin > 60 or offset > 1439: ## see tzinfo docs for the 1439 part raise ValueE...
162
162
542
5
156
tonyg/python-rfc3339
rfc3339.py
Python
parse_time
parse_time
263
304
263
263
63e0f0bc39aed9b6b8509e7e265fb49a8ac82da3
bigcode/the-stack
train
45cc28142fd0eca4d7e321d2
train
function
def make_re(*parts): return re.compile(r'^\s*' + ''.join(parts) + r'\s*$')
def make_re(*parts):
return re.compile(r'^\s*' + ''.join(parts) + r'\s*$')
'(\d\d\d\d)-(\d\d)-(\d\d)' time_re_str = r'(\d\d):(\d\d):(\d\d)(\.(\d+))?([zZ]|(([-+])(\d\d):?(\d\d)))' def make_re(*parts):
64
64
27
6
58
tonyg/python-rfc3339
rfc3339.py
Python
make_re
make_re
156
157
156
156
328fbe221e3b3b0540fa14855a6772e6a822bab9
bigcode/the-stack
train
1707443732051bd22379e7e0
train
function
def utcfromtimestamp(unix_epoch_timestamp): """Interprets its argument as a count of seconds elapsed since the Unix epoch, and returns a datetime.datetime in rfc3339.UTC_TZ timezone.""" (y, m, d, hour, min, sec) = time.gmtime(unix_epoch_timestamp)[:6] return datetime.datetime(y, m, d, hour, min, sec...
def utcfromtimestamp(unix_epoch_timestamp):
"""Interprets its argument as a count of seconds elapsed since the Unix epoch, and returns a datetime.datetime in rfc3339.UTC_TZ timezone.""" (y, m, d, hour, min, sec) = time.gmtime(unix_epoch_timestamp)[:6] return datetime.datetime(y, m, d, hour, min, sec, 0, UTC_TZ)
Return a timezone-aware datetime.datetime object in rfc3339.UTC_TZ timezone, representing the current moment (time.time()). Useful as a replacement for the (timezone-unaware) datetime.datetime.now() method.""" return utcfromtimestamp(time.time()) def utcfromtimestamp(unix_epoch_timestamp):
64
64
95
9
55
tonyg/python-rfc3339
rfc3339.py
Python
utcfromtimestamp
utcfromtimestamp
400
405
400
400
5b7f4601b74048069802843773835bbf7f2bff4f
bigcode/the-stack
train
b7aa062fc7b4d795c3c47804
train
function
def utctotimestamp(dt): """Returns a count of the elapsed seconds between the Unix epoch and the passed-in datetime.datetime object.""" return calendar.timegm(dt.utctimetuple())
def utctotimestamp(dt):
"""Returns a count of the elapsed seconds between the Unix epoch and the passed-in datetime.datetime object.""" return calendar.timegm(dt.utctimetuple())
9.UTC_TZ timezone.""" (y, m, d, hour, min, sec) = time.gmtime(unix_epoch_timestamp)[:6] return datetime.datetime(y, m, d, hour, min, sec, 0, UTC_TZ) def utctotimestamp(dt):
64
64
41
7
57
tonyg/python-rfc3339
rfc3339.py
Python
utctotimestamp
utctotimestamp
407
410
407
407
dc56e4b3bb0b2c495d5e71808420a88373ca1499
bigcode/the-stack
train
06ca67610f1896eea6a57ccd
train
class
class tzinfo(datetime.tzinfo): """ Implementation of a fixed-offset tzinfo. """ def __init__(self, minutesEast = 0, name = 'Z'): """ minutesEast -> number of minutes east of UTC that this tzinfo represents. name -> symbolic (but uninterpreted) name of this tzinfo. """ ...
class tzinfo(datetime.tzinfo):
""" Implementation of a fixed-offset tzinfo. """ def __init__(self, minutesEast = 0, name = 'Z'): """ minutesEast -> number of minutes east of UTC that this tzinfo represents. name -> symbolic (but uninterpreted) name of this tzinfo. """ self.minutesEast = minutes...
'parse_date', 'parse_datetime', 'parse_time', 'now', 'utcfromtimestamp', 'utctotimestamp', 'datetimetostr', 'timestamptostr', 'strtotimestamp', 'timetostr', ] ZERO = datetime.timedelta(0) class tzinfo(datetime.tzinfo):
75
75
252
8
67
tonyg/python-rfc3339
rfc3339.py
Python
tzinfo
tzinfo
119
149
119
119
932b1302a55085a4ad17894efd210fe64e421163
bigcode/the-stack
train
c1eabca4e2f689296ac1c412
train
function
def strtotimestamp(s): """Return the Unix-epoch timestamp corresponding to the given RFC3339 date-time string.""" return utctotimestamp(parse_datetime(s))
def strtotimestamp(s):
"""Return the Unix-epoch timestamp corresponding to the given RFC3339 date-time string.""" return utctotimestamp(parse_datetime(s))
" % dt.replace(tzinfo=None).isoformat() return dt.isoformat() def timestamptostr(ts): """Return a RFC3339 date-time string corresponding to the given Unix-epoch timestamp.""" return datetimetostr(utcfromtimestamp(ts)) def strtotimestamp(s):
64
64
37
6
58
tonyg/python-rfc3339
rfc3339.py
Python
strtotimestamp
strtotimestamp
461
464
461
461
eb13d6e5fc156f4c0dac3cac3e3876f604d7accd
bigcode/the-stack
train
02f1a2b3b426be93ac197235
train
function
def timetostr(t): """ Return a RFC3339 time string corresponding to the given time object. >>> timetostr(datetime.time(0, 0, tzinfo=UTC_TZ)) '00:00:00Z' >>> timetostr(datetime.time(0, 0, tzinfo=tzinfo(60, '+01:00'))) '00:00:00+01:00' >>> timetostr(datetime.time(0, 0, 11, 250000, tzinfo=tzin...
def timetostr(t):
""" Return a RFC3339 time string corresponding to the given time object. >>> timetostr(datetime.time(0, 0, tzinfo=UTC_TZ)) '00:00:00Z' >>> timetostr(datetime.time(0, 0, tzinfo=tzinfo(60, '+01:00'))) '00:00:00+01:00' >>> timetostr(datetime.time(0, 0, 11, 250000, tzinfo=tzinfo(-83, '-01:23'))...
m, d, hour, min, sec, 0, UTC_TZ) def utctotimestamp(dt): """Returns a count of the elapsed seconds between the Unix epoch and the passed-in datetime.datetime object.""" return calendar.timegm(dt.utctimetuple()) def timetostr(t):
64
64
191
6
58
tonyg/python-rfc3339
rfc3339.py
Python
timetostr
timetostr
413
430
413
413
9c5a0ff171d384a450bacda0dbe2977c84e8a5cf
bigcode/the-stack
train
99faa623352ec4ffad3cd1c2
train
function
def _parse_time_components(s, hour, min, sec, frac_sec, wholetz, tzsign, tzhour, tzmin): if frac_sec: frac_sec = float('0.' + frac_sec) else: frac_sec = 0 microsec = int((frac_sec * 1000000) + 0.5) if wholetz == 'z' or wholetz == 'Z': tz = UTC_TZ else: tzhour = int(t...
def _parse_time_components(s, hour, min, sec, frac_sec, wholetz, tzsign, tzhour, tzmin):
if frac_sec: frac_sec = float('0.' + frac_sec) else: frac_sec = 0 microsec = int((frac_sec * 1000000) + 0.5) if wholetz == 'z' or wholetz == 'Z': tz = UTC_TZ else: tzhour = int(tzhour) tzmin = int(tzmin) offset = tzhour * 60 + tzmin if offset ...
) tzhour = offset / 60 tzmin = offset % 60 return '%s%02d:%02d' % (tzsign, tzhour, tzmin) def _parse_time_components(s, hour, min, sec, frac_sec, wholetz, tzsign, tzhour, tzmin):
73
73
246
30
43
tonyg/python-rfc3339
rfc3339.py
Python
_parse_time_components
_parse_time_components
237
260
237
237
cdfc00df2061f464f7b0585222d9ec1c5e8308b3
bigcode/the-stack
train
faf1cab841f85af52d331f4f
train
function
def parse_date(s): """ Given a string matching the 'full-date' production above, returns a datetime.date instance. Any deviation from the allowed format will produce a raised ValueError. >>> parse_date("2008-08-24") datetime.date(2008, 8, 24) >>> parse_date(" 2008-08-24 ") datet...
def parse_date(s):
""" Given a string matching the 'full-date' production above, returns a datetime.date instance. Any deviation from the allowed format will produce a raised ValueError. >>> parse_date("2008-08-24") datetime.date(2008, 8, 24) >>> parse_date(" 2008-08-24 ") datetime.date(2008, 8, 2...
repr(self.name)) UTC_TZ = tzinfo(0, 'Z') date_re_str = r'(\d\d\d\d)-(\d\d)-(\d\d)' time_re_str = r'(\d\d):(\d\d):(\d\d)(\.(\d+))?([zZ]|(([-+])(\d\d):?(\d\d)))' def make_re(*parts): return re.compile(r'^\s*' + ''.join(parts) + r'\s*$') date_re = make_re(date_re_str) datetime_re = make_re(date_re_str, r'[ tT]', ...
147
147
493
5
142
tonyg/python-rfc3339
rfc3339.py
Python
parse_date
parse_date
163
205
163
163
0d3aae4725323966b338311add8554b9aa8f6674
bigcode/the-stack
train
6ee706b1bb5c8d5e5ca35ff1
train
function
def parse_datetime(s): """ Given a string matching the 'date-time' production above, returns a datetime.datetime instance. Any deviation from the allowed format will produce a raised ValueError. >>> parse_datetime("2008-08-24T00:00:00Z") datetime.datetime(2008, 8, 24, 0, 0, tzinfo=rfc3339.UTC_T...
def parse_datetime(s):
""" Given a string matching the 'date-time' production above, returns a datetime.datetime instance. Any deviation from the allowed format will produce a raised ValueError. >>> parse_datetime("2008-08-24T00:00:00Z") datetime.datetime(2008, 8, 24, 0, 0, tzinfo=rfc3339.UTC_TZ) >>> parse_dateti...
tzinfo=rfc3339.tzinfo(-60,'-01:00')) >>> parse_time("00:00:00-01:23") datetime.time(0, 0, tzinfo=rfc3339.tzinfo(-83,'-01:23')) >>> parse_time("24:00:00Z") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "rfc3339.py", line 206, in parse_datetime tz) Va...
256
256
1,464
5
251
tonyg/python-rfc3339
rfc3339.py
Python
parse_datetime
parse_datetime
307
391
307
307
20fd6b2db68f000007a72cd526a56a0a2f83150a
bigcode/the-stack
train
6248ccda8deff7c63b834197
train
function
def _offset_to_tzname(offset): """ Converts an offset in minutes to an RFC 3339 "time-offset" string. >>> _offset_to_tzname(0) '+00:00' >>> _offset_to_tzname(-1) '-00:01' >>> _offset_to_tzname(-60) '-01:00' >>> _offset_to_tzname(-779) '-12:59' >>> _offset_to_tzname(1) '+...
def _offset_to_tzname(offset):
""" Converts an offset in minutes to an RFC 3339 "time-offset" string. >>> _offset_to_tzname(0) '+00:00' >>> _offset_to_tzname(-1) '-00:01' >>> _offset_to_tzname(-60) '-01:00' >>> _offset_to_tzname(-779) '-12:59' >>> _offset_to_tzname(1) '+00:01' >>> _offset_to_tznam...
' """ m = date_re.match(s) if m: (y, m, d) = m.groups() return datetime.date(int(y), int(m), int(d)) else: raise ValueError('Invalid RFC 3339 date string', s) def _offset_to_tzname(offset):
67
67
226
9
58
tonyg/python-rfc3339
rfc3339.py
Python
_offset_to_tzname
_offset_to_tzname
207
234
207
207
cfa24335e4a211d7d8faa01021a528239d32a660
bigcode/the-stack
train
6f87da59df18d0ce6e6e350e
train
class
class ProbMeanBandit(MeanBandit): def __init__(self, mgd_arguments, num_data_features, k, exploration=True): self.exploration = exploration MeanBandit.__init__(self, mgd_arguments, num_data_features, k) def multileave(self, rankings, already_inverted=False): if not already_inverted: ...
class ProbMeanBandit(MeanBandit):
def __init__(self, mgd_arguments, num_data_features, k, exploration=True): self.exploration = exploration MeanBandit.__init__(self, mgd_arguments, num_data_features, k) def multileave(self, rankings, already_inverted=False): if not already_inverted: self.inverted = invert_ra...
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import multileaving.SampleBasedProbabilisticMultileave as pm from utils.rankings import invert_rankings import numpy as np from meanbandit import MeanBandit class ProbMeanBandit(MeanBandit):
68
112
374
10
57
Morgolt/BalancingSpeedQualityOLTR
algorithms/probmeanbandit.py
Python
ProbMeanBandit
ProbMeanBandit
11
49
11
12
a3e31a44ea4132a41a808e6e9d0f917ed8194795
bigcode/the-stack
train
3140cc64d550778c4b481329
train
class
class DocumentGeneratorTest(unittest.TestCase): def setUp(self) -> None: self.json_env = { "id": "b052da30-a4fe-41be-9d36-c7eccd5fa7ef", "name": "Sample-Env", "values": [ { "key": "HOST", "value": "https://cpd-servi...
class DocumentGeneratorTest(unittest.TestCase):
def setUp(self) -> None: self.json_env = { "id": "b052da30-a4fe-41be-9d36-c7eccd5fa7ef", "name": "Sample-Env", "values": [ { "key": "HOST", "value": "https://cpd-service.dev.apps.scholastic.tech", ...
import unittest from constants import RAW, URL_ENCODED from document_generator import DocumentGenerator from models import APIModel, APIBodyModel class DocumentGeneratorTest(unittest.TestCase):
38
256
3,066
8
29
syn2083/postman-doc-gen
tests/test_document_generator.py
Python
DocumentGeneratorTest
DocumentGeneratorTest
8
366
8
9
e58bc59d2b7a54fb109ec643efc56751867a4ee5
bigcode/the-stack
train
15689e8ea88e7ed6ed6ea21f
train
function
def make_style(): # need to keep bindings for s1 and s2 around, else the get eaten by GC global s1, s2 s1 = Tkinter.PhotoImage("search1", data=data, format="gif -index 0") s2 = Tkinter.PhotoImage("search2", data=data, format="gif -index 1") style = ttk.Style() style.element_cre...
def make_style(): # need to keep bindings for s1 and s2 around, else the get eaten by GC
global s1, s2 s1 = Tkinter.PhotoImage("search1", data=data, format="gif -index 0") s2 = Tkinter.PhotoImage("search2", data=data, format="gif -index 1") style = ttk.Style() style.element_create("Search.field", "image", "search1", ("focus", "search2"), border=[22, 7, 14], stic...
TQZBRt9BBJkCGFFVhMwTNBlnBCSCGEIJQQIAklZMXWRBAR RRRWENHwRQEBADs=""" def make_style(): # need to keep bindings for s1 and s2 around, else the get eaten by GC
64
64
193
25
38
habi/nvpy
nvpy/search_entry.py
Python
make_style
make_style
56
73
56
57
416df3fdbe1e0b352dc77b4044d5a8c21167f39b
bigcode/the-stack
train
f1b71c76755c5a61559a8ce3
train
function
def test_list_(): assert list_("") == [''] assert list_("a b c dfg") == ['a', 'b', 'c', 'dfg', ''] assert list_("a 'b c' dfg") == ['a', "'b c'", 'dfg', ''] assert list_('a "b c" dfg') == ['a', '"b c"', 'dfg', ''] assert list_(' a "b c" dfg' + " 'h i j' ") == ['a', '"b c"', 'dfg', "'h i j'", '']
def test_list_():
assert list_("") == [''] assert list_("a b c dfg") == ['a', 'b', 'c', 'dfg', ''] assert list_("a 'b c' dfg") == ['a', "'b c'", 'dfg', ''] assert list_('a "b c" dfg') == ['a', '"b c"', 'dfg', ''] assert list_(' a "b c" dfg' + " 'h i j' ") == ['a', '"b c"', 'dfg', "'h i j'", '']
assert bool_((True,)) is False assert bool_({'a': True}) is False assert bool_({}) is False assert bool_(set()) is False assert bool_({True}) is False assert bool_(None) is False def test_list_():
64
64
133
5
58
anterokangas/ManuscriptManagerOld
tests/test_castings.py
Python
test_list_
test_list_
44
49
44
44
e71c14177b1e5aaa0c73b3a273e020f51fbe94a1
bigcode/the-stack
train
fb1754258528ff2efb0bc5a8
train
function
def test_bool_(): assert bool_(False) is False assert bool_(True) is True assert bool_("False") is False assert bool_("FALSE") is False assert bool_("FaLsE") is False assert bool_("false") is False assert bool_("F") is False assert bool_("f") is False assert bool_("") is False ...
def test_bool_():
assert bool_(False) is False assert bool_(True) is True assert bool_("False") is False assert bool_("FALSE") is False assert bool_("FaLsE") is False assert bool_("false") is False assert bool_("F") is False assert bool_("f") is False assert bool_("") is False assert bool_(" ") ...
from manuscript.tools.castings import bool_ from manuscript.tools.castings import list_ from manuscript.tools.castings import as_is def test_bool_():
30
88
295
5
24
anterokangas/ManuscriptManagerOld
tests/test_castings.py
Python
test_bool_
test_bool_
6
41
6
6
e40684ab52250e3a670be4ce28a596edf2fe7a45
bigcode/the-stack
train
f5f17ac064ef7c100f3c0cf4
train
function
def test_as_is(): assert as_is(None) is None assert as_is("Xyzzy") == "Xyzzy"
def test_as_is():
assert as_is(None) is None assert as_is("Xyzzy") == "Xyzzy"
" dfg') == ['a', '"b c"', 'dfg', ''] assert list_(' a "b c" dfg' + " 'h i j' ") == ['a', '"b c"', 'dfg', "'h i j'", ''] def test_as_is():
64
64
29
5
59
anterokangas/ManuscriptManagerOld
tests/test_castings.py
Python
test_as_is
test_as_is
52
54
52
52
0cc7e74911b701efa5707f5d1a6d11d32d09b96b
bigcode/the-stack
train
5f7c2546cb96cba6bda437df
train
class
class Paperwork(object): """ Allows users to easily create and modify the metadata from the feature class. The data will be returned as a dictionary object for easy of use. This means users can modify values and push them back into the metadata by referencing the key names. To use, just pass ...
class Paperwork(object):
""" Allows users to easily create and modify the metadata from the feature class. The data will be returned as a dictionary object for easy of use. This means users can modify values and push them back into the metadata by referencing the key names. To use, just pass in the path of a feature ...
it loves to parse, change and file metadata back and forth between dictionaries and xml. The results is an easy to use tool where users can script metadata changes without having to parse the XML in XML format. Requires : Python 2.7.x, Python 3.4 ArcGIS 10.3.1/ArcGIS 10.4 Copyright 2015 Esri Licensed un...
256
256
3,518
5
250
ArcGIS/hermes
src/hermes/paperwork.py
Python
Paperwork
Paperwork
34
488
34
34
48942b5d9dbc2ead53493e9932d060dd385a0dac
bigcode/the-stack
train
fb46b42818dee1799f0f744b
train
class
class Boost(Package): """Boost provides free peer-reviewed portable C++ source libraries, emphasizing libraries that work well with the C++ Standard Library. Boost libraries are intended to be widely useful, and usable across a broad spectrum of applications. The Boost license en...
class Boost(Package):
"""Boost provides free peer-reviewed portable C++ source libraries, emphasizing libraries that work well with the C++ Standard Library. Boost libraries are intended to be widely useful, and usable across a broad spectrum of applications. The Boost license encourages both commerci...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import sys import os class Boost(Package):
65
256
7,652
5
59
MiddelkoopT/spack
var/spack/repos/builtin/packages/boost/package.py
Python
Boost
Boost
11
559
11
11
ac0c6c3d541199007956bae16b5437db42bb234e
bigcode/the-stack
train
d67bfaf9eab6126b54362a2f
train
function
def C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after(): """ Summary: Verify Default material library works across different levels, this is the second stage to the test. The reload was required for the editor to pick up changes in default material library in the default.physxconfigurat...
def C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after():
""" Summary: Verify Default material library works across different levels, this is the second stage to the test. The reload was required for the editor to pick up changes in default material library in the default.physxconfiguration file. After the tests are run this script will load the data f...
") terrain_found_3 = ("Test 3: Terrrain Entity found", "Test 3: Terrain Entity was not found") trigger_found_3 = ("Test 3: trigger found", "Test 3: trigger not found") sphere_initial_position_3 = ("Test 3: Sphere initial position valid", "Test 3: Sphere initial po...
256
256
2,394
14
241
fromasmtodisasm/o3de
AutomatedTesting/Gem/PythonTests/physics/material/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after.py
Python
C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after
C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after
40
278
40
40
cbf015415f51c53a5dbb0ca6b86c26ba471d64a3
bigcode/the-stack
train