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
8c3f7826225690fbe7a7366a
train
function
def get_gpu_or_cpu(): """ get device (CPU or GPU) """ device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_gpu = torch.cuda.device_count() print("%s (%d GPUs)" % (device, n_gpu)) return device
def get_gpu_or_cpu():
""" get device (CPU or GPU) """ device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_gpu = torch.cuda.device_count() print("%s (%d GPUs)" % (device, n_gpu)) return device
""" Utils Functions """ import os import random import logging import numpy as np import torch def get_gpu_or_cpu():
28
64
64
6
21
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
get_gpu_or_cpu
get_gpu_or_cpu
12
19
12
12
aa1f37d7e23fc339d748e9e0589f150ecda50aa5
bigcode/the-stack
train
4cfbe26cddc572f10ac5257c
train
function
def tensorboard_logger(name, log_path): """ logger for tensorboard """ logger = logging.getLogger(name) fomatter = logging.Formatter( '[ %(levelname)s|%(filename)s:%(lineno)s] %(asctime)s > %(message)s') if not os.path.isfile(log_path): f = open(log_path, "w+") fileHand...
def tensorboard_logger(name, log_path):
""" logger for tensorboard """ logger = logging.getLogger(name) fomatter = logging.Formatter( '[ %(levelname)s|%(filename)s:%(lineno)s] %(asctime)s > %(message)s') if not os.path.isfile(log_path): f = open(log_path, "w+") fileHandler = logging.FileHandler(log_path) ...
break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() def get_random_word(vocab_words): i = random.randint(0, len(vocab_words)-1) return vocab_words[i] def tensorboard_logger(name, log_path):
64
64
117
9
55
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
tensorboard_logger
tensorboard_logger
77
92
77
77
993ee87a35eb5756c340bd288a6d031b6f81c589
bigcode/the-stack
train
8bd9d5423664490e43d9b6ec
train
function
def split_last(x, shape): """ split the last dimension to given shape """ shape = list(shape) assert shape.count(-1) <= 1 if -1 in shape: shape[shape.index(-1)] = int(x.size(-1) / -np.prod(shape)) return x.view(*x.size()[:-1], *shape)
def split_last(x, shape):
""" split the last dimension to given shape """ shape = list(shape) assert shape.count(-1) <= 1 if -1 in shape: shape[shape.index(-1)] = int(x.size(-1) / -np.prod(shape)) return x.view(*x.size()[:-1], *shape)
("%s (%d GPUs)" % (device, n_gpu)) return device def set_random_seed(seed): """ set random seeds """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def split_last(x, shape):
64
64
79
7
57
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
split_last
split_last
32
40
32
32
f32b61a1a23fc411f122816924ee4a815dfc10a4
bigcode/the-stack
train
b17763d46fdcf55fd557a4ec
train
function
def find_sublist(haystack, needle): h = len(haystack) n = len(needle) skip = {needle[i]: n - i - 1 for i in range(n - 1)} i = n - 1 while i < h: for j in range(n): if haystack[i - j] != needle[-j - 1]: i += skip.get(haystack[i], n) break el...
def find_sublist(haystack, needle):
h = len(haystack) n = len(needle) skip = {needle[i]: n - i - 1 for i in range(n - 1)} i = n - 1 while i < h: for j in range(n): if haystack[i - j] != needle[-j - 1]: i += skip.get(haystack[i], n) break else: return i - n + 1 ...
merge_last(x, n_dims): """ merge the last n_dims to a dimension """ s = x.size() assert n_dims > 1 and n_dims < len(s) return x.view(*s[:-n_dims], -1) def find_sublist(haystack, needle):
64
64
116
10
54
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
find_sublist
find_sublist
50
62
50
50
624bc8c8c857baa0f9f84cad1599d05c2aa079f7
bigcode/the-stack
train
560beb9e46acb852748f1c1a
train
function
def set_random_seed(seed): """ set random seeds """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def set_random_seed(seed):
""" set random seeds """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
""" get device (CPU or GPU) """ device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_gpu = torch.cuda.device_count() print("%s (%d GPUs)" % (device, n_gpu)) return device def set_random_seed(seed):
64
64
40
6
57
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
set_random_seed
set_random_seed
22
29
22
22
e94f6c80a8413d55697f67516448eb5d63757639
bigcode/the-stack
train
07d4b409da57a9a64f5bed6d
train
function
def get_random_word(vocab_words): i = random.randint(0, len(vocab_words)-1) return vocab_words[i]
def get_random_word(vocab_words):
i = random.randint(0, len(vocab_words)-1) return vocab_words[i]
_pair(tokens_a, tokens_b, max_len): while True: if len(tokens_a) + len(tokens_b) <= max_len: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() def get_random_word(vocab_words):
64
64
29
8
56
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
get_random_word
get_random_word
73
75
73
73
979360a96c6edc14df22128e9f4fb087c433fb90
bigcode/the-stack
train
00b6c9d5607943df8d408f57
train
function
def truncate_tokens_pair(tokens_a, tokens_b, max_len): while True: if len(tokens_a) + len(tokens_b) <= max_len: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop()
def truncate_tokens_pair(tokens_a, tokens_b, max_len):
while True: if len(tokens_a) + len(tokens_b) <= max_len: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop()
range(n): if haystack[i - j] != needle[-j - 1]: i += skip.get(haystack[i], n) break else: return i - n + 1 return -1 def truncate_tokens_pair(tokens_a, tokens_b, max_len):
64
64
59
13
50
riteshkumarumassedu/BERT-with-SOP
utils.py
Python
truncate_tokens_pair
truncate_tokens_pair
64
71
64
64
bbfd9e2f04c08fafea9a5e49520486f36df6b658
bigcode/the-stack
train
c9c4fbf193d00ddd9545b7e3
train
class
class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: root = TrieNode() def add(word: List[str]): cur = root for ch in word: idx = ord(ch) - ord("a") if idx not in cur.child: cur....
class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: root = TrieNode() def add(word: List[str]): cur = root for ch in word: idx = ord(ch) - ord("a") if idx not in cur.child: cur.child[idx] = Tri...
])-ord('a'))) subset = mask while subset: s = subset | (1 << (ord(puzzle[0])-ord('a'))) if s in frequency: total += frequency[s] subset = (subset-1) & mask if (1 << (ord(puzzle[0]))-ord('a')) in frequency: ...
134
134
447
3
131
HPluseven/playground
leetcode/others/1178r.py
Python
Solution
Solution
70
117
70
70
b9950ebeb910751ceae91f45dc64480602c15053
bigcode/the-stack
train
5857c78bae142fbc34b0e953
train
class
class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: ans = [0] * len(puzzles) words_cache = [] for word in words: word_set = set(word) if len(word_set) <= 7: words_cache.append(word_set) for idx, p...
class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: ans = [0] * len(puzzles) words_cache = [] for word in words: word_set = set(word) if len(word_set) <= 7: words_cache.append(word_set) for idx, puzzle in enumera...
# timeout class Solution:
6
64
116
3
2
HPluseven/playground
leetcode/others/1178r.py
Python
Solution
Solution
2
17
2
2
51aac90ea631fdb0e1f195892f3b86abfa486c16
bigcode/the-stack
train
f50a5f077a332d63425a1f48
train
class
class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: frequency = collections.Counter() for word in words: mask = 0 for ch in word: mask |= (1 << (ord(ch) - ord('a'))) if str(bin(mask)).count('1') <= 7: ...
class Solution:
def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: frequency = collections.Counter() for word in words: mask = 0 for ch in word: mask |= (1 << (ord(ch) - ord('a'))) if str(bin(mask)).count('1') <= 7: ...
: List[str], puzzles: List[str]) -> List[int]: ans = [0] * len(puzzles) words_cache = [] for word in words: word_set = set(word) if len(word_set) <= 7: words_cache.append(word_set) for idx, puzzle in enumerate(puzzles): for word in wo...
106
106
356
3
102
HPluseven/playground
leetcode/others/1178r.py
Python
Solution
Solution
20
60
20
20
186460b41990db30313eea764b73b0a27ea068dd
bigcode/the-stack
train
157d748522f7604e65d3e196
train
class
class TrieNode: def __init__(self): self.frequency = 0 self.child = dict()
class TrieNode:
def __init__(self): self.frequency = 0 self.child = dict()
= (subset-1) & mask if (1 << (ord(puzzle[0]))-ord('a')) in frequency: total += frequency[1 << (ord(puzzle[0]))-ord('a')] ans.append(total) return ans # trie class TrieNode:
64
64
24
4
59
HPluseven/playground
leetcode/others/1178r.py
Python
TrieNode
TrieNode
64
67
64
64
81e884984fdb80d89a27af48a715844aa707eaf5
bigcode/the-stack
train
93ba1bcb7ad4c5bf7f8f7133
train
class
class VulnerabilityNodeDialog: def __init__(self,objt,environmentName,dupProperty,overridingEnvironment,builder): self.window = builder.get_object("VulnerabilityNodeDialog") self.decorator = NDImplementationDecorator(builder) self.decorator.updateTextCtrl("vulnerabilityNameCtrl",objt.name()) self.deco...
class VulnerabilityNodeDialog:
def __init__(self,objt,environmentName,dupProperty,overridingEnvironment,builder): self.window = builder.get_object("VulnerabilityNodeDialog") self.decorator = NDImplementationDecorator(builder) self.decorator.updateTextCtrl("vulnerabilityNameCtrl",objt.name()) self.decorator.updateTextCtrl("vulnerabi...
AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import sys import gtk from NDImplementationDecorator import NDImplementationDecorator class VulnerabilityNodeDialog:
64
64
214
6
57
RachelLar/cairis_update
cairis/gui/VulnerabilityNodeDialog.py
Python
VulnerabilityNodeDialog
VulnerabilityNodeDialog
24
42
24
24
5a406900a27ac801417a3a8a15e63868ee0e32ce
bigcode/the-stack
train
9807271da798b076dc82dc85
train
function
def initialise_params(): """Parses all arguments and assigns default values when missing. Convert argument strings to objects and assign them as attributes of the namespace. Returns: An object containing all the parsed arguments for script to use. """ args_parser = argparse.ArgumentPar...
def initialise_params():
"""Parses all arguments and assigns default values when missing. Convert argument strings to objects and assign them as attributes of the namespace. Returns: An object containing all the parsed arguments for script to use. """ args_parser = argparse.ArgumentParser() args_parser.add...
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 or agreed to in writing, software #distributed under the License is distributed on an "AS IS" BASIS, #WITHOUT WARR...
165
165
552
4
160
ruchirjain86/professional-services
examples/cloudml-energy-price-forecasting/trainer/task.py
Python
initialise_params
initialise_params
35
130
35
35
d9092bac0397b4a5dce63188bf51af9fcade3472
bigcode/the-stack
train
6e00d28cbac88dc6532d3a67
train
function
def main(): """Main function to be run when executing job. Orchestrates the script """ parameters = initialise_params() tf.logging.set_verbosity(tf.logging.INFO) model_dir = os.path.join(parameters.job_dir, json.loads( os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', ''))...
def main():
"""Main function to be run when executing job. Orchestrates the script """ parameters = initialise_params() tf.logging.set_verbosity(tf.logging.INFO) model_dir = os.path.join(parameters.job_dir, json.loads( os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', '')) run_co...
.get_train_spec( parameters.training_path, parameters.batch_size, parameters.max_steps) eval_spec = inputs.get_eval_spec( parameters.validation_path, parameters.eval_batch_size) tf.estimator.train_and_evaluate( estimator, train_spec, eval_spec ...
64
64
125
3
61
ruchirjain86/professional-services
examples/cloudml-energy-price-forecasting/trainer/task.py
Python
main
main
159
175
159
159
f6070b9fc8ad7150d404a6f677a9bfba02db069a
bigcode/the-stack
train
bb88056e783c7e57a709b998
train
function
def run_experiment(run_config, parameters): """Runs TensorFlow experiment. Creates the model, trains it, and evaluates it. Args: run_config: Configuration for experiment. parameters: Parameters passed to the job. """ estimator = model.create_regressor( config=run_config, pa...
def run_experiment(run_config, parameters):
"""Runs TensorFlow experiment. Creates the model, trains it, and evaluates it. Args: run_config: Configuration for experiment. parameters: Parameters passed to the job. """ estimator = model.create_regressor( config=run_config, parameters=parameters) train_spec = inputs...
help='Evaluation batch size.', default=168, type=int ) args_parser.add_argument( '--max_steps', help='Maximum steps for training.', default=5000, type=int ) return args_parser.parse_args() def run_experiment(run_config, parameters):
64
64
134
9
55
ruchirjain86/professional-services
examples/cloudml-energy-price-forecasting/trainer/task.py
Python
run_experiment
run_experiment
133
156
133
133
dda292e6e3afdc73cf642d2ae8d988e1bdd843fe
bigcode/the-stack
train
a5be66b2f45b85474435f5e2
train
class
class TableTestAsync(AzureTestCase, AsyncTableTestCase): @cosmos_decorator_async async def test_create_table(self, tables_cosmos_account_name, tables_primary_cosmos_account_key): # Arrange ts = TableServiceClient(self.account_url(tables_cosmos_account_name, "cosmos"), credential=tables_primary_c...
class TableTestAsync(AzureTestCase, AsyncTableTestCase): @cosmos_decorator_async
async def test_create_table(self, tables_cosmos_account_name, tables_primary_cosmos_account_key): # Arrange ts = TableServiceClient(self.account_url(tables_cosmos_account_name, "cosmos"), credential=tables_primary_cosmos_account_key) table_name = self._get_table_reference() # Act ...
import pytest from devtools_testutils import AzureTestCase from azure.core.credentials import AzureNamedKeyCredential from azure.core.exceptions import ResourceExistsError from azure.data.tables.aio import TableServiceClient from _shared.asynctestcase import AsyncTableTestCase from _shared.testcase import SLEEP_DELA...
112
256
1,467
22
90
rsdoherty/azure-sdk-for-python
sdk/tables/azure-data-tables/tests/test_table_cosmos_async.py
Python
TableTestAsync
TableTestAsync
17
185
17
18
d89b620be4e1818cbad8c7474556d89cd76427ed
bigcode/the-stack
train
14eb89dda6a404a9b16a8142
train
class
class TestTableUnitTest(AsyncTableTestCase): tables_cosmos_account_name = "fake_storage_account" tables_primary_cosmos_account_key = "fakeXMZjnGsZGvd4bVr3Il5SeHA" credential = AzureNamedKeyCredential(name=tables_cosmos_account_name, key=tables_primary_cosmos_account_key) @pytest.mark.asyncio async ...
class TestTableUnitTest(AsyncTableTestCase):
tables_cosmos_account_name = "fake_storage_account" tables_primary_cosmos_account_key = "fakeXMZjnGsZGvd4bVr3Il5SeHA" credential = AzureNamedKeyCredential(name=tables_cosmos_account_name, key=tables_primary_cosmos_account_key) @pytest.mark.asyncio async def test_unicode_create_table_unicode_name(se...
Act deleted = await ts.delete_table(table_name=table.table_name) # Assert assert deleted is None @cosmos_decorator_async async def test_delete_table_with_non_existing_table_fail_not_exist(self, tables_cosmos_account_name, ...
125
125
418
11
114
rsdoherty/azure-sdk-for-python
sdk/tables/azure-data-tables/tests/test_table_cosmos_async.py
Python
TestTableUnitTest
TestTableUnitTest
188
228
188
188
5d02bd036c6d5a26ce1bf301ca1d851c88ebbefa
bigcode/the-stack
train
046200f01b7a5842180d27aa
train
function
def diagonal_res_to_pixel_res(res): """ >>> '%.2f' % round(diagonal_res_to_pixel_res(14.14214), 4) '10.00' """ return math.sqrt((float(res) ** 2) / 2)
def diagonal_res_to_pixel_res(res):
""" >>> '%.2f' % round(diagonal_res_to_pixel_res(14.14214), 4) '10.00' """ return math.sqrt((float(res) ** 2) / 2)
, tmp_image from mapproxy.test.http import mock_httpd from mapproxy.test.system.test_wms import is_111_capa, is_130_capa, ns130 @pytest.fixture(scope="module") def config_file(): return "scalehints.yaml" def diagonal_res_to_pixel_res(res):
64
64
58
8
56
cunha17/mapproxy
mapproxy/test/system/test_scalehints.py
Python
diagonal_res_to_pixel_res
diagonal_res_to_pixel_res
38
43
38
38
13bc8f4d769cafa7420f22a5382311324d0476eb
bigcode/the-stack
train
2f2103b0f01c25d406dab2e8
train
class
class TestWMS(SysTest): def setup(self): self.common_req = WMS111MapRequest( url="/service?", param=dict(service="WMS", version="1.1.1") ) self.common_map_req = WMS111MapRequest( url="/service?", param=dict( service="WMS", ...
class TestWMS(SysTest):
def setup(self): self.common_req = WMS111MapRequest( url="/service?", param=dict(service="WMS", version="1.1.1") ) self.common_map_req = WMS111MapRequest( url="/service?", param=dict( service="WMS", version="1.1.1", ...
.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # ...
256
256
949
7
249
cunha17/mapproxy
mapproxy/test/system/test_scalehints.py
Python
TestWMS
TestWMS
46
140
46
47
b422c0ccafbfbf3801795016bc54ef3e21277b5d
bigcode/the-stack
train
5d73787af03aafb3d1fe8f80
train
function
@pytest.fixture(scope="module") def config_file(): return "scalehints.yaml"
@pytest.fixture(scope="module") def config_file():
return "scalehints.yaml"
import SysTest from mapproxy.test.image import is_png, is_transparent, tmp_image from mapproxy.test.http import mock_httpd from mapproxy.test.system.test_wms import is_111_capa, is_130_capa, ns130 @pytest.fixture(scope="module") def config_file():
64
64
18
10
53
cunha17/mapproxy
mapproxy/test/system/test_scalehints.py
Python
config_file
config_file
33
35
33
34
244779e2a5f0fbd6a47194945759a1b4a268c8bd
bigcode/the-stack
train
fb17ee4a8a7c8f0ed70b077e
train
function
def test_backwards_compatibility(): check_backwards_compatibility(Zstd.codec_id, arrays, codecs)
def test_backwards_compatibility():
check_backwards_compatibility(Zstd.codec_id, arrays, codecs)
def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr(): check_repr("Zstd(level=3)") def test_backwards_compatibility():
63
64
24
8
55
Czaki/numcodecs
numcodecs/tests/test_zstd.py
Python
test_backwards_compatibility
test_backwards_compatibility
59
60
59
59
758375b8bb8cb924c1f79b0cac7a6e963416e174
bigcode/the-stack
train
04f4a5a52c80dadc52944e35
train
function
def test_config(): for codec in codecs: check_config(codec)
def test_config():
for codec in codecs: check_config(codec)
np.random.randint(-2**63, -2**63 + 20, size=1000, dtype='i8').view('m8[m]'), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec) def test_config():
64
64
15
4
60
Czaki/numcodecs
numcodecs/tests/test_zstd.py
Python
test_config
test_config
50
52
50
50
8cf1740f485be02aa51f85c8822aff1eb562a038
bigcode/the-stack
train
bf41843a67add1135149e55d
train
function
def test_repr(): check_repr("Zstd(level=3)")
def test_repr():
check_repr("Zstd(level=3)")
, size=1000, dtype='i8').view('m8[m]'), ] def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr():
64
64
14
4
60
Czaki/numcodecs
numcodecs/tests/test_zstd.py
Python
test_repr
test_repr
55
56
55
55
d922c29ddd0fee855cd3007e9dd4ddc0ca5463cc
bigcode/the-stack
train
987169e042d7e4bad4dcf4b8
train
function
def test_err_encode_object_buffer(): check_err_encode_object_buffer(Zstd())
def test_err_encode_object_buffer():
check_err_encode_object_buffer(Zstd())
(codec) def test_repr(): check_repr("Zstd(level=3)") def test_backwards_compatibility(): check_backwards_compatibility(Zstd.codec_id, arrays, codecs) def test_err_decode_object_buffer(): check_err_decode_object_buffer(Zstd()) def test_err_encode_object_buffer():
64
64
16
7
57
Czaki/numcodecs
numcodecs/tests/test_zstd.py
Python
test_err_encode_object_buffer
test_err_encode_object_buffer
67
68
67
67
8eb1305fadf59a5dd33ce029d7c86fd427b802de
bigcode/the-stack
train
c49f8e4cd5fb4bc0a9896287
train
function
def test_err_decode_object_buffer(): check_err_decode_object_buffer(Zstd())
def test_err_decode_object_buffer():
check_err_decode_object_buffer(Zstd())
, codec) def test_config(): for codec in codecs: check_config(codec) def test_repr(): check_repr("Zstd(level=3)") def test_backwards_compatibility(): check_backwards_compatibility(Zstd.codec_id, arrays, codecs) def test_err_decode_object_buffer():
64
64
16
7
57
Czaki/numcodecs
numcodecs/tests/test_zstd.py
Python
test_err_decode_object_buffer
test_err_decode_object_buffer
63
64
63
63
db1f605c9a9268b8a26a0b631c2a080aa32f7bc6
bigcode/the-stack
train
865e8ec9ecb72716140cbae6
train
function
def test_encode_decode(): for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec)
def test_encode_decode():
for arr, codec in itertools.product(arrays, codecs): check_encode_decode(arr, codec)
2**63 + 20, size=1000, dtype='i8').view('M8[m]'), np.random.randint(-2**63, -2**63 + 20, size=1000, dtype='i8').view('m8[m]'), ] def test_encode_decode():
64
64
26
5
59
Czaki/numcodecs
numcodecs/tests/test_zstd.py
Python
test_encode_decode
test_encode_decode
45
47
45
45
83270fbbb0e5ce52d002860d61e220f13b1e7512
bigcode/the-stack
train
18c7ccd1a501d03e90732b43
train
function
def empirical_cdf( samples: np.ndarray, num_bins: int = 100 ) -> Tuple[np.ndarray, np.ndarray]: """ Calculate the empirical cdf from the given samples. Parameters ---------- samples Tensor of samples of shape (num_samples, batch_shape) Returns ------- Tensor Empirical...
def empirical_cdf( samples: np.ndarray, num_bins: int = 100 ) -> Tuple[np.ndarray, np.ndarray]:
""" Calculate the empirical cdf from the given samples. Parameters ---------- samples Tensor of samples of shape (num_samples, batch_shape) Returns ------- Tensor Empirically calculated cdf values. shape (num_bins, batch_shape) Tensor Bin edges corresponding t...
# express or implied. See the License for the specific language governing # permissions and limitations under the License. from typing import Tuple, List import pytest import torch import numpy as np from pts.distributions import PiecewiseLinear from pts.modules import PiecewiseLinearOutput def empirical_cdf( sa...
86
86
289
28
57
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
Python
empirical_cdf
empirical_cdf
24
59
24
26
208bb95dd3a09e6fefab1fbea2effc8c3b053c2a
bigcode/the-stack
train
2dd5628faa17858be1d6fa56
train
function
@pytest.mark.parametrize( "batch_shape, num_pieces, num_samples", [((3, 4, 5), 10, 100), ((1,), 2, 1), ((10,), 10, 10), ((10, 5), 2, 1)], ) def test_shapes(batch_shape: Tuple, num_pieces: int, num_samples: int): gamma = torch.ones(size=(*batch_shape,)) slopes = torch.ones(size=(*batch_shape, num_pieces)...
@pytest.mark.parametrize( "batch_shape, num_pieces, num_samples", [((3, 4, 5), 10, 100), ((1,), 2, 1), ((10,), 10, 10), ((10, 5), 2, 1)], ) def test_shapes(batch_shape: Tuple, num_pieces: int, num_samples: int):
gamma = torch.ones(size=(*batch_shape,)) slopes = torch.ones(size=(*batch_shape, num_pieces)) # all positive knot_spacings = ( torch.ones(size=(*batch_shape, num_pieces)) / num_pieces ) # positive and sum to 1 target = torch.ones(size=batch_shape) # shape of gamma distr = PiecewiseLi...
num_samples,)).numpy() assert np.isfinite(samples).all() emp_cdf, edges = empirical_cdf(samples) calc_cdf = distr.cdf(torch.Tensor(edges)).numpy() assert np.allclose(calc_cdf[1:, :], emp_cdf, atol=1e-2) @pytest.mark.parametrize( "batch_shape, num_pieces, num_samples", [((3, 4, 5), 10, 100), ((1...
148
148
496
83
65
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
Python
test_shapes
test_shapes
116
162
116
120
3eeb9ccafeb2d3fef65a5891c54a66d27204458f
bigcode/the-stack
train
f13e235733865a4d5ac41f01
train
function
def test_robustness(): distr_out = PiecewiseLinearOutput(num_pieces=10) args_proj = distr_out.get_args_proj(in_features=30) net_out = torch.normal(mean=0.0, size=(1000, 30), std=1e2) gamma, slopes, knot_spacings = args_proj(net_out) distr = distr_out.distribution((gamma, slopes, knot_spacings)) ...
def test_robustness():
distr_out = PiecewiseLinearOutput(num_pieces=10) args_proj = distr_out.get_args_proj(in_features=30) net_out = torch.normal(mean=0.0, size=(1000, 30), std=1e2) gamma, slopes, knot_spacings = args_proj(net_out) distr = distr_out.distribution((gamma, slopes, knot_spacings)) # compute the 1-quant...
0])).numpy().item() == 1.0 expected_crps = np.array([1.0 + 2.0 / 3.0]) assert np.allclose(distr.crps(torch.Tensor([-2.0])).numpy(), expected_crps) assert np.allclose(distr.crps(torch.Tensor([2.0])).numpy(), expected_crps) def test_robustness():
85
85
286
7
78
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
Python
test_robustness
test_robustness
182
209
182
182
f3a5a7a96a24027ed198d86f86af82efeb1012bc
bigcode/the-stack
train
1eb411f3d0aee315155f9219
train
function
def test_simple_symmetric(): gamma = torch.Tensor([-1.0]) slopes = torch.Tensor([[2.0, 2.0]]) knot_spacings = torch.Tensor([[0.5, 0.5]]) distr = PiecewiseLinear(gamma=gamma, slopes=slopes, knot_spacings=knot_spacings) assert distr.cdf(torch.Tensor([-2.0])).numpy().item() == 0.0 assert distr.cd...
def test_simple_symmetric():
gamma = torch.Tensor([-1.0]) slopes = torch.Tensor([[2.0, 2.0]]) knot_spacings = torch.Tensor([[0.5, 0.5]]) distr = PiecewiseLinear(gamma=gamma, slopes=slopes, knot_spacings=knot_spacings) assert distr.cdf(torch.Tensor([-2.0])).numpy().item() == 0.0 assert distr.cdf(torch.Tensor([+2.0])).numpy...
shape when num_samples # is not None is correct samples = distr.sample((num_samples,)) assert samples.shape == (num_samples, *batch_shape) assert distr.quantile_internal(samples, dim=0).shape == (num_samples, *batch_shape,) def test_simple_symmetric():
63
64
186
6
57
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
Python
test_simple_symmetric
test_simple_symmetric
165
179
165
165
65a80482a0d55c33daa43db369fac474ee20f254
bigcode/the-stack
train
46622c32c574ef0c32d391a4
train
function
@pytest.mark.parametrize( "distr, target, expected_target_cdf, expected_target_crps", [ ( PiecewiseLinear( gamma=torch.ones(size=(1,)), slopes=torch.Tensor([2, 3, 1]).reshape(shape=(1, 3)), knot_spacings=torch.Tensor([0.3, 0.4, 0.3]).reshape(sh...
@pytest.mark.parametrize( "distr, target, expected_target_cdf, expected_target_crps", [ ( PiecewiseLinear( gamma=torch.ones(size=(1,)), slopes=torch.Tensor([2, 3, 1]).reshape(shape=(1, 3)), knot_spacings=torch.Tensor([0.3, 0.4, 0.3]).reshape(sh...
target = torch.Tensor(target).reshape(shape=(len(target),)) expected_target_cdf = np.array(expected_target_cdf).reshape( (len(expected_target_cdf),) ) expected_target_crps = np.array(expected_target_crps).reshape( (len(expected_target_crps),) ) assert all(np.isclose(distr.cdf(ta...
@pytest.mark.parametrize( "distr, target, expected_target_cdf, expected_target_crps", [ ( PiecewiseLinear( gamma=torch.ones(size=(1,)), slopes=torch.Tensor([2, 3, 1]).reshape(shape=(1, 3)), knot_spacings=torch.Tensor([0.3, 0.4, 0.3]).reshape(sh...
275
140
469
275
0
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
Python
test_values
test_values
62
113
62
94
fb1f9407b5a382a1e658c1b357287499e4eea58e
bigcode/the-stack
train
6a121d336a32ad610e064444
train
class
class UnsupportedParameterError(Exception): pass
class UnsupportedParameterError(Exception):
pass
}') > -1: self.type = 'close' else: self.type = None class Enum(object): """A group of constants""" def __init__(self, name): self.name = name self.constants = [] self.comment = '' class UnsupportedParameterError(Exception):
63
64
9
6
57
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
UnsupportedParameterError
UnsupportedParameterError
731
732
731
731
bd00c4980c617f9ed4dddf8117ad3869d93a65ae
bigcode/the-stack
train
ec707670a99695ca30d5ed4f
train
class
class Interface(CodeObject): """Information on an interface""" def __init__(self, name, line_number, lines, source_file): """Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines -- Contents of interface as...
class Interface(CodeObject):
"""Information on an interface""" def __init__(self, name, line_number, lines, source_file): """Initialise an interface Arguments: name -- Interface name line_number -- Line number where the interface starts lines -- Contents of interface as a list of lines sour...
startswith('!>'): self.comment_lines.append( self.source_file.source_lines[line_num].strip()[2:].strip()) line_num -= 1 self.comment_lines.reverse() class Constant(CodeObject): """Information on a public constant""" def __init__(self, name, line_number, assignm...
196
196
654
5
190
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
Interface
Interface
374
463
374
374
1bf76c097d32e72d1b2066ab3f4f85e8e03fe3ee
bigcode/the-stack
train
245e028bd69dcce924e3a928
train
function
def _join_lines(source): """Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source)
def _join_lines(source):
"""Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source)
'close' else: self.type = None class Enum(object): """A group of constants""" def __init__(self, name): self.name = name self.constants = [] self.comment = '' class UnsupportedParameterError(Exception): pass def _join_lines(source):
64
64
46
6
57
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
_join_lines
_join_lines
735
738
735
735
708d4fb872525d3bee70c792aaed11dcc52dcb72
bigcode/the-stack
train
640498589ff2db2b8220ddb6
train
class
class DoxygenGrouping(object): """Store a line used for grouping in Doxygen""" def __init__(self, line_number, line): self.line_number = line_number self.line = line.strip() if line.find(r'\see') > -1: self.type = 'see' elif line.find(r'\addtogroup') > -1: ...
class DoxygenGrouping(object):
"""Store a line used for grouping in Doxygen""" def __init__(self, line_number, line): self.line_number = line_number self.line = line.strip() if line.find(r'\see') > -1: self.type = 'see' elif line.find(r'\addtogroup') > -1: self.type = 'group' ...
source where this is defined lines -- Contents of lines where this type is defined """ super(Type, self).__init__(name, line_number) self.lines = lines self.source_file = source_file self.methods = [] self._get_comments() class DoxygenGrouping(object):
64
64
201
6
58
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
DoxygenGrouping
DoxygenGrouping
699
719
699
699
53b8e58e71a6b6f439795f2dab1c1ce1ff998193
bigcode/the-stack
train
1ee67a8b411185405be6acdc
train
class
class IdentifierSet(set): """Set used to store Fortran identifiers, to allow checking for items with case insensitivity""" def add(self, val): set.add(self, val.lower()) def __contains__(self, val): return set.__contains__(self, val.lower())
class IdentifierSet(set):
"""Set used to store Fortran identifiers, to allow checking for items with case insensitivity""" def add(self, val): set.add(self, val.lower()) def __contains__(self, val): return set.__contains__(self, val.lower())
: val = dict.__getitem__(self, key) except KeyError: for ikey in self: if ikey.lower() == key.lower(): val = dict.__getitem__(self, ikey) break else: raise return val class IdentifierSet(set):
64
64
62
5
58
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
IdentifierSet
IdentifierSet
758
766
758
758
da3805641ac58fde5c829cfc65c6fcbee86d526c
bigcode/the-stack
train
656a9e9da070c148cd231b81
train
class
class IdentifierDict(dict): """Dictionary used to store Fortran identifiers, to allow getting items with case insensitivity""" def __getitem__(self, key): try: val = dict.__getitem__(self, key) except KeyError: for ikey in self: if ikey.lower() == key...
class IdentifierDict(dict):
"""Dictionary used to store Fortran identifiers, to allow getting items with case insensitivity""" def __getitem__(self, key): try: val = dict.__getitem__(self, key) except KeyError: for ikey in self: if ikey.lower() == key.lower(): ...
.comment = '' class UnsupportedParameterError(Exception): pass def _join_lines(source): """Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source) class IdentifierDict(dict):
64
64
96
5
59
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
IdentifierDict
IdentifierDict
741
755
741
741
b02a2732043ca7b52e7c7b5e9efb3f26849ce922
bigcode/the-stack
train
49c95f0281eb11bd7a16905b
train
class
class CodeObject(object): """Base class for any line or section of code""" def __init__(self, name, line_number): self.name = name self.line_number = line_number def _get_comments(self): """Sets the comment_lines property This is a list of comment lines above this section ...
class CodeObject(object):
"""Base class for any line or section of code""" def __init__(self, name, line_number): self.name = name self.line_number = line_number def _get_comments(self): """Sets the comment_lines property This is a list of comment lines above this section or line of code ""...
current_enum.constants.append(o) else: ungrouped_constants.append(o) if current_enum is not None: sys.stderr.write("Error: Didn't match a closing group " "for Doxygen groupings\n") return (enums, ungrouped_constants) class C...
64
64
144
5
59
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
CodeObject
CodeObject
325
344
325
325
22a63ff2b4581d2ccf6372c568c3052a2bdec3f7
bigcode/the-stack
train
7e9f2974d85f82cf4b60b52e
train
class
class Constant(CodeObject): """Information on a public constant""" def __init__(self, name, line_number, assignment, comment): """Initialise Constant Extra arguments: assignment -- Value or another variable assigned to this variable comment -- Contents of the doxygen comment de...
class Constant(CodeObject):
"""Information on a public constant""" def __init__(self, name, line_number, assignment, comment): """Initialise Constant Extra arguments: assignment -- Value or another variable assigned to this variable comment -- Contents of the doxygen comment describing ...
= self.line_number - 1 while self.source_file.source_lines[line_num].strip().startswith('!>'): self.comment_lines.append( self.source_file.source_lines[line_num].strip()[2:].strip()) line_num -= 1 self.comment_lines.reverse() class Constant(CodeObject):
64
64
152
5
59
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
Constant
Constant
347
371
347
347
2e07d7d33cc3fa6b745619f96d4d20fe64d69a63
bigcode/the-stack
train
4b54f0e2fe996ed995ed0fcc
train
class
class Type(CodeObject): """Information on a Fortran type""" def __init__(self, name, line_number, lines, source_file): """Initialise type Arguments: name -- Type name line_number -- Line number in source where this is defined lines -- Contents of lines where this type i...
class Type(CodeObject):
"""Information on a Fortran type""" def __init__(self, name, line_number, lines, source_file): """Initialise type Arguments: name -- Type name line_number -- Line number in source where this is defined lines -- Contents of lines where this type is defined """ ...
_type = Parameter.CUSTOM_TYPE self.type_name = type_params else: sys.stderr.write("Error: Unknown type %s for routine %s\n" % (param_type, routine.name)) self.var_type = None self.type_name = param_type class Type(CodeObject):
64
64
111
5
58
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
Type
Type
680
696
680
680
9f49a27a8f8cd5bdc5b559a67c8feb65b56bce45
bigcode/the-stack
train
524aa52eec30fd3565d289db
train
class
class Enum(object): """A group of constants""" def __init__(self, name): self.name = name self.constants = [] self.comment = ''
class Enum(object):
"""A group of constants""" def __init__(self, name): self.name = name self.constants = [] self.comment = ''
'\brief') + len(r'\brief'):].strip() elif line.find(r'@{') > -1: self.type = 'open' elif line.find(r'@}') > -1: self.type = 'close' else: self.type = None class Enum(object):
64
64
36
4
59
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
Enum
Enum
722
728
722
722
d6c72343ddc1a82fa7589d11255d0a1fcd516852
bigcode/the-stack
train
343eb7233e57e834624de17b
train
class
class Subroutine(CodeObject): """Store information for a subroutine""" def __init__(self, name, line_number, lines, source_file): super(Subroutine, self).__init__(name, line_number) self.lines = lines self.source_file = source_file self.parameters = None self.interface =...
class Subroutine(CodeObject):
"""Store information for a subroutine""" def __init__(self, name, line_number, lines, source_file): super(Subroutine, self).__init__(name, line_number) self.lines = lines self.source_file = source_file self.parameters = None self.interface = None self.self_idx = ...
self.name)) return subroutines def _get_array_routines(self, routine_list): """Return a list of the routines that take array parameters if there is an option between passing an array or a scalar. All other routines are also returned. Arguments: routine_list -- Lis...
256
256
1,009
6
249
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
Subroutine
Subroutine
466
579
466
466
83c8997001a9b0d0c2bf68782ec7b4ce84ad05eb
bigcode/the-stack
train
cc20d04328c583b2d6aef389
train
class
class LibrarySource(object): """Holds info on all the library source code""" class SourceFile(object): """Info for an individual source file""" class SectionFinder(object): """Match a section within a source file""" def __init__(self, source_file): self...
class LibrarySource(object):
"""Holds info on all the library source code""" class SourceFile(object): """Info for an individual source file""" class SectionFinder(object): """Match a section within a source file""" def __init__(self, source_file): self.match = None ...
import sys import os import re from operator import attrgetter class LibrarySource(object):
20
256
2,454
5
14
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
LibrarySource
LibrarySource
7
322
7
7
1b87bc2fc6677e8c1b5a8924c0d15e66ccd15aa0
bigcode/the-stack
train
e457c115950a63ba68678853
train
class
class Parameter(object): """Information on a subroutine parameter""" # Parameter types enum: (INTEGER, FLOAT, DOUBLE, CHARACTER, LOGICAL, CUSTOM_TYPE) = range(6) def __init__(self, name, routine, param_type, type_params, extra_stuff, array, comment): """Initiali...
class Parameter(object):
"""Information on a subroutine parameter""" # Parameter types enum: (INTEGER, FLOAT, DOUBLE, CHARACTER, LOGICAL, CUSTOM_TYPE) = range(6) def __init__(self, name, routine, param_type, type_params, extra_stuff, array, comment): """Initialise a parameter A...
if # the parameter type name starts with the routine type name routine_type_name = '_'.join(self.name.split('_')[0:2]) # Object parameter is either first or last, it is last if this # is a Create or CreateStart routine, otherwise it is first if self.parameter...
221
221
739
4
216
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
Python
Parameter
Parameter
582
677
582
582
1429fc4ba510973d2cbfb8bbed944b93b17b8c12
bigcode/the-stack
train
df71c0743a6463b18a04c2f8
train
function
def mock_stream(data): """Mock a stream with data.""" protocol = mock.Mock(_reading_paused=False) stream = StreamReader(protocol) stream.feed_data(data) stream.feed_eof() return stream
def mock_stream(data):
"""Mock a stream with data.""" protocol = mock.Mock(_reading_paused=False) stream = StreamReader(protocol) stream.feed_data(data) stream.feed_eof() return stream
_qs from aiohttp import ClientSession from aiohttp.client_exceptions import ClientError, ClientResponseError from aiohttp.streams import StreamReader from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE from yarl import URL RETYPE = type(re.compile("")) def mock_stream(data):
63
64
47
5
58
boralyl/pytest-homeassistant
pytest_homeassistant/aiohttp_mock.py
Python
mock_stream
mock_stream
18
24
18
18
5a1170d1bceca10e0d79df969c0c6eb47571d5e9
bigcode/the-stack
train
f3111b086af04cd3f88f4454
train
class
class AiohttpClientMocker: """Mock Aiohttp client requests.""" def __init__(self): """Initialize the request mocker.""" self._mocks = [] self._cookies = {} self.mock_calls = [] def request( self, method, url, *, auth=None, sta...
class AiohttpClientMocker:
"""Mock Aiohttp client requests.""" def __init__(self): """Initialize the request mocker.""" self._mocks = [] self._cookies = {} self.mock_calls = [] def request( self, method, url, *, auth=None, status=200, text=None,...
"""Aiohttp test utils.""" import asyncio from contextlib import contextmanager import json as _json import re from unittest import mock from urllib.parse import parse_qs from aiohttp import ClientSession from aiohttp.client_exceptions import ClientError, ClientResponseError from aiohttp.streams import StreamReader fro...
150
211
704
8
141
boralyl/pytest-homeassistant
pytest_homeassistant/aiohttp_mock.py
Python
AiohttpClientMocker
AiohttpClientMocker
27
148
27
27
5d96672083486e73c78207f9494408b06c3238b7
bigcode/the-stack
train
645c1430d95fd81011090b7d
train
function
@contextmanager def mock_aiohttp_client(): """Context manager to mock aiohttp client.""" mocker = AiohttpClientMocker() def create_session(hass, *args): session = mocker.create_session(hass.loop) async def close_session(event): """Close session.""" await session.clo...
@contextmanager def mock_aiohttp_client():
"""Context manager to mock aiohttp client.""" mocker = AiohttpClientMocker() def create_session(hass, *args): session = mocker.create_session(hass.loop) async def close_session(event): """Close session.""" await session.close() hass.bus.async_listen_once(EV...
request_info = mock.Mock(real_url="http://example.com") raise ClientResponseError( request_info=request_info, history=None, code=self.status, headers=self.headers, ) def close(self): """Mock close.""" @conte...
63
64
123
11
52
boralyl/pytest-homeassistant
pytest_homeassistant/aiohttp_mock.py
Python
mock_aiohttp_client
mock_aiohttp_client
273
293
273
274
47bec441df0cc2a4124480f7f429dc707700ed72
bigcode/the-stack
train
d0821bd0fa2c505ed288973f
train
class
class MockLongPollSideEffect: """Imitate a long_poll request. It should be created and used as a side effect for a GET/PUT/etc. request. Once created, actual responses are queued with queue_response If queue is empty, will await until done. """ def __init__(self): """Initialize the que...
class MockLongPollSideEffect:
"""Imitate a long_poll request. It should be created and used as a side effect for a GET/PUT/etc. request. Once created, actual responses are queued with queue_response If queue is empty, will await until done. """ def __init__(self): """Initialize the queue.""" self.semaphore ...
async def close_session(event): """Close session.""" await session.close() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, close_session) return session with mock.patch( "homeassistant.helpers.aiohttp_client.async_create_clientsession", side_effect=c...
76
76
255
7
68
boralyl/pytest-homeassistant
pytest_homeassistant/aiohttp_mock.py
Python
MockLongPollSideEffect
MockLongPollSideEffect
296
329
296
296
19d52d6746ef3876d6d974d8058ff1b0a727fde4
bigcode/the-stack
train
6f8d439c7acb724995138e04
train
class
class AiohttpClientMockResponse: """Mock Aiohttp client response.""" def __init__( self, method, url, status=200, response=None, json=None, text=None, cookies=None, exc=None, headers=None, side_effect=None, ): "...
class AiohttpClientMockResponse:
"""Mock Aiohttp client response.""" def __init__( self, method, url, status=200, response=None, json=None, text=None, cookies=None, exc=None, headers=None, side_effect=None, ): """Initialize a fake response.""" ...
request", self.match_request) return session async def match_request( self, method, url, *, data=None, auth=None, params=None, headers=None, allow_redirects=None, timeout=None, json=None, cookies=None, *...
202
202
675
8
194
boralyl/pytest-homeassistant
pytest_homeassistant/aiohttp_mock.py
Python
AiohttpClientMockResponse
AiohttpClientMockResponse
151
270
151
151
8361f2b1b8f8eb431585472a4c2d519c65b86662
bigcode/the-stack
train
ba48f186b4d2a1ad75797a75
train
class
class Ingressos: def __init__(self, estoque) -> None: self.estoque = estoque self.lock = Lock() # Instanciando Lock def comprar(self, quantidade): # Sempre que qualquer thread entre no método, ele será trancado para # que outras não o acessem self.lock.acquire() # Tr...
class Ingressos:
def __init__(self, estoque) -> None: self.estoque = estoque self.lock = Lock() # Instanciando Lock def comprar(self, quantidade): # Sempre que qualquer thread entre no método, ele será trancado para # que outras não o acessem self.lock.acquire() # Trancando o método ...
from threading import Thread from threading import Lock from time import sleep """ Quando se utiliza threads e manipula dados ao mesmo tempo, um grande problema pode ocorrer devido a falta de sincronia. """ class Ingressos:
49
70
235
5
44
edersonhs/Python3_Basico_Ao_Avancado
Aulas/Módulos_Python/Threads-Executando_processamentos_em_paralelo/Example4.py
Python
Ingressos
Ingressos
11
38
11
11
192c4a6aed9cc47dc84989779ebaf7f0ce130440
bigcode/the-stack
train
85bd91ea8e094a00d56dc003
train
class
class ExactTargetOAuth2(BaseOAuth2): name = 'exacttarget' def get_user_details(self, response): """Use the email address of the user, suffixed by _et""" user = response.get('token', {})\ .get('request', {})\ .get('user', {}) if 'email' in us...
class ExactTargetOAuth2(BaseOAuth2):
name = 'exacttarget' def get_user_details(self, response): """Use the email address of the user, suffixed by _et""" user = response.get('token', {})\ .get('request', {})\ .get('user', {}) if 'email' in user: user['username'] = us...
""" ExactTarget OAuth support. Support Authentication from IMH using JWT token and pre-shared key. Requires package pyjwt """ from datetime import datetime, timedelta import jwt from ..exceptions import AuthCanceled, AuthFailed from .oauth import BaseOAuth2 class ExactTargetOAuth2(BaseOAuth2):
63
249
831
9
53
candlerb/social-core
social_core/backends/exacttarget.py
Python
ExactTargetOAuth2
ExactTargetOAuth2
14
104
14
14
ab41a1d1e8f89dc6ec0209699f14a5dbabef0e09
bigcode/the-stack
train
dd62e14770859d885e4c49b5
train
class
class TestEvent_SetThenClear100(TestEvent_SetThenClear): N = 100
class TestEvent_SetThenClear100(TestEvent_SetThenClear):
N = 100
e = Event() waiters = [gevent.spawn(e.wait) for i in range(self.N)] gevent.sleep(0.001) e.set() e.clear() for t in waiters: t.join() class TestEvent_SetThenClear100(TestEvent_SetThenClear):
64
64
19
13
51
hackaugusto/gevent
src/greentest/test__event.py
Python
TestEvent_SetThenClear100
TestEvent_SetThenClear100
183
184
183
183
ac304b1edc5a184f8fef31c13a9baa15fc7aa5fb
bigcode/the-stack
train
57f91882aa93d0f2fdeee2e6
train
class
class TestWait(greentest.TestCase): N = 5 count = None timeout = 1 period = timeout / 100.0 def _sender(self, events, asyncs): while events or asyncs: gevent.sleep(self.period) if events: events.pop().set() gevent.sleep(self.period) ...
class TestWait(greentest.TestCase):
N = 5 count = None timeout = 1 period = timeout / 100.0 def _sender(self, events, asyncs): while events or asyncs: gevent.sleep(self.period) if events: events.pop().set() gevent.sleep(self.period) if asyncs: asy...
) for i in range(self.N)] gevent.sleep(0.001) e.set() e.clear() for t in waiters: t.join() class TestEvent_SetThenClear100(TestEvent_SetThenClear): N = 100 class TestEvent_SetThenClear1000(TestEvent_SetThenClear): N = 1000 class TestWait(greentest.TestCase):
85
85
284
9
75
hackaugusto/gevent
src/greentest/test__event.py
Python
TestWait
TestWait
191
223
191
191
20b88fa712f486226847f90ecffaa213768f31fc
bigcode/the-stack
train
5179a5c7d3b35d3cdb3cb79c
train
class
class TestEvent_SetThenClear1000(TestEvent_SetThenClear): N = 1000
class TestEvent_SetThenClear1000(TestEvent_SetThenClear):
N = 1000
(self.N)] gevent.sleep(0.001) e.set() e.clear() for t in waiters: t.join() class TestEvent_SetThenClear100(TestEvent_SetThenClear): N = 100 class TestEvent_SetThenClear1000(TestEvent_SetThenClear):
64
64
21
14
49
hackaugusto/gevent
src/greentest/test__event.py
Python
TestEvent_SetThenClear1000
TestEvent_SetThenClear1000
187
188
187
187
2f8e37b4cdb0dff03bcf830451001c77888690d3
bigcode/the-stack
train
4690a7e66b0cba86221b8cd8
train
class
class TestWait_count1(TestWait): count = 1
class TestWait_count1(TestWait):
count = 1
expected_len = min(self.count, expected_len) self.assertFalse(sender.ready(), sender) sender.kill() self.assertEqual(expected_len, len(results), (expected_len, len(results), results)) class TestWait_notimeout(TestWait): timeout = None class TestWait_count1(TestWait):
64
64
14
8
55
hackaugusto/gevent
src/greentest/test__event.py
Python
TestWait_count1
TestWait_count1
230
231
230
230
ff2d3ac7dd1dd30aab07dafba3172e2a87035ce8
bigcode/the-stack
train
2d0a084c2c66b0ee879205b9
train
class
class TestWaitAsyncResult(AbstractGenericWaitTestCase): def wait(self, timeout): gevent.wait([AsyncResult()], timeout=timeout)
class TestWaitAsyncResult(AbstractGenericWaitTestCase):
def wait(self, timeout): gevent.wait([AsyncResult()], timeout=timeout)
) self.assertFalse(event.ready()) self.assertNotIn(event, o) gevent.spawn(waiter).join() class TestAsyncResultWait(AbstractGenericWaitTestCase): def wait(self, timeout): AsyncResult().wait(timeout=timeout) class TestWaitAsyncResult(AbstractGenericWaitTestCase):
64
64
30
11
53
hackaugusto/gevent
src/greentest/test__event.py
Python
TestWaitAsyncResult
TestWaitAsyncResult
71
74
71
72
b6fb9df27c851660c1932e57ea949abb0d9798b3
bigcode/the-stack
train
a9dee8c2c5a52a13e1e84eb2
train
class
class TestAsyncResult(greentest.TestCase): def test_link(self): ar = AsyncResult() self.assertRaises(TypeError, ar.rawlink, None) ar.unlink(None) # doesn't raise ar.unlink(None) # doesn't raise str(ar) # cover def test_set_exc(self): log = [] e = AsyncRe...
class TestAsyncResult(greentest.TestCase):
def test_link(self): ar = AsyncResult() self.assertRaises(TypeError, ar.rawlink, None) ar.unlink(None) # doesn't raise ar.unlink(None) # doesn't raise str(ar) # cover def test_set_exc(self): log = [] e = AsyncResult() self.assertEqual(e.exc_info, ...
self.assertFalse(event.ready()) self.assertNotIn(event, o) gevent.spawn(waiter).join() class TestAsyncResultWait(AbstractGenericWaitTestCase): def wait(self, timeout): AsyncResult().wait(timeout=timeout) class TestWaitAsyncResult(AbstractGenericWaitTestCase): def wait(self, t...
126
126
421
10
115
hackaugusto/gevent
src/greentest/test__event.py
Python
TestAsyncResult
TestAsyncResult
85
137
85
86
26d5152923378736c91680b89f3c377d18aa1479
bigcode/the-stack
train
c8d6e89bfb17b274bbd90966
train
class
class TestWait_count2(TestWait): count = 2
class TestWait_count2(TestWait):
count = 2
(sender.ready(), sender) sender.kill() self.assertEqual(expected_len, len(results), (expected_len, len(results), results)) class TestWait_notimeout(TestWait): timeout = None class TestWait_count1(TestWait): count = 1 class TestWait_count2(TestWait):
64
64
14
8
55
hackaugusto/gevent
src/greentest/test__event.py
Python
TestWait_count2
TestWait_count2
234
235
234
234
f4261a0962dd1b9c8e1483d5b38697af7b0bf50c
bigcode/the-stack
train
637c2e35488d0302607c7c49
train
class
class TestEvent_SetThenClear(greentest.TestCase): N = 1 def test(self): e = Event() waiters = [gevent.spawn(e.wait) for i in range(self.N)] gevent.sleep(0.001) e.set() e.clear() for t in waiters: t.join()
class TestEvent_SetThenClear(greentest.TestCase):
N = 1 def test(self): e = Event() waiters = [gevent.spawn(e.wait) for i in range(self.N)] gevent.sleep(0.001) e.set() e.clear() for t in waiters: t.join()
.ExpectedException, s1.get) X = object() result = gevent.with_timeout(DELAY, s2.get, timeout_value=X) self.assertIs(result, X) self.assertRaises(greentest.ExpectedException, s3.get) class TestEvent_SetThenClear(greentest.TestCase):
64
64
74
12
52
hackaugusto/gevent
src/greentest/test__event.py
Python
TestEvent_SetThenClear
TestEvent_SetThenClear
170
180
170
170
1dacd8ceb0645fd89d61d1440ef23e35b7765574
bigcode/the-stack
train
76c83573b1eccea6bc8cef39
train
class
class TestAsyncResultAsLinkTarget(greentest.TestCase): error_fatal = False def test_set(self): g = gevent.spawn(lambda: 1) s1, s2, s3 = AsyncResult(), AsyncResult(), AsyncResult() g.link(s1) g.link_value(s2) g.link_exception(s3) self.assertEqual(s1.get(), 1) ...
class TestAsyncResultAsLinkTarget(greentest.TestCase):
error_fatal = False def test_set(self): g = gevent.spawn(lambda: 1) s1, s2, s3 = AsyncResult(), AsyncResult(), AsyncResult() g.link(s1) g.link_value(s2) g.link_exception(s3) self.assertEqual(s1.get(), 1) self.assertEqual(s2.get(), 1) X = object() ...
, X, 'Nobody sent anything to event2 yet it received %r' % (result, )) def test_nonblocking_get(self): ar = AsyncResult() self.assertRaises(gevent.Timeout, ar.get, block=False) self.assertRaises(gevent.Timeout, ar.get_nowait) class TestAsyncResultAsLinkTarget(greentest.TestCase)...
78
78
263
13
65
hackaugusto/gevent
src/greentest/test__event.py
Python
TestAsyncResultAsLinkTarget
TestAsyncResultAsLinkTarget
140
167
140
140
5a92071dcb63c5d5ebb36e8bb68aa64a47bab2fb
bigcode/the-stack
train
01346e3a7d13a160f5ade798
train
class
class TestWait_notimeout(TestWait): timeout = None
class TestWait_notimeout(TestWait):
timeout = None
self.assertTrue(sender.ready(), sender) else: expected_len = min(self.count, expected_len) self.assertFalse(sender.ready(), sender) sender.kill() self.assertEqual(expected_len, len(results), (expected_len, len(results), results)) class TestWait_notimeout(T...
64
64
14
9
55
hackaugusto/gevent
src/greentest/test__event.py
Python
TestWait_notimeout
TestWait_notimeout
226
227
226
226
df2421ad96a08952db084b78595c36621aa02973
bigcode/the-stack
train
147e655f0fcbc30483d6ef55
train
class
class TestWaitEvent(AbstractGenericWaitTestCase): def wait(self, timeout): gevent.wait([Event()], timeout=timeout) def test_set_during_wait(self): # https://github.com/gevent/gevent/issues/771 # broke in the refactoring. we must not add new links # while we're running the callb...
class TestWaitEvent(AbstractGenericWaitTestCase):
def wait(self, timeout): gevent.wait([Event()], timeout=timeout) def test_set_during_wait(self): # https://github.com/gevent/gevent/issues/771 # broke in the refactoring. we must not add new links # while we're running the callback event = Event() def setter():...
Case from greentest.timing import SMALL_TICK from greentest.timing import SMALL_TICK_MAX_ADJ DELAY = SMALL_TICK + SMALL_TICK_MAX_ADJ class TestEventWait(AbstractGenericWaitTestCase): def wait(self, timeout): Event().wait(timeout=timeout) def test_cover(self): str(Event()) class TestWaitEven...
84
84
282
10
74
hackaugusto/gevent
src/greentest/test__event.py
Python
TestWaitEvent
TestWaitEvent
26
62
26
27
e01641eafc8c42d1ec8a33553a73e4a5d1c66f4b
bigcode/the-stack
train
9d23bf9c31a3c6be24131569
train
class
class TestAsyncResultWait(AbstractGenericWaitTestCase): def wait(self, timeout): AsyncResult().wait(timeout=timeout)
class TestAsyncResultWait(AbstractGenericWaitTestCase):
def wait(self, timeout): AsyncResult().wait(timeout=timeout)
loop would # immediately add the waiter and call it o = gevent.wait((event,), timeout=0.01) self.assertFalse(event.ready()) self.assertNotIn(event, o) gevent.spawn(waiter).join() class TestAsyncResultWait(AbstractGenericWaitTestCase):
64
64
27
11
53
hackaugusto/gevent
src/greentest/test__event.py
Python
TestAsyncResultWait
TestAsyncResultWait
65
68
65
66
4c3fc30946dd4ade6404b440ca7ccb54b760cce1
bigcode/the-stack
train
78671caa7d8f27307538b820
train
class
class MyException(Exception): pass
class MyException(Exception):
pass
timeout) class TestWaitAsyncResult(AbstractGenericWaitTestCase): def wait(self, timeout): gevent.wait([AsyncResult()], timeout=timeout) class TestAsyncResultGet(AbstractGenericGetTestCase): def wait(self, timeout): AsyncResult().get(timeout=timeout) class MyException(Exception):
64
64
8
5
59
hackaugusto/gevent
src/greentest/test__event.py
Python
MyException
MyException
82
83
82
82
9281049aec1272d46aef5302c97ef3664114361c
bigcode/the-stack
train
bc9beb96c7f60ed0c1765721
train
class
class TestEventWait(AbstractGenericWaitTestCase): def wait(self, timeout): Event().wait(timeout=timeout) def test_cover(self): str(Event())
class TestEventWait(AbstractGenericWaitTestCase):
def wait(self, timeout): Event().wait(timeout=timeout) def test_cover(self): str(Event())
GenericGetTestCase from greentest.timing import AbstractGenericWaitTestCase from greentest.timing import SMALL_TICK from greentest.timing import SMALL_TICK_MAX_ADJ DELAY = SMALL_TICK + SMALL_TICK_MAX_ADJ class TestEventWait(AbstractGenericWaitTestCase):
64
64
35
10
53
hackaugusto/gevent
src/greentest/test__event.py
Python
TestEventWait
TestEventWait
17
23
17
18
1399f05f84fc702b7ee5e38a2af827e87308c2b5
bigcode/the-stack
train
d1fa465ae9dc73705967138e
train
class
class TestAsyncResultGet(AbstractGenericGetTestCase): def wait(self, timeout): AsyncResult().get(timeout=timeout)
class TestAsyncResultGet(AbstractGenericGetTestCase):
def wait(self, timeout): AsyncResult().get(timeout=timeout)
Wait(AbstractGenericWaitTestCase): def wait(self, timeout): AsyncResult().wait(timeout=timeout) class TestWaitAsyncResult(AbstractGenericWaitTestCase): def wait(self, timeout): gevent.wait([AsyncResult()], timeout=timeout) class TestAsyncResultGet(AbstractGenericGetTestCase):
64
64
27
11
53
hackaugusto/gevent
src/greentest/test__event.py
Python
TestAsyncResultGet
TestAsyncResultGet
77
80
77
78
7a318c50ecfc59a775fda39d602cdb661fd53060
bigcode/the-stack
train
fc1644108fef17234732f843
train
function
def test_payload_too_large_at_data_received_default(app): app.config.REQUEST_MAX_SIZE = 1 @app.route("/1") async def handler2(request): return text("OK") response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Error: Payload Too...
def test_payload_too_large_at_data_received_default(app):
app.config.REQUEST_MAX_SIZE = 1 @app.route("/1") async def handler2(request): return text("OK") response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Error: Payload Too Large"
, exception): return text("Payload Too Large from error_handler.", 413) response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Payload Too Large from error_handler." def test_payload_too_large_at_data_received_default(app):
64
64
76
12
52
sliderSun/sanic
tests/test_payload_too_large.py
Python
test_payload_too_large_at_data_received_default
test_payload_too_large_at_data_received_default
21
30
21
21
5a3da059478ef864305ed19234b7a40b0f7c6f4c
bigcode/the-stack
train
0c799f8bf7fa06f562908a2f
train
function
def test_payload_too_large_at_on_header_default(app): app.config.REQUEST_MAX_SIZE = 500 @app.post("/1") async def handler3(request): return text("OK") data = "a" * 1000 response = app.test_client.post("/1", gather_request=False, data=data) assert response.status == 413 assert respo...
def test_payload_too_large_at_on_header_default(app):
app.config.REQUEST_MAX_SIZE = 500 @app.post("/1") async def handler3(request): return text("OK") data = "a" * 1000 response = app.test_client.post("/1", gather_request=False, data=data) assert response.status == 413 assert response.text == "Error: Payload Too Large"
app.route("/1") async def handler2(request): return text("OK") response = app.test_client.get("/1", gather_request=False) assert response.status == 413 assert response.text == "Error: Payload Too Large" def test_payload_too_large_at_on_header_default(app):
64
64
90
12
52
sliderSun/sanic
tests/test_payload_too_large.py
Python
test_payload_too_large_at_on_header_default
test_payload_too_large_at_on_header_default
33
43
33
33
a52996fc70b6a95c1a9413f72271a761351a1c85
bigcode/the-stack
train
11fd7c291c711c6a59a85407
train
function
def test_payload_too_large_from_error_handler(app): app.config.REQUEST_MAX_SIZE = 1 @app.route("/1") async def handler1(request): return text("OK") @app.exception(PayloadTooLarge) def handler_exception(request, exception): return text("Payload Too Large from error_handler.", 413) ...
def test_payload_too_large_from_error_handler(app):
app.config.REQUEST_MAX_SIZE = 1 @app.route("/1") async def handler1(request): return text("OK") @app.exception(PayloadTooLarge) def handler_exception(request, exception): return text("Payload Too Large from error_handler.", 413) response = app.test_client.get("/1", gather_requ...
from sanic.exceptions import PayloadTooLarge from sanic.response import text def test_payload_too_large_from_error_handler(app):
27
64
107
11
15
sliderSun/sanic
tests/test_payload_too_large.py
Python
test_payload_too_large_from_error_handler
test_payload_too_large_from_error_handler
5
18
5
5
aea72e8e950d10be9be0722e9be65bb46671a1f5
bigcode/the-stack
train
aba4a5bf6101c7132f38669d
train
function
def deep_metric_loss_py(y_true, y_pred): pos_embedding = y_pred[y_true>0] neg_embedding = y_pred[y_true==0] pos_distance = 0 count = 0 for i in range(len(pos_embedding)): for k in range(i + 1, len(pos_embedding)): pos_distance += distance_metric(pos_embedding[i], pos_embedding[...
def deep_metric_loss_py(y_true, y_pred):
pos_embedding = y_pred[y_true>0] neg_embedding = y_pred[y_true==0] pos_distance = 0 count = 0 for i in range(len(pos_embedding)): for k in range(i + 1, len(pos_embedding)): pos_distance += distance_metric(pos_embedding[i], pos_embedding[k]) count+=1 pos_distance...
, [y_true, y_pred], tf.float32) return loss def distance_metric(vec1, vec2): # euclidean distance distance = np.square(vec1-vec2) distance = np.sum(distance) return distance def deep_metric_loss_py(y_true, y_pred):
64
64
186
11
52
KerrWu/fewShotPASI
utils/loss.py
Python
deep_metric_loss_py
deep_metric_loss_py
21
49
21
22
df1b0e6f8ef8288eb30bbb6020daf8e5feef36d2
bigcode/the-stack
train
a81dd0ef98f08087c5a92932
train
function
def deep_metric_loss(y_true, y_pred): loss = tf.py_func(deep_metric_loss_py, [y_true, y_pred], tf.float32) return loss
def deep_metric_loss(y_true, y_pred):
loss = tf.py_func(deep_metric_loss_py, [y_true, y_pred], tf.float32) return loss
import numpy as np import tensorflow as tf def deep_metric_loss(y_true, y_pred):
20
64
37
10
9
KerrWu/fewShotPASI
utils/loss.py
Python
deep_metric_loss
deep_metric_loss
5
8
5
5
52cc90517a567bff7ce1eb68a97a6f287a5f5ee0
bigcode/the-stack
train
e8e6186c041d11f30ea02c92
train
function
def distance_metric(vec1, vec2): # euclidean distance distance = np.square(vec1-vec2) distance = np.sum(distance) return distance
def distance_metric(vec1, vec2): # euclidean distance
distance = np.square(vec1-vec2) distance = np.sum(distance) return distance
import numpy as np import tensorflow as tf def deep_metric_loss(y_true, y_pred): loss = tf.py_func(deep_metric_loss_py, [y_true, y_pred], tf.float32) return loss def distance_metric(vec1, vec2): # euclidean distance
62
64
37
15
46
KerrWu/fewShotPASI
utils/loss.py
Python
distance_metric
distance_metric
12
18
12
14
6786b124b976e0470f725f92003173cc482353cc
bigcode/the-stack
train
3a4bcbb4e55bc23ddb4a34f6
train
function
def extract_from_program(mod, params, target, target_host=None, ops=None): """ Extract tuning tasks from a relay program. This function is the single program version of extract_from_multiple_program. Parameters ---------- mod: tvm.IRModule or relay.function.Function The module or function ...
def extract_from_program(mod, params, target, target_host=None, ops=None):
""" Extract tuning tasks from a relay program. This function is the single program version of extract_from_multiple_program. Parameters ---------- mod: tvm.IRModule or relay.function.Function The module or function to tune params: dict of str to numpy array The associated param...
target) grc.codegen(opt_mod["main"]) except tvm.TVMError: compiler = relay.vm.VMCompiler() if params: compiler.set_params(params) compiler.lower(mod, target=target) def extract_from_program(mod, params, target, target_host=None, ops=None):
64
64
185
17
47
heweiwill/incubator-tvm
python/tvm/autotvm/task/relay_integration.py
Python
extract_from_program
extract_from_program
66
89
66
66
fcce71ef4d74ecc57b9953c729b806140a17583f
bigcode/the-stack
train
09c8931fd30901662c5d2eca
train
function
def _lower(mod, target, params): """ Helper to lower VTA properly. """ # pylint: disable=import-outside-toplevel from tvm import relay from tvm.relay.backend import graph_runtime_codegen if hasattr(target, 'device_name') and target.device_name == "vta": with relay....
def _lower(mod, target, params):
""" Helper to lower VTA properly. """ # pylint: disable=import-outside-toplevel from tvm import relay from tvm.relay.backend import graph_runtime_codegen if hasattr(target, 'device_name') and target.device_name == "vta": with relay.build_config(opt_level=3, disabled_pass={"AlterOpLayout...
copy-paste of implementation by @MerryMercy """ import threading import logging import tvm from .task import create from .topi_integration import TaskExtractEnv logger = logging.getLogger('autotvm') # TODO(moreau89) find a more elegant way to lower for VTAs def _lower(mod, target, params):
79
79
265
11
67
heweiwill/incubator-tvm
python/tvm/autotvm/task/relay_integration.py
Python
_lower
_lower
34
63
34
36
01f07190cdcd93c7ecd094aba350672b81de4c90
bigcode/the-stack
train
d8fa9e3f247116483f4ee5e9
train
function
def extract_from_multiple_program(mods, params, target, target_host=None, ops=None): """ Extract tuning tasks from multiple relay programs. This function collects tuning tasks by building a list of programs with a "tracing" target and tracing all the calls to topi. Parameters ---------- mods: ...
def extract_from_multiple_program(mods, params, target, target_host=None, ops=None):
""" Extract tuning tasks from multiple relay programs. This function collects tuning tasks by building a list of programs with a "tracing" target and tracing all the calls to topi. Parameters ---------- mods: List[tvm.IRModule] or List[relay.function.Function] The list of modules or fu...
: dict of str to numpy array The associated parameters of the program target: tvm.target.Target The compilation target target_host: tvm.target.Target The host compilation target ops: List[relay.op.Op] or None List of relay ops to be tuned. If not specified, all tunable ops wi...
136
136
456
19
117
heweiwill/incubator-tvm
python/tvm/autotvm/task/relay_integration.py
Python
extract_from_multiple_program
extract_from_multiple_program
92
153
92
92
bff2ad841b15d1e81c89a299974eaa46773ecd05
bigcode/the-stack
train
b1fdf21cf4fa4d3c134197d8
train
class
@method_login_and_permission("auth.view_user") class UserAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = User.objects.all() if self.q: qs = qs.filter( Q(username__icontains=self.q) | Q(first_name__icontains=self.q) ...
@method_login_and_permission("auth.view_user") class UserAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self): qs = User.objects.all() if self.q: qs = qs.filter( Q(username__icontains=self.q) | Q(first_name__icontains=self.q) | Q(last_name__icontains=self.q) ) return qs.order_by("username")
(first_name__icontains=self.q) | Q(last_name__icontains=self.q) ) return qs.order_by("username") # this is needed otherwise anyone can see the users in the database @method_login_and_permission("auth.view_user") class UserAutocomplete(autocomplete.Select2QuerySetView):
64
64
86
21
42
jyxzhang/hknweb
hknweb/candidate/views/autocomplete.py
Python
UserAutocomplete
UserAutocomplete
25
35
25
26
9754efc6247ee94cde44aa76b12cf6670d381eab
bigcode/the-stack
train
b417f83ec000a0d649a5c5e2
train
class
@method_login_and_permission("auth.view_user") class OfficerAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = User.objects.filter(groups__name=settings.OFFICER_GROUP) if self.q: qs = qs.filter( Q(username__icontains=self.q) | Q(f...
@method_login_and_permission("auth.view_user") class OfficerAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self): qs = User.objects.filter(groups__name=settings.OFFICER_GROUP) if self.q: qs = qs.filter( Q(username__icontains=self.q) | Q(first_name__icontains=self.q) | Q(last_name__icontains=self.q) ) return q...
.contrib.auth.models import User from django.db.models import Q from dal import autocomplete from hknweb.utils import method_login_and_permission # this is needed otherwise anyone can see the users in the database @method_login_and_permission("auth.view_user") class OfficerAutocomplete(autocomplete.Select2QuerySetV...
64
64
94
21
42
jyxzhang/hknweb
hknweb/candidate/views/autocomplete.py
Python
OfficerAutocomplete
OfficerAutocomplete
11
21
11
12
89f32bed5eb71fd20a51a7a5381d9bd681a5913d
bigcode/the-stack
train
393d4f7108a0654a2f529411
train
function
def simulate_policy(args): data = joblib.load(args.file) if args.deterministic: print('Using the deterministic version of the policy.') policy = data['policy'] else: print('Using the stochastic policy.') policy = data['exploration_policy'] # env = data['env'] # env =...
def simulate_policy(args):
data = joblib.load(args.file) if args.deterministic: print('Using the deterministic version of the policy.') policy = data['policy'] else: print('Using the stochastic policy.') policy = data['exploration_policy'] # env = data['env'] # env = NormalizedBoxEnv(gym.make(...
.utils.pytorch_util import set_gpu_mode import argparse import joblib import uuid import json from robolearn.utils.logging import logger from robolearn_gym_envs.pybullet import Pusher2D3DofGoalCompoEnv from robolearn_gym_envs.pybullet import CogimonLocomotionBulletEnv filename = str(uuid.uuid4()) def simulate_policy(a...
85
85
286
5
80
domingoesteban/robolearn
scripts/sim_policy_robolearn.py
Python
simulate_policy
simulate_policy
17
61
17
17
8a1663b31527ca0adf76860e9812665159070203
bigcode/the-stack
train
115599accc052a2a2d514dca
train
class
class SessionsManager(): """A class to manage sessions Attributes: current_user_id - (int) The ID of the current user session - (Session) Current managed session """ def __init__(self, current_user_id, session=None): self.current_user_id = current_user_id self.session =...
class SessionsManager():
"""A class to manage sessions Attributes: current_user_id - (int) The ID of the current user session - (Session) Current managed session """ def __init__(self, current_user_id, session=None): self.current_user_id = current_user_id self.session = session self.db...
from webapp.DBManager import DBManager from webapp.Session import Session class SessionsManager():
20
244
815
4
15
gslf/ShotBuddy
webapp/SessionsManager.py
Python
SessionsManager
SessionsManager
4
146
4
4
1118ca0127fb5d91f1dd643e39588a41d6640881
bigcode/the-stack
train
4e7be0590a796c085eb51148
train
function
def to_dataset(data,stride=0): labels, token_type_ids, input_ids, attention_masks = [],[],[],[] for item in tqdm(data): result = tokenize_and_align_data(item,stride=stride) labels += result['labels'] input_ids += result['input_ids'] attention_masks += result['atte...
def to_dataset(data,stride=0):
labels, token_type_ids, input_ids, attention_masks = [],[],[],[] for item in tqdm(data): result = tokenize_and_align_data(item,stride=stride) labels += result['labels'] input_ids += result['input_ids'] attention_masks += result['attention_mask'] return Dataset...
_id][word_id] label = data[1][word_id] doc_encoded_labels.append(int(label)) last_word_id = word_id labels.append(doc_encoded_labels) tokenized_inputs["labels"] = labels return tokenized_inputs def to_dataset(data,stride=0):
64
64
97
9
54
jordimas/fullstop-deep-punctuation-prediction
baseline_xlm-roberta.py
Python
to_dataset
to_dataset
65
72
65
65
ad7204692387eb846a14992641f06c065674e70a
bigcode/the-stack
train
8eb35bb7ee7cf373ed3fcbf5
train
function
def compute_metrics_sklearn(pred): mask = np.less(pred.label_ids,0) # mask out -100 values labels = ma.masked_array(pred.label_ids,mask).compressed() preds = ma.masked_array(pred.predictions.argmax(-1),mask).compressed() precision, recall, f1, _ = precision_recall_fscore_support(labels, preds,...
def compute_metrics_sklearn(pred):
mask = np.less(pred.label_ids,0) # mask out -100 values labels = ma.masked_array(pred.label_ids,mask).compressed() preds = ma.masked_array(pred.predictions.argmax(-1),mask).compressed() precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='binary') acc = accuracy...
(train_data,stride=100) del train_data print("tokenize validation data") val_data = val_data[:int(len(val_data)*data_factor)] # limit data to x% tokenized_dataset_val = to_dataset(val_data) del val_data ## metrics def compute_metrics_sklearn(pred):
64
64
132
9
54
jordimas/fullstop-deep-punctuation-prediction
baseline_xlm-roberta.py
Python
compute_metrics_sklearn
compute_metrics_sklearn
87
99
87
87
c91ca8e8210af575efff169922a8ac79516fcc08
bigcode/the-stack
train
768d720e2302e015b354c177
train
function
def tokenize_and_align_data(data,stride=0): tokenizer_settings = {'is_split_into_words':True,'return_offsets_mapping':True, 'padding':False, 'truncation':True, 'stride':stride, 'max_length':tokenizer.model_max_length, 'return_overflowing_tokens':True} to...
def tokenize_and_align_data(data,stride=0):
tokenizer_settings = {'is_split_into_words':True,'return_offsets_mapping':True, 'padding':False, 'truncation':True, 'stride':stride, 'max_length':tokenizer.model_max_length, 'return_overflowing_tokens':True} tokenized_inputs = tokenizer(data[0], **tokeni...
.zip","train","fr") train_data += load("data/sepp_nlg_2021_train_dev_data.zip","train","it") random.shuffle(train_data) random.shuffle(val_data) ## tokenize data tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, strip_accent=False) def tokenize_and_align_data(data,stride=0):
69
69
232
11
58
jordimas/fullstop-deep-punctuation-prediction
baseline_xlm-roberta.py
Python
tokenize_and_align_data
tokenize_and_align_data
40
62
40
40
4512c2c27cd5274a8041e4da82d870e14e27f4f9
bigcode/the-stack
train
087b35af911aef1fc170c635
train
function
def generate_symmetric_key(n, g, x, y): if not is_prime(n): raise ValueError('n must be prime') if not g < n: raise ValueError('g must be lower than n') X = modular_pow(g, x, n) Y = modular_pow(g, y, n) K_Alice = modular_pow(Y, x, n) K_Bob = modular_pow(X, y, n) if K_A...
def generate_symmetric_key(n, g, x, y):
if not is_prime(n): raise ValueError('n must be prime') if not g < n: raise ValueError('g must be lower than n') X = modular_pow(g, x, n) Y = modular_pow(g, y, n) K_Alice = modular_pow(Y, x, n) K_Bob = modular_pow(X, y, n) if K_Alice != K_Bob: raise RuntimeErro...
from math import sqrt from src.helper.math import modular_pow def is_prime(x): for i in range(2, int(sqrt(x))): if x % i == 0: return False return True def generate_symmetric_key(n, g, x, y):
62
64
127
13
48
juniardiakbar/if4020-public-private-key
src/diffiehellman/main.py
Python
generate_symmetric_key
generate_symmetric_key
11
25
11
11
84e4707dcc33c5aaa879db79eabfac195f09e611
bigcode/the-stack
train
069dbcc0355ac582e8706da6
train
function
def is_prime(x): for i in range(2, int(sqrt(x))): if x % i == 0: return False return True
def is_prime(x):
for i in range(2, int(sqrt(x))): if x % i == 0: return False return True
from math import sqrt from src.helper.math import modular_pow def is_prime(x):
18
64
36
5
12
juniardiakbar/if4020-public-private-key
src/diffiehellman/main.py
Python
is_prime
is_prime
5
9
5
5
81095329ad1c1a070212473f1dcc74c9aaedb5a7
bigcode/the-stack
train
643be01dc8104f8651dcdb89
train
class
class NameScanningTest (NameTestFramework): def run_test (self): NameTestFramework.run_test (self) # Initially, all should be empty. assert_equal (self.nodes[0].name_scan (), []) assert_equal (self.nodes[0].name_scan ("foo", 10), []) assert_equal (self.nodes[0].name_filter (), []) assert_equ...
class NameScanningTest (NameTestFramework):
def run_test (self): NameTestFramework.run_test (self) # Initially, all should be empty. assert_equal (self.nodes[0].name_scan (), []) assert_equal (self.nodes[0].name_scan ("foo", 10), []) assert_equal (self.nodes[0].name_filter (), []) assert_equal (self.nodes[0].name_filter ("", 0, 0, 0, "...
#!/usr/bin/env python # Copyright (c) 2014 Daniel Kraft # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # RPC test for the name scanning functions (name_scan and name_filter). # Add python-bitcoinrpc to module search path: im...
132
256
1,007
9
122
FinalHashLLC/namecore
qa/rpc-tests/name_scanning.py
Python
NameScanningTest
NameScanningTest
17
96
17
18
5a0ec4c986f17568e28eb5ac3dac0ca7d287f937
bigcode/the-stack
train
38fe5ccb9554895978852cca
train
class
class VrettasFung(HydrologicalModel): """ This class represents a hydrologic model based on the Vrettas-Fung papers. 1) Vrettas M. D., and Fung I. Y. (2015), "Toward a new parameterization of hydraulic conductivity in climate models: Simulation of rapid groundwater fluctuations in Northern Califo...
class VrettasFung(HydrologicalModel):
""" This class represents a hydrologic model based on the Vrettas-Fung papers. 1) Vrettas M. D., and Fung I. Y. (2015), "Toward a new parameterization of hydraulic conductivity in climate models: Simulation of rapid groundwater fluctuations in Northern California", Journal of Advances in Modeling...
import numpy as np from scipy.interpolate import interp1d from .hydrological_model import HydrologicalModel from ..utilities import logN_rnd class VrettasFung(HydrologicalModel):
43
256
2,483
11
31
vrettasm/HydroModel
code/src/models/vrettas_fung.py
Python
VrettasFung
VrettasFung
8
257
8
8
b0f4e64ac8e4e172f882243829037243b95c657b
bigcode/the-stack
train
c53a1dcd261ef35d2365340a
train
class
class TreeManager(models.Manager): """ A manager for working with trees of objects. """ def __init__(self, parent_attr, left_attr, right_attr, tree_id_attr, level_attr): """ Tree attributes for the model being managed are held as attributes of this manager for la...
class TreeManager(models.Manager):
""" A manager for working with trees of objects. """ def __init__(self, parent_attr, left_attr, right_attr, tree_id_attr, level_attr): """ Tree attributes for the model being managed are held as attributes of this manager for later use, since it will be using ...
""" A custom manager for working with trees of objects. """ from django.db import connection, models, transaction from django.utils.translation import ugettext as _ from mptt.exceptions import InvalidMove __all__ = ('TreeManager',) qn = connection.ops.quote_name COUNT_SUBQUERY = """( SELECT COUNT(*) FROM %(...
222
256
6,301
6
216
bfirsh/django-mptt
mptt/managers.py
Python
TreeManager
TreeManager
32
732
32
32
f354c7861727b51eb7871280459cc5503018764d
bigcode/the-stack
train
e18c0857362b509847373a1e
train
function
@app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html', **index_kw)
@app.route('/', methods=['GET', 'POST']) def index():
return render_template('index.html', **index_kw)
.MAP_PLASMID_PATH.keys() if k.startswith('Lox')] index_kw = {'mod_keys':batch.MAP_MOD_TYPE.keys(), 'assembly_keys':batch.MAP_ASSEMBLY_METHOD.keys(), 'marker_keys':marker_keys} @app.route('/', methods=['GET', 'POST']) def index():
64
64
25
13
51
thomasvstevens/locusmod
app.py
Python
index
index
16
18
16
17
867041625da57b03f78c5603d5f57298ef747f63
bigcode/the-stack
train
244566e86cbd5f3b1d6061e6
train
function
def test(): with app.test_request_context('/', method='GET'): assert request.path == '/' assert request.method == 'GET' with app.test_request_context('/', method='POST'): assert request.path == '/download' assert request.method == 'POST'
def test():
with app.test_request_context('/', method='GET'): assert request.path == '/' assert request.method == 'GET' with app.test_request_context('/', method='POST'): assert request.path == '/download' assert request.method == 'POST'
_idt_csv() b.write_plasmids_zip(request.form['start_plasmids']) b.write_loci_zip() rows = b.list_operations() return render_template('download.html', files=files, rows=rows) return render_template('index.html', **index_kw) def test():
64
64
55
3
61
thomasvstevens/locusmod
app.py
Python
test
test
37
43
37
37
3e4013ab8ac735e4efb90cfa70d1f595d0625495
bigcode/the-stack
train
4b0405c130f304380bfe2a15
train
function
@app.route('/download', methods=['GET', 'POST']) def download(): if request.method == 'POST': batch_kw = {k:v for k,v in request.form.items() if not k.startswith('start')} b = batch.Batch(**batch_kw) shutil.rmtree(batch.paths.OUTPUT_PREFIX) os.mkdir(batch.paths.OUTPUT...
@app.route('/download', methods=['GET', 'POST']) def download():
if request.method == 'POST': batch_kw = {k:v for k,v in request.form.items() if not k.startswith('start')} b = batch.Batch(**batch_kw) shutil.rmtree(batch.paths.OUTPUT_PREFIX) os.mkdir(batch.paths.OUTPUT_PREFIX) b.write_primers_csv() b.assign_numbers(r...
.keys(), 'assembly_keys':batch.MAP_ASSEMBLY_METHOD.keys(), 'marker_keys':marker_keys} @app.route('/', methods=['GET', 'POST']) def index(): return render_template('index.html', **index_kw) @app.route('/download', methods=['GET', 'POST']) def download():
64
64
158
15
49
thomasvstevens/locusmod
app.py
Python
download
download
20
35
20
21
e67ed4a31502edbca0ef31638b4226d909905680
bigcode/the-stack
train
b1e500257a81506d0761e1f1
train
function
def package_files(directory, strip_leading): paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: package_file = os.path.join(path, filename) paths.append(package_file[len(strip_leading):]) return paths
def package_files(directory, strip_leading):
paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: package_file = os.path.join(path, filename) paths.append(package_file[len(strip_leading):]) return paths
from setuptools import setup, find_packages import os #include the non python files def package_files(directory, strip_leading):
26
64
59
9
16
Schmill/donkeycar
setup.py
Python
package_files
package_files
6
12
6
6
0002d8e0fed2805985b10794e1623a3a872c7ca3
bigcode/the-stack
train
c126a9199ba723fb7f18f508
train
function
def checkout_branch(git, remote_exists, branch): if remote_exists: print("Checking out branch '%s'" % branch) git.stash("--include-untracked") git.checkout(branch) try: git.stash("pop") except BaseException: git.checkout("--theirs", ".") gi...
def checkout_branch(git, remote_exists, branch):
if remote_exists: print("Checking out branch '%s'" % branch) git.stash("--include-untracked") git.checkout(branch) try: git.stash("pop") except BaseException: git.checkout("--theirs", ".") git.reset() else: print("Creating new b...
ply.github.com" name = os.environ["GITHUB_ACTOR"] return email, name def get_repo_url(token, github_repository): return "https://x-access-token:%s@github.com/%s" % (token, github_repository) def checkout_branch(git, remote_exists, branch):
64
64
95
11
53
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
checkout_branch
checkout_branch
51
63
51
51
f795f02c2eec95048718beb2fc25e544b3b296f3
bigcode/the-stack
train
0c916ae1c3886d05db7e3f8a
train
function
def push_changes(git, token, github_repository, branch, commit_message): git.add("-A") print("author_name=%s, author_email=%s, committer_name=%s, committer_email=%s" % ( author_name, author_email, committer_name, committer_email)) git.commit(m=commit_message, author="%s <%s>" %(author_name, author_e...
def push_changes(git, token, github_repository, branch, commit_message):
git.add("-A") print("author_name=%s, author_email=%s, committer_name=%s, committer_email=%s" % ( author_name, author_email, committer_name, committer_email)) git.commit(m=commit_message, author="%s <%s>" %(author_name, author_email), committer_name=committer_name, commi...
.stash("pop") except BaseException: git.checkout("--theirs", ".") git.reset() else: print("Creating new branch '%s'" % branch) git.checkout("HEAD", b=branch) def push_changes(git, token, github_repository, branch, commit_message):
64
64
135
16
48
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
push_changes
push_changes
66
74
66
66
9484abea3fe17d6599e9260ea766b5b3a2bab47f
bigcode/the-stack
train
6744bdb411ba38d6fbfdcc00
train
function
def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits): return "".join(random.choice(chars) for _ in range(size))
def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
_EVENT_NAME"]) print(json.dumps(github_event, sort_keys=True, indent=2)) return github_event def get_head_short_sha1(repo): return repo.git.rev_parse("--short", "HEAD") def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits):
64
64
34
20
44
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
get_random_suffix
get_random_suffix
26
27
26
26
cd0d429689cc23a68fbef2881c4251aa5e501eb1
bigcode/the-stack
train
2146dbb827eb9430ada58eff
train
function
def cs_string_to_list(str): # Split the comma separated string into a list l = [i.strip() for i in str.split(",")] # Remove empty strings return list(filter(None, l))
def cs_string_to_list(str): # Split the comma separated string into a list
l = [i.strip() for i in str.split(",")] # Remove empty strings return list(filter(None, l))
committer_name, committer_email=committer_email) repo_url = get_repo_url(token, github_repository) return git.push("-f", repo_url, f"HEAD:refs/heads/{branch}") def cs_string_to_list(str): # Split the comma separated string into a list
63
64
46
18
45
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
cs_string_to_list
cs_string_to_list
77
81
77
78
e289298c71ccc523fb043cc1fefe8bac24366222
bigcode/the-stack
train
95ab1ca0431eb0ac650084dd
train
function
def process_event(github_token, github_repository, repo, branch, base): # Fetch optional environment variables with default values commit_message = os.getenv( "COMMIT_MESSAGE", "Auto-committed changes by create-pull-request action" ) title = os.getenv( "PULL_REQUEST_TITLE", "Auto-generat...
def process_event(github_token, github_repository, repo, branch, base): # Fetch optional environment variables with default values
commit_message = os.getenv( "COMMIT_MESSAGE", "Auto-committed changes by create-pull-request action" ) title = os.getenv( "PULL_REQUEST_TITLE", "Auto-generated by create-pull-request action" ) body = os.getenv( "PULL_REQUEST_BODY", "Auto-generated pull request by " ...
(",")] # Remove empty strings return list(filter(None, l)) def create_project_card(github_repo, project_name, project_column_name, pull_request): # Locate the project by name project = None for project_item in github_repo.get_projects("all"): if project_item.name == project_name: ...
256
256
991
26
230
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
process_event
process_event
115
218
115
116
1b0c0cd29fecb7c2d4f6c467b48bef78e8750e09
bigcode/the-stack
train
a884e25d9d9c6fec791d62c0
train
function
def create_project_card(github_repo, project_name, project_column_name, pull_request): # Locate the project by name project = None for project_item in github_repo.get_projects("all"): if project_item.name == project_name: project = project_item break if not project: ...
def create_project_card(github_repo, project_name, project_column_name, pull_request): # Locate the project by name
project = None for project_item in github_repo.get_projects("all"): if project_item.name == project_name: project = project_item break if not project: print("::warning::Project not found. Unable to create project card.") return # Locate the column by nam...
# Split the comma separated string into a list l = [i.strip() for i in str.split(",")] # Remove empty strings return list(filter(None, l)) def create_project_card(github_repo, project_name, project_column_name, pull_request): # Locate the project by name
64
64
214
26
38
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
create_project_card
create_project_card
84
112
84
85
f3bf1e3323a4b7f76d02b378f0545c92c2fb0f99
bigcode/the-stack
train
e39d353319d7f406bb1baa78
train
function
def get_github_event(github_event_path): with open(github_event_path) as f: github_event = json.load(f) if bool(os.environ.get("DEBUG_EVENT")): print(os.environ["GITHUB_EVENT_NAME"]) print(json.dumps(github_event, sort_keys=True, indent=2)) return github_event
def get_github_event(github_event_path):
with open(github_event_path) as f: github_event = json.load(f) if bool(os.environ.get("DEBUG_EVENT")): print(os.environ["GITHUB_EVENT_NAME"]) print(json.dumps(github_event, sort_keys=True, indent=2)) return github_event
#!/usr/bin/env python3 """ Create Pull Request """ import json import os import random import string import sys import time from git import Repo from github import Github, GithubException def get_github_event(github_event_path):
53
64
71
10
42
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
get_github_event
get_github_event
13
19
13
13
cd7847fa5712aca79a27cd5c77a9f2b7feea1402
bigcode/the-stack
train
7e70cacd8fc52ee0b529f290
train
function
def remote_branch_exists(repo, branch): for ref in repo.remotes.origin.refs: if ref.name == ("origin/%s" % branch): return True return False
def remote_branch_exists(repo, branch):
for ref in repo.remotes.origin.refs: if ref.name == ("origin/%s" % branch): return True return False
_event def get_head_short_sha1(repo): return repo.git.rev_parse("--short", "HEAD") def get_random_suffix(size=7, chars=string.ascii_lowercase + string.digits): return "".join(random.choice(chars) for _ in range(size)) def remote_branch_exists(repo, branch):
64
64
39
8
56
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
remote_branch_exists
remote_branch_exists
30
34
30
30
d266dd26fcde0be5ad1ed01ae97ac6e35c5d4622
bigcode/the-stack
train
1f66f1c8bea218bfa4d6f3e2
train
function
def get_author_default(event_name, event_data): if event_name == "push": email = "{head_commit[author][email]}".format(**event_data) name = "{head_commit[author][name]}".format(**event_data) else: email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com" name = os.environ[...
def get_author_default(event_name, event_data):
if event_name == "push": email = "{head_commit[author][email]}".format(**event_data) name = "{head_commit[author][name]}".format(**event_data) else: email = os.environ["GITHUB_ACTOR"] + "@users.noreply.github.com" name = os.environ["GITHUB_ACTOR"] return email, name
): return "".join(random.choice(chars) for _ in range(size)) def remote_branch_exists(repo, branch): for ref in repo.remotes.origin.refs: if ref.name == ("origin/%s" % branch): return True return False def get_author_default(event_name, event_data):
64
64
92
10
53
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
Python
get_author_default
get_author_default
37
44
37
37
35165ce3dd744b9f148851f0f099a252aaf5767e
bigcode/the-stack
train