id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
22,289
def dump_crypto_meta(crypto_meta): def b64_encode_meta(crypto_meta): return {name: (base64.b64encode(value).decode() if (name in ('iv', 'key')) else (b64_encode_meta(value) if isinstance(value, dict) else value)) for (name, value) in crypto_meta.items()} return urlparse.quote_plus(json.dumps(b64_encode_meta(crypto_...
[ "def", "dump_crypto_meta", "(", "crypto_meta", ")", ":", "def", "b64_encode_meta", "(", "crypto_meta", ")", ":", "return", "{", "name", ":", "(", "base64", ".", "b64encode", "(", "value", ")", ".", "decode", "(", ")", "if", "(", "name", "in", "(", "'iv...
serialize crypto meta to a form suitable for including in a header value .
train
false
22,290
def pusher(url, count, size, poll, copy): ctx = zmq.Context() s = ctx.socket(zmq.PUSH) if poll: p = zmq.Poller() p.register(s) s.connect(url) msg = zmq.Message((' ' * size)) block = (zmq.NOBLOCK if poll else 0) for i in range(count): if poll: res = p.poll() assert (res[0][1] & zmq.POLLOUT) s.send(m...
[ "def", "pusher", "(", "url", ",", "count", ",", "size", ",", "poll", ",", "copy", ")", ":", "ctx", "=", "zmq", ".", "Context", "(", ")", "s", "=", "ctx", ".", "socket", "(", "zmq", ".", "PUSH", ")", "if", "poll", ":", "p", "=", "zmq", ".", ...
send a bunch of messages on a push socket .
train
false
22,291
def unregister_trophy(trophy): warnings.warn(u'unregister_trophy() is deprecated. Please use reviewboard.accounts.trophies:trophies_registry.unregister() instead.', DeprecationWarning) if (not issubclass(trophy, TrophyType)): raise TypeError(u'Only TrophyType subclasses can be unregistered') try: trophies_regist...
[ "def", "unregister_trophy", "(", "trophy", ")", ":", "warnings", ".", "warn", "(", "u'unregister_trophy() is deprecated. Please use reviewboard.accounts.trophies:trophies_registry.unregister() instead.'", ",", "DeprecationWarning", ")", "if", "(", "not", "issubclass", "(", "tro...
unregister a trophytype subclass .
train
false
22,292
def _check_rbenv(ret, user=None): if (not __salt__['rbenv.is_installed'](user)): ret['result'] = False ret['comment'] = 'Rbenv is not installed.' return ret
[ "def", "_check_rbenv", "(", "ret", ",", "user", "=", "None", ")", ":", "if", "(", "not", "__salt__", "[", "'rbenv.is_installed'", "]", "(", "user", ")", ")", ":", "ret", "[", "'result'", "]", "=", "False", "ret", "[", "'comment'", "]", "=", "'Rbenv i...
check to see if rbenv is installed .
train
false
22,293
def partial_check_positive_definite(C): if (C.ndim == 1): d = C else: d = np.diag(C) (i,) = np.nonzero(np.logical_or(np.isnan(d), (d <= 0))) if len(i): raise PositiveDefiniteError('Simple check failed. Diagonal contains negatives', i)
[ "def", "partial_check_positive_definite", "(", "C", ")", ":", "if", "(", "C", ".", "ndim", "==", "1", ")", ":", "d", "=", "C", "else", ":", "d", "=", "np", ".", "diag", "(", "C", ")", "(", "i", ",", ")", "=", "np", ".", "nonzero", "(", "np", ...
simple but partial check for positive definiteness .
train
false
22,294
def rand_str(size=9999999999, hash_type=None): if (not hash_type): hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(to_bytes(str(random.SystemRandom().randint(0, size)))).hexdigest()
[ "def", "rand_str", "(", "size", "=", "9999999999", ",", "hash_type", "=", "None", ")", ":", "if", "(", "not", "hash_type", ")", ":", "hash_type", "=", "'md5'", "hasher", "=", "getattr", "(", "hashlib", ",", "hash_type", ")", "return", "hasher", "(", "t...
return a random string size size of the string to generate hash_type hash type to use .
train
false
22,295
def test_read(): django_conf.settings.TOP_SECRET = 1234 assert (assets_conf.settings.TOP_SECRET == 1234) django_conf.settings.TOP_SECRET = 'helloworld' assert (assets_conf.settings.TOP_SECRET == 'helloworld')
[ "def", "test_read", "(", ")", ":", "django_conf", ".", "settings", ".", "TOP_SECRET", "=", "1234", "assert", "(", "assets_conf", ".", "settings", ".", "TOP_SECRET", "==", "1234", ")", "django_conf", ".", "settings", ".", "TOP_SECRET", "=", "'helloworld'", "a...
test that we can read djangos own config values from our own settings object .
train
false
22,296
@with_session def reset_schema(plugin, session=None): if (plugin not in plugin_schemas): raise ValueError((u'The plugin %s has no stored schema to reset.' % plugin)) table_names = plugin_schemas[plugin].get(u'tables', []) tables = [table_schema(name, session) for name in table_names] for table in tables: try: ...
[ "@", "with_session", "def", "reset_schema", "(", "plugin", ",", "session", "=", "None", ")", ":", "if", "(", "plugin", "not", "in", "plugin_schemas", ")", ":", "raise", "ValueError", "(", "(", "u'The plugin %s has no stored schema to reset.'", "%", "plugin", ")"...
removes all tables from given plugin from the database .
train
false
22,297
def toUTF8(s): return s
[ "def", "toUTF8", "(", "s", ")", ":", "return", "s" ]
for some strange reason .
train
false
22,298
def CHECK_EXTRACT_CMD(state, package_tarball_paths): if (not package_tarball_paths): return def extracted_size(tarball_path): with tarfile.open(tarball_path) as tar_bz2: return reduce(add, (m.size for m in tar_bz2.getmembers()), 0) size = reduce(add, (extracted_size(dist) for dist in package_tarball_paths), 0...
[ "def", "CHECK_EXTRACT_CMD", "(", "state", ",", "package_tarball_paths", ")", ":", "if", "(", "not", "package_tarball_paths", ")", ":", "return", "def", "extracted_size", "(", "tarball_path", ")", ":", "with", "tarfile", ".", "open", "(", "tarball_path", ")", "...
check whether there is enough space for extract packages .
train
false
22,299
def disable_signal_for_loaddata(signal_handler): @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs.get(u'raw', False): return return signal_handler(*args, **kwargs) return wrapper
[ "def", "disable_signal_for_loaddata", "(", "signal_handler", ")", ":", "@", "wraps", "(", "signal_handler", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "u'raw'", ",", "False", ")", ":", "return...
decorator that turns off signal handlers when loading fixture data .
train
false
22,300
def killall(greenlets, exception=GreenletExit, block=True, timeout=None): greenlets = list(greenlets) if (not greenlets): return loop = greenlets[0].loop if block: waiter = Waiter() loop.run_callback(_killall3, greenlets, exception, waiter) t = Timeout._start_new_or_dummy(timeout) try: alive = waiter.g...
[ "def", "killall", "(", "greenlets", ",", "exception", "=", "GreenletExit", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "greenlets", "=", "list", "(", "greenlets", ")", "if", "(", "not", "greenlets", ")", ":", "return", "loop", "="...
forceably terminate all the greenlets by causing them to raise exception .
train
false
22,301
def structparser(token): m = STRUCT_PACK_RE.match(token) if (not m): return [token] else: endian = m.group('endian') if (endian is None): return [token] formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt')) fmt = ''.join([((f[(-1)] * int(f[:(-1)])) if (len(f) != 1) else f) for f in formatlist]) if ...
[ "def", "structparser", "(", "token", ")", ":", "m", "=", "STRUCT_PACK_RE", ".", "match", "(", "token", ")", "if", "(", "not", "m", ")", ":", "return", "[", "token", "]", "else", ":", "endian", "=", "m", ".", "group", "(", "'endian'", ")", "if", "...
parse struct-like format string token into sub-token list .
train
true
22,302
def test_adapthist_color(): img = skimage.img_as_uint(data.astronaut()) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') (hist, bin_centers) = exposure.histogram(img) assert (len(w) > 0) with expected_warnings(['precision loss']): adapted = exposure.equalize_adapthist(img, clip...
[ "def", "test_adapthist_color", "(", ")", ":", "img", "=", "skimage", ".", "img_as_uint", "(", "data", ".", "astronaut", "(", ")", ")", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "w", ":", "warnings", ".", "simplefil...
test an rgb color uint16 image .
train
false
22,303
def assertIsNone(expr, msg=''): return assertIs(expr, None, msg)
[ "def", "assertIsNone", "(", "expr", ",", "msg", "=", "''", ")", ":", "return", "assertIs", "(", "expr", ",", "None", ",", "msg", ")" ]
checks that expr is none .
train
false
22,304
def binary_replace(data, a, b): if on_win: if has_pyzzer_entry_point(data): return replace_pyzzer_entry_point_shebang(data, a, b) else: return data def replace(match): occurances = match.group().count(a) padding = ((len(a) - len(b)) * occurances) if (padding < 0): raise _PaddingError return (matc...
[ "def", "binary_replace", "(", "data", ",", "a", ",", "b", ")", ":", "if", "on_win", ":", "if", "has_pyzzer_entry_point", "(", "data", ")", ":", "return", "replace_pyzzer_entry_point_shebang", "(", "data", ",", "a", ",", "b", ")", "else", ":", "return", "...
perform a binary replacement of data .
train
false
22,308
@pytest.fixture(scope=u'function') def remove_cheese_file(request): def fin_remove_cheese_file(): if os.path.exists(u'tests/files/cheese.txt'): os.remove(u'tests/files/cheese.txt') request.addfinalizer(fin_remove_cheese_file)
[ "@", "pytest", ".", "fixture", "(", "scope", "=", "u'function'", ")", "def", "remove_cheese_file", "(", "request", ")", ":", "def", "fin_remove_cheese_file", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "u'tests/files/cheese.txt'", ")", ":", ...
remove the cheese text file which is created by the tests .
train
false
22,309
def ellip_harm_2(h2, k2, n, p, s): with np.errstate(all='ignore'): return _ellip_harm_2_vec(h2, k2, n, p, s)
[ "def", "ellip_harm_2", "(", "h2", ",", "k2", ",", "n", ",", "p", ",", "s", ")", ":", "with", "np", ".", "errstate", "(", "all", "=", "'ignore'", ")", ":", "return", "_ellip_harm_2_vec", "(", "h2", ",", "k2", ",", "n", ",", "p", ",", "s", ")" ]
ellipsoidal harmonic functions f^p_n(l) these are also known as lame functions of the second kind .
train
false
22,310
def _glanceclient_from_endpoint(context, endpoint, version=1): params = {} params['identity_headers'] = generate_identity_headers(context) if endpoint.startswith('https://'): params['insecure'] = CONF.glance.api_insecure params['ssl_compression'] = False sslutils.is_enabled(CONF) if CONF.ssl.cert_file: pa...
[ "def", "_glanceclient_from_endpoint", "(", "context", ",", "endpoint", ",", "version", "=", "1", ")", ":", "params", "=", "{", "}", "params", "[", "'identity_headers'", "]", "=", "generate_identity_headers", "(", "context", ")", "if", "endpoint", ".", "startsw...
instantiate a new glanceclient .
train
false
22,311
def find_bindir_path(config_file): try: fd = open(config_file) except IOError as e: utils.err(('Error for Config file (%s): %s' % (config_file, e))) return None try: for line in fd: if line.startswith('{path_config_bindir'): return line.split(',')[1].split('"')[1] finally: fd.close()
[ "def", "find_bindir_path", "(", "config_file", ")", ":", "try", ":", "fd", "=", "open", "(", "config_file", ")", "except", "IOError", "as", "e", ":", "utils", ".", "err", "(", "(", "'Error for Config file (%s): %s'", "%", "(", "config_file", ",", "e", ")",...
returns the bin directory path .
train
false
22,312
def msolve(f, x): f = lambdify(x, f) x0 = (-0.001) dx = 0.001 while ((f((x0 - dx)) * f(x0)) > 0): x0 = (x0 - dx) x_max = (x0 - dx) x_min = x0 assert (f(x_max) > 0) assert (f(x_min) < 0) for n in range(100): x0 = ((x_max + x_min) / 2) if (f(x0) > 0): x_max = x0 else: x_min = x0 return x0
[ "def", "msolve", "(", "f", ",", "x", ")", ":", "f", "=", "lambdify", "(", "x", ",", "f", ")", "x0", "=", "(", "-", "0.001", ")", "dx", "=", "0.001", "while", "(", "(", "f", "(", "(", "x0", "-", "dx", ")", ")", "*", "f", "(", "x0", ")", ...
finds the first root of f(x) to the left of 0 .
train
false
22,313
def test_inequalities_symbol_name_same_complex(): for a in (x, S(0), (S(1) / 3), pi, oo): raises(TypeError, (lambda : Gt(a, I))) raises(TypeError, (lambda : (a > I))) raises(TypeError, (lambda : Lt(a, I))) raises(TypeError, (lambda : (a < I))) raises(TypeError, (lambda : Ge(a, I))) raises(TypeError, (lambd...
[ "def", "test_inequalities_symbol_name_same_complex", "(", ")", ":", "for", "a", "in", "(", "x", ",", "S", "(", "0", ")", ",", "(", "S", "(", "1", ")", "/", "3", ")", ",", "pi", ",", "oo", ")", ":", "raises", "(", "TypeError", ",", "(", "lambda", ...
using the operator and functional forms should give same results .
train
false
22,315
def allow_interpreter_mode(fn): @functools.wraps(fn) def _core(*args, **kws): config.COMPATIBILITY_MODE = True try: fn(*args, **kws) finally: config.COMPATIBILITY_MODE = False return _core
[ "def", "allow_interpreter_mode", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "_core", "(", "*", "args", ",", "**", "kws", ")", ":", "config", ".", "COMPATIBILITY_MODE", "=", "True", "try", ":", "fn", "(", "*", "args", ...
temporarily re-enable intepreter mode .
train
false
22,316
def tunnelX11(node, display=None): if ((display is None) and ('DISPLAY' in environ)): display = environ['DISPLAY'] if (display is None): error('Error: Cannot connect to display\n') return (None, None) (host, screen) = display.split(':') if ((not host) or (host == 'unix')): quietRun('xhost +si:localuser:root...
[ "def", "tunnelX11", "(", "node", ",", "display", "=", "None", ")", ":", "if", "(", "(", "display", "is", "None", ")", "and", "(", "'DISPLAY'", "in", "environ", ")", ")", ":", "display", "=", "environ", "[", "'DISPLAY'", "]", "if", "(", "display", "...
create an x11 tunnel from node:6000 to the root host display: display on root host returns: node $display .
train
false
22,317
def edit_recarray(r, formatd=None, stringd=None, constant=None, autowin=True): liststore = RecListStore(r, formatd=formatd, stringd=stringd) treeview = RecTreeView(liststore, constant=constant) if autowin: win = gtk.Window() win.add(treeview) win.show_all() return (liststore, treeview, win) else: return (...
[ "def", "edit_recarray", "(", "r", ",", "formatd", "=", "None", ",", "stringd", "=", "None", ",", "constant", "=", "None", ",", "autowin", "=", "True", ")", ":", "liststore", "=", "RecListStore", "(", "r", ",", "formatd", "=", "formatd", ",", "stringd",...
create a recliststore and rectreeview and return them .
train
false
22,318
def _fetch_from_local_file(pathfinder=_find_yaml_path, fileopener=open): yaml_path = pathfinder() if yaml_path: config = Config() config.ah__conf__load_from_yaml(LoadSingleConf(fileopener(yaml_path))) logging.debug('Loaded conf parameters from conf.yaml.') return config return None
[ "def", "_fetch_from_local_file", "(", "pathfinder", "=", "_find_yaml_path", ",", "fileopener", "=", "open", ")", ":", "yaml_path", "=", "pathfinder", "(", ")", "if", "yaml_path", ":", "config", "=", "Config", "(", ")", "config", ".", "ah__conf__load_from_yaml", ...
get the configuration that was uploaded with this version .
train
false
22,319
def _get_user_statuses(user, course_key, checkpoint): enrollment_cache_key = CourseEnrollment.cache_key_name(user.id, unicode(course_key)) has_skipped_cache_key = SkippedReverification.cache_key_name(user.id, unicode(course_key)) verification_status_cache_key = VerificationStatus.cache_key_name(user.id, unicode(cour...
[ "def", "_get_user_statuses", "(", "user", ",", "course_key", ",", "checkpoint", ")", ":", "enrollment_cache_key", "=", "CourseEnrollment", ".", "cache_key_name", "(", "user", ".", "id", ",", "unicode", "(", "course_key", ")", ")", "has_skipped_cache_key", "=", "...
retrieve all the information we need to determine the users group .
train
false
22,320
def _compose2(f, g): return (lambda *args, **kwargs: f(g(*args, **kwargs)))
[ "def", "_compose2", "(", "f", ",", "g", ")", ":", "return", "(", "lambda", "*", "args", ",", "**", "kwargs", ":", "f", "(", "g", "(", "*", "args", ",", "**", "kwargs", ")", ")", ")" ]
compose 2 callables .
train
false
22,321
def _extract_doc_comment_continuous(content, line, column, markers): marker_len = len(markers[1]) doc_comment = content[line][column:] line += 1 while (line < len(content)): pos = content[line].find(markers[1]) if (pos == (-1)): return (line, 0, doc_comment) else: doc_comment += content[line][(pos + mar...
[ "def", "_extract_doc_comment_continuous", "(", "content", ",", "line", ",", "column", ",", "markers", ")", ":", "marker_len", "=", "len", "(", "markers", "[", "1", "]", ")", "doc_comment", "=", "content", "[", "line", "]", "[", "column", ":", "]", "line"...
extract a documentation that starts at given beginning with continuous layout .
train
false
22,323
def delinkify(text, allow_domains=None, allow_relative=False): text = force_unicode(text) if (not text): return u'' parser = html5lib.HTMLParser(tokenizer=HTMLSanitizer) forest = parser.parseFragment(text) if (allow_domains is None): allow_domains = [] elif isinstance(allow_domains, basestring): allow_domai...
[ "def", "delinkify", "(", "text", ",", "allow_domains", "=", "None", ",", "allow_relative", "=", "False", ")", ":", "text", "=", "force_unicode", "(", "text", ")", "if", "(", "not", "text", ")", ":", "return", "u''", "parser", "=", "html5lib", ".", "HTM...
remove links from text .
train
false
22,324
def serialize(name, dataset=None, dataset_pillar=None, user=None, group=None, mode=None, backup='', makedirs=False, show_diff=True, create=True, merge_if_exists=False, **kwargs): if ('env' in kwargs): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longe...
[ "def", "serialize", "(", "name", ",", "dataset", "=", "None", ",", "dataset_pillar", "=", "None", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "None", ",", "backup", "=", "''", ",", "makedirs", "=", "False", ",", "show_diff"...
save a collection to database .
train
false
22,325
def volume_delete(provider, names, **kwargs): client = _get_client() info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs) return info
[ "def", "volume_delete", "(", "provider", ",", "names", ",", "**", "kwargs", ")", ":", "client", "=", "_get_client", "(", ")", "info", "=", "client", ".", "extra_action", "(", "provider", "=", "provider", ",", "names", "=", "names", ",", "action", "=", ...
delete block storage device .
train
true
22,327
def no_testtools_skip_decorator(logical_line): if TESTTOOLS_SKIP_DECORATOR.match(logical_line): (yield (0, 'T109: Cannot use testtools.skip decorator; instead use decorators.skip_because from tempest.lib'))
[ "def", "no_testtools_skip_decorator", "(", "logical_line", ")", ":", "if", "TESTTOOLS_SKIP_DECORATOR", ".", "match", "(", "logical_line", ")", ":", "(", "yield", "(", "0", ",", "'T109: Cannot use testtools.skip decorator; instead use decorators.skip_because from tempest.lib'", ...
check that methods do not have the testtools .
train
false
22,328
def _find_file_type(file_names, extension): return filter((lambda f: f.lower().endswith(extension)), file_names)
[ "def", "_find_file_type", "(", "file_names", ",", "extension", ")", ":", "return", "filter", "(", "(", "lambda", "f", ":", "f", ".", "lower", "(", ")", ".", "endswith", "(", "extension", ")", ")", ",", "file_names", ")" ]
returns files that end with the given extension from a list of file names .
train
false
22,331
@requires_segment_info def output_lister(pl, segment_info): return ((updated(segment_info, output=output[u'name']), {u'draw_inner_divider': None}) for output in get_connected_xrandr_outputs(pl))
[ "@", "requires_segment_info", "def", "output_lister", "(", "pl", ",", "segment_info", ")", ":", "return", "(", "(", "updated", "(", "segment_info", ",", "output", "=", "output", "[", "u'name'", "]", ")", ",", "{", "u'draw_inner_divider'", ":", "None", "}", ...
list all outputs in segment_info format .
train
false
22,332
def endian_swap_words(source): assert ((len(source) % 4) == 0) words = ('I' * (len(source) // 4)) return struct.pack(('<' + words), *struct.unpack(('>' + words), source))
[ "def", "endian_swap_words", "(", "source", ")", ":", "assert", "(", "(", "len", "(", "source", ")", "%", "4", ")", "==", "0", ")", "words", "=", "(", "'I'", "*", "(", "len", "(", "source", ")", "//", "4", ")", ")", "return", "struct", ".", "pac...
endian-swap each word in source bitstring .
train
true
22,333
def sync_contains(value): return var_contains('SYNC', value)
[ "def", "sync_contains", "(", "value", ")", ":", "return", "var_contains", "(", "'SYNC'", ",", "value", ")" ]
verify if sync variable contains a value in make .
train
false
22,335
def set_identity_pool_roles(IdentityPoolId, AuthenticatedRole=None, UnauthenticatedRole=None, region=None, key=None, keyid=None, profile=None): conn_params = dict(region=region, key=key, keyid=keyid, profile=profile) conn = _get_conn(**conn_params) try: if AuthenticatedRole: role_arn = _get_role_arn(Authenticat...
[ "def", "set_identity_pool_roles", "(", "IdentityPoolId", ",", "AuthenticatedRole", "=", "None", ",", "UnauthenticatedRole", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", ...
given an identity pool id .
train
true
22,336
def _retrieve_grains(proxy): global GRAINS_CACHE if (not GRAINS_CACHE): GRAINS_CACHE = proxy['napalm.grains']() return GRAINS_CACHE
[ "def", "_retrieve_grains", "(", "proxy", ")", ":", "global", "GRAINS_CACHE", "if", "(", "not", "GRAINS_CACHE", ")", ":", "GRAINS_CACHE", "=", "proxy", "[", "'napalm.grains'", "]", "(", ")", "return", "GRAINS_CACHE" ]
retrieves the grains from the network device if not cached already .
train
false
22,337
def getfigs(*fig_nums): from matplotlib._pylab_helpers import Gcf if (not fig_nums): fig_managers = Gcf.get_all_fig_managers() return [fm.canvas.figure for fm in fig_managers] else: figs = [] for num in fig_nums: f = Gcf.figs.get(num) if (f is None): print ('Warning: figure %s not available.' % num...
[ "def", "getfigs", "(", "*", "fig_nums", ")", ":", "from", "matplotlib", ".", "_pylab_helpers", "import", "Gcf", "if", "(", "not", "fig_nums", ")", ":", "fig_managers", "=", "Gcf", ".", "get_all_fig_managers", "(", ")", "return", "[", "fm", ".", "canvas", ...
get a list of matplotlib figures by figure numbers .
train
true
22,338
def calculator_prompt(): print 'Welcome to the calculator. Press Ctrl+C to exit.' cp = CalcParser() try: while True: try: line = raw_input('--> ') print cp.calc(line) except ParseError as err: print 'Error:', err except KeyboardInterrupt: print '... Thanks for using the calculator.'
[ "def", "calculator_prompt", "(", ")", ":", "print", "'Welcome to the calculator. Press Ctrl+C to exit.'", "cp", "=", "CalcParser", "(", ")", "try", ":", "while", "True", ":", "try", ":", "line", "=", "raw_input", "(", "'--> '", ")", "print", "cp", ".", "calc",...
a toy calculator prompt for interactive computations .
train
false
22,340
def readUntilWhitespace(stream, maxchars=None): txt = b_('') while True: tok = stream.read(1) if (tok.isspace() or (not tok)): break txt += tok if (len(txt) == maxchars): break return txt
[ "def", "readUntilWhitespace", "(", "stream", ",", "maxchars", "=", "None", ")", ":", "txt", "=", "b_", "(", "''", ")", "while", "True", ":", "tok", "=", "stream", ".", "read", "(", "1", ")", "if", "(", "tok", ".", "isspace", "(", ")", "or", "(", ...
reads non-whitespace characters and returns them .
train
false
22,341
def getMemoryUsage(): return (_thisProcess.memory_info()[0] / 1048576.0)
[ "def", "getMemoryUsage", "(", ")", ":", "return", "(", "_thisProcess", ".", "memory_info", "(", ")", "[", "0", "]", "/", "1048576.0", ")" ]
get the memory currently used by this python process .
train
false
22,343
def log_buffer_bytes(): return logs_buffer().bytes()
[ "def", "log_buffer_bytes", "(", ")", ":", "return", "logs_buffer", "(", ")", ".", "bytes", "(", ")" ]
returns the size of the logs buffer .
train
false
22,344
def __fixlocaluser(username): if ('\\' not in username): username = '{0}\\{1}'.format(__salt__['grains.get']('host'), username) return username.lower()
[ "def", "__fixlocaluser", "(", "username", ")", ":", "if", "(", "'\\\\'", "not", "in", "username", ")", ":", "username", "=", "'{0}\\\\{1}'", ".", "format", "(", "__salt__", "[", "'grains.get'", "]", "(", "'host'", ")", ",", "username", ")", "return", "us...
prefixes a username w/o a backslash with the computername i .
train
false
22,348
def test_consistency_cpu_serial(): seed = 12345 n_samples = 5 n_streams = 12 n_substreams = 7 samples = [] curr_rstate = numpy.array(([seed] * 6), dtype='int32') for i in range(n_streams): stream_rstate = curr_rstate.copy() for j in range(n_substreams): rstate = theano.shared(numpy.array([stream_rstate.co...
[ "def", "test_consistency_cpu_serial", "(", ")", ":", "seed", "=", "12345", "n_samples", "=", "5", "n_streams", "=", "12", "n_substreams", "=", "7", "samples", "=", "[", "]", "curr_rstate", "=", "numpy", ".", "array", "(", "(", "[", "seed", "]", "*", "6...
verify that the random numbers generated by mrg_uniform .
train
false
22,350
def open_docs(kind=None, version=None): if (kind is None): kind = get_config('MNE_DOCS_KIND', 'api') help_dict = dict(api='python_reference.html', tutorials='tutorials.html', examples='auto_examples/index.html') if (kind not in help_dict): raise ValueError(('kind must be one of %s, got %s' % (sorted(help_dict.ke...
[ "def", "open_docs", "(", "kind", "=", "None", ",", "version", "=", "None", ")", ":", "if", "(", "kind", "is", "None", ")", ":", "kind", "=", "get_config", "(", "'MNE_DOCS_KIND'", ",", "'api'", ")", "help_dict", "=", "dict", "(", "api", "=", "'python_...
launch a new web browser tab with the mne documentation .
train
false
22,351
def UnregisterPythonExe(exeAlias): try: win32api.RegDeleteKey(GetRootKey(), ((GetAppPathsKey() + '\\') + exeAlias)) except win32api.error as exc: import winerror if (exc.winerror != winerror.ERROR_FILE_NOT_FOUND): raise return
[ "def", "UnregisterPythonExe", "(", "exeAlias", ")", ":", "try", ":", "win32api", ".", "RegDeleteKey", "(", "GetRootKey", "(", ")", ",", "(", "(", "GetAppPathsKey", "(", ")", "+", "'\\\\'", ")", "+", "exeAlias", ")", ")", "except", "win32api", ".", "error...
unregister a .
train
false
22,352
def _api_config_set_apikey(output, kwargs): cfg.api_key.set(config.create_api_key()) config.save_config() return report(output, keyword='apikey', data=cfg.api_key())
[ "def", "_api_config_set_apikey", "(", "output", ",", "kwargs", ")", ":", "cfg", ".", "api_key", ".", "set", "(", "config", ".", "create_api_key", "(", ")", ")", "config", ".", "save_config", "(", ")", "return", "report", "(", "output", ",", "keyword", "=...
api: accepts output .
train
false
22,353
def _gen_rules_port_max(port_max, top_bit): rules = [] mask = (top_bit - 1) while True: if ((port_max & mask) == mask): rules.append(_hex_format((port_max & (~ mask)), mask)) break top_bit >>= 1 mask >>= 1 if ((port_max & top_bit) == top_bit): rules.append(_hex_format(((port_max & (~ mask)) & (~ top...
[ "def", "_gen_rules_port_max", "(", "port_max", ",", "top_bit", ")", ":", "rules", "=", "[", "]", "mask", "=", "(", "top_bit", "-", "1", ")", "while", "True", ":", "if", "(", "(", "port_max", "&", "mask", ")", "==", "mask", ")", ":", "rules", ".", ...
encode a port range range(port_max & ~ .
train
false
22,354
@pytest.fixture def samp_hub(request): my_hub = SAMPHubServer() my_hub.start() request.addfinalizer(my_hub.stop)
[ "@", "pytest", ".", "fixture", "def", "samp_hub", "(", "request", ")", ":", "my_hub", "=", "SAMPHubServer", "(", ")", "my_hub", ".", "start", "(", ")", "request", ".", "addfinalizer", "(", "my_hub", ".", "stop", ")" ]
a fixture that can be used by client tests that require a hub .
train
false
22,355
@plugin.route('/play/<url>') def play_video_by_url(url): quality = plugin.get_setting('quality') url = api.get_media_stream_by_url(quality, url) plugin.log.info(('Play Quality: %s' % quality)) plugin.log.info(('Playing url: %s' % url)) return plugin.set_resolved_url(url)
[ "@", "plugin", ".", "route", "(", "'/play/<url>'", ")", "def", "play_video_by_url", "(", "url", ")", ":", "quality", "=", "plugin", ".", "get_setting", "(", "'quality'", ")", "url", "=", "api", ".", "get_media_stream_by_url", "(", "quality", ",", "url", ")...
this method is used to play any shahid .
train
false
22,356
@Profiler.profile def test_bulk_save(n): session = Session(bind=engine) session.bulk_save_objects([Customer(name=('customer name %d' % i), description=('customer description %d' % i)) for i in range(n)]) session.commit()
[ "@", "Profiler", ".", "profile", "def", "test_bulk_save", "(", "n", ")", ":", "session", "=", "Session", "(", "bind", "=", "engine", ")", "session", ".", "bulk_save_objects", "(", "[", "Customer", "(", "name", "=", "(", "'customer name %d'", "%", "i", ")...
individual insert/commit pairs using the "bulk" api .
train
false
22,357
def datasets_from_deployment(deployment): for node in deployment.nodes.itervalues(): if (node.manifestations is None): continue for manifestation in node.manifestations.values(): if manifestation.primary: (yield api_dataset_from_dataset_and_node(manifestation.dataset, node.uuid))
[ "def", "datasets_from_deployment", "(", "deployment", ")", ":", "for", "node", "in", "deployment", ".", "nodes", ".", "itervalues", "(", ")", ":", "if", "(", "node", ".", "manifestations", "is", "None", ")", ":", "continue", "for", "manifestation", "in", "...
extract the primary datasets from the supplied deployment instance .
train
false
22,358
@contextmanager def pending_warnings(): logger = logging.getLogger() memhandler = MemoryHandler() memhandler.setLevel(logging.WARNING) try: handlers = [] for handler in logger.handlers[:]: if isinstance(handler, WarningStreamHandler): logger.removeHandler(handler) handlers.append(handler) logger.ad...
[ "@", "contextmanager", "def", "pending_warnings", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "memhandler", "=", "MemoryHandler", "(", ")", "memhandler", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "try", ":", "handlers", ...
contextmanager to pend logging warnings temporary .
train
false
22,359
def compile_info(session, vm_ref): power_state = get_power_state(session, vm_ref) max_mem = session.call_xenapi('VM.get_memory_static_max', vm_ref) mem = session.call_xenapi('VM.get_memory_dynamic_max', vm_ref) num_cpu = session.call_xenapi('VM.get_VCPUs_max', vm_ref) return hardware.InstanceInfo(state=power_state...
[ "def", "compile_info", "(", "session", ",", "vm_ref", ")", ":", "power_state", "=", "get_power_state", "(", "session", ",", "vm_ref", ")", "max_mem", "=", "session", ".", "call_xenapi", "(", "'VM.get_memory_static_max'", ",", "vm_ref", ")", "mem", "=", "sessio...
fill record with vm status information .
train
false
22,361
def get_text_from_files(vision, index, input_filenames): texts = vision.detect_text(input_filenames) for (filename, text) in texts.items(): extract_descriptions(filename, index, text)
[ "def", "get_text_from_files", "(", "vision", ",", "index", ",", "input_filenames", ")", ":", "texts", "=", "vision", ".", "detect_text", "(", "input_filenames", ")", "for", "(", "filename", ",", "text", ")", "in", "texts", ".", "items", "(", ")", ":", "e...
call the vision api on a file and index the results .
train
false
22,362
def flow_hierarchy(G, weight=None): if (not G.is_directed()): raise nx.NetworkXError('G must be a digraph in flow_heirarchy') scc = nx.strongly_connected_components(G) return (1.0 - (sum((G.subgraph(c).size(weight) for c in scc)) / float(G.size(weight))))
[ "def", "flow_hierarchy", "(", "G", ",", "weight", "=", "None", ")", ":", "if", "(", "not", "G", ".", "is_directed", "(", ")", ")", ":", "raise", "nx", ".", "NetworkXError", "(", "'G must be a digraph in flow_heirarchy'", ")", "scc", "=", "nx", ".", "stro...
returns the flow hierarchy of a directed network .
train
false
22,363
def build_dqn(num_actions, action_repeat): inputs = tf.placeholder(tf.float32, [None, action_repeat, 84, 84]) net = tf.transpose(inputs, [0, 2, 3, 1]) net = tflearn.conv_2d(net, 32, 8, strides=4, activation='relu') net = tflearn.conv_2d(net, 64, 4, strides=2, activation='relu') net = tflearn.fully_connected(net, 2...
[ "def", "build_dqn", "(", "num_actions", ",", "action_repeat", ")", ":", "inputs", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "[", "None", ",", "action_repeat", ",", "84", ",", "84", "]", ")", "net", "=", "tf", ".", "transpose", "(...
building a dqn .
train
false
22,365
@pytest.mark.cmd @pytest.mark.django_db def test_import_onefile_with_user(capfd, tmpdir, site_users): from pootle_store.models import Store user = site_users['user'].username p = tmpdir.mkdir('sub').join('store0.po') store = Store.objects.get(pootle_path='/language0/project0/store0.po') p.write(str(get_translated_...
[ "@", "pytest", ".", "mark", ".", "cmd", "@", "pytest", ".", "mark", ".", "django_db", "def", "test_import_onefile_with_user", "(", "capfd", ",", "tmpdir", ",", "site_users", ")", ":", "from", "pootle_store", ".", "models", "import", "Store", "user", "=", "...
load an one unit po file .
train
false
22,368
def get_pricing_steps_for_products(context, products): (mod, ctx) = _get_module_and_context(context) steps = mod.get_pricing_steps_for_products(ctx, products) for module in get_discount_modules(): steps = module.get_pricing_steps_for_products(ctx, products, steps) return steps
[ "def", "get_pricing_steps_for_products", "(", "context", ",", "products", ")", ":", "(", "mod", ",", "ctx", ")", "=", "_get_module_and_context", "(", "context", ")", "steps", "=", "mod", ".", "get_pricing_steps_for_products", "(", "ctx", ",", "products", ")", ...
get pricing steps for a bunch of products .
train
false
22,369
def decorate_urlpatterns(urlpatterns, decorator): for pattern in urlpatterns: if hasattr(pattern, u'url_patterns'): decorate_urlpatterns(pattern.url_patterns, decorator) if (DJANGO_VERSION < (1, 10)): if hasattr(pattern, u'_callback'): pattern._callback = update_wrapper(decorator(pattern.callback), patte...
[ "def", "decorate_urlpatterns", "(", "urlpatterns", ",", "decorator", ")", ":", "for", "pattern", "in", "urlpatterns", ":", "if", "hasattr", "(", "pattern", ",", "u'url_patterns'", ")", ":", "decorate_urlpatterns", "(", "pattern", ".", "url_patterns", ",", "decor...
decorate all the views in the passed urlpatterns list with the given decorator .
train
false
22,370
def reorder_plugins(placeholder, parent_id, language, order): plugins = CMSPlugin.objects.filter(parent=parent_id, placeholder=placeholder, language=language).order_by('position') order = list(order) if order: plugins = plugins.filter(pk__in=order) for plugin in plugins.iterator(): position = order.index(plug...
[ "def", "reorder_plugins", "(", "placeholder", ",", "parent_id", ",", "language", ",", "order", ")", ":", "plugins", "=", "CMSPlugin", ".", "objects", ".", "filter", "(", "parent", "=", "parent_id", ",", "placeholder", "=", "placeholder", ",", "language", "="...
reorder the plugins according the order parameter .
train
false
22,372
@treeio_login_required @handle_response_format @_process_mass_form def type_view(request, type_id, response_format='html'): item_type = get_object_or_404(ItemType, pk=type_id) if (not request.user.profile.has_permission(item_type)): return user_denied(request, message="You don't have access to this Item Type", resp...
[ "@", "treeio_login_required", "@", "handle_response_format", "@", "_process_mass_form", "def", "type_view", "(", "request", ",", "type_id", ",", "response_format", "=", "'html'", ")", ":", "item_type", "=", "get_object_or_404", "(", "ItemType", ",", "pk", "=", "ty...
contacts by type .
train
false
22,373
def pbkdf2(password, salt, iterations, dklen=0, digest=None): assert (iterations > 0) if (not digest): digest = hashlib.sha256 password = force_bytes(password) salt = force_bytes(salt) hlen = digest().digest_size if (not dklen): dklen = hlen if (dklen > (((2 ** 32) - 1) * hlen)): raise OverflowError(u'dkle...
[ "def", "pbkdf2", "(", "password", ",", "salt", ",", "iterations", ",", "dklen", "=", "0", ",", "digest", "=", "None", ")", ":", "assert", "(", "iterations", ">", "0", ")", "if", "(", "not", "digest", ")", ":", "digest", "=", "hashlib", ".", "sha256...
module function to hash a password according to the pbkdf2 specification .
train
false
22,374
def assert_not_instance_of(expected, actual, msg=None): assert (not isinstance(actual, expected, msg))
[ "def", "assert_not_instance_of", "(", "expected", ",", "actual", ",", "msg", "=", "None", ")", ":", "assert", "(", "not", "isinstance", "(", "actual", ",", "expected", ",", "msg", ")", ")" ]
verify that object is not an instance of expected .
train
false
22,375
def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper): Loader.add_path_resolver(tag, path, kind) Dumper.add_path_resolver(tag, path, kind)
[ "def", "add_path_resolver", "(", "tag", ",", "path", ",", "kind", "=", "None", ",", "Loader", "=", "Loader", ",", "Dumper", "=", "Dumper", ")", ":", "Loader", ".", "add_path_resolver", "(", "tag", ",", "path", ",", "kind", ")", "Dumper", ".", "add_path...
add a path based resolver for the given tag .
train
true
22,376
def StartSerialServer(context=None, identity=None, **kwargs): framer = kwargs.pop('framer', ModbusAsciiFramer) server = ModbusSerialServer(context, framer, identity, **kwargs) server.serve_forever()
[ "def", "StartSerialServer", "(", "context", "=", "None", ",", "identity", "=", "None", ",", "**", "kwargs", ")", ":", "framer", "=", "kwargs", ".", "pop", "(", "'framer'", ",", "ModbusAsciiFramer", ")", "server", "=", "ModbusSerialServer", "(", "context", ...
helper method to start the modbus async serial server .
train
false
22,379
def task_notify(form): vars = form.vars pe_id = vars.pe_id if (not pe_id): return user = current.auth.user if (user and (user.pe_id == pe_id)): return if (int(vars.status) not in current.response.s3.project_task_active_statuses): return if ((form.record is None) or (int(pe_id) != form.record.pe_id)): set...
[ "def", "task_notify", "(", "form", ")", ":", "vars", "=", "form", ".", "vars", "pe_id", "=", "vars", ".", "pe_id", "if", "(", "not", "pe_id", ")", ":", "return", "user", "=", "current", ".", "auth", ".", "user", "if", "(", "user", "and", "(", "us...
if the task is assigned to someone then notify them .
train
false
22,380
def _section_cohort_management(course, access): course_key = course.id ccx_enabled = hasattr(course_key, 'ccx') section_data = {'section_key': 'cohort_management', 'section_display_name': _('Cohorts'), 'access': access, 'ccx_is_enabled': ccx_enabled, 'course_cohort_settings_url': reverse('course_cohort_settings', kw...
[ "def", "_section_cohort_management", "(", "course", ",", "access", ")", ":", "course_key", "=", "course", ".", "id", "ccx_enabled", "=", "hasattr", "(", "course_key", ",", "'ccx'", ")", "section_data", "=", "{", "'section_key'", ":", "'cohort_management'", ",", ...
provide data for the corresponding cohort management section .
train
false
22,381
def setUnjellyableForClassTree(module, baseClass, prefix=None): if (prefix is None): prefix = module.__name__ if prefix: prefix = ('%s.' % prefix) for i in dir(module): i_ = getattr(module, i) if (type(i_) == types.ClassType): if issubclass(i_, baseClass): setUnjellyableForClass(('%s%s' % (prefix, i))...
[ "def", "setUnjellyableForClassTree", "(", "module", ",", "baseClass", ",", "prefix", "=", "None", ")", ":", "if", "(", "prefix", "is", "None", ")", ":", "prefix", "=", "module", ".", "__name__", "if", "prefix", ":", "prefix", "=", "(", "'%s.'", "%", "p...
set all classes in a module derived from c{baseclass} as copiers for a corresponding remote class .
train
false
22,382
def create_import_job(task): ij = ImportJob(task=task, user=g.user) save_to_db(ij, 'Import job saved')
[ "def", "create_import_job", "(", "task", ")", ":", "ij", "=", "ImportJob", "(", "task", "=", "task", ",", "user", "=", "g", ".", "user", ")", "save_to_db", "(", "ij", ",", "'Import job saved'", ")" ]
create import record in db .
train
false
22,384
def find_number(s): r = re.search('[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?', s) if (r is not None): return r.span(0) return None
[ "def", "find_number", "(", "s", ")", ":", "r", "=", "re", ".", "search", "(", "'[+-]?(\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)([eE][+-]?\\\\d+)?'", ",", "s", ")", "if", "(", "r", "is", "not", "None", ")", ":", "return", "r", ".", "span", "(", "0", ")", "return", ...
returns none if there are no numbers in the string .
train
false
22,385
def tmul(lin_op, value, is_abs=False): if (lin_op.type is lo.VARIABLE): return {lin_op.data: value} elif (lin_op.type is lo.NO_OP): return {} else: if is_abs: result = op_abs_tmul(lin_op, value) else: result = op_tmul(lin_op, value) result_dicts = [] for arg in lin_op.args: result_dicts.append(t...
[ "def", "tmul", "(", "lin_op", ",", "value", ",", "is_abs", "=", "False", ")", ":", "if", "(", "lin_op", ".", "type", "is", "lo", ".", "VARIABLE", ")", ":", "return", "{", "lin_op", ".", "data", ":", "value", "}", "elif", "(", "lin_op", ".", "type...
multiply the transpose of the expression tree by a vector .
train
false
22,386
def get_deployment_id(): try: acc = appscale_info.get_appcontroller_client() if acc.deployment_id_exists(): return acc.get_deployment_id() except AppControllerException: logging.exception('AppControllerException while querying for deployment ID.') return None
[ "def", "get_deployment_id", "(", ")", ":", "try", ":", "acc", "=", "appscale_info", ".", "get_appcontroller_client", "(", ")", "if", "acc", ".", "deployment_id_exists", "(", ")", ":", "return", "acc", ".", "get_deployment_id", "(", ")", "except", "AppControlle...
retrieves the deployment id for this appscale deployment .
train
false
22,388
def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs): for method_name in interface.names(): if (not isinstance(interface[method_name], Method)): raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name)) def class_decorator(cls): for na...
[ "def", "interface_decorator", "(", "decorator_name", ",", "interface", ",", "method_decorator", ",", "*", "args", ",", "**", "kwargs", ")", ":", "for", "method_name", "in", "interface", ".", "names", "(", ")", ":", "if", "(", "not", "isinstance", "(", "int...
create a class decorator which applies a method decorator to each method of an interface .
train
false
22,389
def natural(text): def num(s): 'Convert text segment to int if necessary' return (int(s) if s.isdigit() else s) return [num(s) for s in re.split('(\\d+)', str(text))]
[ "def", "natural", "(", "text", ")", ":", "def", "num", "(", "s", ")", ":", "return", "(", "int", "(", "s", ")", "if", "s", ".", "isdigit", "(", ")", "else", "s", ")", "return", "[", "num", "(", "s", ")", "for", "s", "in", "re", ".", "split"...
restrict input type to the natural numbers .
train
false
22,390
@cleanup def test_SymLogNorm_colorbar(): norm = mcolors.SymLogNorm(0.1, vmin=(-1), vmax=1, linscale=1) fig = plt.figure() cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm) plt.close(fig)
[ "@", "cleanup", "def", "test_SymLogNorm_colorbar", "(", ")", ":", "norm", "=", "mcolors", ".", "SymLogNorm", "(", "0.1", ",", "vmin", "=", "(", "-", "1", ")", ",", "vmax", "=", "1", ",", "linscale", "=", "1", ")", "fig", "=", "plt", ".", "figure", ...
test un-called symlognorm in a colorbar .
train
false
22,392
def _default_template_ctx_processor(): reqctx = _request_ctx_stack.top appctx = _app_ctx_stack.top rv = {} if (appctx is not None): rv['g'] = appctx.g if (reqctx is not None): rv['request'] = reqctx.request rv['session'] = reqctx.session return rv
[ "def", "_default_template_ctx_processor", "(", ")", ":", "reqctx", "=", "_request_ctx_stack", ".", "top", "appctx", "=", "_app_ctx_stack", ".", "top", "rv", "=", "{", "}", "if", "(", "appctx", "is", "not", "None", ")", ":", "rv", "[", "'g'", "]", "=", ...
default template context processor .
train
true
22,393
def print_mathml(expr, **settings): s = MathMLPrinter(settings) xml = s._print(sympify(expr)) s.apply_patch() pretty_xml = xml.toprettyxml() s.restore_patch() print(pretty_xml)
[ "def", "print_mathml", "(", "expr", ",", "**", "settings", ")", ":", "s", "=", "MathMLPrinter", "(", "settings", ")", "xml", "=", "s", ".", "_print", "(", "sympify", "(", "expr", ")", ")", "s", ".", "apply_patch", "(", ")", "pretty_xml", "=", "xml", ...
prints a pretty representation of the mathml code for expr examples .
train
false
22,395
def selectionsort(a): for i in range(len(a)): min = i for j in range(i, len(a)): if (a[j] < a[min]): min = j (a[i], a[min]) = (a[min], a[i]) return a
[ "def", "selectionsort", "(", "a", ")", ":", "for", "i", "in", "range", "(", "len", "(", "a", ")", ")", ":", "min", "=", "i", "for", "j", "in", "range", "(", "i", ",", "len", "(", "a", ")", ")", ":", "if", "(", "a", "[", "j", "]", "<", "...
selectionsort implementation .
train
false
22,396
@contextmanager def attempt_effective_uid(username, suppress_errors=False): original_euid = os.geteuid() new_euid = pwd.getpwnam(username).pw_uid restore_euid = False if (original_euid != new_euid): try: os.seteuid(new_euid) except OSError as e: if ((not suppress_errors) or (e.errno != 1)): raise el...
[ "@", "contextmanager", "def", "attempt_effective_uid", "(", "username", ",", "suppress_errors", "=", "False", ")", ":", "original_euid", "=", "os", ".", "geteuid", "(", ")", "new_euid", "=", "pwd", ".", "getpwnam", "(", "username", ")", ".", "pw_uid", "resto...
a context manager to temporarily change the effective user id .
train
false
22,398
def approx_point_big(src, dest): xy = src.read((2 * 8)) dest.write(xy[:5]) dest.write('\x00\x00\x00') dest.write(xy[8:13]) dest.write('\x00\x00\x00')
[ "def", "approx_point_big", "(", "src", ",", "dest", ")", ":", "xy", "=", "src", ".", "read", "(", "(", "2", "*", "8", ")", ")", "dest", ".", "write", "(", "xy", "[", ":", "5", "]", ")", "dest", ".", "write", "(", "'\\x00\\x00\\x00'", ")", "dest...
copy a pair of big-endian doubles between files .
train
false
22,399
def educate_backticks(s): return s.replace('``', '&#8220;').replace("''", '&#8221;')
[ "def", "educate_backticks", "(", "s", ")", ":", "return", "s", ".", "replace", "(", "'``'", ",", "'&#8220;'", ")", ".", "replace", "(", "\"''\"", ",", "'&#8221;'", ")" ]
parameter: string .
train
false
22,400
def user_name_validator(key, data, errors, context): model = context['model'] new_user_name = data[key] if (not isinstance(new_user_name, basestring)): raise Invalid(_('User names must be strings')) user = model.User.get(new_user_name) if (user is not None): user_obj_from_context = context.get('user_obj') if...
[ "def", "user_name_validator", "(", "key", ",", "data", ",", "errors", ",", "context", ")", ":", "model", "=", "context", "[", "'model'", "]", "new_user_name", "=", "data", "[", "key", "]", "if", "(", "not", "isinstance", "(", "new_user_name", ",", "bases...
validate a new user name .
train
false
22,403
@handle_response_format @treeio_login_required def asset_view(request, asset_id, response_format='html'): asset = get_object_or_404(Asset, pk=asset_id) return render_to_response('finance/asset_view', {'asset': asset}, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "asset_view", "(", "request", ",", "asset_id", ",", "response_format", "=", "'html'", ")", ":", "asset", "=", "get_object_or_404", "(", "Asset", ",", "pk", "=", "asset_id", ")", "return", "rende...
single transaction view page .
train
false
22,404
def do_comparison(good_record, test_record): good_handle = StringIO(good_record) test_handle = StringIO(test_record) while True: good_line = good_handle.readline() test_line = test_handle.readline() if ((not good_line) and (not test_line)): break if (not good_line): raise AssertionError(('Extra info in...
[ "def", "do_comparison", "(", "good_record", ",", "test_record", ")", ":", "good_handle", "=", "StringIO", "(", "good_record", ")", "test_handle", "=", "StringIO", "(", "test_record", ")", "while", "True", ":", "good_line", "=", "good_handle", ".", "readline", ...
compare two records to see if they are the same .
train
false
22,405
def test_cat_list_input(test_data): num_items = CountDistinct(values=test_data.cat_list).value bar_builder = BarBuilder(test_data.cat_list) bar_builder.create() assert (len(bar_builder.comp_glyphs) == num_items)
[ "def", "test_cat_list_input", "(", "test_data", ")", ":", "num_items", "=", "CountDistinct", "(", "values", "=", "test_data", ".", "cat_list", ")", ".", "value", "bar_builder", "=", "BarBuilder", "(", "test_data", ".", "cat_list", ")", "bar_builder", ".", "cre...
given values of categorical data .
train
false
22,408
def _enqueue_suggestion_email_task(exploration_id, thread_id): payload = {'exploration_id': exploration_id, 'thread_id': thread_id} taskqueue_services.enqueue_task(feconf.TASK_URL_SUGGESTION_EMAILS, payload, 0)
[ "def", "_enqueue_suggestion_email_task", "(", "exploration_id", ",", "thread_id", ")", ":", "payload", "=", "{", "'exploration_id'", ":", "exploration_id", ",", "'thread_id'", ":", "thread_id", "}", "taskqueue_services", ".", "enqueue_task", "(", "feconf", ".", "TAS...
adds a send suggestion email task into the task queue .
train
false
22,409
def verify_open(strategy, backend, user=None, **kwargs): if ((not user) and (not appsettings.REGISTRATION_OPEN)): raise AuthException(backend, _(u'New registrations are disabled!'))
[ "def", "verify_open", "(", "strategy", ",", "backend", ",", "user", "=", "None", ",", "**", "kwargs", ")", ":", "if", "(", "(", "not", "user", ")", "and", "(", "not", "appsettings", ".", "REGISTRATION_OPEN", ")", ")", ":", "raise", "AuthException", "("...
checks whether it is possible to create new user .
train
false
22,410
def Q(filter_, thing): if isinstance(filter_, type([])): return flatten(*[_Q(x, thing) for x in filter_]) elif isinstance(filter_, type({})): d = dict.fromkeys(list(filter_.keys())) for k in d: d[k] = Q(k, thing) return d elif (' ' in filter_): parts = filter_.strip().split() r = None for p in parts...
[ "def", "Q", "(", "filter_", ",", "thing", ")", ":", "if", "isinstance", "(", "filter_", ",", "type", "(", "[", "]", ")", ")", ":", "return", "flatten", "(", "*", "[", "_Q", "(", "x", ",", "thing", ")", "for", "x", "in", "filter_", "]", ")", "...
type: - list: a flattened list of all searches - dict: dict with vals each of which is that search notes: [1] parent thing .
train
false
22,412
def train_test_split(*arrays, **options): n_arrays = len(arrays) if (n_arrays == 0): raise ValueError('At least one array required as input') test_size = options.pop('test_size', None) train_size = options.pop('train_size', None) random_state = options.pop('random_state', None) stratify = options.pop('stratify'...
[ "def", "train_test_split", "(", "*", "arrays", ",", "**", "options", ")", ":", "n_arrays", "=", "len", "(", "arrays", ")", "if", "(", "n_arrays", "==", "0", ")", ":", "raise", "ValueError", "(", "'At least one array required as input'", ")", "test_size", "="...
split arrays or matrices into random train and test subsets quick utility that wraps input validation and next(shufflesplit() .
train
false
22,413
def decorated_with_property(node): if (not node.decorators): return False for decorator in node.decorators.nodes: if (not isinstance(decorator, astroid.Name)): continue try: for infered in decorator.infer(): if isinstance(infered, astroid.Class): if ((infered.root().name == BUILTINS_NAME) and (in...
[ "def", "decorated_with_property", "(", "node", ")", ":", "if", "(", "not", "node", ".", "decorators", ")", ":", "return", "False", "for", "decorator", "in", "node", ".", "decorators", ".", "nodes", ":", "if", "(", "not", "isinstance", "(", "decorator", "...
detect if the given function node is decorated with a property .
train
false
22,414
def Internaldate2tuple(resp): mo = InternalDate.match(resp) if (not mo): return None mon = Mon2num[mo.group('mon')] zonen = mo.group('zonen') day = int(mo.group('day')) year = int(mo.group('year')) hour = int(mo.group('hour')) min = int(mo.group('min')) sec = int(mo.group('sec')) zoneh = int(mo.group('zoneh...
[ "def", "Internaldate2tuple", "(", "resp", ")", ":", "mo", "=", "InternalDate", ".", "match", "(", "resp", ")", "if", "(", "not", "mo", ")", ":", "return", "None", "mon", "=", "Mon2num", "[", "mo", ".", "group", "(", "'mon'", ")", "]", "zonen", "=",...
parse an imap4 internaldate string .
train
false
22,415
def watch_server_pids(server_pids, interval=1, **kwargs): status = {} start = time.time() end = (start + interval) server_pids = dict(server_pids) while True: for (server, pids) in server_pids.items(): for pid in pids: try: os.waitpid(pid, os.WNOHANG) except OSError as e: if (e.errno not in ...
[ "def", "watch_server_pids", "(", "server_pids", ",", "interval", "=", "1", ",", "**", "kwargs", ")", ":", "status", "=", "{", "}", "start", "=", "time", ".", "time", "(", ")", "end", "=", "(", "start", "+", "interval", ")", "server_pids", "=", "dict"...
monitor a collection of server pids yielding back those pids that arent responding to signals .
train
false
22,416
def _ask_snippets(snippets): display = [(as_unicode('%i: %s (%s)') % ((i + 1), escape(s.description, '\\'), escape(s.location, '\\'))) for (i, s) in enumerate(snippets)] return _ask_user(snippets, display)
[ "def", "_ask_snippets", "(", "snippets", ")", ":", "display", "=", "[", "(", "as_unicode", "(", "'%i: %s (%s)'", ")", "%", "(", "(", "i", "+", "1", ")", ",", "escape", "(", "s", ".", "description", ",", "'\\\\'", ")", ",", "escape", "(", "s", ".", ...
given a list of snippets .
train
false
22,417
def onInterfaceAppReady(): INFO_MSG(('onInterfaceAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s' % (os.getenv('KBE_BOOTIDX_GROUP'), os.getenv('KBE_BOOTIDX_GLOBAL')))) g_poller.start('localhost', 30040)
[ "def", "onInterfaceAppReady", "(", ")", ":", "INFO_MSG", "(", "(", "'onInterfaceAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s'", "%", "(", "os", ".", "getenv", "(", "'KBE_BOOTIDX_GROUP'", ")", ",", "os", ".", "getenv", "(", "'KBE_BOOTIDX_GLOBAL'", ")", ")"...
kbengine method .
train
false
22,418
def path_hack(): this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), '..') sympy_dir = os.path.normpath(sympy_dir) sys.path.insert(0, sympy_dir) return sympy_dir
[ "def", "path_hack", "(", ")", ":", "this_file", "=", "os", ".", "path", ".", "abspath", "(", "__file__", ")", "sympy_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "this_file", ")", ",", "'..'", ")", "sympy_...
hack sys .
train
false
22,420
def _bytes_iterator_py2(bytes_): for b in bytes_: (yield b)
[ "def", "_bytes_iterator_py2", "(", "bytes_", ")", ":", "for", "b", "in", "bytes_", ":", "(", "yield", "b", ")" ]
returns iterator over a bytestring in python 2 .
train
false
22,421
def connect_cognito_identity(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): from boto.cognito.identity.layer1 import CognitoIdentityConnection return CognitoIdentityConnection(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **kwargs)
[ "def", "connect_cognito_identity", "(", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "**", "kwargs", ")", ":", "from", "boto", ".", "cognito", ".", "identity", ".", "layer1", "import", "CognitoIdentityConnection", "return", "Co...
connect to amazon cognito identity :type aws_access_key_id: string .
train
false