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
48,303
def vm_running(name): name = name.lower() ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if (name in __salt__['vmadm.list'](order='hostname', search='state=running')): ret['result'] = True ret['comment'] = 'vm {0} already running'.format(name) else: ret['result'] = (True if __opts__['test'] else __salt__['vmadm.start'](name, key='hostname')) if ((not isinstance(ret['result'], bool)) and ret['result'].get('Error')): ret['result'] = False ret['comment'] = 'failed to start {0}'.format(name) else: ret['changes'][name] = 'running' ret['comment'] = 'vm {0} started'.format(name) return ret
[ "def", "vm_running", "(", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "(", "name", ...
ensure vm is in the running state on the computenode name : string hostname of vm .
train
true
48,304
def test_sg_filter_trivial(): x = np.array([1.0]) y = savgol_filter(x, 1, 0) assert_equal(y, [1.0]) x = np.array([3.0]) y = savgol_filter(x, 3, 1, mode='constant') assert_almost_equal(y, [1.0], decimal=15) x = np.array([3.0]) y = savgol_filter(x, 3, 1, mode='nearest') assert_almost_equal(y, [3.0], decimal=15) x = np.array(([1.0] * 3)) y = savgol_filter(x, 3, 1, mode='wrap') assert_almost_equal(y, [1.0, 1.0, 1.0], decimal=15)
[ "def", "test_sg_filter_trivial", "(", ")", ":", "x", "=", "np", ".", "array", "(", "[", "1.0", "]", ")", "y", "=", "savgol_filter", "(", "x", ",", "1", ",", "0", ")", "assert_equal", "(", "y", ",", "[", "1.0", "]", ")", "x", "=", "np", ".", "...
test some trivial edge cases for savgol_filter() .
train
false
48,307
def faces(G): f = set() for (v1, edges) in G.items(): for v2 in edges: for v3 in G[v2]: if (v1 == v3): continue if (v1 in G[v3]): f.add(frozenset([v1, v2, v3])) else: for v4 in G[v3]: if (v4 == v2): continue if (v1 in G[v4]): f.add(frozenset([v1, v2, v3, v4])) else: for v5 in G[v4]: if ((v5 == v3) or (v5 == v2)): continue if (v1 in G[v5]): f.add(frozenset([v1, v2, v3, v4, v5])) return f
[ "def", "faces", "(", "G", ")", ":", "f", "=", "set", "(", ")", "for", "(", "v1", ",", "edges", ")", "in", "G", ".", "items", "(", ")", ":", "for", "v2", "in", "edges", ":", "for", "v3", "in", "G", "[", "v2", "]", ":", "if", "(", "v1", "...
return a set of faces in g .
train
false
48,309
def jitclass(spec): def wrap(cls): if config.DISABLE_JIT: return cls else: return register_class_type(cls, spec, types.ClassType, ClassBuilder) return wrap
[ "def", "jitclass", "(", "spec", ")", ":", "def", "wrap", "(", "cls", ")", ":", "if", "config", ".", "DISABLE_JIT", ":", "return", "cls", "else", ":", "return", "register_class_type", "(", "cls", ",", "spec", ",", "types", ".", "ClassType", ",", "ClassB...
a decorator for creating a jitclass .
train
false
48,310
def run_in_subprocess_with_hash_randomization(function, function_args=(), function_kwargs={}, command=sys.executable, module='sympy.utilities.runtests', force=False): p = subprocess.Popen([command, '-RV'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.communicate() if (p.returncode != 0): return False hash_seed = os.getenv('PYTHONHASHSEED') if (not hash_seed): os.environ['PYTHONHASHSEED'] = str(random.randrange((2 ** 32))) elif (not force): return False commandstring = ('import sys; from %s import %s;sys.exit(%s(*%s, **%s))' % (module, function, function, repr(function_args), repr(function_kwargs))) try: p = subprocess.Popen([command, '-R', '-c', commandstring]) p.communicate() except KeyboardInterrupt: p.wait() finally: if (hash_seed is None): del os.environ['PYTHONHASHSEED'] else: os.environ['PYTHONHASHSEED'] = hash_seed return p.returncode
[ "def", "run_in_subprocess_with_hash_randomization", "(", "function", ",", "function_args", "=", "(", ")", ",", "function_kwargs", "=", "{", "}", ",", "command", "=", "sys", ".", "executable", ",", "module", "=", "'sympy.utilities.runtests'", ",", "force", "=", "...
run a function in a python subprocess with hash randomization enabled .
train
false
48,311
def failhard(role): raise FileserverConfigError('Failed to load {0}'.format(role))
[ "def", "failhard", "(", "role", ")", ":", "raise", "FileserverConfigError", "(", "'Failed to load {0}'", ".", "format", "(", "role", ")", ")" ]
fatal configuration issue .
train
false
48,312
def email_notification(version, build, email): log.debug(LOG_TEMPLATE.format(project=version.project.slug, version=version.slug, msg=('sending email to: %s' % email))) context = {'version': version, 'project': version.project, 'build': build, 'build_url': 'https://{0}{1}'.format(getattr(settings, 'PRODUCTION_DOMAIN', 'readthedocs.org'), build.get_absolute_url()), 'unsub_url': 'https://{0}{1}'.format(getattr(settings, 'PRODUCTION_DOMAIN', 'readthedocs.org'), reverse('projects_notifications', args=[version.project.slug]))} if build.commit: title = _('Failed: {project.name} ({commit})').format(commit=build.commit[:8], **context) else: title = _('Failed: {project.name} ({version.verbose_name})').format(**context) send_email(email, title, template='projects/email/build_failed.txt', template_html='projects/email/build_failed.html', context=context)
[ "def", "email_notification", "(", "version", ",", "build", ",", "email", ")", ":", "log", ".", "debug", "(", "LOG_TEMPLATE", ".", "format", "(", "project", "=", "version", ".", "project", ".", "slug", ",", "version", "=", "version", ".", "slug", ",", "...
send email notifications for build failure .
train
false
48,313
def head_pos_to_trans_rot_t(quats): t = quats[..., 0].copy() rotation = quat_to_rot(quats[..., 1:4]) translation = quats[..., 4:7].copy() return (translation, rotation, t)
[ "def", "head_pos_to_trans_rot_t", "(", "quats", ")", ":", "t", "=", "quats", "[", "...", ",", "0", "]", ".", "copy", "(", ")", "rotation", "=", "quat_to_rot", "(", "quats", "[", "...", ",", "1", ":", "4", "]", ")", "translation", "=", "quats", "[",...
convert maxfilter-formatted head position quaternions .
train
false
48,314
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('--console-type', default='serial', help=_('Type of serial console, default="serial".')) def do_get_serial_console(cs, args): if (args.console_type not in ('serial',)): raise exceptions.CommandError(_("Invalid parameter value for 'console_type', currently supported 'serial'.")) server = _find_server(cs, args.server) data = server.get_serial_console(args.console_type) print_console(cs, data)
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "@", "utils", ".", "arg", "(", "'--console-type'", ",", "default", "=", "'serial'", ",", "help", "=", "_", "(...
get a serial console to a server .
train
false
48,316
@utils.arg('--fields', default=None, metavar='<fields>', help=_('Comma-separated list of fields to display. Use the show command to see which fields are available.')) @deprecated_network def do_network_list(cs, args): network_list = cs.networks.list() columns = ['ID', 'Label', 'Cidr'] columns += _get_list_table_columns_and_formatters(args.fields, network_list, exclude_fields=(c.lower() for c in columns))[0] utils.print_list(network_list, columns)
[ "@", "utils", ".", "arg", "(", "'--fields'", ",", "default", "=", "None", ",", "metavar", "=", "'<fields>'", ",", "help", "=", "_", "(", "'Comma-separated list of fields to display. Use the show command to see which fields are available.'", ")", ")", "@", "deprecated_ne...
print a list of available networks .
train
false
48,317
def tdecode(data, key, decode=base64.b64decode, salt_length=16): if decode: data = decode(data) salt = data[:salt_length] return crypt(data[salt_length:], sha1((key + salt)).digest())
[ "def", "tdecode", "(", "data", ",", "key", ",", "decode", "=", "base64", ".", "b64decode", ",", "salt_length", "=", "16", ")", ":", "if", "decode", ":", "data", "=", "decode", "(", "data", ")", "salt", "=", "data", "[", ":", "salt_length", "]", "re...
rc4 decryption of encoded data .
train
false
48,318
def randomPolicy(Ts): numA = len(Ts) dim = len(Ts[0]) return ((ones((dim, numA)) / float(numA)), mean(array(Ts), axis=0))
[ "def", "randomPolicy", "(", "Ts", ")", ":", "numA", "=", "len", "(", "Ts", ")", "dim", "=", "len", "(", "Ts", "[", "0", "]", ")", "return", "(", "(", "ones", "(", "(", "dim", ",", "numA", ")", ")", "/", "float", "(", "numA", ")", ")", ",", ...
each action is equally likely .
train
false
48,319
def raise_invalid(request, location='body', name=None, description=None, **kwargs): request.errors.add(location, name, description, **kwargs) response = json_error_handler(request) raise response
[ "def", "raise_invalid", "(", "request", ",", "location", "=", "'body'", ",", "name", "=", "None", ",", "description", "=", "None", ",", "**", "kwargs", ")", ":", "request", ".", "errors", ".", "add", "(", "location", ",", "name", ",", "description", ",...
helper to raise a validation error .
train
false
48,320
@rule(u'.*') @priority(u'low') def collectlines(bot, trigger): if trigger.is_privmsg: return if (trigger.sender not in bot.memory[u'find_lines']): bot.memory[u'find_lines'][trigger.sender] = SopelMemory() if (Identifier(trigger.nick) not in bot.memory[u'find_lines'][trigger.sender]): bot.memory[u'find_lines'][trigger.sender][Identifier(trigger.nick)] = list() templist = bot.memory[u'find_lines'][trigger.sender][Identifier(trigger.nick)] line = trigger.group() if line.startswith(u's/'): return elif line.startswith(u'\x01ACTION'): line = line[:(-1)] templist.append(line) else: templist.append(line) del templist[:(-10)] bot.memory[u'find_lines'][trigger.sender][Identifier(trigger.nick)] = templist
[ "@", "rule", "(", "u'.*'", ")", "@", "priority", "(", "u'low'", ")", "def", "collectlines", "(", "bot", ",", "trigger", ")", ":", "if", "trigger", ".", "is_privmsg", ":", "return", "if", "(", "trigger", ".", "sender", "not", "in", "bot", ".", "memory...
create a temporary log of what people say .
train
false
48,321
def parseLineReplace(firstWordTable, line, output): firstWord = gcodec.getFirstWordFromLine(line) if (firstWord in firstWordTable): line = firstWordTable[firstWord] gcodec.addLineAndNewlineIfNecessary(line, output)
[ "def", "parseLineReplace", "(", "firstWordTable", ",", "line", ",", "output", ")", ":", "firstWord", "=", "gcodec", ".", "getFirstWordFromLine", "(", "line", ")", "if", "(", "firstWord", "in", "firstWordTable", ")", ":", "line", "=", "firstWordTable", "[", "...
parse the line and replace it if the first word of the line is in the first word table .
train
false
48,322
def _parse_tformat(tform): try: (repeat, format, option) = TFORMAT_RE.match(tform.strip()).groups() except Exception: raise VerifyError('Format {!r} is not recognized.'.format(tform)) if (repeat == ''): repeat = 1 else: repeat = int(repeat) return (repeat, format.upper(), option)
[ "def", "_parse_tformat", "(", "tform", ")", ":", "try", ":", "(", "repeat", ",", "format", ",", "option", ")", "=", "TFORMAT_RE", ".", "match", "(", "tform", ".", "strip", "(", ")", ")", ".", "groups", "(", ")", "except", "Exception", ":", "raise", ...
parse tformn keyword for a binary table into a tuple .
train
false
48,323
def _retrieve_ntp_peers(): return __salt__['ntp.peers']()
[ "def", "_retrieve_ntp_peers", "(", ")", ":", "return", "__salt__", "[", "'ntp.peers'", "]", "(", ")" ]
retrieves configured ntp peers .
train
false
48,324
def author(name): return ('from:%s' % name)
[ "def", "author", "(", "name", ")", ":", "return", "(", "'from:%s'", "%", "name", ")" ]
returns a twitter query-by-author-name that can be passed to twitter .
train
false
48,326
def _generate_sample_indices(random_state, n_samples): random_instance = check_random_state(random_state) sample_indices = random_instance.randint(0, n_samples, n_samples) return sample_indices
[ "def", "_generate_sample_indices", "(", "random_state", ",", "n_samples", ")", ":", "random_instance", "=", "check_random_state", "(", "random_state", ")", "sample_indices", "=", "random_instance", ".", "randint", "(", "0", ",", "n_samples", ",", "n_samples", ")", ...
private function used to _parallel_build_trees function .
train
false
48,327
def uidFromString(uidString): try: return int(uidString) except ValueError: if (pwd is None): raise return pwd.getpwnam(uidString)[2]
[ "def", "uidFromString", "(", "uidString", ")", ":", "try", ":", "return", "int", "(", "uidString", ")", "except", "ValueError", ":", "if", "(", "pwd", "is", "None", ")", ":", "raise", "return", "pwd", ".", "getpwnam", "(", "uidString", ")", "[", "2", ...
convert a user identifier .
train
false
48,328
def has_scope(context=None): if (not booted(context)): return False _sd_version = version(context) if (_sd_version is None): return False return (_sd_version >= 205)
[ "def", "has_scope", "(", "context", "=", "None", ")", ":", "if", "(", "not", "booted", "(", "context", ")", ")", ":", "return", "False", "_sd_version", "=", "version", "(", "context", ")", "if", "(", "_sd_version", "is", "None", ")", ":", "return", "...
scopes were introduced in systemd 205 .
train
true
48,330
def test_api_fixture(hug_api): assert isinstance(hug_api, hug.API) assert (hug_api != api)
[ "def", "test_api_fixture", "(", "hug_api", ")", ":", "assert", "isinstance", "(", "hug_api", ",", "hug", ".", "API", ")", "assert", "(", "hug_api", "!=", "api", ")" ]
ensure its possible to dynamically insert a new hug api on demand .
train
false
48,332
def assert_instance_of(expected, actual, msg=None): assert isinstance(actual, expected), msg
[ "def", "assert_instance_of", "(", "expected", ",", "actual", ",", "msg", "=", "None", ")", ":", "assert", "isinstance", "(", "actual", ",", "expected", ")", ",", "msg" ]
verify that object is an instance of expected .
train
false
48,333
def _create_transformations(all_tokens, seen_ts): for (parent, token) in all_tokens: if isinstance(token, TransformationToken): if (token.number not in seen_ts): raise RuntimeError(('Tabstop %i is not known but is used by a Transformation' % token.number)) Transformation(parent, seen_ts[token.number], token)
[ "def", "_create_transformations", "(", "all_tokens", ",", "seen_ts", ")", ":", "for", "(", "parent", ",", "token", ")", "in", "all_tokens", ":", "if", "isinstance", "(", "token", ",", "TransformationToken", ")", ":", "if", "(", "token", ".", "number", "not...
create the objects that need to know about tabstops .
train
false
48,334
def java_library(name, srcs=[], deps=[], resources=[], source_encoding=None, warnings=None, prebuilt=False, binary_jar='', exported_deps=[], provided_deps=[], **kwargs): target = JavaLibrary(name, srcs, deps, resources, source_encoding, warnings, prebuilt, binary_jar, exported_deps, provided_deps, kwargs) blade.blade.register_target(target)
[ "def", "java_library", "(", "name", ",", "srcs", "=", "[", "]", ",", "deps", "=", "[", "]", ",", "resources", "=", "[", "]", ",", "source_encoding", "=", "None", ",", "warnings", "=", "None", ",", "prebuilt", "=", "False", ",", "binary_jar", "=", "...
define java_library target .
train
false
48,335
def trim_dir(directory): def access_time(f): return os.stat(os.path.join(directory, f)).st_atime files = sorted(os.listdir(directory), key=access_time) file_name = os.path.join(directory, files[0]) log.debug(u'removing least accessed file: %s', file_name) os.remove(file_name)
[ "def", "trim_dir", "(", "directory", ")", ":", "def", "access_time", "(", "f", ")", ":", "return", "os", ".", "stat", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "f", ")", ")", ".", "st_atime", "files", "=", "sorted", "(", "os", "...
removed the least accessed file on a given dir .
train
false
48,336
def find_asgs(conn, module, name=None, tags=None): try: asgs_paginator = conn.get_paginator('describe_auto_scaling_groups') asgs = asgs_paginator.paginate().build_full_result() except ClientError as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) matched_asgs = [] if (name is not None): name_prog = re.compile(('^' + name)) for asg in asgs['AutoScalingGroups']: if name: matched_name = name_prog.search(asg['AutoScalingGroupName']) else: matched_name = True if tags: matched_tags = match_asg_tags(tags, asg) else: matched_tags = True if (matched_name and matched_tags): matched_asgs.append(camel_dict_to_snake_dict(asg)) return matched_asgs
[ "def", "find_asgs", "(", "conn", ",", "module", ",", "name", "=", "None", ",", "tags", "=", "None", ")", ":", "try", ":", "asgs_paginator", "=", "conn", ".", "get_paginator", "(", "'describe_auto_scaling_groups'", ")", "asgs", "=", "asgs_paginator", ".", "...
args: conn : valid boto3 asg client .
train
false
48,337
def libvlc_media_player_pause(p_mi): f = (_Cfunctions.get('libvlc_media_player_pause', None) or _Cfunction('libvlc_media_player_pause', ((1,),), None, None, MediaPlayer)) return f(p_mi)
[ "def", "libvlc_media_player_pause", "(", "p_mi", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_player_pause'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_player_pause'", ",", "(", "(", "1", ",", ")", ",", ")", ",", ...
toggle pause .
train
false
48,338
def center_and_norm(x, axis=(-1)): x = np.rollaxis(x, axis) x -= x.mean(axis=0) x /= x.std(axis=0)
[ "def", "center_and_norm", "(", "x", ",", "axis", "=", "(", "-", "1", ")", ")", ":", "x", "=", "np", ".", "rollaxis", "(", "x", ",", "axis", ")", "x", "-=", "x", ".", "mean", "(", "axis", "=", "0", ")", "x", "/=", "x", ".", "std", "(", "ax...
centers and norms x **in place** parameters x: ndarray array with an axis of observations measured on random variables .
train
false
48,340
def htmlsafe_dumps(obj, **kwargs): rv = dumps(obj, **kwargs).replace(u'<', u'\\u003c').replace(u'>', u'\\u003e').replace(u'&', u'\\u0026').replace(u"'", u'\\u0027') if (not _slash_escape): rv = rv.replace('\\/', '/') return rv
[ "def", "htmlsafe_dumps", "(", "obj", ",", "**", "kwargs", ")", ":", "rv", "=", "dumps", "(", "obj", ",", "**", "kwargs", ")", ".", "replace", "(", "u'<'", ",", "u'\\\\u003c'", ")", ".", "replace", "(", "u'>'", ",", "u'\\\\u003e'", ")", ".", "replace"...
works exactly like :func:dumps but is safe for use in <script> tags .
train
true
48,341
def get_dict(*keys, **extras): _keys = ('url', 'args', 'form', 'data', 'origin', 'headers', 'files', 'json') assert all(map(_keys.__contains__, keys)) data = request.data form = semiflatten(request.form) try: _json = json.loads(data.decode('utf-8')) except (ValueError, TypeError): _json = None d = dict(url=get_url(request), args=semiflatten(request.args), form=form, data=json_safe(data), origin=request.headers.get('X-Forwarded-For', request.remote_addr), headers=get_headers(), files=get_files(), json=_json) out_d = dict() for key in keys: out_d[key] = d.get(key) out_d.update(extras) return out_d
[ "def", "get_dict", "(", "*", "keys", ",", "**", "extras", ")", ":", "_keys", "=", "(", "'url'", ",", "'args'", ",", "'form'", ",", "'data'", ",", "'origin'", ",", "'headers'", ",", "'files'", ",", "'json'", ")", "assert", "all", "(", "map", "(", "_...
returns request dict of given keys .
train
true
48,342
def process_result(method, result): if (method.post_process_func is not None): result = method.post_process_func(result) if method.boolean: if (result in [1, '1']): result = True elif (result in [0, '0']): result = False return result
[ "def", "process_result", "(", "method", ",", "result", ")", ":", "if", "(", "method", ".", "post_process_func", "is", "not", "None", ")", ":", "result", "=", "method", ".", "post_process_func", "(", "result", ")", "if", "method", ".", "boolean", ":", "if...
process given c{b{result}} based on flags set in c{b{method}} .
train
false
48,343
def threshold_yen(image, nbins=256): (hist, bin_centers) = histogram(image.ravel(), nbins) if (bin_centers.size == 1): return bin_centers[0] pmf = (hist.astype(np.float32) / hist.sum()) P1 = np.cumsum(pmf) P1_sq = np.cumsum((pmf ** 2)) P2_sq = np.cumsum((pmf[::(-1)] ** 2))[::(-1)] crit = np.log((((P1_sq[:(-1)] * P2_sq[1:]) ** (-1)) * ((P1[:(-1)] * (1.0 - P1[:(-1)])) ** 2))) return bin_centers[crit.argmax()]
[ "def", "threshold_yen", "(", "image", ",", "nbins", "=", "256", ")", ":", "(", "hist", ",", "bin_centers", ")", "=", "histogram", "(", "image", ".", "ravel", "(", ")", ",", "nbins", ")", "if", "(", "bin_centers", ".", "size", "==", "1", ")", ":", ...
return threshold value based on yens method .
train
false
48,344
def write_worksheet_hyperlinks(doc, worksheet): write_hyperlinks = False for cell in worksheet.get_cell_collection(): if (cell.hyperlink_rel_id is not None): write_hyperlinks = True break if write_hyperlinks: start_tag(doc, 'hyperlinks') for cell in worksheet.get_cell_collection(): if (cell.hyperlink_rel_id is not None): attrs = {'display': cell.hyperlink, 'ref': cell.get_coordinate(), 'r:id': cell.hyperlink_rel_id} tag(doc, 'hyperlink', attrs) end_tag(doc, 'hyperlinks')
[ "def", "write_worksheet_hyperlinks", "(", "doc", ",", "worksheet", ")", ":", "write_hyperlinks", "=", "False", "for", "cell", "in", "worksheet", ".", "get_cell_collection", "(", ")", ":", "if", "(", "cell", ".", "hyperlink_rel_id", "is", "not", "None", ")", ...
write worksheet hyperlinks to xml .
train
false
48,345
def set_remove_subs(ssli): part = [] for s in sorted(list(set(ssli)), key=(lambda x: len(set(x))))[::(-1)]: if (not any((set(s).issubset(set(t)) for t in part))): part.append(s) return part
[ "def", "set_remove_subs", "(", "ssli", ")", ":", "part", "=", "[", "]", "for", "s", "in", "sorted", "(", "list", "(", "set", "(", "ssli", ")", ")", ",", "key", "=", "(", "lambda", "x", ":", "len", "(", "set", "(", "x", ")", ")", ")", ")", "...
remove sets that are subsets of another set from a list of tuples parameters ssli : list of tuples each tuple is considered as a set returns part : list of tuples new list with subset tuples removed .
train
false
48,346
def for_all_dtypes_combination(names=('dtyes',), no_float16=False, no_bool=False, full=None): types = _make_all_dtypes(no_float16, no_bool) return for_dtypes_combination(types, names, full)
[ "def", "for_all_dtypes_combination", "(", "names", "=", "(", "'dtyes'", ",", ")", ",", "no_float16", "=", "False", ",", "no_bool", "=", "False", ",", "full", "=", "None", ")", ":", "types", "=", "_make_all_dtypes", "(", "no_float16", ",", "no_bool", ")", ...
decorator that checks the fixture with a product set of all dtypes .
train
false
48,347
def send_video_status_update(updates): for update in updates: update_video_status(update.get('edxVideoId'), update.get('status')) LOGGER.info('VIDEOS: Video status update with id [%s], status [%s] and message [%s]', update.get('edxVideoId'), update.get('status'), update.get('message')) return JsonResponse()
[ "def", "send_video_status_update", "(", "updates", ")", ":", "for", "update", "in", "updates", ":", "update_video_status", "(", "update", ".", "get", "(", "'edxVideoId'", ")", ",", "update", ".", "get", "(", "'status'", ")", ")", "LOGGER", ".", "info", "("...
update video status in edx-val .
train
false
48,349
def __main__(argv=None): import sys as _sys if (not argv): argv = _sys.argv exitcode = None try: unittest.main(argv=argv, defaultTest='suite') except SystemExit as exc: exitcode = exc.code return exitcode
[ "def", "__main__", "(", "argv", "=", "None", ")", ":", "import", "sys", "as", "_sys", "if", "(", "not", "argv", ")", ":", "argv", "=", "_sys", ".", "argv", "exitcode", "=", "None", "try", ":", "unittest", ".", "main", "(", "argv", "=", "argv", ",...
mainline function for this module .
train
false
48,350
def drop_views(manager, views): check_exists(manager, views, VIEW_TYPE) for view in views: manager.execute(('DROP VIEW `%s`' % view))
[ "def", "drop_views", "(", "manager", ",", "views", ")", ":", "check_exists", "(", "manager", ",", "views", ",", "VIEW_TYPE", ")", "for", "view", "in", "views", ":", "manager", ".", "execute", "(", "(", "'DROP VIEW `%s`'", "%", "view", ")", ")" ]
drops the specified views from the database if a specified view does not exist in the database .
train
false
48,351
def flightmode_menu(): modes = mestate.mlog.flightmode_list() ret = [] idx = 0 for (mode, t1, t2) in modes: modestr = ('%s %us' % (mode, (t2 - t1))) ret.append(MPMenuCheckbox(modestr, modestr, ('mode-%u' % idx))) idx += 1 mestate.flightmode_selections.append(False) return ret
[ "def", "flightmode_menu", "(", ")", ":", "modes", "=", "mestate", ".", "mlog", ".", "flightmode_list", "(", ")", "ret", "=", "[", "]", "idx", "=", "0", "for", "(", "mode", ",", "t1", ",", "t2", ")", "in", "modes", ":", "modestr", "=", "(", "'%s %...
construct flightmode menu .
train
true
48,352
def url_unquote(s, charset='utf-8', errors='replace'): if isinstance(s, unicode): s = s.encode(charset) return _decode_unicode(_unquote(s), charset, errors)
[ "def", "url_unquote", "(", "s", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "s", "=", "s", ".", "encode", "(", "charset", ")", "return", "_decode_unicode", "(", "_...
url decode a single string with a given encoding .
train
true
48,353
def image_to_base64(image): ax = image.axes binary_buffer = io.BytesIO() lim = ax.axis() ax.axis(image.get_extent()) image.write_png(binary_buffer) ax.axis(lim) binary_buffer.seek(0) return base64.b64encode(binary_buffer.read()).decode('utf-8')
[ "def", "image_to_base64", "(", "image", ")", ":", "ax", "=", "image", ".", "axes", "binary_buffer", "=", "io", ".", "BytesIO", "(", ")", "lim", "=", "ax", ".", "axis", "(", ")", "ax", ".", "axis", "(", "image", ".", "get_extent", "(", ")", ")", "...
convert a matplotlib image to a base64 png representation parameters image : matplotlib image object the image to be converted .
train
true
48,356
def get_bumper_sources(video): try: val_profiles = ['desktop_webm', 'desktop_mp4'] val_video_urls = edxval_api.get_urls_for_profiles(video.bumper['edx_video_id'], val_profiles) bumper_sources = filter(None, [val_video_urls[p] for p in val_profiles]) except edxval_api.ValInternalError: log.warning('Could not retrieve information from VAL for Bumper edx Video ID: %s.', video.bumper['edx_video_id']) return [] return bumper_sources
[ "def", "get_bumper_sources", "(", "video", ")", ":", "try", ":", "val_profiles", "=", "[", "'desktop_webm'", ",", "'desktop_mp4'", "]", "val_video_urls", "=", "edxval_api", ".", "get_urls_for_profiles", "(", "video", ".", "bumper", "[", "'edx_video_id'", "]", ",...
get bumper sources from edxval .
train
false
48,357
def set_symbols(pcontracts, dt_start='1980-1-1', dt_end='2100-1-1', n=None, spec_date={}): global _simulator _simulator = ExecuteUnit(pcontracts, dt_start, dt_end, n, spec_date) return _simulator
[ "def", "set_symbols", "(", "pcontracts", ",", "dt_start", "=", "'1980-1-1'", ",", "dt_end", "=", "'2100-1-1'", ",", "n", "=", "None", ",", "spec_date", "=", "{", "}", ")", ":", "global", "_simulator", "_simulator", "=", "ExecuteUnit", "(", "pcontracts", ",...
args: pcontracts : list of pcontracts dt_start : start time of all pcontracts dt_end : end time of all pcontracts n : last n bars spec_date : time range for specific pcontracts .
train
false
48,358
def GetIOServicesByType(service_type): serial_port_iterator = ctypes.c_void_p() iokit.IOServiceGetMatchingServices(kIOMasterPortDefault, iokit.IOServiceMatching(service_type.encode('mac_roman')), ctypes.byref(serial_port_iterator)) services = [] while iokit.IOIteratorIsValid(serial_port_iterator): service = iokit.IOIteratorNext(serial_port_iterator) if (not service): break services.append(service) iokit.IOObjectRelease(serial_port_iterator) return services
[ "def", "GetIOServicesByType", "(", "service_type", ")", ":", "serial_port_iterator", "=", "ctypes", ".", "c_void_p", "(", ")", "iokit", ".", "IOServiceGetMatchingServices", "(", "kIOMasterPortDefault", ",", "iokit", ".", "IOServiceMatching", "(", "service_type", ".", ...
returns iterator over specified service_type .
train
false
48,359
def server_error(request, template_name='500.html'): r = render_to_response(template_name, context_instance=RequestContext(request)) r.status_code = 500 return r
[ "def", "server_error", "(", "request", ",", "template_name", "=", "'500.html'", ")", ":", "r", "=", "render_to_response", "(", "template_name", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ")", "r", ".", "status_code", "=", "500", "retu...
a simple 500 handler so we get media .
train
false
48,360
def decrypt_secret(secret, key): decrypted_data = '' j = 0 for i in range(0, len(secret), 8): enc_block = secret[i:(i + 8)] block_key = key[j:(j + 7)] des_key = str_to_key(block_key) des = DES.new(des_key, DES.MODE_ECB) decrypted_data += des.decrypt(enc_block) j += 7 if (len(key[j:(j + 7)]) < 7): j = len(key[j:(j + 7)]) (dec_data_len,) = unpack('<L', decrypted_data[:4]) return decrypted_data[8:(8 + dec_data_len)]
[ "def", "decrypt_secret", "(", "secret", ",", "key", ")", ":", "decrypted_data", "=", "''", "j", "=", "0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "secret", ")", ",", "8", ")", ":", "enc_block", "=", "secret", "[", "i", ":", "(", "...
python implementation of systemfunction005 .
train
false
48,361
def set_saucelabs_job_status(jobid, passed=True): config = get_saucelabs_username_and_key() url = 'http://saucelabs.com/rest/v1/{}/jobs/{}'.format(config['username'], world.jobid) body_content = dumps({'passed': passed}) base64string = encodestring('{}:{}'.format(config['username'], config['access-key']))[:(-1)] headers = {'Authorization': 'Basic {}'.format(base64string)} result = requests.put(url, data=body_content, headers=headers) return (result.status_code == 200)
[ "def", "set_saucelabs_job_status", "(", "jobid", ",", "passed", "=", "True", ")", ":", "config", "=", "get_saucelabs_username_and_key", "(", ")", "url", "=", "'http://saucelabs.com/rest/v1/{}/jobs/{}'", ".", "format", "(", "config", "[", "'username'", "]", ",", "w...
sets the job status on sauce labs .
train
false
48,362
def use_aio(): from txaio import aio txaio._use_framework(aio)
[ "def", "use_aio", "(", ")", ":", "from", "txaio", "import", "aio", "txaio", ".", "_use_framework", "(", "aio", ")" ]
monkey-patched for doc-building .
train
false
48,363
def get_trigger_db_by_uid(uid): try: return Trigger.get_by_uid(uid) except StackStormDBObjectNotFoundError as e: LOG.debug('Database lookup for uid="%s" resulted in exception : %s.', uid, e, exc_info=True) return None
[ "def", "get_trigger_db_by_uid", "(", "uid", ")", ":", "try", ":", "return", "Trigger", ".", "get_by_uid", "(", "uid", ")", "except", "StackStormDBObjectNotFoundError", "as", "e", ":", "LOG", ".", "debug", "(", "'Database lookup for uid=\"%s\" resulted in exception : %...
returns the trigger object from db given a trigger uid .
train
false
48,364
def checkIntf(intf): config = quietRun(('ifconfig %s 2>/dev/null' % intf), shell=True) if (not config): error('Error:', intf, 'does not exist!\n') exit(1) ips = re.findall('\\d+\\.\\d+\\.\\d+\\.\\d+', config) if ips: error('Error:', intf, 'has an IP address,and is probably in use!\n') exit(1)
[ "def", "checkIntf", "(", "intf", ")", ":", "config", "=", "quietRun", "(", "(", "'ifconfig %s 2>/dev/null'", "%", "intf", ")", ",", "shell", "=", "True", ")", "if", "(", "not", "config", ")", ":", "error", "(", "'Error:'", ",", "intf", ",", "'does not ...
make sure intf exists and is not configured .
train
false
48,365
def ContinuousRV(symbol, density, set=Interval((- oo), oo)): pdf = Lambda(symbol, density) dist = ContinuousDistributionHandmade(pdf, set) return SingleContinuousPSpace(symbol, dist).value
[ "def", "ContinuousRV", "(", "symbol", ",", "density", ",", "set", "=", "Interval", "(", "(", "-", "oo", ")", ",", "oo", ")", ")", ":", "pdf", "=", "Lambda", "(", "symbol", ",", "density", ")", "dist", "=", "ContinuousDistributionHandmade", "(", "pdf", ...
create a continuous random variable given the following: -- a symbol -- a probability density function -- set on which the pdf is valid returns a randomsymbol .
train
false
48,366
def phi(n): assert isinstance(n, integer_types) if (n < 3): return 1 result = 1 ff = factorization(n) for f in ff: e = f[1] if (e > 1): result = ((result * (f[0] ** (e - 1))) * (f[0] - 1)) else: result = (result * (f[0] - 1)) return result
[ "def", "phi", "(", "n", ")", ":", "assert", "isinstance", "(", "n", ",", "integer_types", ")", "if", "(", "n", "<", "3", ")", ":", "return", "1", "result", "=", "1", "ff", "=", "factorization", "(", "n", ")", "for", "f", "in", "ff", ":", "e", ...
return the euler totient function of n .
train
true
48,367
def MakeHTTPException(code=500, msg='Error'): response = requests.Response() response.status_code = code return requests.ConnectionError(msg, response=response)
[ "def", "MakeHTTPException", "(", "code", "=", "500", ",", "msg", "=", "'Error'", ")", ":", "response", "=", "requests", ".", "Response", "(", ")", "response", ".", "status_code", "=", "code", "return", "requests", ".", "ConnectionError", "(", "msg", ",", ...
a helper for creating a httperror exception .
train
false
48,368
def create_chart(klass, values, compute_values=True, **kws): _chart = klass(values, title='title', xlabel='xlabel', ylabel='ylabel', legend='top_left', xscale='linear', yscale='linear', width=800, height=600, tools=True, filename=False, server=False, notebook=False, **kws) return _chart
[ "def", "create_chart", "(", "klass", ",", "values", ",", "compute_values", "=", "True", ",", "**", "kws", ")", ":", "_chart", "=", "klass", "(", "values", ",", "title", "=", "'title'", ",", "xlabel", "=", "'xlabel'", ",", "ylabel", "=", "'ylabel'", ","...
create a new chart class instance with values and the extra kws keyword parameters .
train
false
48,370
def find_subscription_type(subscription): subs_available = list(constants.USER_SUBSCRIPTIONS_AVAILABLE.keys()) subs_available.extend(list(constants.NODE_SUBSCRIPTIONS_AVAILABLE.keys())) for available in subs_available: if (available in subscription): return available
[ "def", "find_subscription_type", "(", "subscription", ")", ":", "subs_available", "=", "list", "(", "constants", ".", "USER_SUBSCRIPTIONS_AVAILABLE", ".", "keys", "(", ")", ")", "subs_available", ".", "extend", "(", "list", "(", "constants", ".", "NODE_SUBSCRIPTIO...
find subscription type string within specific subscription .
train
false
48,371
def get_session_plot_options(): return copy.deepcopy(_session['plot_options'])
[ "def", "get_session_plot_options", "(", ")", ":", "return", "copy", ".", "deepcopy", "(", "_session", "[", "'plot_options'", "]", ")" ]
returns a copy of the user supplied plot options .
train
false
48,372
def _read_tagdesc(f): tagdesc = {'offset': _read_long(f)} if (tagdesc['offset'] == (-1)): tagdesc['offset'] = _read_uint64(f) tagdesc['typecode'] = _read_long(f) tagflags = _read_long(f) tagdesc['array'] = ((tagflags & 4) == 4) tagdesc['structure'] = ((tagflags & 32) == 32) tagdesc['scalar'] = (tagdesc['typecode'] in DTYPE_DICT) return tagdesc
[ "def", "_read_tagdesc", "(", "f", ")", ":", "tagdesc", "=", "{", "'offset'", ":", "_read_long", "(", "f", ")", "}", "if", "(", "tagdesc", "[", "'offset'", "]", "==", "(", "-", "1", ")", ")", ":", "tagdesc", "[", "'offset'", "]", "=", "_read_uint64"...
function to read in a tag descriptor .
train
false
48,373
def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): return available_extensions(user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas).get(name, None)
[ "def", "get_available_extension", "(", "name", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "return", "available_exten...
get info about an available postgresql extension cli example: .
train
true
48,374
def Tm_staluc(s, dnac=50, saltc=50, rna=0): warnings.warn(('Tm_staluc may be depreciated in the future. Use Tm_NN ' + 'instead.'), PendingDeprecationWarning) if (not rna): return Tm_NN(s, dnac1=(dnac / 2.0), dnac2=(dnac / 2.0), Na=saltc) elif (rna == 1): return Tm_NN(s, dnac1=(dnac / 2.0), dnac2=(dnac / 2.0), Na=saltc, nn_table=RNA_NN2) else: raise ValueError('rna={0} not supported'.format(rna))
[ "def", "Tm_staluc", "(", "s", ",", "dnac", "=", "50", ",", "saltc", "=", "50", ",", "rna", "=", "0", ")", ":", "warnings", ".", "warn", "(", "(", "'Tm_staluc may be depreciated in the future. Use Tm_NN '", "+", "'instead.'", ")", ",", "PendingDeprecationWarnin...
returns dna/dna tm using nearest neighbor thermodynamics .
train
false
48,375
def paypal_time(time_obj=None): if (time_obj is None): time_obj = time.gmtime() return time.strftime(PayPalNVP.TIMESTAMP_FORMAT, time_obj)
[ "def", "paypal_time", "(", "time_obj", "=", "None", ")", ":", "if", "(", "time_obj", "is", "None", ")", ":", "time_obj", "=", "time", ".", "gmtime", "(", ")", "return", "time", ".", "strftime", "(", "PayPalNVP", ".", "TIMESTAMP_FORMAT", ",", "time_obj", ...
returns a time suitable for paypal time fields .
train
true
48,376
def md5_hexdigest(file): if isinstance(file, compat.string_types): with open(file, u'rb') as infile: return _md5_hexdigest(infile) return _md5_hexdigest(file)
[ "def", "md5_hexdigest", "(", "file", ")", ":", "if", "isinstance", "(", "file", ",", "compat", ".", "string_types", ")", ":", "with", "open", "(", "file", ",", "u'rb'", ")", "as", "infile", ":", "return", "_md5_hexdigest", "(", "infile", ")", "return", ...
calculate and return the md5 checksum for a given file .
train
false
48,377
def uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=None, n_runs=5, seed=42): random_labels = np.random.RandomState(seed).randint scores = np.zeros((len(n_clusters_range), n_runs)) if (fixed_n_classes is not None): labels_a = random_labels(low=0, high=fixed_n_classes, size=n_samples) for (i, k) in enumerate(n_clusters_range): for j in range(n_runs): if (fixed_n_classes is None): labels_a = random_labels(low=0, high=k, size=n_samples) labels_b = random_labels(low=0, high=k, size=n_samples) scores[(i, j)] = score_func(labels_a, labels_b) return scores
[ "def", "uniform_labelings_scores", "(", "score_func", ",", "n_samples", ",", "n_clusters_range", ",", "fixed_n_classes", "=", "None", ",", "n_runs", "=", "5", ",", "seed", "=", "42", ")", ":", "random_labels", "=", "np", ".", "random", ".", "RandomState", "(...
compute score for 2 random uniform cluster labelings .
train
false
48,378
def post_object(url, token, container, name, headers, http_conn=None, response_dict=None, service_token=None): if http_conn: (parsed, conn) = http_conn else: (parsed, conn) = http_connection(url) path = ('%s/%s/%s' % (parsed.path, quote(container), quote(name))) headers['X-Auth-Token'] = token if service_token: headers['X-Service-Token'] = service_token conn.request('POST', path, '', headers) resp = conn.getresponse() body = resp.read() http_log((('%s%s' % (url.replace(parsed.path, ''), path)), 'POST'), {'headers': headers}, resp, body) store_response(resp, response_dict) if ((resp.status < 200) or (resp.status >= 300)): raise ClientException.from_response(resp, 'Object POST failed', body)
[ "def", "post_object", "(", "url", ",", "token", ",", "container", ",", "name", ",", "headers", ",", "http_conn", "=", "None", ",", "response_dict", "=", "None", ",", "service_token", "=", "None", ")", ":", "if", "http_conn", ":", "(", "parsed", ",", "c...
update object metadata .
train
false
48,379
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get new repository .
train
false
48,380
def with_kill_srv(f): @wraps(f) def wrapper(self, *args): pidfile = args[(-1)] try: return f(self, *args) finally: _kill_srv(pidfile) return wrapper
[ "def", "with_kill_srv", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "self", ",", "*", "args", ")", ":", "pidfile", "=", "args", "[", "(", "-", "1", ")", "]", "try", ":", "return", "f", "(", "self", ",", "*", "args"...
helper to decorate tests which receive in the last argument tmpdir to pass to kill_srv to be used in tandem with @with_tmpdir .
train
false
48,381
def _get_default_retry_params(): default = getattr(_thread_local_settings, 'default_retry_params', None) if ((default is None) or (not default.belong_to_current_request())): return RetryParams() else: return copy.copy(default)
[ "def", "_get_default_retry_params", "(", ")", ":", "default", "=", "getattr", "(", "_thread_local_settings", ",", "'default_retry_params'", ",", "None", ")", "if", "(", "(", "default", "is", "None", ")", "or", "(", "not", "default", ".", "belong_to_current_reque...
get default retryparams for current request and current thread .
train
true
48,383
def _get_env(): env = dict(os.environ) env['PYTHONPATH'] = os.pathsep.join(sys.path) return env
[ "def", "_get_env", "(", ")", ":", "env", "=", "dict", "(", "os", ".", "environ", ")", "env", "[", "'PYTHONPATH'", "]", "=", "os", ".", "pathsep", ".", "join", "(", "sys", ".", "path", ")", "return", "env" ]
extracts the environment pythonpath and appends the current sys .
train
true
48,384
def list_manage_opts(): return [(g, copy.deepcopy(o)) for (g, o) in _manage_opts]
[ "def", "list_manage_opts", "(", ")", ":", "return", "[", "(", "g", ",", "copy", ".", "deepcopy", "(", "o", ")", ")", "for", "(", "g", ",", "o", ")", "in", "_manage_opts", "]" ]
return a list of oslo_config options available in glance manage .
train
false
48,385
def _get_dtype_from_object(dtype): if (isinstance(dtype, type) and issubclass(dtype, np.generic)): return dtype elif is_categorical(dtype): return CategoricalDtype().type elif is_datetimetz(dtype): return DatetimeTZDtype(dtype).type elif isinstance(dtype, np.dtype): try: _validate_date_like_dtype(dtype) except TypeError: pass return dtype.type elif isinstance(dtype, string_types): if (dtype in ['datetimetz', 'datetime64tz']): return DatetimeTZDtype.type elif (dtype in ['period']): raise NotImplementedError if ((dtype == 'datetime') or (dtype == 'timedelta')): dtype += '64' try: return _get_dtype_from_object(getattr(np, dtype)) except (AttributeError, TypeError): pass return _get_dtype_from_object(np.dtype(dtype))
[ "def", "_get_dtype_from_object", "(", "dtype", ")", ":", "if", "(", "isinstance", "(", "dtype", ",", "type", ")", "and", "issubclass", "(", "dtype", ",", "np", ".", "generic", ")", ")", ":", "return", "dtype", "elif", "is_categorical", "(", "dtype", ")",...
get a numpy dtype .
train
false
48,386
def LoadConfigsFromFile(file_path): with open(file_path) as data: return {d['check_id']: d for d in yaml.safe_load_all(data)}
[ "def", "LoadConfigsFromFile", "(", "file_path", ")", ":", "with", "open", "(", "file_path", ")", "as", "data", ":", "return", "{", "d", "[", "'check_id'", "]", ":", "d", "for", "d", "in", "yaml", ".", "safe_load_all", "(", "data", ")", "}" ]
loads check definitions from a file .
train
false
48,387
def _dot_buildout(directory): return os.path.join(os.path.abspath(directory), '.buildout')
[ "def", "_dot_buildout", "(", "directory", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "directory", ")", ",", "'.buildout'", ")" ]
get the local marker directory .
train
false
48,388
def make_syncdb(): statuses = [] hue_exec = os.path.join(common.INSTALL_ROOT, 'build', 'env', 'bin', 'hue') if os.path.exists(hue_exec): statuses.append(runcmd([hue_exec, 'syncdb', '--noinput'])) statuses.append(runcmd([hue_exec, 'migrate', '--merge'])) return (not any(statuses))
[ "def", "make_syncdb", "(", ")", ":", "statuses", "=", "[", "]", "hue_exec", "=", "os", ".", "path", ".", "join", "(", "common", ".", "INSTALL_ROOT", ",", "'build'", ",", "'env'", ",", "'bin'", ",", "'hue'", ")", "if", "os", ".", "path", ".", "exist...
make_syncdb() -> true/false .
train
false
48,389
@register.tag def get_flatpages(parser, token): bits = token.split_contents() syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s ['url_starts_with'] [for user] as context_name" % dict(tag_name=bits[0])) if ((len(bits) >= 3) and (len(bits) <= 6)): if ((len(bits) % 2) == 0): prefix = bits[1] else: prefix = None if (bits[(-2)] != 'as'): raise template.TemplateSyntaxError(syntax_message) context_name = bits[(-1)] if (len(bits) >= 5): if (bits[(-4)] != 'for'): raise template.TemplateSyntaxError(syntax_message) user = bits[(-3)] else: user = None return FlatpageNode(context_name, starts_with=prefix, user=user) else: raise template.TemplateSyntaxError(syntax_message)
[ "@", "register", ".", "tag", "def", "get_flatpages", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "syntax_message", "=", "(", "\"%(tag_name)s expects a syntax of %(tag_name)s ['url_starts_with'] [for user] as context_name\"...
retrieves all flatpage objects available for the current site and visible to the specific user .
train
false
48,390
@receiver(SignalHandler.library_updated) def listen_for_library_update(sender, library_key, **kwargs): if LibrarySearchIndexer.indexing_is_enabled(): from .tasks import update_library_index update_library_index.delay(unicode(library_key), datetime.now(UTC).isoformat())
[ "@", "receiver", "(", "SignalHandler", ".", "library_updated", ")", "def", "listen_for_library_update", "(", "sender", ",", "library_key", ",", "**", "kwargs", ")", ":", "if", "LibrarySearchIndexer", ".", "indexing_is_enabled", "(", ")", ":", "from", ".", "tasks...
receives signal and kicks off celery task to update search index .
train
false
48,391
def all_users(number=(-1), etag=None): return gh.all_users(number, etag)
[ "def", "all_users", "(", "number", "=", "(", "-", "1", ")", ",", "etag", "=", "None", ")", ":", "return", "gh", ".", "all_users", "(", "number", ",", "etag", ")" ]
iterate over every user in the order they signed up for github .
train
false
48,394
def listening_ports(attrs=None, where=None): return _osquery_cmd(table='listening_ports', attrs=attrs, where=where)
[ "def", "listening_ports", "(", "attrs", "=", "None", ",", "where", "=", "None", ")", ":", "return", "_osquery_cmd", "(", "table", "=", "'listening_ports'", ",", "attrs", "=", "attrs", ",", "where", "=", "where", ")" ]
return listening_ports information from osquery cli example: .
train
false
48,395
def standardise_name(name): try: return numeric_to_rational(''.join(name)) except (ValueError, ZeroDivisionError): return ''.join((ch for ch in name if (ch not in '_- '))).upper()
[ "def", "standardise_name", "(", "name", ")", ":", "try", ":", "return", "numeric_to_rational", "(", "''", ".", "join", "(", "name", ")", ")", "except", "(", "ValueError", ",", "ZeroDivisionError", ")", ":", "return", "''", ".", "join", "(", "(", "ch", ...
standardises a property or value name .
train
false
48,396
def is_ascii_encodable(s): try: s.encode('ascii') except UnicodeEncodeError: return False except UnicodeDecodeError: return False except AttributeError: return False return True
[ "def", "is_ascii_encodable", "(", "s", ")", ":", "try", ":", "s", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "return", "False", "except", "UnicodeDecodeError", ":", "return", "False", "except", "AttributeError", ":", "return", "Fa...
check if argument encodes to ascii without error .
train
false
48,397
def cloudfiles(module, container_, state, meta_, clear_meta, typ, ttl, public, private, web_index, web_error): cf = pyrax.cloudfiles if (cf is None): module.fail_json(msg='Failed to instantiate client. This typically indicates an invalid region or an incorrectly capitalized region name.') if (typ == 'container'): container(cf, module, container_, state, meta_, clear_meta, ttl, public, private, web_index, web_error) else: meta(cf, module, container_, state, meta_, clear_meta)
[ "def", "cloudfiles", "(", "module", ",", "container_", ",", "state", ",", "meta_", ",", "clear_meta", ",", "typ", ",", "ttl", ",", "public", ",", "private", ",", "web_index", ",", "web_error", ")", ":", "cf", "=", "pyrax", ".", "cloudfiles", "if", "(",...
dispatch from here to work with metadata or file objects .
train
false
48,400
def bin_list_to_int(bin_list): return (bin_list << range(len(bin_list))).sum(0)
[ "def", "bin_list_to_int", "(", "bin_list", ")", ":", "return", "(", "bin_list", "<<", "range", "(", "len", "(", "bin_list", ")", ")", ")", ".", "sum", "(", "0", ")" ]
create int from binary repr from URL .
train
false
48,401
def _create_row_request(table_name, row_key=None, start_key=None, end_key=None, filter_=None, limit=None): request_kwargs = {'table_name': table_name} if ((row_key is not None) and ((start_key is not None) or (end_key is not None))): raise ValueError('Row key and row range cannot be set simultaneously') range_kwargs = {} if ((start_key is not None) or (end_key is not None)): if (start_key is not None): range_kwargs['start_key_closed'] = _to_bytes(start_key) if (end_key is not None): range_kwargs['end_key_open'] = _to_bytes(end_key) if (filter_ is not None): request_kwargs['filter'] = filter_.to_pb() if (limit is not None): request_kwargs['rows_limit'] = limit message = data_messages_v2_pb2.ReadRowsRequest(**request_kwargs) if (row_key is not None): message.rows.row_keys.append(_to_bytes(row_key)) if range_kwargs: message.rows.row_ranges.add(**range_kwargs) return message
[ "def", "_create_row_request", "(", "table_name", ",", "row_key", "=", "None", ",", "start_key", "=", "None", ",", "end_key", "=", "None", ",", "filter_", "=", "None", ",", "limit", "=", "None", ")", ":", "request_kwargs", "=", "{", "'table_name'", ":", "...
creates a request to read rows in a table .
train
false
48,402
def _pyopenssl_cert_or_req_san(cert_or_req): part_separator = ':' parts_separator = ', ' prefix = ('DNS' + part_separator) if isinstance(cert_or_req, OpenSSL.crypto.X509): func = OpenSSL.crypto.dump_certificate else: func = OpenSSL.crypto.dump_certificate_request text = func(OpenSSL.crypto.FILETYPE_TEXT, cert_or_req).decode('utf-8') match = re.search('X509v3 Subject Alternative Name:\\s*(.*)', text) sans_parts = ([] if (match is None) else match.group(1).split(parts_separator)) return [part.split(part_separator)[1] for part in sans_parts if part.startswith(prefix)]
[ "def", "_pyopenssl_cert_or_req_san", "(", "cert_or_req", ")", ":", "part_separator", "=", "':'", "parts_separator", "=", "', '", "prefix", "=", "(", "'DNS'", "+", "part_separator", ")", "if", "isinstance", "(", "cert_or_req", ",", "OpenSSL", ".", "crypto", ".", ...
get subject alternative names from certificate or csr using pyopenssl .
train
false
48,404
def test_render_to_file(Chart, datas): file_name = ('/tmp/test_graph-%s.svg' % uuid.uuid4()) if os.path.exists(file_name): os.remove(file_name) chart = Chart() chart = make_data(chart, datas) chart.render_to_file(file_name) with io.open(file_name, encoding='utf-8') as f: assert ('pygal' in f.read()) os.remove(file_name)
[ "def", "test_render_to_file", "(", "Chart", ",", "datas", ")", ":", "file_name", "=", "(", "'/tmp/test_graph-%s.svg'", "%", "uuid", ".", "uuid4", "(", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "file_name", ")", ":", "os", ".", "remove", "(...
test in file rendering .
train
false
48,405
def H(s): return md5_hex(s)
[ "def", "H", "(", "s", ")", ":", "return", "md5_hex", "(", "s", ")" ]
the hash function h .
train
false
48,406
def unpickle_backend(cls, args, kwargs): return cls(app=current_app._get_current_object(), *args, **kwargs)
[ "def", "unpickle_backend", "(", "cls", ",", "args", ",", "kwargs", ")", ":", "return", "cls", "(", "app", "=", "current_app", ".", "_get_current_object", "(", ")", ",", "*", "args", ",", "**", "kwargs", ")" ]
return an unpickled backend .
train
false
48,409
def install_openblas(): chdir(SRC_DIR) apt_command('build-dep libopenblas-dev') if glob.glob('*openblas*.deb'): run_command('dpkg -i *openblas*.deb') else: apt_command('source libopenblas-dev') chdir('openblas-*') patch = open('fix_makefile_system.patch', 'w') patch.write(OPENBLAS_0_1ALPHA_2_PATCH) patch.close() run_command(('patch -p1 < %s' % patch.name)) rule_file = open('Makefile.rule', 'a') lines = ['DYNAMIC_ARCH=1', 'NUM_THREADS=64', 'NO_LAPACK=1', 'NO_AFFINITY=1'] rule_file.write('\n'.join(lines)) rule_file.close() run_command('fakeroot debian/rules custom') run_command('dpkg -i ../*openblas*.deb') run_command('echo libopenblas-base hold | dpkg --set-selections') run_command('echo libopenblas-dev hold | dpkg --set-selections')
[ "def", "install_openblas", "(", ")", ":", "chdir", "(", "SRC_DIR", ")", "apt_command", "(", "'build-dep libopenblas-dev'", ")", "if", "glob", ".", "glob", "(", "'*openblas*.deb'", ")", ":", "run_command", "(", "'dpkg -i *openblas*.deb'", ")", "else", ":", "apt_c...
docstring for install_openblas .
train
false
48,412
def __IndexListForQuery(query): (required, kind, ancestor, props) = datastore_index.CompositeIndexForQuery(query) if (not required): return [] index_pb = entity_pb.Index() index_pb.set_entity_type(kind) index_pb.set_ancestor(bool(ancestor)) for (name, direction) in datastore_index.GetRecommendedIndexProperties(props): prop_pb = entity_pb.Index_Property() prop_pb.set_name(name) prop_pb.set_direction(direction) index_pb.property_list().append(prop_pb) return [index_pb]
[ "def", "__IndexListForQuery", "(", "query", ")", ":", "(", "required", ",", "kind", ",", "ancestor", ",", "props", ")", "=", "datastore_index", ".", "CompositeIndexForQuery", "(", "query", ")", "if", "(", "not", "required", ")", ":", "return", "[", "]", ...
get the composite index definition used by the query .
train
false
48,413
def issue_section_order(issue): try: return LOG_SECTION.values().index(issue_section(issue)) except: return (-1)
[ "def", "issue_section_order", "(", "issue", ")", ":", "try", ":", "return", "LOG_SECTION", ".", "values", "(", ")", ".", "index", "(", "issue_section", "(", "issue", ")", ")", "except", ":", "return", "(", "-", "1", ")" ]
returns the section order for the given issue .
train
false
48,414
def test_routing_class_based_method_view_with_cli_routing(): @hug.object.http_methods() class EndPoint(object, ): @hug.object.cli def get(self): return 'hi there!' def post(self): return 'bye' assert (hug.test.get(api, 'endpoint').data == 'hi there!') assert (hug.test.post(api, 'endpoint').data == 'bye') assert (hug.test.cli(EndPoint.get) == 'hi there!')
[ "def", "test_routing_class_based_method_view_with_cli_routing", "(", ")", ":", "@", "hug", ".", "object", ".", "http_methods", "(", ")", "class", "EndPoint", "(", "object", ",", ")", ":", "@", "hug", ".", "object", ".", "cli", "def", "get", "(", "self", ")...
test creating class based routers using method mappings exposing cli endpoints .
train
false
48,415
def get_dist_ops(operator): return (SpatiaLiteDistance(operator),)
[ "def", "get_dist_ops", "(", "operator", ")", ":", "return", "(", "SpatiaLiteDistance", "(", "operator", ")", ",", ")" ]
returns operations for regular distances; spherical distances are not currently supported .
train
false
48,416
def is_fakes3(s3_url): if (s3_url is not None): return (urlparse.urlparse(s3_url).scheme in ('fakes3', 'fakes3s')) else: return False
[ "def", "is_fakes3", "(", "s3_url", ")", ":", "if", "(", "s3_url", "is", "not", "None", ")", ":", "return", "(", "urlparse", ".", "urlparse", "(", "s3_url", ")", ".", "scheme", "in", "(", "'fakes3'", ",", "'fakes3s'", ")", ")", "else", ":", "return", ...
return true if s3_url has scheme fakes3:// .
train
false
48,417
@require_admin_context def volume_type_qos_disassociate_all(context, qos_specs_id): session = get_session() with session.begin(): session.query(models.VolumeTypes).filter_by(qos_specs_id=qos_specs_id).update({'qos_specs_id': None, 'updated_at': timeutils.utcnow()})
[ "@", "require_admin_context", "def", "volume_type_qos_disassociate_all", "(", "context", ",", "qos_specs_id", ")", ":", "session", "=", "get_session", "(", ")", "with", "session", ".", "begin", "(", ")", ":", "session", ".", "query", "(", "models", ".", "Volum...
disassociate all volume types associated with specified qos specs .
train
false
48,419
def parse_externals_xml(decoded_str, prefix=''): prefix = os.path.normpath(prefix) prefix = os.path.normcase(prefix) doc = xml.dom.pulldom.parseString(_get_xml_data(decoded_str)) externals = list() for (event, node) in doc: if ((event == 'START_ELEMENT') and (node.nodeName == 'target')): doc.expandNode(node) path = os.path.normpath(node.getAttribute('path')) if os.path.normcase(path).startswith(prefix): path = path[(len(prefix) + 1):] data = _get_target_property(node) for external in parse_external_prop(data): externals.append(joinpath(path, external)) return externals
[ "def", "parse_externals_xml", "(", "decoded_str", ",", "prefix", "=", "''", ")", ":", "prefix", "=", "os", ".", "path", ".", "normpath", "(", "prefix", ")", "prefix", "=", "os", ".", "path", ".", "normcase", "(", "prefix", ")", "doc", "=", "xml", "."...
parse a propget svn:externals xml .
train
false
48,420
def testunsupportedpagebreak(): document = newdocument() docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0] try: docbody.append(pagebreak(type='unsup')) except ValueError: return assert False
[ "def", "testunsupportedpagebreak", "(", ")", ":", "document", "=", "newdocument", "(", ")", "docbody", "=", "document", ".", "xpath", "(", "'/w:document/w:body'", ",", "namespaces", "=", "nsprefixes", ")", "[", "0", "]", "try", ":", "docbody", ".", "append",...
ensure unsupported page break types are trapped .
train
false
48,421
def random_partition(n, n_data): all_idxs = numpy.arange(n_data) numpy.random.shuffle(all_idxs) idxs1 = all_idxs[:n] idxs2 = all_idxs[n:] return (idxs1, idxs2)
[ "def", "random_partition", "(", "n", ",", "n_data", ")", ":", "all_idxs", "=", "numpy", ".", "arange", "(", "n_data", ")", "numpy", ".", "random", ".", "shuffle", "(", "all_idxs", ")", "idxs1", "=", "all_idxs", "[", ":", "n", "]", "idxs2", "=", "all_...
return n random rows of data (and also the other len-n rows) .
train
true
48,422
def plot_bar_graphs(ax, prng, min_value=5, max_value=25, nb_samples=5): x = np.arange(nb_samples) (ya, yb) = prng.randint(min_value, max_value, size=(2, nb_samples)) width = 0.25 ax.bar(x, ya, width) ax.bar((x + width), yb, width, color='C2') ax.set_xticks((x + width)) ax.set_xticklabels(['a', 'b', 'c', 'd', 'e']) return ax
[ "def", "plot_bar_graphs", "(", "ax", ",", "prng", ",", "min_value", "=", "5", ",", "max_value", "=", "25", ",", "nb_samples", "=", "5", ")", ":", "x", "=", "np", ".", "arange", "(", "nb_samples", ")", "(", "ya", ",", "yb", ")", "=", "prng", ".", ...
plot two bar graphs side by side .
train
false
48,423
def kwarg(**kwargs): return kwargs
[ "def", "kwarg", "(", "**", "kwargs", ")", ":", "return", "kwargs" ]
print out the data passed into the function **kwargs .
train
false
48,426
def get_google_api_auth(module, scopes=[], user_agent_product='ansible-python-api', user_agent_version='NA'): if (not HAS_GOOGLE_API_LIB): module.fail_json(msg='Please install google-api-python-client library') if (not scopes): scopes = ['https://www.googleapis.com/auth/cloud-platform'] try: (credentials, conn_params) = get_google_credentials(module, scopes, require_valid_json=True, check_libcloud=False) http = set_user_agent(Http(), ('%s-%s' % (user_agent_product, user_agent_version))) http_auth = credentials.authorize(http) return (http_auth, conn_params) except Exception as e: module.fail_json(msg=unexpected_error_msg(e), changed=False) return (None, None)
[ "def", "get_google_api_auth", "(", "module", ",", "scopes", "=", "[", "]", ",", "user_agent_product", "=", "'ansible-python-api'", ",", "user_agent_version", "=", "'NA'", ")", ":", "if", "(", "not", "HAS_GOOGLE_API_LIB", ")", ":", "module", ".", "fail_json", "...
authentication for use with google-python-api-client .
train
false
48,427
@task def test_pypi(release='2'): version = get_sympy_version() release = str(release) if (release not in {'2', '3'}): raise ValueError(("release must be one of '2', '3', not %s" % release)) venv = '/home/vagrant/repos/test-{release}-pip-virtualenv'.format(release=release) with use_venv(release): make_virtualenv(venv) with virtualenv(venv): run('pip install sympy') run('python -c "import sympy; assert sympy.__version__ == \'{version}\'"'.format(version=version))
[ "@", "task", "def", "test_pypi", "(", "release", "=", "'2'", ")", ":", "version", "=", "get_sympy_version", "(", ")", "release", "=", "str", "(", "release", ")", "if", "(", "release", "not", "in", "{", "'2'", ",", "'3'", "}", ")", ":", "raise", "Va...
test that the sympy can be pip installed .
train
false