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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1dd2260a2e9de33d91e82a9 | train | function | def polarity_all_expr(expression, value):
pols = polarity_expr(expression.term, value)
return pols
| def polarity_all_expr(expression, value):
| pols = polarity_expr(expression.term, value)
return pols
|
return pols
def polarity_not_expr(expression, value):
pols = polarity_expr(expression.term, rev_pol(value))
return pols
def polarity_exists_expr(expression, value):
pols = polarity_expr(expression.term, value)
return pols
def polarity_all_expr(expression, value):
| 64 | 64 | 24 | 8 | 55 | verypluming/SyGNS | scripts/nltk2pol.py | Python | polarity_all_expr | polarity_all_expr | 81 | 83 | 81 | 81 | 888e359f16bc637ad605febba892651dea2c4558 | bigcode/the-stack | train |
3e5a7032b09de168173ccd13 | train | function | def polarity_or_expr(expression, value):
left = polarity_expr(expression.first, value)
right = polarity_expr(expression.second, value)
pols = left + right
return pols
| def polarity_or_expr(expression, value):
| left = polarity_expr(expression.first, value)
right = polarity_expr(expression.second, value)
pols = left + right
return pols
| urry()
res = [(str(fun), value)]
return res
def polarity_and_expr(expression, value):
left = polarity_expr(expression.first, value)
right = polarity_expr(expression.second, value)
pols = left + right
return pols
def polarity_or_expr(expression, value):
| 64 | 64 | 41 | 8 | 55 | verypluming/SyGNS | scripts/nltk2pol.py | Python | polarity_or_expr | polarity_or_expr | 57 | 61 | 57 | 57 | 0ff72e14a31d294a8541e17b74d42ee528a61330 | bigcode/the-stack | train |
cab4b1703f31714433a67ebc | train | function | def rev_pol(value):
if value == 0:
out = 1
else:
out = 0
return out
| def rev_pol(value):
| if value == 0:
out = 1
else:
out = 0
return out
|
from nltk.sem.logic import ApplicationExpression
from nltk.sem.logic import AndExpression
from nltk.sem.logic import OrExpression
from nltk.sem.logic import ImpExpression
from nltk.sem.logic import NegatedExpression
from nltk.sem.logic import ExistsExpression
from nltk.sem.logic import AllExpression
def rev_pol(value)... | 63 | 64 | 31 | 5 | 57 | verypluming/SyGNS | scripts/nltk2pol.py | Python | rev_pol | rev_pol | 11 | 16 | 11 | 11 | 8c00087d4db5e3280b7dae1a483051bb7d2618ba | bigcode/the-stack | train |
60faa28c77a3c11d9378f838 | train | function | def polarity_and_expr(expression, value):
left = polarity_expr(expression.first, value)
right = polarity_expr(expression.second, value)
pols = left + right
return pols
| def polarity_and_expr(expression, value):
| left = polarity_expr(expression.first, value)
right = polarity_expr(expression.second, value)
pols = left + right
return pols
| ):
pols = polarity_all_expr(expression, value)
else:
pols = []
return pols
def polarity_application_expr(expression, value):
fun, args = expression.uncurry()
res = [(str(fun), value)]
return res
def polarity_and_expr(expression, value):
| 64 | 64 | 41 | 8 | 55 | verypluming/SyGNS | scripts/nltk2pol.py | Python | polarity_and_expr | polarity_and_expr | 50 | 54 | 50 | 50 | 783670a74c28e0094d55a89a5b0959c0b9821a0e | bigcode/the-stack | train |
08cbb42290ad5b56167550d2 | train | function | def calculate_polarity(expression):
pols = polarity_expr(expression, 1)
return pols
| def calculate_polarity(expression):
| pols = polarity_expr(expression, 1)
return pols
|
from nltk.sem.logic import NegatedExpression
from nltk.sem.logic import ExistsExpression
from nltk.sem.logic import AllExpression
def rev_pol(value):
if value == 0:
out = 1
else:
out = 0
return out
def calculate_polarity(expression):
| 64 | 64 | 23 | 7 | 56 | verypluming/SyGNS | scripts/nltk2pol.py | Python | calculate_polarity | calculate_polarity | 19 | 21 | 19 | 19 | 9d8c1174d15a91bc684f9b7c9a72fd9733745207 | bigcode/the-stack | train |
65e44a9c4763627ea924b88c | train | function | def polarity_imp_expr(expression, value):
left = polarity_expr(expression.first, rev_pol(value))
right = polarity_expr(expression.second, value)
pols = left + right
return pols
| def polarity_imp_expr(expression, value):
| left = polarity_expr(expression.first, rev_pol(value))
right = polarity_expr(expression.second, value)
pols = left + right
return pols
| value)
pols = left + right
return pols
def polarity_or_expr(expression, value):
left = polarity_expr(expression.first, value)
right = polarity_expr(expression.second, value)
pols = left + right
return pols
def polarity_imp_expr(expression, value):
| 64 | 64 | 43 | 8 | 55 | verypluming/SyGNS | scripts/nltk2pol.py | Python | polarity_imp_expr | polarity_imp_expr | 64 | 68 | 64 | 64 | f6510374976a1570e8ed047544a3ebb8c7983c38 | bigcode/the-stack | train |
7219fe27b56be2e86039d33e | train | function | def twitter_get_friend_list(username: str) -> dict:
"""
Get json with friends by username from twitter.
"""
reqest_url = "https://api.twitter.com/1.1/friends/list.json"
bearer_token = "AAAAAAAAAAAAAAAAAAAAAEMUNAEAAAAALiiYRGBM1bAuk5SG3CcMokTqTCk%3DtrUF8xGO2dBSvMGiWWQlv5Vm0DvLcdibTMqyLv4zVv14a7Rze7"
... | def twitter_get_friend_list(username: str) -> dict:
| """
Get json with friends by username from twitter.
"""
reqest_url = "https://api.twitter.com/1.1/friends/list.json"
bearer_token = "AAAAAAAAAAAAAAAAAAAAAEMUNAEAAAAALiiYRGBM1bAuk5SG3CcMokTqTCk%3DtrUF8xGO2dBSvMGiWWQlv5Vm0DvLcdibTMqyLv4zVv14a7Rze7"
headers = {
'Authorization': 'Bearer {}'... | '''
Lab 2, Task 2. Archakov Vsevolod.
'''
import requests
def twitter_get_friend_list(username: str) -> dict:
| 32 | 64 | 183 | 12 | 19 | SevkavTV/JSON_navigator-Lab2_Task2- | navigate_json.py | Python | twitter_get_friend_list | twitter_get_friend_list | 7 | 26 | 7 | 7 | 40a1df504068d36f1b04ad22fc5158ca7448f5b9 | bigcode/the-stack | train |
baac6996314fdcf31d28da02 | train | function | def search_by_keys(search_item):
if isinstance(search_item, dict):
for key in search_item.keys():
print(key + '\n')
search_key = ''
count = 0
while search_key not in search_item:
if count > 0:
print('There is no such key!!!')
count... | def search_by_keys(search_item):
| if isinstance(search_item, dict):
for key in search_item.keys():
print(key + '\n')
search_key = ''
count = 0
while search_key not in search_item:
if count > 0:
print('There is no such key!!!')
count += 1
search_key = in... | 'Bearer {}'.format(bearer_token)
}
params = {
'screen_name': f'@{username}',
'count': 15
}
response = requests.get(
reqest_url, headers=headers, params=params)
return response.json()['users']
def search_by_keys(search_item):
| 66 | 66 | 222 | 7 | 59 | SevkavTV/JSON_navigator-Lab2_Task2- | navigate_json.py | Python | search_by_keys | search_by_keys | 29 | 63 | 29 | 29 | 71b5ccd29962314bf2e6cd0af656b2349c5431ef | bigcode/the-stack | train |
7c3099bc6083910e90640e64 | train | class | class DistributedValue(object):
_multiprocess = False
def __init__(self, typ, metric_name, name, labelnames, labelvalues, multiprocess_mode='', **kwargs):
if typ == 'gauge':
# if multiprocess_mode == 'all':
# raise Exception('multiprocess_mode=all not supported in distribute... | class DistributedValue(object):
| _multiprocess = False
def __init__(self, typ, metric_name, name, labelnames, labelvalues, multiprocess_mode='', **kwargs):
if typ == 'gauge':
# if multiprocess_mode == 'all':
# raise Exception('multiprocess_mode=all not supported in distributed storage')
typ_pref... | ([core.Gauge.__wrapped__._type + '_' + mode for mode in core.Gauge.__wrapped__._MULTIPROC_MODES])
return __cached_get_all_typ
prometheus_cache_key_prefix = 'pcachekey.'
def get_cache_key(typ, hostname, pid, prometheus_cache_key_prefix=prometheus_cache_key_prefix):
return '{prometheus_cache_key_prefix}{typ};... | 126 | 126 | 420 | 5 | 120 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | DistributedValue | DistributedValue | 151 | 206 | 151 | 151 | a3d3aa9a1ad294af63b78ad450e7a3d4e4a2a752 | bigcode/the-stack | train |
2eb622c76a6943e9fe2cf567 | train | function | def mark_distributed_process_dead(pid):
remove_from_distributed_list(pid)
| def mark_distributed_process_dead(pid):
| remove_from_distributed_list(pid)
| .name + '_count', labels)] = acc
# Convert to correct sample format.
metric.samples = [core.Sample(name, dict(labels), value, samples_ts.get((name, labels))) for (name, labels), value in samples.items()]
return metrics.values()
def mark_distributed_process_dead(pid):
| 64 | 64 | 16 | 8 | 56 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | mark_distributed_process_dead | mark_distributed_process_dead | 329 | 330 | 329 | 329 | 488d5b2981bc115ec36f9c6d09ed626dd4842822 | bigcode/the-stack | train |
d976fd4392fcd12c321ffef4 | train | function | def remove_from_distributed_list(pid):
with gc_disabled():
with distributed_list_lock:
l = cache.get(distributed_list_cache_key, set())
if (hostname, pid) in l:
l.remove((hostname, pid))
if (hostname, pid) in added_to_distributed_list:
add... | def remove_from_distributed_list(pid):
| with gc_disabled():
with distributed_list_lock:
l = cache.get(distributed_list_cache_key, set())
if (hostname, pid) in l:
l.remove((hostname, pid))
if (hostname, pid) in added_to_distributed_list:
added_to_distributed_list.remove((hostname... | _list_lock:
l = cache.get(distributed_list_cache_key, set())
l.add((hostname, pid))
cache.set(distributed_list_cache_key, l, distributed_list_ttl_minutes * 60)
added_to_distributed_list.add((hostname, pid))
def remove_from_distributed_list(pid):
| 64 | 64 | 96 | 8 | 56 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | remove_from_distributed_list | remove_from_distributed_list | 100 | 110 | 100 | 100 | b0bf4b8518453f826bb23a46a6eb3ab2584685f4 | bigcode/the-stack | train |
e2d34829164c206891e59df5 | train | function | @contextmanager
def gc_disabled():
was_enabled_previously = gc.isenabled()
gc.disable()
yield
if was_enabled_previously:
gc.enable()
| @contextmanager
def gc_disabled():
| was_enabled_previously = gc.isenabled()
gc.disable()
yield
if was_enabled_previously:
gc.enable()
| _list'
distributed_list_lock = CacheLock(distributed_list_cache_key, ttl=20)
added_to_distributed_list = set()
distributed_list_ttl_minutes = 60 * 24 * 5
distributed_value_ttl_minutes = 60 * 24 * 5
@contextmanager
def gc_disabled():
| 64 | 64 | 36 | 8 | 55 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | gc_disabled | gc_disabled | 81 | 87 | 81 | 82 | 594751e2b1f9a2d670143e1ab9a6f05dafda3247 | bigcode/the-stack | train |
20999716645b8b39f56cf052 | train | class | class CacheLock(object):
def __init__(self, lock_id, ttl):
self.id = 'cachelock-{0}'.format(lock_id)
self.ttl = ttl
self.status = False
self.timeout_at = None
def __nonzero__(self):
return self.status
def __enter__(self):
trys = 40
while trys:
... | class CacheLock(object):
| def __init__(self, lock_id, ttl):
self.id = 'cachelock-{0}'.format(lock_id)
self.ttl = ttl
self.status = False
self.timeout_at = None
def __nonzero__(self):
return self.status
def __enter__(self):
trys = 40
while trys:
self.timeout_at = t... | _django_cache', 'default')]
hostname = socket.gethostname()
in_lock = None
lock = Lock()
class FakeSuccessContextManager(object):
def __nonzero__(self):
return True
def __enter__(self):
return self
def __exit__(self, *args):
pass
class CacheLock(object):
| 71 | 71 | 238 | 5 | 65 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | CacheLock | CacheLock | 39 | 69 | 39 | 39 | 8646e5f8e0e39489480cc2abc68f887242a9a5c8 | bigcode/the-stack | train |
47b88741c5fbb16ea7200222 | train | function | def add_to_distributed_list(pid):
if not (hostname, pid) in added_to_distributed_list:
with gc_disabled():
with distributed_list_lock:
l = cache.get(distributed_list_cache_key, set())
l.add((hostname, pid))
cache.set(distributed_list_cache_key, l, ... | def add_to_distributed_list(pid):
| if not (hostname, pid) in added_to_distributed_list:
with gc_disabled():
with distributed_list_lock:
l = cache.get(distributed_list_cache_key, set())
l.add((hostname, pid))
cache.set(distributed_list_cache_key, l, distributed_list_ttl_minutes * 60)... | 24 * 5
distributed_value_ttl_minutes = 60 * 24 * 5
@contextmanager
def gc_disabled():
was_enabled_previously = gc.isenabled()
gc.disable()
yield
if was_enabled_previously:
gc.enable()
def add_to_distributed_list(pid):
| 64 | 64 | 87 | 8 | 56 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | add_to_distributed_list | add_to_distributed_list | 90 | 97 | 90 | 90 | 6c6caee65a47c54fec2e748a4ddbfa410c065eaa | bigcode/the-stack | train |
1d9add4d07019006c216a6e7 | train | function | def get_all_typ():
from . import core
global __cached_get_all_typ
if __cached_get_all_typ is None:
__cached_get_all_typ = []
for name, obj in inspect.getmembers(core):
if inspect.isclass(obj):
typ = getattr(obj, '_type', None)
if typ:
... | def get_all_typ():
| from . import core
global __cached_get_all_typ
if __cached_get_all_typ is None:
__cached_get_all_typ = []
for name, obj in inspect.getmembers(core):
if inspect.isclass(obj):
typ = getattr(obj, '_type', None)
if typ:
__cached_ge... | (hostname, pid) in added_to_distributed_list:
added_to_distributed_list.remove((hostname, pid))
cache.set(distributed_list_cache_key, l, distributed_list_ttl_minutes * 60)
_pidFunc = os.getpid
__cached_get_all_typ = None
def get_all_typ():
| 64 | 64 | 168 | 5 | 58 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | get_all_typ | get_all_typ | 118 | 136 | 118 | 118 | 3452b42f3c8ddb87f1d7b79951bff25f56d25514 | bigcode/the-stack | train |
70e5051ae53ff68fe2bf7e27 | train | function | def deconstruct_cache_key(cache_key):
l = cache_key.replace(prometheus_cache_key_prefix, '').split(';')
return l
| def deconstruct_cache_key(cache_key):
| l = cache_key.replace(prometheus_cache_key_prefix, '').split(';')
return l
| prometheus_cache_key_prefix = 'pcachekey.'
def get_cache_key(typ, hostname, pid, prometheus_cache_key_prefix=prometheus_cache_key_prefix):
return '{prometheus_cache_key_prefix}{typ};{hostname};{pid}'.format(**locals())
def deconstruct_cache_key(cache_key):
| 64 | 64 | 28 | 8 | 56 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | deconstruct_cache_key | deconstruct_cache_key | 146 | 148 | 146 | 146 | a815132dc677016203657dd702c6a0b8e93ddf69 | bigcode/the-stack | train |
a7279d56c3d397237746278f | train | class | class FakeSuccessContextManager(object):
def __nonzero__(self):
return True
def __enter__(self):
return self
def __exit__(self, *args):
pass
| class FakeSuccessContextManager(object):
| def __nonzero__(self):
return True
def __enter__(self):
return self
def __exit__(self, *args):
pass
| from collections import defaultdict
from contextlib import contextmanager
from threading import Lock
from django.core.cache import caches
cache = caches[os.environ.get('prometheus_django_cache', 'default')]
hostname = socket.gethostname()
in_lock = None
lock = Lock()
class FakeSuccessContextManager(object):
| 64 | 64 | 43 | 7 | 57 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | FakeSuccessContextManager | FakeSuccessContextManager | 28 | 36 | 28 | 28 | f2b7b5796dd51baf85849f5a20216e56f186673b | bigcode/the-stack | train |
a03f1466ac3df1e6212b22c8 | train | class | class DistributedCollector(object):
def __init__(self, registry):
if registry:
registry.register(self)
self.accumulate = True
def collect(self):
cache_keys = set()
distributed_list = cache.get(distributed_list_cache_key, set())
for hostname, pid in distribute... | class DistributedCollector(object):
| def __init__(self, registry):
if registry:
registry.register(self)
self.accumulate = True
def collect(self):
cache_keys = set()
distributed_list = cache.get(distributed_list_cache_key, set())
for hostname, pid in distributed_list:
for typ in get_a... | hostname, pid)
def __get_dict(self):
return cache.get(self.cachekey, {})
def __set_dict(self, dict_value):
cache.set(self.cachekey, dict_value, distributed_value_ttl_minutes*60)
def __reset(self):
ts = int(time.time())
d = self.__get_dict()
if not self.valuekey in... | 256 | 256 | 1,026 | 5 | 250 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | DistributedCollector | DistributedCollector | 209 | 326 | 209 | 209 | 3686dd04bc43c1d4b722087c69e8b0378ff6fed4 | bigcode/the-stack | train |
6a2147b3646ad95629ee5abe | train | function | def get_cache_key(typ, hostname, pid, prometheus_cache_key_prefix=prometheus_cache_key_prefix):
return '{prometheus_cache_key_prefix}{typ};{hostname};{pid}'.format(**locals())
| def get_cache_key(typ, hostname, pid, prometheus_cache_key_prefix=prometheus_cache_key_prefix):
| return '{prometheus_cache_key_prefix}{typ};{hostname};{pid}'.format(**locals())
| type + '_' + mode for mode in core.Gauge.__wrapped__._MULTIPROC_MODES])
return __cached_get_all_typ
prometheus_cache_key_prefix = 'pcachekey.'
def get_cache_key(typ, hostname, pid, prometheus_cache_key_prefix=prometheus_cache_key_prefix):
| 63 | 64 | 44 | 23 | 40 | Sovetnikov/client_python | prometheus_client/distributed.py | Python | get_cache_key | get_cache_key | 142 | 143 | 142 | 142 | 1e1b170f5ef49429b11e5233392aedfffb2da809 | bigcode/the-stack | train |
eb02014ec3e379ba7bda3176 | train | function | def build_suite(args):
"""Build a test suite by loading TAP files or a TAP stream."""
loader = Loader()
if len(args.files) == 0 or args.files[0] == '-':
suite = loader.load_suite_from_stdin()
else:
suite = loader.load(args.files)
return suite
| def build_suite(args):
| """Build a test suite by loading TAP files or a TAP stream."""
loader = Loader()
if len(args.files) == 0 or args.files[0] == '-':
suite = loader.load_suite_from_stdin()
else:
suite = loader.load(args.files)
return suite
| stream=sys.stderr):
"""Entry point for ``tappy`` command."""
args = parse_args(argv)
suite = build_suite(args)
runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
result = runner.run(suite)
return get_status(result)
def build_suite(args):
| 64 | 64 | 68 | 5 | 59 | Mark-E-Hamilton/tappy | tap/main.py | Python | build_suite | build_suite | 21 | 28 | 21 | 21 | 82c78d7b0e24a8cb63521e67556335f49c8c72ae | bigcode/the-stack | train |
4baeb28ec9c6496e4e4c162b | train | function | def get_status(result):
"""Get a return status from the result."""
if result.wasSuccessful():
return 0
else:
return 1
| def get_status(result):
| """Get a return status from the result."""
if result.wasSuccessful():
return 0
else:
return 1
| to use a TAP stream on STDIN.
# But they probably didn't mean it if there is no pipe connected.
# In that case, print the help and exit.
if not args.files and sys.stdin.isatty():
sys.exit(parser.print_help())
return args
def get_status(result):
| 64 | 64 | 34 | 5 | 58 | Mark-E-Hamilton/tappy | tap/main.py | Python | get_status | get_status | 57 | 62 | 57 | 57 | 9b8f9ba2c1de89bdd2b2c44b850fbd0aefca60ea | bigcode/the-stack | train |
4206af1e94b72fa3f4a92700 | train | function | def main(argv=sys.argv, stream=sys.stderr):
"""Entry point for ``tappy`` command."""
args = parse_args(argv)
suite = build_suite(args)
runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
result = runner.run(suite)
return get_status(result)
| def main(argv=sys.argv, stream=sys.stderr):
| """Entry point for ``tappy`` command."""
args = parse_args(argv)
suite = build_suite(args)
runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
result = runner.run(suite)
return get_status(result)
| # Copyright (c) 2016, Matt Layman
import argparse
import sys
import unittest
from tap.i18n import _
from tap.loader import Loader
def main(argv=sys.argv, stream=sys.stderr):
| 45 | 64 | 65 | 10 | 34 | Mark-E-Hamilton/tappy | tap/main.py | Python | main | main | 11 | 18 | 11 | 11 | a847981bb6502587f35600875113762625422936 | bigcode/the-stack | train |
e0592e39d5488c14e72b9a31 | train | function | def parse_args(argv):
description = _('A TAP consumer for Python')
epilog = _(
'When no files are given or a dash (-) is used for the file name, '
'tappy will read a TAP stream from STDIN.')
parser = argparse.ArgumentParser(description=description, epilog=epilog)
parser.add_argument(
... | def parse_args(argv):
| description = _('A TAP consumer for Python')
epilog = _(
'When no files are given or a dash (-) is used for the file name, '
'tappy will read a TAP stream from STDIN.')
parser = argparse.ArgumentParser(description=description, epilog=epilog)
parser.add_argument(
'files', metavar=... | build_suite(args):
"""Build a test suite by loading TAP files or a TAP stream."""
loader = Loader()
if len(args.files) == 0 or args.files[0] == '-':
suite = loader.load_suite_from_stdin()
else:
suite = loader.load(args.files)
return suite
def parse_args(argv):
| 72 | 72 | 243 | 5 | 66 | Mark-E-Hamilton/tappy | tap/main.py | Python | parse_args | parse_args | 31 | 54 | 31 | 31 | 0864c710c64d618ab0e4723270e16f86eabb765b | bigcode/the-stack | train |
b157043fd82f0bc3d4d75208 | train | class | class SFASoapBinding(Binding):
def __getattr__(self, attr):
soap_callable = Binding.__getattr__(self, attr)
return SFACallable(soap_callable)
| class SFASoapBinding(Binding):
| def __getattr__(self, attr):
soap_callable = Binding.__getattr__(self, attr)
return SFACallable(soap_callable)
| xmlrpc_result
class SFACallable:
def __init__(self, soap_callable):
self.soap_callable = soap_callable
def __call__(self, *args):
outer_result = self.soap_callable(*args)
return outer_result['Result']
class SFASoapBinding(Binding):
| 64 | 64 | 42 | 9 | 55 | planetlab/sfa | sfa/util/soapprotocol.py | Python | SFASoapBinding | SFASoapBinding | 20 | 23 | 20 | 20 | 508b7c6c443a26d9d7d2a515f55cbf5ab5074d4b | bigcode/the-stack | train |
6d95c09f28278ad6caf550d0 | train | function | def get_server(url, key_file, cert_file):
auth = {
'transport' : HTTPSConnection,
'transdict' : {'cert_file' : cert_file,
'key_file' : key_file
},
}
return SFASoapBinding(url=url, **auth)
| def get_server(url, key_file, cert_file):
| auth = {
'transport' : HTTPSConnection,
'transdict' : {'cert_file' : cert_file,
'key_file' : key_file
},
}
return SFASoapBinding(url=url, **auth)
| _callable(*args)
return outer_result['Result']
class SFASoapBinding(Binding):
def __getattr__(self, attr):
soap_callable = Binding.__getattr__(self, attr)
return SFACallable(soap_callable)
def get_server(url, key_file, cert_file):
| 64 | 64 | 64 | 11 | 53 | planetlab/sfa | sfa/util/soapprotocol.py | Python | get_server | get_server | 26 | 34 | 26 | 26 | fab70fa03d109085b4a302759e2e92305dfeee7a | bigcode/the-stack | train |
e96f82004aff074e8343ce19 | train | class | class SFACallable:
def __init__(self, soap_callable):
self.soap_callable = soap_callable
def __call__(self, *args):
outer_result = self.soap_callable(*args)
return outer_result['Result']
| class SFACallable:
| def __init__(self, soap_callable):
self.soap_callable = soap_callable
def __call__(self, *args):
outer_result = self.soap_callable(*args)
return outer_result['Result']
| -specific code for SFA Client
from httplib import HTTPSConnection
from ZSI.client import Binding
def xmlrpc_like_callable (soap_callable, *x):
soap_result = soap_callable(*x)
xmlrpc_result = soap_result['Result']
return xmlrpc_result
class SFACallable:
| 64 | 64 | 51 | 6 | 57 | planetlab/sfa | sfa/util/soapprotocol.py | Python | SFACallable | SFACallable | 11 | 17 | 11 | 11 | 015e4d53ab62bd751c9e970a6d77d45d4f3f965b | bigcode/the-stack | train |
d48e04291768024bb45e9734 | train | function | def xmlrpc_like_callable (soap_callable, *x):
soap_result = soap_callable(*x)
xmlrpc_result = soap_result['Result']
return xmlrpc_result
| def xmlrpc_like_callable (soap_callable, *x):
| soap_result = soap_callable(*x)
xmlrpc_result = soap_result['Result']
return xmlrpc_result
| # SOAP-specific code for SFA Client
from httplib import HTTPSConnection
from ZSI.client import Binding
def xmlrpc_like_callable (soap_callable, *x):
| 35 | 64 | 37 | 12 | 22 | planetlab/sfa | sfa/util/soapprotocol.py | Python | xmlrpc_like_callable | xmlrpc_like_callable | 6 | 9 | 6 | 6 | 98b5c60a21aa73b240e0f30a2139838e586bcc7f | bigcode/the-stack | train |
1c336d43b5546479b20bbb4a | train | function | def _test_serialize(dataset):
pipeline = PcaFeaturesPipeline()
pipeline.write_pipeline()
pipeline.fit_serialize(dataset)
pipeline.deserialize_score(dataset)
pipeline.delete_pipeline()
pipeline.delete_serialized_pipeline()
| def _test_serialize(dataset):
| pipeline = PcaFeaturesPipeline()
pipeline.write_pipeline()
pipeline.fit_serialize(dataset)
pipeline.deserialize_score(dataset)
pipeline.delete_pipeline()
pipeline.delete_serialized_pipeline()
| from kf_d3m_primitives.feature_selection.pca_features.pca_features_pipeline import PcaFeaturesPipeline
def _test_serialize(dataset):
| 31 | 64 | 46 | 8 | 22 | cdbethune/d3m-primitives | tests/test_pcafeatures.py | Python | _test_serialize | _test_serialize | 3 | 10 | 3 | 4 | 866ee8e6f6ecb5be0fca24816ef30f11582a1633 | bigcode/the-stack | train |
0bcd59013d47fadc5cae3c1d | train | function | def test_serialization_dataset_baseball():
_test_serialize('185_baseball_MIN_METADATA')
| def test_serialization_dataset_baseball():
| _test_serialize('185_baseball_MIN_METADATA')
| ca_features_pipeline import PcaFeaturesPipeline
def _test_serialize(dataset):
pipeline = PcaFeaturesPipeline()
pipeline.write_pipeline()
pipeline.fit_serialize(dataset)
pipeline.deserialize_score(dataset)
pipeline.delete_pipeline()
pipeline.delete_serialized_pipeline()
def test_serializati... | 63 | 64 | 20 | 8 | 55 | cdbethune/d3m-primitives | tests/test_pcafeatures.py | Python | test_serialization_dataset_baseball | test_serialization_dataset_baseball | 12 | 13 | 12 | 12 | d39c6e2feb43486bd11aea998739a9a60ead1e3c | bigcode/the-stack | train |
d5ab5df625eff5b5edbfaafa | train | function | def save_pickled_compatible(obj_to_pickle, file_name):
'''
Save an object to the specified file in a backward compatible
way for Pybind objects. See:
http://pybind11.readthedocs.io/en/stable/advanced/classes.html#pickling-support
and https://github.com/pybind/pybind11/issues/271... | def save_pickled_compatible(obj_to_pickle, file_name):
| '''
Save an object to the specified file in a backward compatible
way for Pybind objects. See:
http://pybind11.readthedocs.io/en/stable/advanced/classes.html#pickling-support
and https://github.com/pybind/pybind11/issues/271
'''
try:
import cPickle as pickle #... | import pkgutil
import sys
def save_pickled_compatible(obj_to_pickle, file_name):
| 20 | 64 | 140 | 13 | 6 | oms1226/dlib-19.13 | tools/python/test/utils.py | Python | save_pickled_compatible | save_pickled_compatible | 4 | 17 | 4 | 4 | e60a474e6ab3f207cbe81f668f5e15d3dd9b3799 | bigcode/the-stack | train |
92878a31696bfa1b9336b31d | train | function | def is_numpy_installed():
'''
Returns True if Numpy is installed otherwise False
'''
if pkgutil.find_loader("numpy"):
return True
else:
return False
| def is_numpy_installed():
| '''
Returns True if Numpy is installed otherwise False
'''
if pkgutil.find_loader("numpy"):
return True
else:
return False
| 2.7
except ImportError:
import pickle
with open(file_name, "rb") as handle:
data = handle.read()
if not is_python3():
return pickle.loads(data)
else:
return pickle.loads(data, encoding="bytes")
def is_numpy_installed():
| 64 | 64 | 41 | 6 | 58 | oms1226/dlib-19.13 | tools/python/test/utils.py | Python | is_numpy_installed | is_numpy_installed | 35 | 42 | 35 | 35 | 406e346f5bfde56b351416007fadcf7f6a01cfe0 | bigcode/the-stack | train |
9e802dd6380053e6d045d408 | train | function | def load_pickled_compatible(file_name):
'''
Loads a pickled object from the specified file
'''
try:
import cPickle as pickle # Use cPickle on Python 2.7
except ImportError:
import pickle
with open(file_name, "rb") as handle:
data = handle.read()
... | def load_pickled_compatible(file_name):
| '''
Loads a pickled object from the specified file
'''
try:
import cPickle as pickle # Use cPickle on Python 2.7
except ImportError:
import pickle
with open(file_name, "rb") as handle:
data = handle.read()
if not is_python3():
retu... | Pickle as pickle # Use cPickle on Python 2.7
except ImportError:
import pickle
data = pickle.dumps(obj_to_pickle, 2)
with open(file_name, "wb") as handle:
handle.write(data)
def load_pickled_compatible(file_name):
| 64 | 64 | 100 | 9 | 55 | oms1226/dlib-19.13 | tools/python/test/utils.py | Python | load_pickled_compatible | load_pickled_compatible | 19 | 33 | 19 | 19 | defe9e95ebeea49b35950e0f9fd7ab8c3f4ada9f | bigcode/the-stack | train |
33a11f6cc55f58f4a7348595 | train | function | def is_python3():
'''
Returns True if using Python 3 or above, otherwise False
'''
return sys.version_info >= (3, 0)
| def is_python3():
| '''
Returns True if using Python 3 or above, otherwise False
'''
return sys.version_info >= (3, 0)
| return pickle.loads(data)
else:
return pickle.loads(data, encoding="bytes")
def is_numpy_installed():
'''
Returns True if Numpy is installed otherwise False
'''
if pkgutil.find_loader("numpy"):
return True
else:
return False
def is_python3():
| 64 | 64 | 35 | 5 | 58 | oms1226/dlib-19.13 | tools/python/test/utils.py | Python | is_python3 | is_python3 | 44 | 48 | 44 | 44 | f7c41a3b15b085eca4ed6199335e8b3280cb1baa | bigcode/the-stack | train |
784039e67ee8319be36dc6d3 | train | function | def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_len... | def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
| """Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeatur... | features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature([feature.label_id])
features["is_real_example"] = create_int_feature(
[int(feature.is_real_example)])
tf_example = tf.... | 112 | 112 | 374 | 20 | 92 | cclauss/biobert | run_re.py | Python | file_based_input_fn_builder | file_based_input_fn_builder | 549 | 594 | 549 | 550 | 4e2fb53eec2edca3d23d034bc022c0723daae5c7 | bigcode/the-stack | train |
98f50f5f45baddff56c47b13 | train | function | def input_fn_builder(features, seq_length, is_training, drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
all_input_ids = []
all_input_mask = []
all_segment_ids = []
all_label_ids = []
for feature in features:
all_input_ids.append(feature.input_ids)
all_input_mask.... | def input_fn_builder(features, seq_length, is_training, drop_remainder):
| """Creates an `input_fn` closure to be passed to TPUEstimator."""
all_input_ids = []
all_input_mask = []
all_segment_ids = []
all_label_ids = []
for feature in features:
all_input_ids.append(feature.input_ids)
all_input_mask.append(feature.input_mask)
all_segment_ids.append(feature.segment_ids... | ,
eval_metrics=eval_metrics,
scaffold_fn=scaffold_fn)
else:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions={"probabilities": probabilities},
scaffold_fn=scaffold_fn)
return output_spec
return model_fn
# This function is not used... | 105 | 105 | 352 | 16 | 89 | cclauss/biobert | run_re.py | Python | input_fn_builder | input_fn_builder | 753 | 802 | 753 | 753 | 12613b5108e4e0b285cfdc180ac342ac6dbbe662 | bigcode/the-stack | train |
958686418446d663218dad66 | train | class | class XnliProcessor(DataProcessor):
"""Processor for the XNLI data set."""
def __init__(self):
self.language = "zh"
def get_train_examples(self, data_dir):
"""See base class."""
lines = self._read_tsv(
os.path.join(data_dir, "multinli",
"multinli.train.%s.tsv" % self.lan... | class XnliProcessor(DataProcessor):
| """Processor for the XNLI data set."""
def __init__(self):
self.language = "zh"
def get_train_examples(self, data_dir):
"""See base class."""
lines = self._read_tsv(
os.path.join(data_dir, "multinli",
"multinli.train.%s.tsv" % self.language))
examples = []
for (i... | InputExample`s for prediction."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
@classmethod
def _read_tsv(cls, input_file, quotechar=None):
"""Reads a tab separated value file."""
with tf.gfile.Open(input_file,... | 123 | 123 | 412 | 8 | 114 | cclauss/biobert | run_re.py | Python | XnliProcessor | XnliProcessor | 207 | 252 | 207 | 207 | 2a356ff239219f213a92d8d4f83a12422e262382 | bigcode/the-stack | train |
9004ba8ea1939d950a9af207 | train | function | def convert_examples_to_features(examples, label_list, max_seq_length,
tokenizer):
"""Convert a set of `InputExample`s to a list of `InputFeatures`."""
features = []
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing examp... | def convert_examples_to_features(examples, label_list, max_seq_length,
tokenizer):
| """Convert a set of `InputExample`s to a list of `InputFeatures`."""
features = []
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index, example, label_list,
... | =batch_size, drop_remainder=drop_remainder)
return d
return input_fn
# This function is not used by this file but is still used by the Colab and
# people who depend on it.
def convert_examples_to_features(examples, label_list, max_seq_length,
tokenizer):
| 64 | 64 | 118 | 18 | 46 | cclauss/biobert | run_re.py | Python | convert_examples_to_features | convert_examples_to_features | 807 | 820 | 807 | 808 | 7204535d5653e439749cedb03b1ec77319757bf0 | bigcode/the-stack | train |
6eeb8f81b4ea5be6cd926aaf | train | function | def convert_single_example(ex_index, example, label_list, max_seq_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[0... | def convert_single_example(ex_index, example, label_list, max_seq_length,
tokenizer):
| """Converts a single `InputExample` into a single `InputFeatures`."""
if isinstance(example, PaddingInputExample):
return InputFeatures(
input_ids=[0] * max_seq_length,
input_mask=[0] * max_seq_length,
segment_ids=[0] * max_seq_length,
label_id=0,
is_real_example=False)
... | .join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_... | 256 | 256 | 1,002 | 19 | 236 | cclauss/biobert | run_re.py | Python | convert_single_example | convert_single_example | 417 | 516 | 417 | 418 | 0dc7963c53a263f6afc14b33121e2ba4f1bf8826 | bigcode/the-stack | train |
ec48c1b6a004379e2c2aef09 | train | class | class BioBERTProcessor(DataProcessor):
"""Processor for the BioBERT data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""S... | class BioBERTProcessor(DataProcessor):
| """Processor for the BioBERT data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._crea... | % (set_type, i)
text_a = tokenization.convert_to_unicode(line[3])
text_b = tokenization.convert_to_unicode(line[4])
if set_type == "test":
label = "0"
else:
label = tokenization.convert_to_unicode(line[0])
examples.append(
InputExample(guid=guid, text_a=text_a, t... | 100 | 100 | 334 | 8 | 91 | cclauss/biobert | run_re.py | Python | BioBERTProcessor | BioBERTProcessor | 335 | 373 | 335 | 335 | 60bf7211301a7243464e9c81001dc7b6450ef37f | bigcode/the-stack | train |
8005ddc12cfd7ce1b3a16363 | train | class | class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
input_ids,
input_mask,
segment_ids,
label_id,
is_real_example=True):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_id... | class InputFeatures(object):
| """A single set of features of data."""
def __init__(self,
input_ids,
input_mask,
segment_ids,
label_id,
is_real_example=True):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.labe... | batch
size. The alternative is to drop the last batch, which is bad because it means
the entire output data won't be generated.
We use this class instead of `None` because treating `None` as padding
battches could cause silent errors.
"""
class InputFeatures(object):
| 63 | 64 | 86 | 5 | 58 | cclauss/biobert | run_re.py | Python | InputFeatures | InputFeatures | 161 | 174 | 161 | 161 | df2f8d3e74cacf24046502271b9345feaa1ad4d2 | bigcode/the-stack | train |
361264cfbb54ae450e78754c | train | class | class ColaProcessor(DataProcessor):
"""Processor for the CoLA data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See bas... | class ColaProcessor(DataProcessor):
| """Processor for the CoLA data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_... | s" % (set_type, i)
if set_type == "test":
text_a = tokenization.convert_to_unicode(line[1])
label = "0"
else:
text_a = tokenization.convert_to_unicode(line[0])
label = tokenization.convert_to_unicode(line[1])
examples.append(
InputExample(guid=guid, text_a=tex... | 99 | 99 | 331 | 6 | 92 | cclauss/biobert | run_re.py | Python | ColaProcessor | ColaProcessor | 376 | 414 | 376 | 376 | 1699ab585f7f9b981c91473c48368f511417e6a3 | bigcode/the-stack | train |
6882c23e5d1b9922449cd363 | train | function | def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"cola": ColaProcessor,
"mnli": MnliProcessor,
"mrpc": MrpcProcessor,
"xnli": XnliProcessor,
"gad": BioBERTProcessor,
"polysearch": BioBERTProcessor,
"mirnadisease": BioBERTProcessor,
"euadr": BioBE... | def main(_):
| tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"cola": ColaProcessor,
"mnli": MnliProcessor,
"mrpc": MrpcProcessor,
"xnli": XnliProcessor,
"gad": BioBERTProcessor,
"polysearch": BioBERTProcessor,
"mirnadisease": BioBERTProcessor,
"euadr": BioBERTProcessor,
... | ],
dtype=tf.int32),
"segment_ids":
tf.constant(
all_segment_ids,
shape=[num_examples, seq_length],
dtype=tf.int32),
"label_ids":
tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),
})
if is_tra... | 256 | 256 | 1,847 | 4 | 251 | cclauss/biobert | run_re.py | Python | main | main | 823 | 1,018 | 823 | 823 | ba396b836afcaccdf77d7060ea1bcff93e106641 | bigcode/the-stack | train |
7c36ec60ada1cfd9917779fe | train | function | def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer, output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logg... | def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer, output_file):
| """Convert a set of `InputExample`s to a TFRecord file."""
writer = tf.python_io.TFRecordWriter(output_file)
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (ex_index, len(examples)))
feature = convert_single_example(ex_index,... | id = %d)" % (example.label, label_id))
feature = InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
is_real_example=True)
return feature
def file_based_convert_examples_to_features(
examples, label_list, max_seq_length, tokenizer... | 78 | 78 | 263 | 23 | 54 | cclauss/biobert | run_re.py | Python | file_based_convert_examples_to_features | file_based_convert_examples_to_features | 519 | 546 | 519 | 520 | fdebcc3ce4d7b385ca6a3be5cdf890b01e4fcb2e | bigcode/the-stack | train |
d002d9eb622a9dd1406e2604 | train | function | def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-arg... | def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
| """Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, f... | _initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, outpu... | 228 | 228 | 762 | 38 | 190 | cclauss/biobert | run_re.py | Python | model_fn_builder | model_fn_builder | 659 | 748 | 659 | 661 | bbb56635cbb2a6e0a0f59645efcadfebbf7d0ded | bigcode/the-stack | train |
69c7440badbb3ce4f32a54c5 | train | class | class MrpcProcessor(DataProcessor):
"""Processor for the MRPC data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See bas... | class MrpcProcessor(DataProcessor):
| """Processor for the MRPC data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_... | text_a = tokenization.convert_to_unicode(line[8])
text_b = tokenization.convert_to_unicode(line[9])
if set_type == "test":
label = "contradiction"
else:
label = tokenization.convert_to_unicode(line[-1])
examples.append(
InputExample(guid=guid, text_a=text_a, text_... | 94 | 94 | 316 | 7 | 86 | cclauss/biobert | run_re.py | Python | MrpcProcessor | MrpcProcessor | 296 | 333 | 296 | 296 | d4cf55ff37b853dcb9b7f3faa6aa71bcc2f3043d | bigcode/the-stack | train |
8466d2ab3f2e7b17c158c924 | train | class | class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For s... | class InputExample(object):
| """A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks... | "metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
class InputExample(object):
| 63 | 64 | 177 | 5 | 58 | cclauss/biobert | run_re.py | Python | InputExample | InputExample | 127 | 145 | 127 | 127 | aed6d08bca36f2d00edbf1f0e419e3093d7bd4ca | bigcode/the-stack | train |
f4f8c92ac69c3010b4ae7b1a | train | function | def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one s... | def _truncate_seq_pair(tokens_a, tokens_b, max_length):
| """Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncat... | d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
| 64 | 64 | 146 | 14 | 49 | cclauss/biobert | run_re.py | Python | _truncate_seq_pair | _truncate_seq_pair | 597 | 611 | 597 | 597 | e0549efd31813094d65cd90ad15dfcd4e0c0a190 | bigcode/the-stack | train |
f2be1604a9e2732a62bfdfc3 | train | class | class PaddingInputExample(object):
"""Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. The alternative is to drop the last batch, w... | class PaddingInputExample(object):
| """Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. The alternative is to drop the last batch, which is bad because it means
the ... | Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class PaddingInputExample(object):
| 64 | 64 | 116 | 6 | 57 | cclauss/biobert | run_re.py | Python | PaddingInputExample | PaddingInputExample | 148 | 158 | 148 | 148 | 087437aaf9a5b7b06a67fb01434ed0eba552276e | bigcode/the-stack | train |
9dd63d98dc7fc93fa2988066 | train | class | class MnliProcessor(DataProcessor):
"""Processor for the MultiNLI data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See... | class MnliProcessor(DataProcessor):
| """Processor for the MultiNLI data set (GLUE version)."""
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._cre... | text_a = tokenization.convert_to_unicode(line[6])
text_b = tokenization.convert_to_unicode(line[7])
label = tokenization.convert_to_unicode(line[1])
examples.append(
InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
def get_labels(self):
"""See b... | 101 | 102 | 340 | 7 | 94 | cclauss/biobert | run_re.py | Python | MnliProcessor | MnliProcessor | 255 | 293 | 255 | 255 | df1d9134d8434642296d07f7fa1790d4cc35819c | bigcode/the-stack | train |
4f3951c6300f0041a9ac8a5a | train | function | def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
labels, num_labels, use_one_hot_embeddings):
"""Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_ma... | def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
labels, num_labels, use_one_hot_embeddings):
| """Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
# In the demo, we are doing a simple classifica... | of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()... | 111 | 111 | 371 | 30 | 81 | cclauss/biobert | run_re.py | Python | create_model | create_model | 614 | 656 | 614 | 615 | 0de2005be46f972696fccca82387bc90b3663337 | bigcode/the-stack | train |
97d378364d25f8a6c6277f4c | train | class | class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `In... | class DataProcessor(object):
| """Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set.... | input_mask,
segment_ids,
label_id,
is_real_example=True):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
self.is_real_example = is_real_example
class DataProcessor(object):
| 64 | 64 | 212 | 5 | 58 | cclauss/biobert | run_re.py | Python | DataProcessor | DataProcessor | 177 | 204 | 177 | 177 | 1fb008be080630c086a32cc34d7077f421ed8163 | bigcode/the-stack | train |
52d30ba038b4dd95db176482 | train | class | class Namespace:
def __init__(self, api_server_authorized_ip_ranges=None, cluster_autoscaler_profile=None):
self.api_server_authorized_ip_ranges = api_server_authorized_ip_ranges
self.cluster_autoscaler_profile = cluster_autoscaler_profile
| class Namespace:
| def __init__(self, api_server_authorized_ip_ranges=None, cluster_autoscaler_profile=None):
self.api_server_authorized_ip_ranges = api_server_authorized_ip_ranges
self.cluster_autoscaler_profile = cluster_autoscaler_profile
| :67cf"
namespace = Namespace(api_server_authorized_ip_ranges)
err = "--api-server-authorized-ip-ranges cannot be IPv6 addresses"
with self.assertRaises(CLIError) as cm:
validators.validate_ip_ranges(namespace)
self.assertEqual(str(cm.exception), err)
class Namespace:
| 64 | 64 | 55 | 3 | 61 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | Namespace | Namespace | 100 | 103 | 100 | 100 | e0fa7cb7bd7e58b851b1c739f07ce43692ce17ab | bigcode/the-stack | train |
cff57db4c863ece91fb86ad1 | train | class | class TestCredentialFormat(unittest.TestCase):
def test_invalid_format(self):
credential_format = "foobar"
namespace = CredentialFormatNamespace(credential_format)
err = ("--format can only be azure or exec.")
with self.assertRaises(CLIError) as cm:
validators.validate_c... | class TestCredentialFormat(unittest.TestCase):
| def test_invalid_format(self):
credential_format = "foobar"
namespace = CredentialFormatNamespace(credential_format)
err = ("--format can only be azure or exec.")
with self.assertRaises(CLIError) as cm:
validators.validate_credential_format(namespace)
self.assert... | ": "Microsoft.ContainerService/AKSTestFeaturePreview,Microsoft.ContainerService/AKSExampleFeaturePreview"}
self.assertEqual(t16, g16)
class CredentialFormatNamespace:
def __init__(self, credential_format):
self.credential_format = credential_format
class TestCredentialFormat(unittest.TestCase):
| 64 | 64 | 107 | 8 | 55 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | TestCredentialFormat | TestCredentialFormat | 379 | 393 | 379 | 379 | 8b450ad603eca823fc168dabe33f0ba6203d073b | bigcode/the-stack | train |
4eaa749a371687f0d2daa471 | train | class | class MaxSurgeNamespace:
def __init__(self, max_surge):
self.max_surge = max_surge
| class MaxSurgeNamespace:
| def __init__(self, max_surge):
self.max_surge = max_surge
| = VnetSubnetIdNamespace(invalid_vnet_subnet_id)
validators.validate_vnet_subnet_id(namespace)
class VnetSubnetIdNamespace:
def __init__(self, vnet_subnet_id):
self.vnet_subnet_id = vnet_subnet_id
class MaxSurgeNamespace:
| 64 | 64 | 27 | 6 | 57 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | MaxSurgeNamespace | MaxSurgeNamespace | 137 | 139 | 137 | 137 | 229904da80e1ca3710c1ebb6f9a3da35dc0bc28b | bigcode/the-stack | train |
6d5ed30c6856298539f5dd92 | train | class | class CredentialFormatNamespace:
def __init__(self, credential_format):
self.credential_format = credential_format
| class CredentialFormatNamespace:
| def __init__(self, credential_format):
self.credential_format = credential_format
| ending_values_to_same_key=True)
g16 = {"WindowsContainerRuntime": "containerd", "AKSHTTPCustomFeatures": "Microsoft.ContainerService/AKSTestFeaturePreview,Microsoft.ContainerService/AKSExampleFeaturePreview"}
self.assertEqual(t16, g16)
class CredentialFormatNamespace:
| 64 | 64 | 24 | 5 | 59 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | CredentialFormatNamespace | CredentialFormatNamespace | 374 | 376 | 374 | 374 | d372abcfc8c7542a820455939ce54b8f70f43626 | bigcode/the-stack | train |
ce075bd1b14357d23a877505 | train | class | class TestLabels(unittest.TestCase):
def test_invalid_labels_prefix(self):
invalid_labels = "k8s##.io/label1=value"
namespace = LabelsNamespace(invalid_labels)
err = ("Invalid label: k8s##.io/label1=value. Prefix part a DNS-1123 label must consist of lower case "
"alphanumeric... | class TestLabels(unittest.TestCase):
| def test_invalid_labels_prefix(self):
invalid_labels = "k8s##.io/label1=value"
namespace = LabelsNamespace(invalid_labels)
err = ("Invalid label: k8s##.io/label1=value. Prefix part a DNS-1123 label must consist of lower case "
"alphanumeric characters or '-', and must start an... | invalid_vnet_subnet_id = ""
namespace = VnetSubnetIdNamespace(invalid_vnet_subnet_id)
validators.validate_vnet_subnet_id(namespace)
class VnetSubnetIdNamespace:
def __init__(self, vnet_subnet_id):
self.vnet_subnet_id = vnet_subnet_id
class MaxSurgeNamespace:
def __init__(self, max_s... | 256 | 256 | 1,099 | 7 | 249 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | TestLabels | TestLabels | 159 | 255 | 159 | 159 | 1c3a7d591b9b6ff831a02be0d9e62df9da53aca7 | bigcode/the-stack | train |
6a5f3c5eb0229bac12db2ae5 | train | class | class TestVNetSubnetId(unittest.TestCase):
def test_invalid_vnet_subnet_id(self):
invalid_vnet_subnet_id = "dummy subnet id"
namespace = VnetSubnetIdNamespace(invalid_vnet_subnet_id)
err = ("--vnet-subnet-id is not a valid Azure resource ID.")
with self.assertRaises(CLIError) as cm:... | class TestVNetSubnetId(unittest.TestCase):
| def test_invalid_vnet_subnet_id(self):
invalid_vnet_subnet_id = "dummy subnet id"
namespace = VnetSubnetIdNamespace(invalid_vnet_subnet_id)
err = ("--vnet-subnet-id is not a valid Azure resource ID.")
with self.assertRaises(CLIError) as cm:
validators.validate_vnet_subne... | validators.validate_ip_ranges(namespace)
self.assertEqual(str(cm.exception), err)
class Namespace:
def __init__(self, api_server_authorized_ip_ranges=None, cluster_autoscaler_profile=None):
self.api_server_authorized_ip_ranges = api_server_authorized_ip_ranges
self.cluster_autoscaler_prof... | 81 | 81 | 270 | 10 | 70 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | TestVNetSubnetId | TestVNetSubnetId | 106 | 129 | 106 | 106 | 8c5a8e3d2bc5e577ba5e24fc81b8e841ff4bc977 | bigcode/the-stack | train |
8818a274068594ac67e89e41 | train | class | class TestExtractCommaSeparatedString(unittest.TestCase):
def test_extract_comma_separated_string(self):
s1 = None
t1 = validators.extract_comma_separated_string(s1, keep_none=True, default_value="")
g1 = None
self.assertEqual(t1, g1)
s2 = None
t2 = validators.extrac... | class TestExtractCommaSeparatedString(unittest.TestCase):
| def test_extract_comma_separated_string(self):
s1 = None
t1 = validators.extract_comma_separated_string(s1, keep_none=True, default_value="")
g1 = None
self.assertEqual(t1, g1)
s2 = None
t2 = validators.extract_comma_separated_string(s2, keep_none=False, default_valu... | pool_labels(namespace)
class LabelsNamespace:
def __init__(self, labels):
self.labels = labels
class AssignIdentityNamespace:
def __init__(self, assign_identity):
self.assign_identity = assign_identity
class TestAssignIdentity(unittest.TestCase):
def test_invalid_identity_id(self):
... | 256 | 256 | 1,018 | 10 | 246 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | TestExtractCommaSeparatedString | TestExtractCommaSeparatedString | 294 | 371 | 294 | 294 | 65f22f09eb662d7f35bc3f7c5c3a21d8ae72ef5b | bigcode/the-stack | train |
c3aea7001134eb712052f480 | train | class | class MockCLI(CLI):
def __init__(self):
super(MockCLI, self).__init__(cli_name='mock_cli', config_dir=GLOBAL_CONFIG_DIR,
config_env_var_prefix=ENV_VAR_PREFIX, commands_loader_cls=MockLoader)
self.cloud = get_active_cloud(self)
| class MockCLI(CLI):
| def __init__(self):
super(MockCLI, self).__init__(cli_name='mock_cli', config_dir=GLOBAL_CONFIG_DIR,
config_env_var_prefix=ENV_VAR_PREFIX, commands_loader_cls=MockLoader)
self.cloud = get_active_cloud(self)
| import GLOBAL_CONFIG_DIR, ENV_VAR_PREFIX
from azure.cli.core.cloud import get_active_cloud
from azure.cli.core.profiles import get_sdk, ResourceType, supported_api_version
from azure.cli.core.util import CLIError
from azure.cli.command_modules.acs import _validators as validators
class MockCLI(CLI):
| 64 | 64 | 61 | 6 | 57 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | MockCLI | MockCLI | 18 | 22 | 18 | 18 | c1848f5a01d1e8f09e9e8d038684c03dde4a23ee | bigcode/the-stack | train |
ab6b7cb089ead7a333614bdd | train | class | class AssignIdentityNamespace:
def __init__(self, assign_identity):
self.assign_identity = assign_identity
| class AssignIdentityNamespace:
| def __init__(self, assign_identity):
self.assign_identity = assign_identity
| /label=value")
validators.validate_nodepool_labels(namespace)
namespace = LabelsNamespace(["k8s.io/label=value", "label2=value2"])
validators.validate_nodepool_labels(namespace)
class LabelsNamespace:
def __init__(self, labels):
self.labels = labels
class AssignIdentityNamespace:
| 64 | 64 | 23 | 5 | 58 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | AssignIdentityNamespace | AssignIdentityNamespace | 263 | 265 | 263 | 263 | 4cc81809cb5b2661a5b2512c336bd0552b19e7bf | bigcode/the-stack | train |
b4ef6a0c13a81ff42c0b9716 | train | class | class VnetSubnetIdNamespace:
def __init__(self, vnet_subnet_id):
self.vnet_subnet_id = vnet_subnet_id
| class VnetSubnetIdNamespace:
| def __init__(self, vnet_subnet_id):
self.vnet_subnet_id = vnet_subnet_id
| )
validators.validate_vnet_subnet_id(namespace)
def test_empty_vnet_subnet_id(self):
invalid_vnet_subnet_id = ""
namespace = VnetSubnetIdNamespace(invalid_vnet_subnet_id)
validators.validate_vnet_subnet_id(namespace)
class VnetSubnetIdNamespace:
| 64 | 64 | 34 | 7 | 57 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | VnetSubnetIdNamespace | VnetSubnetIdNamespace | 132 | 134 | 132 | 132 | 4d26b66500a6f1de1f315d91e063111186ce8e8e | bigcode/the-stack | train |
2a79ac29f75cdab86989af1b | train | class | class MockCmd(object):
def __init__(self, ctx, arguments={}):
self.cli_ctx = ctx
self.loader = MockLoader(self.cli_ctx)
self.arguments = arguments
def get_models(self, *attr_args, **kwargs):
return get_sdk(self.cli_ctx, ResourceType.MGMT_CONTAINERSERVICE, 'ManagedClusterProperti... | class MockCmd(object):
| def __init__(self, ctx, arguments={}):
self.cli_ctx = ctx
self.loader = MockLoader(self.cli_ctx)
self.arguments = arguments
def get_models(self, *attr_args, **kwargs):
return get_sdk(self.cli_ctx, ResourceType.MGMT_CONTAINERSERVICE, 'ManagedClusterPropertiesAutoScalerProfile',
... | def get_models(self, *attr_args, **_):
from azure.cli.core.profiles import get_sdk
return get_sdk(self.ctx, ResourceType.MGMT_CONTAINERSERVICE, 'ManagedClusterPropertiesAutoScalerProfile',
mod='models', operation_group='managed_clusters')
class MockCmd(object):
| 64 | 64 | 89 | 5 | 59 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | MockCmd | MockCmd | 35 | 43 | 35 | 35 | ba63b51546fe6e1a5eaee784c3e263a287d36b15 | bigcode/the-stack | train |
3d3477294ca8c7191edd5632 | train | class | class TestMaxSurge(unittest.TestCase):
def test_valid_cases(self):
valid = ["5", "33%", "1", "100%"]
for v in valid:
validators.validate_max_surge(MaxSurgeNamespace(v))
def test_throws_on_string(self):
with self.assertRaises(CLIError) as cm:
validators.validate_m... | class TestMaxSurge(unittest.TestCase):
| def test_valid_cases(self):
valid = ["5", "33%", "1", "100%"]
for v in valid:
validators.validate_max_surge(MaxSurgeNamespace(v))
def test_throws_on_string(self):
with self.assertRaises(CLIError) as cm:
validators.validate_max_surge(MaxSurgeNamespace("foobar"))
... | :
def __init__(self, vnet_subnet_id):
self.vnet_subnet_id = vnet_subnet_id
class MaxSurgeNamespace:
def __init__(self, max_surge):
self.max_surge = max_surge
class TestMaxSurge(unittest.TestCase):
| 64 | 64 | 154 | 9 | 54 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | TestMaxSurge | TestMaxSurge | 142 | 156 | 142 | 142 | 30a5a607e038801110755b830da19293abd0a993 | bigcode/the-stack | train |
9d6aaa5d1f623fd01cee0c46 | train | class | class LabelsNamespace:
def __init__(self, labels):
self.labels = labels
| class LabelsNamespace:
| def __init__(self, labels):
self.labels = labels
| ), err)
def test_valid_labels(self):
namespace = LabelsNamespace("k8s.io/label=value")
validators.validate_nodepool_labels(namespace)
namespace = LabelsNamespace(["k8s.io/label=value", "label2=value2"])
validators.validate_nodepool_labels(namespace)
class LabelsNamespace:
| 64 | 64 | 19 | 4 | 60 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | LabelsNamespace | LabelsNamespace | 258 | 260 | 258 | 258 | 2936b0a607b33869f7b267ae19ca1a4fd25b3d70 | bigcode/the-stack | train |
8b0e51bc09492705e05157f3 | train | class | class MockLoader(object):
def __init__(self, ctx):
self.ctx = ctx
def get_models(self, *attr_args, **_):
from azure.cli.core.profiles import get_sdk
return get_sdk(self.ctx, ResourceType.MGMT_CONTAINERSERVICE, 'ManagedClusterPropertiesAutoScalerProfile',
mod='mode... | class MockLoader(object):
| def __init__(self, ctx):
self.ctx = ctx
def get_models(self, *attr_args, **_):
from azure.cli.core.profiles import get_sdk
return get_sdk(self.ctx, ResourceType.MGMT_CONTAINERSERVICE, 'ManagedClusterPropertiesAutoScalerProfile',
mod='models', operation_group='mana... | CLI(CLI):
def __init__(self):
super(MockCLI, self).__init__(cli_name='mock_cli', config_dir=GLOBAL_CONFIG_DIR,
config_env_var_prefix=ENV_VAR_PREFIX, commands_loader_cls=MockLoader)
self.cloud = get_active_cloud(self)
class MockLoader(object):
| 64 | 64 | 79 | 5 | 59 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | MockLoader | MockLoader | 25 | 32 | 25 | 25 | 7cdee232dd4699fb2e98356bc28e6ae3cca73e10 | bigcode/the-stack | train |
06a33dfbf19f238c49c09b1d | train | class | class TestAssignIdentity(unittest.TestCase):
def test_invalid_identity_id(self):
invalid_identity_id = "dummy identity id"
namespace = AssignIdentityNamespace(invalid_identity_id)
err = ("--assign-identity is not a valid Azure resource ID.")
with self.assertRaises(CLIError) as cm:
... | class TestAssignIdentity(unittest.TestCase):
| def test_invalid_identity_id(self):
invalid_identity_id = "dummy identity id"
namespace = AssignIdentityNamespace(invalid_identity_id)
err = ("--assign-identity is not a valid Azure resource ID.")
with self.assertRaises(CLIError) as cm:
validators.validate_assign_identit... | "label2=value2"])
validators.validate_nodepool_labels(namespace)
class LabelsNamespace:
def __init__(self, labels):
self.labels = labels
class AssignIdentityNamespace:
def __init__(self, assign_identity):
self.assign_identity = assign_identity
class TestAssignIdentity(unittest.TestC... | 64 | 64 | 200 | 8 | 55 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | TestAssignIdentity | TestAssignIdentity | 268 | 291 | 268 | 268 | 5aedbdcf3a6df3ef2955b2f9a90a1bc002594e00 | bigcode/the-stack | train |
9f8a10068b97f9677d54e3f4 | train | class | class TestValidateIPRanges(unittest.TestCase):
def test_simultaneous_allow_and_disallow_with_spaces(self):
api_server_authorized_ip_ranges = " 0.0.0.0/32 , 129.1.1.1.1 "
namespace = Namespace(api_server_authorized_ip_ranges)
err = ("Setting --api-server-authorized-ip-ranges to 0.0.0.0/32 is ... | class TestValidateIPRanges(unittest.TestCase):
| def test_simultaneous_allow_and_disallow_with_spaces(self):
api_server_authorized_ip_ranges = " 0.0.0.0/32 , 129.1.1.1.1 "
namespace = Namespace(api_server_authorized_ip_ranges)
err = ("Setting --api-server-authorized-ip-ranges to 0.0.0.0/32 is not allowed with other IP ranges."
... | Loader(object):
def __init__(self, ctx):
self.ctx = ctx
def get_models(self, *attr_args, **_):
from azure.cli.core.profiles import get_sdk
return get_sdk(self.ctx, ResourceType.MGMT_CONTAINERSERVICE, 'ManagedClusterPropertiesAutoScalerProfile',
mod='models', opera... | 175 | 175 | 585 | 9 | 166 | SaurabhSharma-MSFT/azure-cli | src/azure-cli/azure/cli/command_modules/acs/tests/latest/test_validators.py | Python | TestValidateIPRanges | TestValidateIPRanges | 46 | 97 | 46 | 46 | e3ee32dcec320af53fbbdf894d16cccd60e7c89c | bigcode/the-stack | train |
b7309949890a9e35089d7a9a | train | function | def countMed(val_collab, val_real, df_collab, df_real):
aux_count = 0
for i in range(len(df_real)):
comp_collab = df_collab.iloc[i].medium
comp_real = df_real.iloc[i].medium
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
| def countMed(val_collab, val_real, df_collab, df_real):
| aux_count = 0
for i in range(len(df_real)):
comp_collab = df_collab.iloc[i].medium
comp_real = df_real.iloc[i].medium
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
| [i].low
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
def countMed(val_collab, val_real, df_collab, df_real):
| 64 | 64 | 98 | 17 | 46 | mida-project/sa-uta7-recall-precision | src/methods/classifications.py | Python | countMed | countMed | 36 | 45 | 36 | 36 | 98aad5effe4e8ead5e236fa090cc88bf59906454 | bigcode/the-stack | train |
c8f862cf8140d2d6b97ed764 | train | function | def countLow(val_collab, val_real, df_collab, df_real):
aux_count = 0
for i in range(len(df_real)):
comp_collab = df_collab.iloc[i].low
comp_real = df_real.iloc[i].low
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
| def countLow(val_collab, val_real, df_collab, df_real):
| aux_count = 0
for i in range(len(df_real)):
comp_collab = df_collab.iloc[i].low
comp_real = df_real.iloc[i].low
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
| , Instituto Superior Técnico (IST)"
__credits__ = [
"Bruno Oliveira",
"Carlos Santiago",
"Jacinto C. Nascimento",
"Pedro Miraldo",
"Nuno Nunes"
]
def countLow(val_collab, val_real, df_collab, df_real):
| 64 | 64 | 98 | 17 | 47 | mida-project/sa-uta7-recall-precision | src/methods/classifications.py | Python | countLow | countLow | 25 | 34 | 25 | 25 | 556e71952a92fd1c209c6f4ea56891458ec68252 | bigcode/the-stack | train |
bdd403097b40c30133991bc2 | train | function | def countHgh(val_collab, val_real, df_collab, df_real):
aux_count = 0
for i in range(len(df_real)):
comp_collab = df_collab.iloc[i].high
comp_real = df_real.iloc[i].high
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
| def countHgh(val_collab, val_real, df_collab, df_real):
| aux_count = 0
for i in range(len(df_real)):
comp_collab = df_collab.iloc[i].high
comp_real = df_real.iloc[i].high
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
| ].medium
cond001 = val_collab == comp_collab
cond002 = val_real == comp_real
if cond001 and cond002:
aux_count += 1
return aux_count
def countHgh(val_collab, val_real, df_collab, df_real):
| 64 | 64 | 99 | 18 | 45 | mida-project/sa-uta7-recall-precision | src/methods/classifications.py | Python | countHgh | countHgh | 47 | 56 | 47 | 47 | da61fec1c8180af6980e436a5743f0ac30a07d51 | bigcode/the-stack | train |
4f3a4f4de8c210ea014ec413 | train | class | class ApiTestFast(unittest.TestCase):
@classmethod
def setUpClass(cls):
ray.init(
num_cpus=4, num_gpus=0, local_mode=True, include_dashboard=False)
@classmethod
def tearDownClass(cls):
ray.shutdown()
_register_all()
def setUp(self):
self.tmpdir = tempfil... | class ApiTestFast(unittest.TestCase):
@classmethod
| def setUpClass(cls):
ray.init(
num_cpus=4, num_gpus=0, local_mode=True, include_dashboard=False)
@classmethod
def tearDownClass(cls):
ray.shutdown()
_register_all()
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmt... | _"): # Date suffix
found = True
break
self.assertFalse(found)
class ShimCreationTest(unittest.TestCase):
def testCreateScheduler(self):
kwargs = {"metric": "metric_foo", "mode": "min"}
scheduler = "async_hyperband"
shim_scheduler = tune... | 256 | 256 | 990 | 12 | 244 | benblack769/ray | python/ray/tune/tests/test_api.py | Python | ApiTestFast | ApiTestFast | 1,139 | 1,280 | 1,139 | 1,140 | f729302fd49c7bceafaf0f846532c9cd5e9a028b | bigcode/the-stack | train |
90997b0f4a936ab6b27bb887 | train | class | class ShimCreationTest(unittest.TestCase):
def testCreateScheduler(self):
kwargs = {"metric": "metric_foo", "mode": "min"}
scheduler = "async_hyperband"
shim_scheduler = tune.create_scheduler(scheduler, **kwargs)
real_scheduler = AsyncHyperBandScheduler(**kwargs)
assert type... | class ShimCreationTest(unittest.TestCase):
| def testCreateScheduler(self):
kwargs = {"metric": "metric_foo", "mode": "min"}
scheduler = "async_hyperband"
shim_scheduler = tune.create_scheduler(scheduler, **kwargs)
real_scheduler = AsyncHyperBandScheduler(**kwargs)
assert type(shim_scheduler) is type(real_scheduler)
... | (tmp_dir))
self.assertIn("test_trial_dir", subdirs)
found = False
for subdir in subdirs:
if subdir.startswith("test_trial_dir_"): # Date suffix
found = True
break
self.assertFalse(found)
class ShimCreationTest(unitt... | 66 | 66 | 223 | 8 | 58 | benblack769/ray | python/ray/tune/tests/test_api.py | Python | ShimCreationTest | ShimCreationTest | 1,115 | 1,136 | 1,115 | 1,115 | 62495cc946de4fc14d02795cb824a4679d3ab608 | bigcode/the-stack | train |
52c95832848ddf23731d2b56 | train | class | class TrainableFunctionApiTest(unittest.TestCase):
def setUp(self):
ray.init(num_cpus=4, num_gpus=0, object_store_memory=150 * 1024 * 1024)
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
ray.shutdown()
_register_all() # re-register the evicted objects
shutil.rmtre... | class TrainableFunctionApiTest(unittest.TestCase):
| def setUp(self):
ray.init(num_cpus=4, num_gpus=0, object_store_memory=150 * 1024 * 1024)
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
ray.shutdown()
_register_all() # re-register the evicted objects
shutil.rmtree(self.tmpdir)
def checkAndReturnConsistentLog... |
from ray import tune
from ray.tune import (DurableTrainable, Trainable, TuneError, Stopper,
EarlyStopping, run)
from ray.tune import register_env, register_trainable, run_experiments
from ray.tune.schedulers import (TrialScheduler, FIFOScheduler,
AsyncHyperBandSc... | 256 | 256 | 8,257 | 10 | 245 | benblack769/ray | python/ray/tune/tests/test_api.py | Python | TrainableFunctionApiTest | TrainableFunctionApiTest | 36 | 1,112 | 36 | 36 | 8dde1eb53220d8a76d36ea1abc527906d66f4891 | bigcode/the-stack | train |
1f8b141d3312c4bf55237bc1 | train | function | def TESTFOLDER(foldername):
data = PreTest()
print("[*] Given folder: ", foldername)
for i in glob.glob(foldername + "/*.apk"):
classify(i, data)
| def TESTFOLDER(foldername):
| data = PreTest()
print("[*] Given folder: ", foldername)
for i in glob.glob(foldername + "/*.apk"):
classify(i, data)
| file is Malign")
else:
print ("| => The APK file is Bengin")
print("|_________________________________________________________________________")
def TESTFILE(filename):
fs = filename.split(",")
data = PreTest()
for f in fs:
classify(f, data)
def TESTFOLDER(foldername):
| 64 | 64 | 44 | 7 | 57 | tantran1999/Android-Malware-Detection | test.py | Python | TESTFOLDER | TESTFOLDER | 58 | 62 | 58 | 58 | 8567b8a2a527196dda5bfd6efd983957b00310b1 | bigcode/the-stack | train |
9a35c2fa6fcf93054534141e | train | function | def TESTFILE(filename):
fs = filename.split(",")
data = PreTest()
for f in fs:
classify(f, data)
| def TESTFILE(filename):
| fs = filename.split(",")
data = PreTest()
for f in fs:
classify(f, data)
| )
print("+-------------------------------------------------------------------------")
print("| Given APK file: ", apk)
if res_predict == [0]:
print ("| => The APK file is Malign")
else:
print ("| => The APK file is Bengin")
print("|___________________________________________________... | 64 | 64 | 30 | 5 | 59 | tantran1999/Android-Malware-Detection | test.py | Python | TESTFILE | TESTFILE | 52 | 56 | 52 | 52 | 417bae3659ee73ee1b5fe276f12834926b8e429e | bigcode/the-stack | train |
01c195cb10ccd5b01e602030 | train | function | def classify(apk, data):
a,d,dx = AnalyzeAPK(apk)
if int(a.valid_apk) == 0:
return 0
feats = list()
feats += (data.makeHotVector([data.vocabPerm.index(p) for p in a.get_permissions() if p in data.vocabPerm], \
data.vocabLengths["perm"])).tolist()
feats +=... | def classify(apk, data):
| a,d,dx = AnalyzeAPK(apk)
if int(a.valid_apk) == 0:
return 0
feats = list()
feats += (data.makeHotVector([data.vocabPerm.index(p) for p in a.get_permissions() if p in data.vocabPerm], \
data.vocabLengths["perm"])).tolist()
feats += (data.makeHotVector([dat... | sklearn.model_selection import train_test_split
from keras.layers import Input, Dense
from keras.models import Model, load_model
from dbn.tensorflow import SupervisedDBNClassification
from dbn.models import UnsupervisedDBN
from sklearn.svm import SVC, LinearSVC, NuSVR
from sklearn.pipeline import Pipeline
from sklearn... | 103 | 103 | 346 | 7 | 95 | tantran1999/Android-Malware-Detection | test.py | Python | classify | classify | 20 | 50 | 20 | 20 | 0140f60d393470c57c8321fd1bef7b6577a2b723 | bigcode/the-stack | train |
3f4daa4af9ec352f3ba1912a | train | class | class DebugWindow(Window):
'''Enables a number of nice things not within the default window'''
mode_index = modes.index(gl.TRIANGLES)
fill_index = fills.index(gl.LINE)
@property
def fill(self):
fill = fills[self.fill_index]
return fill
@property
def mode(self):
mod... | class DebugWindow(Window):
| '''Enables a number of nice things not within the default window'''
mode_index = modes.index(gl.TRIANGLES)
fill_index = fills.index(gl.LINE)
@property
def fill(self):
fill = fills[self.fill_index]
return fill
@property
def mode(self):
mode = modes[self.mode_index]
... | INES_ADJACENCY,
gl.LINE_STRIP_ADJACENCY,
# gl.QUADS,
gl.TRIANGLES,
gl.TRIANGLE_STRIP,
gl.TRIANGLE_FAN,
gl.TRIANGLE_STRIP_ADJACENCY,
gl.TRIANGLES_ADJACENCY,
# gl.PATCHES,
])
fills = [
gl.FILL,
gl.POINT,
gl.LINE
]
class DebugWindow(Window):
| 98 | 98 | 329 | 5 | 93 | brianbruggeman/oogli | tests/DebugWindow.py | Python | DebugWindow | DebugWindow | 37 | 71 | 37 | 37 | f401c0a385f9036dd250309a47a8b22f36aa11b0 | bigcode/the-stack | train |
afa832d0953e6f52b0b355b2 | train | class | class TestEasyGDFUtils(unittest.TestCase):
def test_get_example_screen_tout_filename(self):
# Just run the function and make sure we don't error out
easygdf.get_example_screen_tout_filename()
def test_get_example_initial_distribution(self):
easygdf.get_example_initial_distribution()
| class TestEasyGDFUtils(unittest.TestCase):
| def test_get_example_screen_tout_filename(self):
# Just run the function and make sure we don't error out
easygdf.get_example_screen_tout_filename()
def test_get_example_initial_distribution(self):
easygdf.get_example_initial_distribution()
| # This file is part of easygdf and is released under the BSD 3-clause license
import unittest
import easygdf
class TestEasyGDFUtils(unittest.TestCase):
| 40 | 64 | 64 | 10 | 29 | st-walker/easygdf | easygdf/tests/test_utils.py | Python | TestEasyGDFUtils | TestEasyGDFUtils | 8 | 14 | 8 | 8 | 225e9688831ee9d6eb4adafee9de7dec5769676d | bigcode/the-stack | train |
f81daae1fdf20fc4e5d92ed6 | train | function | def get_array_layout(instrument_name):
"""
Returns the array layout for the given instrument as an
`astropy.table.Table` object.
"""
name = instrument_name.lower()
try:
layoutfile = get_dataset_path(f'{name}_arraylayout.fits')
except KeyError:
layoutfile = get_dataset_path(f'... | def get_array_layout(instrument_name):
| """
Returns the array layout for the given instrument as an
`astropy.table.Table` object.
"""
name = instrument_name.lower()
try:
layoutfile = get_dataset_path(f'{name}_arraylayout.fits')
except KeyError:
layoutfile = get_dataset_path(f'{name}_arraylayout.fits.gz')
return... | license - see LICENSE.rst
"""
Array layout utilities
"""
from astropy.table import Table
from ctapipe.utils import get_dataset_path
_telclass_map = {0: 'SST', 1: 'MST', 2: 'LST'}
def get_array_layout(instrument_name):
| 63 | 64 | 91 | 8 | 55 | cta-sst-1m/ctapipe | ctapipe/io/array.py | Python | get_array_layout | get_array_layout | 11 | 21 | 11 | 11 | a9044427e9cdef479970a3bb2683a92c333e54d6 | bigcode/the-stack | train |
d8b76a8b5fae0776d7e4a101 | train | function | def load_array_layout_from_file(array_layout_filename):
"""
Read an array layout from a FITS file with a ``TELARRAY`` extension
"""
return Table.read(array_layout_filename, hdu='TELARRAY')
| def load_array_layout_from_file(array_layout_filename):
| """
Read an array layout from a FITS file with a ``TELARRAY`` extension
"""
return Table.read(array_layout_filename, hdu='TELARRAY')
| _name.lower()
try:
layoutfile = get_dataset_path(f'{name}_arraylayout.fits')
except KeyError:
layoutfile = get_dataset_path(f'{name}_arraylayout.fits.gz')
return load_array_layout_from_file(layoutfile)
def load_array_layout_from_file(array_layout_filename):
| 64 | 64 | 46 | 10 | 54 | cta-sst-1m/ctapipe | ctapipe/io/array.py | Python | load_array_layout_from_file | load_array_layout_from_file | 24 | 28 | 24 | 24 | 052ed685b20b268918e34903a79b47f16f5d4be6 | bigcode/the-stack | train |
ed756c5bbe9032b92a624cc1 | train | class | class ResDownS(nn.Module):
def __init__(self, inplane, outplane):
super(ResDownS, self).__init__()
self.downsample = nn.Sequential(
nn.Conv2d(inplane, outplane, kernel_size=1, bias=False),
nn.BatchNorm2d(outplane))
def forward(self, x):
x = self.downsampl... | class ResDownS(nn.Module):
| def __init__(self, inplane, outplane):
super(ResDownS, self).__init__()
self.downsample = nn.Sequential(
nn.Conv2d(inplane, outplane, kernel_size=1, bias=False),
nn.BatchNorm2d(outplane))
def forward(self, x):
x = self.downsample(x)
if x.size(3) <... | features import Features
from .rpn import RPN, DepthCorr
from .mask import Mask
import torch
import torch.nn as nn
import torch.nn.functional as F
from siamMask.utils.load_helper import load_pretrain
from .resnet import resnet50
class ResDownS(nn.Module):
| 64 | 64 | 120 | 7 | 56 | starkgate/UltimateLabeling | siamMask/models/custom.py | Python | ResDownS | ResDownS | 17 | 29 | 17 | 17 | 30f08cf0de929fba1ae5617e9b9766ba69d61ec8 | bigcode/the-stack | train |
ad05b6d8e353c376adbec49f | train | class | class Custom(SiamMask):
def __init__(self, pretrain=False, **kwargs):
super(Custom, self).__init__(**kwargs)
self.features = ResDown(pretrain=pretrain)
self.rpn_model = UP(anchor_num=self.anchor_num, feature_in=256, feature_out=256)
self.mask_model = MaskCorr()
self.refine_mo... | class Custom(SiamMask):
| def __init__(self, pretrain=False, **kwargs):
super(Custom, self).__init__(**kwargs)
self.features = ResDown(pretrain=pretrain)
self.rpn_model = UP(anchor_num=self.anchor_num, feature_in=256, feature_out=256)
self.mask_model = MaskCorr()
self.refine_model = Refine()
def ... | 31, 31)))
out = self.post1(F.upsample(self.h1(out) + self.v1(p1), size=(61, 61)))
out = self.post2(F.upsample(self.h0(out) + self.v0(p0), size=(127, 127)))
out = out.view(-1, 127*127)
return out
class Custom(SiamMask):
| 86 | 86 | 289 | 6 | 79 | starkgate/UltimateLabeling | siamMask/models/custom.py | Python | Custom | Custom | 129 | 157 | 129 | 129 | d385c312d9d4dbe4ffe72a49feb67f5b8ffae39b | bigcode/the-stack | train |
8104a748b202257ec500f0f1 | train | class | class MaskCorr(Mask):
def __init__(self, oSz=63):
super(MaskCorr, self).__init__()
self.oSz = oSz
self.mask = DepthCorr(256, 256, self.oSz**2)
def forward(self, z, x):
return self.mask(z, x)
| class MaskCorr(Mask):
| def __init__(self, oSz=63):
super(MaskCorr, self).__init__()
self.oSz = oSz
self.mask = DepthCorr(256, 256, self.oSz**2)
def forward(self, z, x):
return self.mask(z, x)
| .cls_output)
self.loc = DepthCorr(feature_in, feature_out, self.loc_output)
def forward(self, z_f, x_f):
cls = self.cls(z_f, x_f)
loc = self.loc(z_f, x_f)
return cls, loc
class MaskCorr(Mask):
| 64 | 64 | 71 | 6 | 57 | starkgate/UltimateLabeling | siamMask/models/custom.py | Python | MaskCorr | MaskCorr | 72 | 79 | 72 | 72 | 62a4e2287fa6cd4260b2f29138164f556ca7c6f5 | bigcode/the-stack | train |
c68c245b875ed7630a7ea4cd | train | class | class ResDown(Features):
def __init__(self, pretrain=False):
super(ResDown, self).__init__()
self.features = resnet50(layer3=True, layer4=False)
if pretrain:
load_pretrain(self.features, 'resnet.model')
self.downsample = ResDownS(1024, 256)
def forward(self, x):
... | class ResDown(Features):
| def __init__(self, pretrain=False):
super(ResDown, self).__init__()
self.features = resnet50(layer3=True, layer4=False)
if pretrain:
load_pretrain(self.features, 'resnet.model')
self.downsample = ResDownS(1024, 256)
def forward(self, x):
output = self.featur... | 2d(outplane))
def forward(self, x):
x = self.downsample(x)
if x.size(3) < 20:
l, r = 4, -4
x = x[:, :, l:r, l:r]
return x
class ResDown(Features):
| 64 | 64 | 137 | 6 | 57 | starkgate/UltimateLabeling | siamMask/models/custom.py | Python | ResDown | ResDown | 32 | 49 | 32 | 32 | def50ec5041f1532f4033169f2c8c3bc4aef367f | bigcode/the-stack | train |
7dd4804ee7a3f20706cadee6 | train | class | class UP(RPN):
def __init__(self, anchor_num=5, feature_in=256, feature_out=256):
super(UP, self).__init__()
self.anchor_num = anchor_num
self.feature_in = feature_in
self.feature_out = feature_out
self.cls_output = 2 * self.anchor_num
self.loc_output = 4 * self.anc... | class UP(RPN):
| def __init__(self, anchor_num=5, feature_in=256, feature_out=256):
super(UP, self).__init__()
self.anchor_num = anchor_num
self.feature_in = feature_in
self.feature_out = feature_out
self.cls_output = 2 * self.anchor_num
self.loc_output = 4 * self.anchor_num
... | , x):
output = self.features(x)
p3 = self.downsample(output[-1])
return p3
def forward_all(self, x):
output = self.features(x)
p3 = self.downsample(output[-1])
return output, p3
class UP(RPN):
| 64 | 64 | 155 | 5 | 58 | starkgate/UltimateLabeling | siamMask/models/custom.py | Python | UP | UP | 52 | 69 | 52 | 52 | 3bf7d10616cf21856ace151335146b961808eb3a | bigcode/the-stack | train |
1ced20fcc0ab01ce4b57ce60 | train | class | class Refine(nn.Module):
def __init__(self):
"""
Mask refinement module
Please refer SiamMask (Appendix A)
https://arxiv.org/abs/1812.05050
"""
super(Refine, self).__init__()
self.v0 = nn.Sequential(nn.Conv2d(64, 16, 3, padding=1), nn.ReLU(),
... | class Refine(nn.Module):
| def __init__(self):
"""
Mask refinement module
Please refer SiamMask (Appendix A)
https://arxiv.org/abs/1812.05050
"""
super(Refine, self).__init__()
self.v0 = nn.Sequential(nn.Conv2d(64, 16, 3, padding=1), nn.ReLU(),
nn.Conv2d(16, 4... | init__(self, anchor_num=5, feature_in=256, feature_out=256):
super(UP, self).__init__()
self.anchor_num = anchor_num
self.feature_in = feature_in
self.feature_out = feature_out
self.cls_output = 2 * self.anchor_num
self.loc_output = 4 * self.anchor_num
self.cls... | 224 | 224 | 749 | 6 | 218 | starkgate/UltimateLabeling | siamMask/models/custom.py | Python | Refine | Refine | 82 | 126 | 82 | 82 | df40749b06e260683c96f981ff454196af094f58 | bigcode/the-stack | train |
1b3fca5db9cb42d08de7f1da | train | class | class ShardReader:
"""
Wrapper class which is represent ShardReader class in c++ module.
The class would read a batch of data from MindRecord File series.
"""
def __init__(self):
self._reader = ms.ShardReader()
def open(self, file_name, num_consumer=4, columns=None, operator=None):
... | class ShardReader:
| """
Wrapper class which is represent ShardReader class in c++ module.
The class would read a batch of data from MindRecord File series.
"""
def __init__(self):
self._reader = ms.ShardReader()
def open(self, file_name, num_consumer=4, columns=None, operator=None):
"""
Op... | 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 WARRANTIES OR CONDITIONS OF ANY... | 165 | 165 | 551 | 5 | 160 | unseenme/mindspore | mindspore/mindrecord/shardreader.py | Python | ShardReader | ShardReader | 24 | 118 | 24 | 24 | bfd5592331613c45926dd4e447beb9d7951e1479 | bigcode/the-stack | train |
17c89cd6be7c1f667976a5e0 | train | class | class Invoice(models.Model):
date = models.DateField()
subtotal = models.DecimalField(decimal_places=2, max_digits=15)
vat_percentage = models.DecimalField(decimal_places=2, max_digits=4)
total = models.DecimalField(decimal_places=2, max_digits=15, default=0)
total_paid = models.DecimalField(decimal... | class Invoice(models.Model):
| date = models.DateField()
subtotal = models.DecimalField(decimal_places=2, max_digits=15)
vat_percentage = models.DecimalField(decimal_places=2, max_digits=4)
total = models.DecimalField(decimal_places=2, max_digits=15, default=0)
total_paid = models.DecimalField(decimal_places=2, max_digits=15)
... | from django.db import models
from django.core.validators import MinValueValidator
from ..clients.models import Client
from ..items.models import Item
class Invoice(models.Model):
| 34 | 64 | 141 | 5 | 28 | jahidulrudro/Invoice-Maker-Django-VueJs | backend/invoices/models.py | Python | Invoice | Invoice | 8 | 19 | 8 | 8 | 33dd701a43fe324a69d79a44be979d86048c25db | bigcode/the-stack | train |
ea5645d89b453e0a4980a641 | train | class | class InvoiceItem(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(validators=[MinValueValidator(1)])
invoice = models.ForeignKey(
Invoice,
on_delete=models.CASCADE,
related_name='invoice_items',
)
def __str__(self):
... | class InvoiceItem(models.Model):
| item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(validators=[MinValueValidator(1)])
invoice = models.ForeignKey(
Invoice,
on_delete=models.CASCADE,
related_name='invoice_items',
)
def __str__(self):
return self.item.name
| _due = models.DecimalField(decimal_places=2, max_digits=15)
payment_term = models.CharField(max_length=128)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
def __str__(self):
return f'Invoice# {self.pk}'
class InvoiceItem(models.Model):
| 63 | 64 | 72 | 6 | 57 | jahidulrudro/Invoice-Maker-Django-VueJs | backend/invoices/models.py | Python | InvoiceItem | InvoiceItem | 22 | 32 | 22 | 22 | fb1f9de095be251285d7803e832b402e89b3f709 | bigcode/the-stack | train |
9a914d73fad8ea496de3bd83 | train | class | class agipd_cxigeom2nexus(object):
def __init__(self, args):
self.params_from_phil(args)
if self.params.detector_distance == None:
self.params.detector_distance = (
177.0 # Set detector distance arbitrarily if nothing is provided
)
self.hierarchy = re... | class agipd_cxigeom2nexus(object):
| def __init__(self, args):
self.params_from_phil(args)
if self.params.detector_distance == None:
self.params.detector_distance = (
177.0 # Set detector distance arbitrarily if nothing is provided
)
self.hierarchy = read_geom(self.params.geom_file)
... | detector_distance = None
.type = float
.help = AGIPD Detector distance
wavelength = None
.type = float
.help = AGIPD wavelength override
mode = vds cxi
.type = choice
.optional = False
.help = Input data file format. VDS: virtual data set. CXI: \
Cheetah file format.
"""
)
... | 256 | 256 | 2,517 | 13 | 243 | dperl-sol/cctbx_project | xfel/euxfel/agipd_cxigeom2nexus.py | Python | agipd_cxigeom2nexus | agipd_cxigeom2nexus | 54 | 335 | 54 | 54 | 0977a836646696dfc4de56cd475728d86cdcc64f | bigcode/the-stack | train |
fe3a54fa02c688015e1af196 | train | function | def get_git_revision_hash():
definitions_path = os.path.join(os.path.dirname(sys.argv[0]), "definitions")
current_dir = os.getcwd()
os.chdir(definitions_path)
definitions_hash = subprocess.check_output(["git", "rev-parse", "HEAD"]).strip()
os.chdir(current_dir)
return definitions_hash.decode()
| def get_git_revision_hash():
| definitions_path = os.path.join(os.path.dirname(sys.argv[0]), "definitions")
current_dir = os.getcwd()
os.chdir(definitions_path)
definitions_hash = subprocess.check_output(["git", "rev-parse", "HEAD"]).strip()
os.chdir(current_dir)
return definitions_hash.decode()
| .geom file
The cxi file is generated by cheetah after processing the raw images and doing appropriate gain corrections
The assumed parameters for the detector can be seen in the __init__ function and should be changed
if they are modified at EU XFEL in the future
"""
def get_git_revision_hash():
| 64 | 64 | 70 | 6 | 58 | dperl-sol/cctbx_project | xfel/euxfel/agipd_cxigeom2nexus.py | Python | get_git_revision_hash | get_git_revision_hash | 45 | 51 | 45 | 45 | 86b3c70e6cd0f394a5ed25648d9fd418c6638a6e | bigcode/the-stack | train |
ef6833e58b787837d2d43d72 | train | class | class PriorBox(object):
def __init__(self, cfg, image_size=None, phase='train'):
super(PriorBox, self).__init__()
self.min_sizes = cfg['min_sizes']
self.steps = cfg['steps']
self.clip = cfg['clip']
self.image_size = image_size
self.feature_maps = [[ceil(self.image_siz... | class PriorBox(object):
| def __init__(self, cfg, image_size=None, phase='train'):
super(PriorBox, self).__init__()
self.min_sizes = cfg['min_sizes']
self.steps = cfg['steps']
self.clip = cfg['clip']
self.image_size = image_size
self.feature_maps = [[ceil(self.image_size[0]/step), ceil(self.im... | from itertools import product as product
from math import ceil
import torch
class PriorBox(object):
| 20 | 96 | 321 | 5 | 14 | Danil328/Pytorch_Retinaface | retinaface/layers/functions/prior_box.py | Python | PriorBox | PriorBox | 7 | 34 | 7 | 7 | 0996c37117d00758dc6363b27c57c6dcf305f4bc | bigcode/the-stack | train |
fdfbb76a371d8565071937f7 | train | function | def generate_csrf_key():
with open('data/csrf.key', 'w') as f:
key = ''
encoding = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
length = random.randint(40, 50)
for _ in range(length):
key += random.choice(encoding)
f.write(key)
print(key)
| def generate_csrf_key():
| with open('data/csrf.key', 'w') as f:
key = ''
encoding = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
length = random.randint(40, 50)
for _ in range(length):
key += random.choice(encoding)
f.write(key)
print(key)
| import secrets
import random
import sys
def generate_csrf_key():
| 15 | 64 | 73 | 6 | 8 | n-xlkt/onomancer | onomancer/scripts.py | Python | generate_csrf_key | generate_csrf_key | 6 | 14 | 6 | 6 | 6b43c0b6c06583db63aa7a551a6e12df2f646f13 | bigcode/the-stack | train |
f73ee97f29faff038fde5f61 | train | function | def generate_mod_key():
with open('data/mod.key', 'w') as f:
sec = secrets.token_urlsafe(32)
f.write(sec)
print(sec)
| def generate_mod_key():
| with open('data/mod.key', 'w') as f:
sec = secrets.token_urlsafe(32)
f.write(sec)
print(sec)
| .key', 'w') as f:
key = ''
encoding = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
length = random.randint(40, 50)
for _ in range(length):
key += random.choice(encoding)
f.write(key)
print(key)
def generate_mod_key():
| 64 | 64 | 38 | 5 | 59 | n-xlkt/onomancer | onomancer/scripts.py | Python | generate_mod_key | generate_mod_key | 17 | 21 | 17 | 17 | 5e2d0d217d0a036d32a00dfbac96c9cd4d2ed3fc | bigcode/the-stack | train |
61304c66997037fa4a43e776 | train | function | def generate_app_key():
with open('data/appsecret.key', 'w') as f:
sec = secrets.token_urlsafe(random.randint(40, 50))
f.write(sec)
print(sec)
| def generate_app_key():
| with open('data/appsecret.key', 'w') as f:
sec = secrets.token_urlsafe(random.randint(40, 50))
f.write(sec)
print(sec)
| in range(length):
key += random.choice(encoding)
f.write(key)
print(key)
def generate_mod_key():
with open('data/mod.key', 'w') as f:
sec = secrets.token_urlsafe(32)
f.write(sec)
print(sec)
def generate_app_key():
| 64 | 64 | 44 | 5 | 59 | n-xlkt/onomancer | onomancer/scripts.py | Python | generate_app_key | generate_app_key | 24 | 28 | 24 | 24 | 1b8b914f1248f21283ec9291d2dc5119f9a537b2 | bigcode/the-stack | train |
251a7aaa69c3583bd58bbc46 | train | function | @init
def set_properties(project):
project.depends_on("requests", "~=2.23")
project.set_property("verbose", True)
project.set_property("coverage_break_build", False)
project.set_property("flake8_break_build", True)
project.set_property("flake8_extend_ignore", "E303")
project.set_property("flak... | @init
def set_properties(project):
| project.depends_on("requests", "~=2.23")
project.set_property("verbose", True)
project.set_property("coverage_break_build", False)
project.set_property("flake8_break_build", True)
project.set_property("flake8_extend_ignore", "E303")
project.set_property("flake8_include_test_sources", True)
... | "arcadiy@ivanov.biz")]
license = "Apache License, Version 2.0"
url = "https://github.com/arcivanov/pypi-cleanup"
urls = {"Bug Tracker": "https://github.com/arcivanov/pypi-cleanup/issues",
"Source Code": "https://github.com/arcivanov/pypi-cleanup",
"Documentation": "https://github.com/arcivanov/pypi-cl... | 128 | 129 | 431 | 8 | 120 | arcivanov/pypi-cleanup | build.py | Python | set_properties | set_properties | 45 | 84 | 45 | 46 | 33094e922721410ecf38e57af5c66d0a2af11ba7 | bigcode/the-stack | train |
baa490cfbda2e2ced9590ac8 | train | class | class Player():
def __init__(self, mode=None):
if mode is None:
mode = default_mode
if (not mode == 'server') and (not mode == 'direct'):
logger.error('unknown mode %s, trying default mode', mode)
mode = default_mode
if mode == 'server':
# try... | class Player():
| def __init__(self, mode=None):
if mode is None:
mode = default_mode
if (not mode == 'server') and (not mode == 'direct'):
logger.error('unknown mode %s, trying default mode', mode)
mode = default_mode
if mode == 'server':
# try to check whether... | """ Play via sound server """
import logging
import requests
from vlcplayer import vlcplayer
logger = logging.getLogger(__name__)
default_mode = 'server'
baseurl = 'http://localhost:7070/'
def send_request(req):
try:
requests.post(baseurl + req)
except Exception as e:
logger.error(e)
class P... | 77 | 192 | 641 | 3 | 74 | swipswaps/susi_linux | susi_linux/player.py | Python | Player | Player | 19 | 100 | 19 | 20 | ba25294643f5186649bab4e90ad859a46bc9a468 | bigcode/the-stack | train |
4febedfb8f216798a0415015 | train | function | def send_request(req):
try:
requests.post(baseurl + req)
except Exception as e:
logger.error(e)
| def send_request(req):
| try:
requests.post(baseurl + req)
except Exception as e:
logger.error(e)
| """ Play via sound server """
import logging
import requests
from vlcplayer import vlcplayer
logger = logging.getLogger(__name__)
default_mode = 'server'
baseurl = 'http://localhost:7070/'
def send_request(req):
| 51 | 64 | 27 | 5 | 46 | swipswaps/susi_linux | susi_linux/player.py | Python | send_request | send_request | 12 | 16 | 12 | 12 | a27592d9ec72fa1e15e7699faedbfd137e7a736f | bigcode/the-stack | train |
d7ca46d2c85dd94e48912ab7 | train | function | def main(cli_args, prog=None): # type: (List[str], Optional[str]) -> None
'''
Parses the CLI arguments and invokes the build process.
:param cli_args: CLI arguments
'''
parser = main_parser()
if prog:
parser.prog = prog
args = parser.parse_args(cli_args)
distributions = []
... | def main(cli_args, prog=None): # type: (List[str], Optional[str]) -> None
| '''
Parses the CLI arguments and invokes the build process.
:param cli_args: CLI arguments
'''
parser = main_parser()
if prog:
parser.prog = prog
args = parser.parse_args(cli_args)
distributions = []
config_settings = {}
if args.config_setting:
for arg in args.... | not check for the dependencies')
parser.add_argument('--no-isolation', '-n',
action='store_true',
help='do not isolate the build in a virtual environment')
parser.add_argument('--config-setting', '-C',
action='append',
... | 88 | 88 | 296 | 22 | 65 | di/python-build | src/build/__main__.py | Python | main | main | 124 | 168 | 124 | 124 | 835f161486aa2059637b9d3aad809a9b06417ac0 | bigcode/the-stack | train |
bf0a0538abe98c767a47c30a | train | function | def _build_in_current_env(builder, outdir, distributions, skip_dependencies=False):
# type: (ProjectBuilder, str, List[str], bool) -> None
for dist in distributions:
if not skip_dependencies:
missing = builder.check_dependencies(dist)
if missing:
_error('Missing d... | def _build_in_current_env(builder, outdir, distributions, skip_dependencies=False):
# type: (ProjectBuilder, str, List[str], bool) -> None
| for dist in distributions:
if not skip_dependencies:
missing = builder.check_dependencies(dist)
if missing:
_error('Missing dependencies:' + ''.join(['\n\t' + dep for dep in missing]))
builder.build(dist, outdir)
| IsolatedEnvironment() as env:
env.install(builder.build_dependencies)
for distribution in distributions:
builder.build(distribution, outdir)
def _build_in_current_env(builder, outdir, distributions, skip_dependencies=False):
# type: (ProjectBuilder, str, List[str], bool) -> None
| 64 | 64 | 89 | 35 | 29 | di/python-build | src/build/__main__.py | Python | _build_in_current_env | _build_in_current_env | 50 | 58 | 50 | 51 | 1391e542200aa225e2a216666a8832992ee20aa5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.