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
34,300
def add_request(request_type, path, data=None): global q q.put({'type': request_type, 'path': path, 'data': data})
[ "def", "add_request", "(", "request_type", ",", "path", ",", "data", "=", "None", ")", ":", "global", "q", "q", ".", "put", "(", "{", "'type'", ":", "request_type", ",", "'path'", ":", "path", ",", "'data'", ":", "data", "}", ")" ]
add a request to the queue .
train
false
34,301
def _get_active_config_key(app_version): return db.Key.from_path(CONFIG_KIND, ('%s/%s' % (app_version, ACTIVE_KEY_NAME)), namespace=NAMESPACE)
[ "def", "_get_active_config_key", "(", "app_version", ")", ":", "return", "db", ".", "Key", ".", "from_path", "(", "CONFIG_KIND", ",", "(", "'%s/%s'", "%", "(", "app_version", ",", "ACTIVE_KEY_NAME", ")", ")", ",", "namespace", "=", "NAMESPACE", ")" ]
generate the key for the active config record belonging to app_version .
train
false
34,302
def runsimple(func, port=8080): import SimpleHTTPServer, SocketServer, BaseHTTPServer, urlparse import socket, errno import traceback class WSGIHandler(SimpleHTTPServer.SimpleHTTPRequestHandler, ): def run_wsgi_app(self): (protocol, host, path, parameters, query, fragment) = urlparse.urlparse(('http://dummyhost%s' % self.path)) env = {'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': self.rfile, 'wsgi.errors': sys.stderr, 'wsgi.multithread': 1, 'wsgi.multiprocess': 0, 'wsgi.run_once': 0, 'REQUEST_METHOD': self.command, 'REQUEST_URI': self.path, 'PATH_INFO': path, 'QUERY_STRING': query, 'CONTENT_TYPE': self.headers.get('Content-Type', ''), 'CONTENT_LENGTH': self.headers.get('Content-Length', ''), 'REMOTE_ADDR': self.client_address[0], 'SERVER_NAME': self.server.server_address[0], 'SERVER_PORT': str(self.server.server_address[1]), 'SERVER_PROTOCOL': self.request_version} for (http_header, http_value) in self.headers.items(): env[('HTTP_%s' % http_header.replace('-', '_').upper())] = http_value self.wsgi_sent_headers = 0 self.wsgi_headers = [] try: result = self.server.app(env, self.wsgi_start_response) try: try: for data in result: if data: self.wsgi_write_data(data) finally: if hasattr(result, 'close'): result.close() except socket.error as socket_err: if (socket_err.args[0] in (errno.ECONNABORTED, errno.EPIPE)): return except socket.timeout as socket_timeout: return except: print >>debug, traceback.format_exc(), internalerror() if (not self.wsgi_sent_headers): self.wsgi_start_response(ctx.status, ctx.headers) self.wsgi_write_data(ctx.output) if (not self.wsgi_sent_headers): self.wsgi_write_data(' ') return do_POST = run_wsgi_app def do_GET(self): if self.path.startswith('/static/'): SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) else: self.run_wsgi_app() def wsgi_start_response(self, response_status, response_headers, exc_info=None): if self.wsgi_sent_headers: raise Exception('Headers already sent and start_response called again!') self.wsgi_headers = (response_status, response_headers) return self.wsgi_write_data def wsgi_write_data(self, data): if (not self.wsgi_sent_headers): (status, headers) = self.wsgi_headers status_code = status[:status.find(' ')] status_msg = status[(status.find(' ') + 1):] self.send_response(int(status_code), status_msg) for (header, value) in headers: self.send_header(header, value) self.end_headers() self.wsgi_sent_headers = 1 self.wfile.write(data) class WSGIServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer, ): def __init__(self, func): BaseHTTPServer.HTTPServer.__init__(self, ('0.0.0.0', int(port)), WSGIHandler) self.app = func self.serverShuttingDown = 0 print (('Launching server: http://0.0.0.0:' + str(port)) + '/') WSGIServer(func).serve_forever()
[ "def", "runsimple", "(", "func", ",", "port", "=", "8080", ")", ":", "import", "SimpleHTTPServer", ",", "SocketServer", ",", "BaseHTTPServer", ",", "urlparse", "import", "socket", ",", "errno", "import", "traceback", "class", "WSGIHandler", "(", "SimpleHTTPServe...
runs [cherrypy][cp] wsgi server hosting wsgi app func .
train
false
34,303
def make_stats(mapping): stats = ['Clustersize DCTB #'] counts = defaultdict(int) for key in mapping.keys(): counts[len(mapping[key])] += 1 keys = sorted(counts.keys()) for key in keys: stats.append(('%d: DCTB DCTB %d' % ((key + 1), counts[key]))) return '\n'.join(stats)
[ "def", "make_stats", "(", "mapping", ")", ":", "stats", "=", "[", "'Clustersize DCTB #'", "]", "counts", "=", "defaultdict", "(", "int", ")", "for", "key", "in", "mapping", ".", "keys", "(", ")", ":", "counts", "[", "len", "(", "mapping", "[", "key", ...
calculates some cluster statistics .
train
false
34,304
def oo_pdb(arg): pdb.set_trace() return arg
[ "def", "oo_pdb", "(", "arg", ")", ":", "pdb", ".", "set_trace", "(", ")", "return", "arg" ]
this pops you into a pdb instance where arg is the data passed in from the filter .
train
false
34,305
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('console_type', metavar='<console-type>', help=_('Type of spice console ("spice-html5").')) def do_get_spice_console(cs, args): server = _find_server(cs, args.server) data = server.get_spice_console(args.console_type) print_console(cs, data)
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "@", "utils", ".", "arg", "(", "'console_type'", ",", "metavar", "=", "'<console-type>'", ",", "help", "=", "_"...
get a spice console to a server .
train
false
34,306
def v8(method_v8): if (method_v8.__name__ == 'read'): return multi(method_v8) method_v8._api = 'v8' return method_v8
[ "def", "v8", "(", "method_v8", ")", ":", "if", "(", "method_v8", ".", "__name__", "==", "'read'", ")", ":", "return", "multi", "(", "method_v8", ")", "method_v8", ".", "_api", "=", "'v8'", "return", "method_v8" ]
decorate a method that supports the new-style api only .
train
false
34,309
def get_non_courseware_topics(request, course_key, course, topic_ids): non_courseware_topics = [] existing_topic_ids = set() for (name, entry) in sorted(course.discussion_topics.items(), key=(lambda item: item[1].get('sort_key', item[0]))): if ((not topic_ids) or (entry['id'] in topic_ids)): discussion_topic = DiscussionTopic(entry['id'], name, get_thread_list_url(request, course_key, [entry['id']])) non_courseware_topics.append(DiscussionTopicSerializer(discussion_topic).data) if (topic_ids and (entry['id'] in topic_ids)): existing_topic_ids.add(entry['id']) return (non_courseware_topics, existing_topic_ids)
[ "def", "get_non_courseware_topics", "(", "request", ",", "course_key", ",", "course", ",", "topic_ids", ")", ":", "non_courseware_topics", "=", "[", "]", "existing_topic_ids", "=", "set", "(", ")", "for", "(", "name", ",", "entry", ")", "in", "sorted", "(", ...
returns a list of topic trees that are not linked to courseware .
train
false
34,310
def test_long_int(): sigma = (((10 ** 21) * u.M_p) / (u.cm ** 2)) sigma.to((u.M_sun / (u.pc ** 2)))
[ "def", "test_long_int", "(", ")", ":", "sigma", "=", "(", "(", "(", "10", "**", "21", ")", "*", "u", ".", "M_p", ")", "/", "(", "u", ".", "cm", "**", "2", ")", ")", "sigma", ".", "to", "(", "(", "u", ".", "M_sun", "/", "(", "u", ".", "p...
issue #672 .
train
false
34,311
def test_str_args_deprecated(tmpdir, testdir): from _pytest.main import EXIT_NOTESTSCOLLECTED warnings = [] class Collect: def pytest_logwarning(self, message): warnings.append(message) ret = pytest.main(('%s -x' % tmpdir), plugins=[Collect()]) testdir.delete_loaded_modules() msg = 'passing a string to pytest.main() is deprecated, pass a list of arguments instead.' assert (msg in warnings) assert (ret == EXIT_NOTESTSCOLLECTED)
[ "def", "test_str_args_deprecated", "(", "tmpdir", ",", "testdir", ")", ":", "from", "_pytest", ".", "main", "import", "EXIT_NOTESTSCOLLECTED", "warnings", "=", "[", "]", "class", "Collect", ":", "def", "pytest_logwarning", "(", "self", ",", "message", ")", ":"...
deprecate passing strings to pytest .
train
false
34,312
def _parse_codec_options(options): return CodecOptions(document_class=options.get('document_class', DEFAULT_CODEC_OPTIONS.document_class), tz_aware=options.get('tz_aware', DEFAULT_CODEC_OPTIONS.tz_aware), uuid_representation=options.get('uuidrepresentation', DEFAULT_CODEC_OPTIONS.uuid_representation), unicode_decode_error_handler=options.get('unicode_decode_error_handler', DEFAULT_CODEC_OPTIONS.unicode_decode_error_handler), tzinfo=options.get('tzinfo', DEFAULT_CODEC_OPTIONS.tzinfo))
[ "def", "_parse_codec_options", "(", "options", ")", ":", "return", "CodecOptions", "(", "document_class", "=", "options", ".", "get", "(", "'document_class'", ",", "DEFAULT_CODEC_OPTIONS", ".", "document_class", ")", ",", "tz_aware", "=", "options", ".", "get", ...
parse bson codec options .
train
true
34,313
def get_html5_ids(html5_sources): html5_ids = [x.split('/')[(-1)].rsplit('.', 1)[0] for x in html5_sources] return html5_ids
[ "def", "get_html5_ids", "(", "html5_sources", ")", ":", "html5_ids", "=", "[", "x", ".", "split", "(", "'/'", ")", "[", "(", "-", "1", ")", "]", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "for", "x", "in", "html5_sources", "]", "r...
helper method to parse out an html5 source into the ideas note: this assumes that / are not in the filename .
train
false
34,314
def pr_rebuild_path(pe_id, clear=False): if isinstance(pe_id, Row): pe_id = pe_id.pe_id rtable = current.s3db.pr_role query = (((rtable.pe_id == pe_id) & (rtable.role_type == OU)) & (rtable.deleted != True)) db = current.db db(query).update(path=None) roles = db(query).select(rtable.id, rtable.pe_id, rtable.path, rtable.role_type) for role in roles: if (role.path is None): pr_role_rebuild_path(role, clear=clear)
[ "def", "pr_rebuild_path", "(", "pe_id", ",", "clear", "=", "False", ")", ":", "if", "isinstance", "(", "pe_id", ",", "Row", ")", ":", "pe_id", "=", "pe_id", ".", "pe_id", "rtable", "=", "current", ".", "s3db", ".", "pr_role", "query", "=", "(", "(", ...
rebuild the ancestor path of all roles in the ou hierarchy a person entity defines .
train
false
34,316
def test_get_debug_values_success(): prev_value = config.compute_test_value for mode in ['ignore', 'warn', 'raise']: try: config.compute_test_value = mode x = T.vector() x.tag.test_value = numpy.zeros((4,), dtype=config.floatX) y = numpy.zeros((5, 5)) iters = 0 for (x_val, y_val) in op.get_debug_values(x, y): assert (x_val.shape == (4,)) assert (y_val.shape == (5, 5)) iters += 1 assert (iters == 1) finally: config.compute_test_value = prev_value
[ "def", "test_get_debug_values_success", "(", ")", ":", "prev_value", "=", "config", ".", "compute_test_value", "for", "mode", "in", "[", "'ignore'", ",", "'warn'", ",", "'raise'", "]", ":", "try", ":", "config", ".", "compute_test_value", "=", "mode", "x", "...
tests that get_debug_value returns values when available .
train
false
34,317
def escape_md(text): return md_chars_matcher.sub('\\\\\\1', text)
[ "def", "escape_md", "(", "text", ")", ":", "return", "md_chars_matcher", ".", "sub", "(", "'\\\\\\\\\\\\1'", ",", "text", ")" ]
escapes markdown-sensitive characters .
train
false
34,319
def audit_period_bounds(current_period=False): (begin, end) = utils.last_completed_audit_period() if current_period: audit_start = end audit_end = timeutils.utcnow() else: audit_start = begin audit_end = end return (audit_start, audit_end)
[ "def", "audit_period_bounds", "(", "current_period", "=", "False", ")", ":", "(", "begin", ",", "end", ")", "=", "utils", ".", "last_completed_audit_period", "(", ")", "if", "current_period", ":", "audit_start", "=", "end", "audit_end", "=", "timeutils", ".", ...
get the start and end of the relevant audit usage period .
train
false
34,322
def send_loop(): while True: while (not Message.objects.all()): logging.debug((u'sleeping for %s seconds before checking queue again' % EMPTY_QUEUE_SLEEP)) time.sleep(EMPTY_QUEUE_SLEEP) send_all()
[ "def", "send_loop", "(", ")", ":", "while", "True", ":", "while", "(", "not", "Message", ".", "objects", ".", "all", "(", ")", ")", ":", "logging", ".", "debug", "(", "(", "u'sleeping for %s seconds before checking queue again'", "%", "EMPTY_QUEUE_SLEEP", ")",...
loop indefinitely .
train
true
34,324
def tuplize(seq): if isinstance(seq, (list, tuple)): return tuple((tuplize(i) for i in seq)) return seq
[ "def", "tuplize", "(", "seq", ")", ":", "if", "isinstance", "(", "seq", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "tuple", "(", "(", "tuplize", "(", "i", ")", "for", "i", "in", "seq", ")", ")", "return", "seq" ]
turn all nested sequences to tuples in given sequence .
train
false
34,325
def html_visit_inheritance_diagram(self, node): graph = node['graph'] graph_hash = get_graph_hash(node) name = ('inheritance%s' % graph_hash) urls = {} for child in node: if (child.get('refuri') is not None): urls[child['reftitle']] = child.get('refuri') elif (child.get('refid') is not None): urls[child['reftitle']] = ('#' + child.get('refid')) dotcode = graph.generate_dot(name, urls, env=self.builder.env) render_dot_html(self, node, dotcode, [], 'inheritance', 'inheritance', alt=('Inheritance diagram of ' + node['content'])) raise nodes.SkipNode
[ "def", "html_visit_inheritance_diagram", "(", "self", ",", "node", ")", ":", "graph", "=", "node", "[", "'graph'", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "(", "'inheritance%s'", "%", "graph_hash", ")", "urls", "=", "{", "}...
output the graph for html .
train
false
34,327
def new(rsa_key): return PKCS115_SigScheme(rsa_key)
[ "def", "new", "(", "rsa_key", ")", ":", "return", "PKCS115_SigScheme", "(", "rsa_key", ")" ]
creates a new image with the given mode and size .
train
false
34,328
def string_io(data=None): try: return cStringIO(bytes(data)) except (UnicodeEncodeError, TypeError): return StringIO(data)
[ "def", "string_io", "(", "data", "=", "None", ")", ":", "try", ":", "return", "cStringIO", "(", "bytes", "(", "data", ")", ")", "except", "(", "UnicodeEncodeError", ",", "TypeError", ")", ":", "return", "StringIO", "(", "data", ")" ]
pass data through to stringio module and return result .
train
false
34,329
def setup_active_tag_values(active_tag_values, data): for category in list(active_tag_values.keys()): if (category in data): active_tag_values[category] = data[category]
[ "def", "setup_active_tag_values", "(", "active_tag_values", ",", "data", ")", ":", "for", "category", "in", "list", "(", "active_tag_values", ".", "keys", "(", ")", ")", ":", "if", "(", "category", "in", "data", ")", ":", "active_tag_values", "[", "category"...
setup/update active_tag values with dict-like data .
train
false
34,330
@then('the command output should not contain the following log records') def step_command_output_should_not_contain_log_records(context): assert context.table, 'REQUIRE: context.table' context.table.require_columns(['category', 'level', 'message']) format = getattr(context, 'log_record_format', context.config.logging_format) for row in context.table.rows: output = LogRecordTable.make_output_for_row(row, format) context.execute_steps(u'\n Then the command output should not contain:\n """\n {expected_output}\n """\n '.format(expected_output=output))
[ "@", "then", "(", "'the command output should not contain the following log records'", ")", "def", "step_command_output_should_not_contain_log_records", "(", "context", ")", ":", "assert", "context", ".", "table", ",", "'REQUIRE: context.table'", "context", ".", "table", ".",...
verifies that the command output contains the specified log records .
train
true
34,332
@contextlib.contextmanager def namespace_tree_context(**kwargs): kwargs.setdefault('meta_path', sys.meta_path) kwargs.setdefault('path_hooks', sys.path_hooks) import_context = util.import_state(**kwargs) with import_context: with sys_modules_context(): (yield)
[ "@", "contextlib", ".", "contextmanager", "def", "namespace_tree_context", "(", "**", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'meta_path'", ",", "sys", ".", "meta_path", ")", "kwargs", ".", "setdefault", "(", "'path_hooks'", ",", "sys", ".", "...
save import state and sys .
train
false
34,333
def _list_nodes(full=False, for_output=False): fetch = True page = 1 ret = {} while fetch: items = query(method='droplets', command=(('?page=' + str(page)) + '&per_page=200')) for node in items['droplets']: name = node['name'] ret[name] = {} if full: ret[name] = _get_full_output(node, for_output=for_output) else: (public_ips, private_ips) = _get_ips(node['networks']) ret[name] = {'id': node['id'], 'image': node['image']['name'], 'name': name, 'private_ips': private_ips, 'public_ips': public_ips, 'size': node['size_slug'], 'state': str(node['status'])} page += 1 try: fetch = ('next' in items['links']['pages']) except KeyError: fetch = False return ret
[ "def", "_list_nodes", "(", "full", "=", "False", ",", "for_output", "=", "False", ")", ":", "fetch", "=", "True", "page", "=", "1", "ret", "=", "{", "}", "while", "fetch", ":", "items", "=", "query", "(", "method", "=", "'droplets'", ",", "command", ...
helper function to format and parse node data .
train
true
34,334
def _drop_index(engine, table, idx_name): for idx in getattr(table, 'indexes'): if (idx.name == idx_name): break else: raise Exception(("Index '%s' not found!" % idx_name)) idx.drop(engine) table.indexes.remove(idx)
[ "def", "_drop_index", "(", "engine", ",", "table", ",", "idx_name", ")", ":", "for", "idx", "in", "getattr", "(", "table", ",", "'indexes'", ")", ":", "if", "(", "idx", ".", "name", "==", "idx_name", ")", ":", "break", "else", ":", "raise", "Exceptio...
drop index from db and remove index from sqlalchemy table metadata .
train
false
34,335
def _wait_for_io_events(socks, events, timeout=None): if (not HAS_SELECT): raise ValueError('Platform does not have a selector') if (not isinstance(socks, list)): if hasattr(socks, 'fileno'): socks = [socks] else: socks = list(socks) with DefaultSelector() as selector: for sock in socks: selector.register(sock, events) return [key[0].fileobj for key in selector.select(timeout) if (key[1] & events)]
[ "def", "_wait_for_io_events", "(", "socks", ",", "events", ",", "timeout", "=", "None", ")", ":", "if", "(", "not", "HAS_SELECT", ")", ":", "raise", "ValueError", "(", "'Platform does not have a selector'", ")", "if", "(", "not", "isinstance", "(", "socks", ...
waits for io events to be available from a list of sockets or optionally a single socket if passed in .
train
true
34,336
def in6_isaddrllallnodes(str): return (inet_pton(socket.AF_INET6, 'ff02::1') == inet_pton(socket.AF_INET6, str))
[ "def", "in6_isaddrllallnodes", "(", "str", ")", ":", "return", "(", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "'ff02::1'", ")", "==", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "str", ")", ")" ]
returns true if address is the link-local all-nodes multicast address .
train
false
34,337
def get_copy_virtual_disk_spec(client_factory, adapter_type='lsilogic', disk_type='preallocated'): dest_spec = client_factory.create('ns0:VirtualDiskSpec') dest_spec.adapterType = adapter_type dest_spec.diskType = disk_type return dest_spec
[ "def", "get_copy_virtual_disk_spec", "(", "client_factory", ",", "adapter_type", "=", "'lsilogic'", ",", "disk_type", "=", "'preallocated'", ")", ":", "dest_spec", "=", "client_factory", ".", "create", "(", "'ns0:VirtualDiskSpec'", ")", "dest_spec", ".", "adapterType"...
builds the virtual disk copy spec .
train
false
34,338
def delete_local_backup_file(local_file): if (not remove(local_file)): logging.warning("No local backup file '{0}' to delete. Skipping...".format(local_file))
[ "def", "delete_local_backup_file", "(", "local_file", ")", ":", "if", "(", "not", "remove", "(", "local_file", ")", ")", ":", "logging", ".", "warning", "(", "\"No local backup file '{0}' to delete. Skipping...\"", ".", "format", "(", "local_file", ")", ")" ]
removes the local backup file .
train
false
34,340
def _get_course_cohort_settings_representation(course, course_cohort_settings): (cohorted_course_wide_discussions, cohorted_inline_discussions) = get_cohorted_discussions(course, course_cohort_settings) return {'id': course_cohort_settings.id, 'is_cohorted': course_cohort_settings.is_cohorted, 'cohorted_inline_discussions': cohorted_inline_discussions, 'cohorted_course_wide_discussions': cohorted_course_wide_discussions, 'always_cohort_inline_discussions': course_cohort_settings.always_cohort_inline_discussions}
[ "def", "_get_course_cohort_settings_representation", "(", "course", ",", "course_cohort_settings", ")", ":", "(", "cohorted_course_wide_discussions", ",", "cohorted_inline_discussions", ")", "=", "get_cohorted_discussions", "(", "course", ",", "course_cohort_settings", ")", "...
returns a json representation of a course cohort settings .
train
false
34,341
def get_module_version(module_name): mod = __import__(module_name) return getattr(mod, '__version__', getattr(mod, 'VERSION', None))
[ "def", "get_module_version", "(", "module_name", ")", ":", "mod", "=", "__import__", "(", "module_name", ")", "return", "getattr", "(", "mod", ",", "'__version__'", ",", "getattr", "(", "mod", ",", "'VERSION'", ",", "None", ")", ")" ]
return module version or none if version cant be retrieved .
train
false
34,342
def system_parallel(commands, timeout=None, ignore_status=False): return [bg_jobs.exit_status for bg_jobs in run_parallel(commands, timeout=timeout, ignore_status=ignore_status, stdout_tee=TEE_TO_LOGS, stderr_tee=TEE_TO_LOGS)]
[ "def", "system_parallel", "(", "commands", ",", "timeout", "=", "None", ",", "ignore_status", "=", "False", ")", ":", "return", "[", "bg_jobs", ".", "exit_status", "for", "bg_jobs", "in", "run_parallel", "(", "commands", ",", "timeout", "=", "timeout", ",", ...
this function returns a list of exit statuses for the respective list of commands .
train
false
34,343
def is_symmetric_and_hollow(matrix): return ((matrix.T == matrix).all() and (trace(matrix) == 0))
[ "def", "is_symmetric_and_hollow", "(", "matrix", ")", ":", "return", "(", "(", "matrix", ".", "T", "==", "matrix", ")", ".", "all", "(", ")", "and", "(", "trace", "(", "matrix", ")", "==", "0", ")", ")" ]
return true if matrix is symmetric and hollow .
train
false
34,344
def unjellyFromSource(stringOrFile): ns = {'Instance': Instance, 'InstanceMethod': InstanceMethod, 'Class': Class, 'Function': Function, 'Module': Module, 'Ref': Ref, 'Deref': Deref, 'Copyreg': Copyreg} if hasattr(stringOrFile, 'read'): source = stringOrFile.read() else: source = stringOrFile code = compile(source, '<source>', 'exec') eval(code, ns, ns) if ('app' in ns): return unjellyFromAOT(ns['app']) else: raise ValueError(("%s needs to define an 'app', it didn't!" % stringOrFile))
[ "def", "unjellyFromSource", "(", "stringOrFile", ")", ":", "ns", "=", "{", "'Instance'", ":", "Instance", ",", "'InstanceMethod'", ":", "InstanceMethod", ",", "'Class'", ":", "Class", ",", "'Function'", ":", "Function", ",", "'Module'", ":", "Module", ",", "...
pass me a string of code or a filename that defines an app variable .
train
false
34,345
def survey_T(phrase, langDict): if ((phrase in langDict) and (langDict[phrase] != '')): return langDict[phrase] else: return phrase
[ "def", "survey_T", "(", "phrase", ",", "langDict", ")", ":", "if", "(", "(", "phrase", "in", "langDict", ")", "and", "(", "langDict", "[", "phrase", "]", "!=", "''", ")", ")", ":", "return", "langDict", "[", "phrase", "]", "else", ":", "return", "p...
function to translate a phrase using the dictionary passed in @todo: parameter description .
train
false
34,348
def validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_args): _check_arg_length(fname, (args + tuple(kwargs.values())), max_fname_arg_count, compat_args) args_dict = dict(zip(compat_args, args)) for key in args_dict: if (key in kwargs): raise TypeError("{fname}() got multiple values for keyword argument '{arg}'".format(fname=fname, arg=key)) kwargs.update(args_dict) validate_kwargs(fname, kwargs, compat_args)
[ "def", "validate_args_and_kwargs", "(", "fname", ",", "args", ",", "kwargs", ",", "max_fname_arg_count", ",", "compat_args", ")", ":", "_check_arg_length", "(", "fname", ",", "(", "args", "+", "tuple", "(", "kwargs", ".", "values", "(", ")", ")", ")", ",",...
checks whether parameters passed to the *args and **kwargs argument in a function fname are valid parameters as specified in *compat_args and whether or not they are set to their default values .
train
true
34,349
def _G_test(site_counts): from math import log G = 0 tot = sum(site_counts) tot_syn = (site_counts[0] + site_counts[2]) tot_non = (site_counts[1] + site_counts[3]) tot_fix = sum(site_counts[:2]) tot_poly = sum(site_counts[2:]) exp = [((tot_fix * tot_syn) / tot), ((tot_fix * tot_non) / tot), ((tot_poly * tot_syn) / tot), ((tot_poly * tot_non) / tot)] for (obs, ex) in zip(site_counts, exp): G += (obs * log((obs / ex))) G *= 2 return chisqprob(G, 1)
[ "def", "_G_test", "(", "site_counts", ")", ":", "from", "math", "import", "log", "G", "=", "0", "tot", "=", "sum", "(", "site_counts", ")", "tot_syn", "=", "(", "site_counts", "[", "0", "]", "+", "site_counts", "[", "2", "]", ")", "tot_non", "=", "...
g test for 2x2 contingency table .
train
false
34,350
def scite(exe=u'scite'): install_editor((exe + u' {filename} -goto:{line}'))
[ "def", "scite", "(", "exe", "=", "u'scite'", ")", ":", "install_editor", "(", "(", "exe", "+", "u' {filename} -goto:{line}'", ")", ")" ]
scite or sc1 .
train
false
34,351
def open_only(func): @wraps(func) def _check(self, *args, **kwds): if (self.closed or self.eof_received or self.eof_sent or (not self.active)): raise SSHException('Channel is not open') return func(self, *args, **kwds) return _check
[ "def", "open_only", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_check", "(", "self", ",", "*", "args", ",", "**", "kwds", ")", ":", "if", "(", "self", ".", "closed", "or", "self", ".", "eof_received", "or", "self", ".", "eof_s...
decorator for .
train
true
34,352
def read_points_from_xml(xmlFileName): xmldoc = minidom.parse(xmlFileName) facelist = xmldoc.getElementsByTagName('face') faces = {} for xmlFace in facelist: fileName = xmlFace.attributes['file'].value xf = int(xmlFace.attributes['xf'].value) yf = int(xmlFace.attributes['yf'].value) xs = int(xmlFace.attributes['xs'].value) ys = int(xmlFace.attributes['ys'].value) xm = int(xmlFace.attributes['xm'].value) ym = int(xmlFace.attributes['ym'].value) faces[fileName] = array([xf, yf, xs, ys, xm, ym]) return faces
[ "def", "read_points_from_xml", "(", "xmlFileName", ")", ":", "xmldoc", "=", "minidom", ".", "parse", "(", "xmlFileName", ")", "facelist", "=", "xmldoc", ".", "getElementsByTagName", "(", "'face'", ")", "faces", "=", "{", "}", "for", "xmlFace", "in", "facelis...
reads control points for face alignment .
train
false
34,354
@removals.remove(message='keystoneclient auth plugins are deprecated. Use keystoneauth.', version='2.1.0', removal_version='3.0.0') def get_plugin_options(name): return base.get_plugin_class(name).get_options()
[ "@", "removals", ".", "remove", "(", "message", "=", "'keystoneclient auth plugins are deprecated. Use keystoneauth.'", ",", "version", "=", "'2.1.0'", ",", "removal_version", "=", "'3.0.0'", ")", "def", "get_plugin_options", "(", "name", ")", ":", "return", "base", ...
get the oslo_config options for a specific plugin .
train
false
34,356
@requires_ftp @requires_good_network def test_fetch_file_ftp(): _test_fetch('ftp://speedtest.tele2.net/1KB.zip')
[ "@", "requires_ftp", "@", "requires_good_network", "def", "test_fetch_file_ftp", "(", ")", ":", "_test_fetch", "(", "'ftp://speedtest.tele2.net/1KB.zip'", ")" ]
test file downloading over ftp .
train
false
34,357
def id_srand(n): return _id.id_srand(n)
[ "def", "id_srand", "(", "n", ")", ":", "return", "_id", ".", "id_srand", "(", "n", ")" ]
generate standard uniform pseudorandom numbers via a very efficient lagged fibonacci method .
train
false
34,358
def stringfilter(func): def _dec(*args, **kwargs): if args: args = list(args) args[0] = force_text(args[0]) if (isinstance(args[0], SafeData) and getattr(_dec._decorated_function, u'is_safe', False)): return mark_safe(func(*args, **kwargs)) return func(*args, **kwargs) _dec._decorated_function = getattr(func, u'_decorated_function', func) return wraps(func)(_dec)
[ "def", "stringfilter", "(", "func", ")", ":", "def", "_dec", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "args", ":", "args", "=", "list", "(", "args", ")", "args", "[", "0", "]", "=", "force_text", "(", "args", "[", "0", "]", ")", ...
decorator for filters which should only receive unicode objects .
train
false
34,359
def _query_include_self(X, include_self): if include_self: query = X._fit_X else: query = None return query
[ "def", "_query_include_self", "(", "X", ",", "include_self", ")", ":", "if", "include_self", ":", "query", "=", "X", ".", "_fit_X", "else", ":", "query", "=", "None", "return", "query" ]
return the query based on include_self param .
train
false
34,360
def _get_docker_py_versioninfo(): try: return docker.version_info except AttributeError: pass
[ "def", "_get_docker_py_versioninfo", "(", ")", ":", "try", ":", "return", "docker", ".", "version_info", "except", "AttributeError", ":", "pass" ]
returns the version_info tuple from docker-py .
train
false
34,361
def _get_target_host(iscsi_string): if iscsi_string: return iscsi_string[0:iscsi_string.find(':')] elif ((iscsi_string is None) or CONF.target_host): return CONF.target_host
[ "def", "_get_target_host", "(", "iscsi_string", ")", ":", "if", "iscsi_string", ":", "return", "iscsi_string", "[", "0", ":", "iscsi_string", ".", "find", "(", "':'", ")", "]", "elif", "(", "(", "iscsi_string", "is", "None", ")", "or", "CONF", ".", "targ...
retrieve target host .
train
false
34,363
def FindNextMultiLineCommentStart(lines, lineix): while (lineix < len(lines)): if lines[lineix].strip().startswith('/*'): if (lines[lineix].strip().find('*/', 2) < 0): return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "(", "lineix", "<", "len", "(", "lines", ")", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "if",...
find the beginning marker for a multiline comment .
train
true
34,364
def OpenDocumentPresentation(): doc = OpenDocument('application/vnd.oasis.opendocument.presentation') doc.presentation = Presentation() doc.body.addElement(doc.presentation) return doc
[ "def", "OpenDocumentPresentation", "(", ")", ":", "doc", "=", "OpenDocument", "(", "'application/vnd.oasis.opendocument.presentation'", ")", "doc", ".", "presentation", "=", "Presentation", "(", ")", "doc", ".", "body", ".", "addElement", "(", "doc", ".", "present...
creates a presentation document .
train
false
34,365
@hug.get('/image.png', output=hug.output_format.png_image) def image(): return '../artwork/logo.png'
[ "@", "hug", ".", "get", "(", "'/image.png'", ",", "output", "=", "hug", ".", "output_format", ".", "png_image", ")", "def", "image", "(", ")", ":", "return", "'../artwork/logo.png'" ]
dynamically creates an image type handler for the specified image type .
train
false
34,366
@contextmanager def func_globals_inject(func, **overrides): if hasattr(func, 'im_func'): func = func.__func__ func_globals = func.__globals__ injected_func_globals = [] overridden_func_globals = {} for override in overrides: if (override in func_globals): overridden_func_globals[override] = func_globals[override] else: injected_func_globals.append(override) func_globals.update(overrides) (yield) func_globals.update(overridden_func_globals) for injected in injected_func_globals: del func_globals[injected]
[ "@", "contextmanager", "def", "func_globals_inject", "(", "func", ",", "**", "overrides", ")", ":", "if", "hasattr", "(", "func", ",", "'im_func'", ")", ":", "func", "=", "func", ".", "__func__", "func_globals", "=", "func", ".", "__globals__", "injected_fun...
override specific variables within a functions global context .
train
true
34,367
def test_read_twoline_human(): table = '\n+------+----------+\n| Col1 | Col2 |\n+------|----------+\n| 1.2 | "hello" |\n| 2.4 | \'s worlds|\n+------+----------+\n' dat = ascii.read(table, Reader=ascii.FixedWidthTwoLine, delimiter='+', header_start=1, position_line=0, data_start=3, data_end=(-1)) assert_equal(dat.dtype.names, ('Col1', 'Col2')) assert_almost_equal(dat[1][0], 2.4) assert_equal(dat[0][1], '"hello"') assert_equal(dat[1][1], "'s worlds")
[ "def", "test_read_twoline_human", "(", ")", ":", "table", "=", "'\\n+------+----------+\\n| Col1 | Col2 |\\n+------|----------+\\n| 1.2 | \"hello\" |\\n| 2.4 | \\'s worlds|\\n+------+----------+\\n'", "dat", "=", "ascii", ".", "read", "(", "table", ",", "Reader", "=", "asc...
read text table designed for humans and test having position line before the header line .
train
false
34,368
@pytest.mark.django_db @pytest.mark.usefixtures('regular_user') def test_picotable_correctly_sorts_translated_fields(rf, admin_user, regular_user): populate_if_required() columns = [Column('id', 'Id', filter_config=Filter(), display=instance_id), Column('name', 'Name', sort_field='translations__name', filter_config=TextFilter(filter_field='translations__name'))] pico = get_pico(rf, model=Product, columns=columns) sorted_products = pico.get_data({'perPage': 100, 'page': 1, 'sort': '+name'}) sorted_names = [p['name'] for p in sorted_products['items']] assert (sorted_names == sorted(sorted_names)) sorted_products = pico.get_data({'perPage': 100, 'page': 1, 'sort': '-name'}) sorted_names = [p['name'] for p in sorted_products['items']] assert (sorted_names == sorted(sorted_names, reverse=True))
[ "@", "pytest", ".", "mark", ".", "django_db", "@", "pytest", ".", "mark", ".", "usefixtures", "(", "'regular_user'", ")", "def", "test_picotable_correctly_sorts_translated_fields", "(", "rf", ",", "admin_user", ",", "regular_user", ")", ":", "populate_if_required", ...
make sure that translated fields .
train
false
34,370
def diamond_graph(create_using=None): description = ['adjacencylist', 'Diamond Graph', 4, [[2, 3], [1, 3, 4], [1, 2, 4], [2, 3]]] G = make_small_undirected_graph(description, create_using) return G
[ "def", "diamond_graph", "(", "create_using", "=", "None", ")", ":", "description", "=", "[", "'adjacencylist'", ",", "'Diamond Graph'", ",", "4", ",", "[", "[", "2", ",", "3", "]", ",", "[", "1", ",", "3", ",", "4", "]", ",", "[", "1", ",", "2", ...
return the diamond graph .
train
false
34,371
def assert_quantities_allclose(coord, q1s, attrs): q2s = [getattr(coord, attr) for attr in attrs] assert (len(q1s) == len(q2s)) for (q1, q2) in zip(q1s, q2s): assert (q1.shape == q2.shape) assert allclose(q1, q2, rtol=0, atol=(1e-13 * q1.unit))
[ "def", "assert_quantities_allclose", "(", "coord", ",", "q1s", ",", "attrs", ")", ":", "q2s", "=", "[", "getattr", "(", "coord", ",", "attr", ")", "for", "attr", "in", "attrs", "]", "assert", "(", "len", "(", "q1s", ")", "==", "len", "(", "q2s", ")...
compare two tuples of quantities .
train
false
34,372
@should_profile_cpu def start_cpu_profiling(): import yappi yappi.start() dump_data_every_thread(dump_data, DELAY_MINUTES, SAVE_THREAD_PTR)
[ "@", "should_profile_cpu", "def", "start_cpu_profiling", "(", ")", ":", "import", "yappi", "yappi", ".", "start", "(", ")", "dump_data_every_thread", "(", "dump_data", ",", "DELAY_MINUTES", ",", "SAVE_THREAD_PTR", ")" ]
if the environment variable w3af_profiling is set to 1 .
train
false
34,377
def _full_ct_query(action, actor_only=None): actstream.registry.check(action.actor) query = _ct_query(action.actor) if (action.target is not None): actstream.registry.check(action.target) query |= _ct_query(action.target, actor_only) if (action.action_object is not None): actstream.registry.check(action.action_object) query |= _ct_query(action.action_object, actor_only) return query
[ "def", "_full_ct_query", "(", "action", ",", "actor_only", "=", "None", ")", ":", "actstream", ".", "registry", ".", "check", "(", "action", ".", "actor", ")", "query", "=", "_ct_query", "(", "action", ".", "actor", ")", "if", "(", "action", ".", "targ...
build a query that matches objects with a content type that matches an action .
train
false
34,379
@testing.requires_testing_data def test_warn_inverse_operator(): bad_info = copy.deepcopy(_get_evoked().info) bad_info['projs'] = list() fwd_op = read_forward_solution(fname_fwd, surf_ori=True) noise_cov = read_cov(fname_cov) with warnings.catch_warnings(record=True) as w: make_inverse_operator(bad_info, fwd_op, noise_cov) assert_equal(len(w), 1)
[ "@", "testing", ".", "requires_testing_data", "def", "test_warn_inverse_operator", "(", ")", ":", "bad_info", "=", "copy", ".", "deepcopy", "(", "_get_evoked", "(", ")", ".", "info", ")", "bad_info", "[", "'projs'", "]", "=", "list", "(", ")", "fwd_op", "=...
test mne inverse warning without average eeg projection .
train
false
34,380
def AddAclSample(): client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) acl_entry = gdata.docs.data.AclEntry(scope=gdata.acl.data.AclScope(value='user@example.com', type='user'), role=gdata.acl.data.AclRole(value='reader')) client.AddAclEntry(doc, acl_entry, send_notification=False)
[ "def", "AddAclSample", "(", ")", ":", "client", "=", "CreateClient", "(", ")", "doc", "=", "gdata", ".", "docs", ".", "data", ".", "Resource", "(", "type", "=", "'document'", ",", "title", "=", "'My Sample Doc'", ")", "doc", "=", "client", ".", "Create...
delete a resource .
train
false
34,382
def globber_full(path, pattern=u'*'): if os.path.exists(path): try: return [os.path.join(path, f) for f in os.listdir(path) if fnmatch.fnmatch(f, pattern)] except UnicodeDecodeError: path = path.encode('utf-8') return [os.path.join(path, f) for f in os.listdir(path) if fnmatch.fnmatch(f, pattern)] else: return []
[ "def", "globber_full", "(", "path", ",", "pattern", "=", "u'*'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "try", ":", "return", "[", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "for", "f", "in", ...
return matching full file/folder names in folder path .
train
false
34,385
def expand_schema(): _sync_common_repo(version=None) _sync_repo(repo_name=EXPAND_REPO)
[ "def", "expand_schema", "(", ")", ":", "_sync_common_repo", "(", "version", "=", "None", ")", "_sync_repo", "(", "repo_name", "=", "EXPAND_REPO", ")" ]
expand the database schema ahead of data migration .
train
false
34,386
def api_dataset_from_dataset_and_node(dataset, node_uuid): result = dict(dataset_id=dataset.dataset_id, deleted=dataset.deleted, primary=unicode(node_uuid), metadata=thaw(dataset.metadata)) if (dataset.maximum_size is not None): result[u'maximum_size'] = dataset.maximum_size return result
[ "def", "api_dataset_from_dataset_and_node", "(", "dataset", ",", "node_uuid", ")", ":", "result", "=", "dict", "(", "dataset_id", "=", "dataset", ".", "dataset_id", ",", "deleted", "=", "dataset", ".", "deleted", ",", "primary", "=", "unicode", "(", "node_uuid...
return a dataset dict which conforms to /v1/endpoints .
train
false
34,387
@gen.engine def WriteRegistry(logs_store, path, processed_list, callback): contents = '\n'.join(processed_list) (yield gen.Task(logs_store.Put, path, contents)) callback()
[ "@", "gen", ".", "engine", "def", "WriteRegistry", "(", "logs_store", ",", "path", ",", "processed_list", ",", "callback", ")", ":", "contents", "=", "'\\n'", ".", "join", "(", "processed_list", ")", "(", "yield", "gen", ".", "Task", "(", "logs_store", "...
turns processed_list into a new-line separated string and writes it to path in s3 .
train
false
34,389
def split_locale(loc): def split(st, char): '\n Split a string `st` once by `char`; always return a two-element list\n even if the second element is empty.\n ' split_st = st.split(char, 1) if (len(split_st) == 1): split_st.append('') return split_st comps = {} (work_st, comps['charmap']) = split(loc, ' ') (work_st, comps['modifier']) = split(work_st, '@') (work_st, comps['codeset']) = split(work_st, '.') (comps['language'], comps['territory']) = split(work_st, '_') return comps
[ "def", "split_locale", "(", "loc", ")", ":", "def", "split", "(", "st", ",", "char", ")", ":", "split_st", "=", "st", ".", "split", "(", "char", ",", "1", ")", "if", "(", "len", "(", "split_st", ")", "==", "1", ")", ":", "split_st", ".", "appen...
split a locale specifier .
train
true
34,391
def adapt_ndarray(obj): if (obj.ndim == 0): return float(obj) else: return adapt_obj(obj)
[ "def", "adapt_ndarray", "(", "obj", ")", ":", "if", "(", "obj", ".", "ndim", "==", "0", ")", ":", "return", "float", "(", "obj", ")", "else", ":", "return", "adapt_obj", "(", "obj", ")" ]
convert numpy scalars to floats before storing in sqlite .
train
false
34,392
@pytest.mark.cmd @pytest.mark.django_db def test_find_duplicate_emails_nodups(capfd, no_extra_users): call_command('find_duplicate_emails') (out, err) = capfd.readouterr() assert ('There are no accounts with duplicate emails' in out)
[ "@", "pytest", ".", "mark", ".", "cmd", "@", "pytest", ".", "mark", ".", "django_db", "def", "test_find_duplicate_emails_nodups", "(", "capfd", ",", "no_extra_users", ")", ":", "call_command", "(", "'find_duplicate_emails'", ")", "(", "out", ",", "err", ")", ...
no duplicates found .
train
false
34,397
def acl_group_remove_hosts(id, hosts): group = models.AclGroup.smart_get(id) group.check_for_acl_violation_acl_group() hosts = models.Host.smart_get_bulk(hosts) group.hosts.remove(*hosts) group.on_host_membership_change()
[ "def", "acl_group_remove_hosts", "(", "id", ",", "hosts", ")", ":", "group", "=", "models", ".", "AclGroup", ".", "smart_get", "(", "id", ")", "group", ".", "check_for_acl_violation_acl_group", "(", ")", "hosts", "=", "models", ".", "Host", ".", "smart_get_b...
remove hosts from an acl group .
train
false
34,398
def is_task_successful(request, task_id): response_data = {'task': {'id': task_id, 'executed': AsyncResult(task_id).successful()}} return HttpResponse(serialize(response_data), mimetype='application/json')
[ "def", "is_task_successful", "(", "request", ",", "task_id", ")", ":", "response_data", "=", "{", "'task'", ":", "{", "'id'", ":", "task_id", ",", "'executed'", ":", "AsyncResult", "(", "task_id", ")", ".", "successful", "(", ")", "}", "}", "return", "Ht...
returns task execute status in json format .
train
false
34,400
def inplace_csr_column_scale(X, scale): assert (scale.shape[0] == X.shape[1]) X.data *= scale.take(X.indices, mode='clip')
[ "def", "inplace_csr_column_scale", "(", "X", ",", "scale", ")", ":", "assert", "(", "scale", ".", "shape", "[", "0", "]", "==", "X", ".", "shape", "[", "1", "]", ")", "X", ".", "data", "*=", "scale", ".", "take", "(", "X", ".", "indices", ",", ...
inplace column scaling of a csr matrix .
train
false
34,401
def print_unittest_summary(result): buff = StringIO() buff.write('-------------------------------------------------------------\nSUMMARY:\n') if result.wasSuccessful(): buff.write('\x1b[32m * RESULT: SUCCESS\x1b[0m\n') else: buff.write(' * RESULT: FAIL\n') buff.write((' * TESTS: %s\n' % result.testsRun)) buff.write((' * ERRORS: %s [%s]\n' % (len(result.errors), ', '.join(_format_errors(result.errors))))) buff.write((' * FAILURES: %s [%s]\n' % (len(result.failures), ', '.join(_format_errors(result.failures))))) print(buff.getvalue())
[ "def", "print_unittest_summary", "(", "result", ")", ":", "buff", "=", "StringIO", "(", ")", "buff", ".", "write", "(", "'-------------------------------------------------------------\\nSUMMARY:\\n'", ")", "if", "result", ".", "wasSuccessful", "(", ")", ":", "buff", ...
print summary of python unittest result to stdout .
train
false
34,402
def normalized_mean_absolute_error(y_real, y_pred, max_rating, min_rating): (y_real, y_pred) = check_arrays(y_real, y_pred) mae = mean_absolute_error(y_real, y_pred) return (mae / (max_rating - min_rating))
[ "def", "normalized_mean_absolute_error", "(", "y_real", ",", "y_pred", ",", "max_rating", ",", "min_rating", ")", ":", "(", "y_real", ",", "y_pred", ")", "=", "check_arrays", "(", "y_real", ",", "y_pred", ")", "mae", "=", "mean_absolute_error", "(", "y_real", ...
it computes the normalized average absolute difference between predicted and actual ratings for users .
train
false
34,404
def is_executable(exe): return os.access(exe, os.X_OK)
[ "def", "is_executable", "(", "exe", ")", ":", "return", "os", ".", "access", "(", "exe", ",", "os", ".", "X_OK", ")" ]
checks a file is executable .
train
false
34,405
def _index_to_label(index): if isinstance(index, pd.MultiIndex): return '-'.join(map(str, index.names)) else: return index.name
[ "def", "_index_to_label", "(", "index", ")", ":", "if", "isinstance", "(", "index", ",", "pd", ".", "MultiIndex", ")", ":", "return", "'-'", ".", "join", "(", "map", "(", "str", ",", "index", ".", "names", ")", ")", "else", ":", "return", "index", ...
convert a pandas index or multiindex to an axis label .
train
false
34,407
def getPrivacyList(disp, listname): try: resp = disp.SendAndWaitForResponse(Iq('get', NS_PRIVACY, payload=[Node('list', {'name': listname})])) if isResultNode(resp): return resp.getQueryPayload()[0] except: pass
[ "def", "getPrivacyList", "(", "disp", ",", "listname", ")", ":", "try", ":", "resp", "=", "disp", ".", "SendAndWaitForResponse", "(", "Iq", "(", "'get'", ",", "NS_PRIVACY", ",", "payload", "=", "[", "Node", "(", "'list'", ",", "{", "'name'", ":", "list...
requests specific privacy list listname .
train
false
34,408
def get_scene_exceptions(tvdb_id): myDB = db.DBConnection('cache.db') exceptions = myDB.select('SELECT DISTINCT show_name FROM scene_exceptions WHERE tvdb_id = ?', [tvdb_id]) return [cur_exception['show_name'] for cur_exception in exceptions]
[ "def", "get_scene_exceptions", "(", "tvdb_id", ")", ":", "myDB", "=", "db", ".", "DBConnection", "(", "'cache.db'", ")", "exceptions", "=", "myDB", ".", "select", "(", "'SELECT DISTINCT show_name FROM scene_exceptions WHERE tvdb_id = ?'", ",", "[", "tvdb_id", "]", "...
given a tvdb_id .
train
false
34,409
def _check_perms_changes(name, newperms, runas=None, existing=None): if (not newperms): return False if (existing is None): try: existing = __salt__['rabbitmq.list_user_permissions'](name, runas=runas) except CommandExecutionError as err: log.error('Error: {0}'.format(err)) return False perm_need_change = False for vhost_perms in newperms: for (vhost, perms) in six.iteritems(vhost_perms): if (vhost in existing): existing_vhost = existing[vhost] if (perms != existing_vhost): if ((existing_vhost == '') and (perms == ['', '', ''])): continue perm_need_change = True else: perm_need_change = True return perm_need_change
[ "def", "_check_perms_changes", "(", "name", ",", "newperms", ",", "runas", "=", "None", ",", "existing", "=", "None", ")", ":", "if", "(", "not", "newperms", ")", ":", "return", "False", "if", "(", "existing", "is", "None", ")", ":", "try", ":", "exi...
check whether rabbitmq users permissions need to be changed .
train
true
34,410
def qcow2size(qcow2): output = check_output(['qemu-img', 'info', qcow2]) try: assert ('format: qcow' in output) bytes = int(re.findall('(\\d+) bytes', output)[0]) except: raise Exception(('Could not determine size of %s' % qcow2)) return bytes
[ "def", "qcow2size", "(", "qcow2", ")", ":", "output", "=", "check_output", "(", "[", "'qemu-img'", ",", "'info'", ",", "qcow2", "]", ")", "try", ":", "assert", "(", "'format: qcow'", "in", "output", ")", "bytes", "=", "int", "(", "re", ".", "findall", ...
return virtual disk size of qcow2 image .
train
false
34,411
def io_add_watch(*args, **kwargs): (channel, priority, condition, func, user_data) = _io_add_watch_get_args(*args, **kwargs) return GLib.io_add_watch(channel, priority, condition, func, *user_data)
[ "def", "io_add_watch", "(", "*", "args", ",", "**", "kwargs", ")", ":", "(", "channel", ",", "priority", ",", "condition", ",", "func", ",", "user_data", ")", "=", "_io_add_watch_get_args", "(", "*", "args", ",", "**", "kwargs", ")", "return", "GLib", ...
io_add_watch -> event_source_id .
train
true
34,414
def get_sidebar_announcements_context(request, objects): must_show_announcement = False announcements = [] if (SIDEBAR_COOKIE_NAME in request.COOKIES): try: is_sidebar_open = bool(int(request.COOKIES[SIDEBAR_COOKIE_NAME])) except ValueError: is_sidebar_open = True request.session['is_sidebar_open'] = is_sidebar_open else: is_sidebar_open = request.session.get('is_sidebar_open', True) for item in objects: announcement = item.get_announcement(request.user) if (announcement is None): continue announcements.append(announcement) if request.user.is_anonymous: continue ann_mtime = dateformat.format(announcement.modified_on, 'U') stored_mtime = request.session.get(announcement.virtual_path, None) if (ann_mtime != stored_mtime): must_show_announcement = True request.session[announcement.virtual_path] = ann_mtime ctx = {'announcements': announcements, 'is_sidebar_open': (must_show_announcement or is_sidebar_open), 'has_sidebar': (len(announcements) > 0)} return ctx
[ "def", "get_sidebar_announcements_context", "(", "request", ",", "objects", ")", ":", "must_show_announcement", "=", "False", "announcements", "=", "[", "]", "if", "(", "SIDEBAR_COOKIE_NAME", "in", "request", ".", "COOKIES", ")", ":", "try", ":", "is_sidebar_open"...
return the announcements context for the browser pages sidebar .
train
false
34,415
def _check_path(p): for (a, b) in zip(p[:(-1)], p[1:]): if (adjacency[a[0]][b[0]] != a[2]): return False if (adjacency[b[0]][a[0]] != b[1]): return False return True
[ "def", "_check_path", "(", "p", ")", ":", "for", "(", "a", ",", "b", ")", "in", "zip", "(", "p", "[", ":", "(", "-", "1", ")", "]", ",", "p", "[", "1", ":", "]", ")", ":", "if", "(", "adjacency", "[", "a", "[", "0", "]", "]", "[", "b"...
make sure that a path is actually a string of nodes with connected ports returns true if path is valid .
train
false
34,416
def get_body(body, time, location=None, ephemeris=None): if (location is None): location = time.location cartrep = _get_apparent_body_position(body, time, ephemeris) icrs = ICRS(cartrep) if (location is not None): (obsgeoloc, obsgeovel) = location.get_gcrs_posvel(time) gcrs = icrs.transform_to(GCRS(obstime=time, obsgeoloc=obsgeoloc, obsgeovel=obsgeovel)) else: gcrs = icrs.transform_to(GCRS(obstime=time)) return SkyCoord(gcrs)
[ "def", "get_body", "(", "body", ",", "time", ",", "location", "=", "None", ",", "ephemeris", "=", "None", ")", ":", "if", "(", "location", "is", "None", ")", ":", "location", "=", "time", ".", "location", "cartrep", "=", "_get_apparent_body_position", "(...
get a ~astropy .
train
false
34,417
def rax_find_loadbalancer(module, rax_module, loadbalancer): clb = rax_module.cloud_loadbalancers try: found = clb.get(loadbalancer) except: found = [] for lb in clb.list(): if (loadbalancer == lb.name): found.append(lb) if (not found): module.fail_json(msg='No loadbalancer was matched') if (len(found) > 1): module.fail_json(msg='Multiple loadbalancers matched') found = found[0] return found
[ "def", "rax_find_loadbalancer", "(", "module", ",", "rax_module", ",", "loadbalancer", ")", ":", "clb", "=", "rax_module", ".", "cloud_loadbalancers", "try", ":", "found", "=", "clb", ".", "get", "(", "loadbalancer", ")", "except", ":", "found", "=", "[", ...
find a cloud load balancer by id or name .
train
false
34,418
def _parse_date_rfc822_grubby(dt): _rfc822_date_grubby = ('%s %s %s' % (_rfc822_month, _rfc822_day, _rfc822_year)) _rfc822_match_grubby = re.compile(('(?:%s[,]? )?%s(?: %s)?' % (_rfc822_dayname, _rfc822_date_grubby, _rfc822_time))).match try: m = _rfc822_match_grubby(dt.lower()).groupdict(0) except AttributeError: return None return _parse_date_group_rfc822(m)
[ "def", "_parse_date_rfc822_grubby", "(", "dt", ")", ":", "_rfc822_date_grubby", "=", "(", "'%s %s %s'", "%", "(", "_rfc822_month", ",", "_rfc822_day", ",", "_rfc822_year", ")", ")", "_rfc822_match_grubby", "=", "re", ".", "compile", "(", "(", "'(?:%s[,]? )?%s(?: %...
parse date format similar to rfc 822 .
train
false
34,419
def lower_triangle(matlist, K): copy_matlist = copy.deepcopy(matlist) (lower_triangle, upper_triangle) = LU(copy_matlist, K, reverse=1) return lower_triangle
[ "def", "lower_triangle", "(", "matlist", ",", "K", ")", ":", "copy_matlist", "=", "copy", ".", "deepcopy", "(", "matlist", ")", "(", "lower_triangle", ",", "upper_triangle", ")", "=", "LU", "(", "copy_matlist", ",", "K", ",", "reverse", "=", "1", ")", ...
transforms a given matrix to a lower triangle matrix by performing row operations on it .
train
false
34,420
def get_file_context_from_ctx(ctx, filename): deleted = False filename = basic_util.strip_path(filename) for ctx_file in ctx.files(): ctx_file_name = basic_util.strip_path(ctx_file) if (filename == ctx_file_name): try: fctx = ctx[ctx_file] return fctx except LookupError: deleted = True if deleted: return 'DELETED' return None
[ "def", "get_file_context_from_ctx", "(", "ctx", ",", "filename", ")", ":", "deleted", "=", "False", "filename", "=", "basic_util", ".", "strip_path", "(", "filename", ")", "for", "ctx_file", "in", "ctx", ".", "files", "(", ")", ":", "ctx_file_name", "=", "...
return the mercurial file context for a specified file .
train
false
34,421
def sortedSeasons(m): seasons = m.get('episodes', {}).keys() seasons.sort() return seasons
[ "def", "sortedSeasons", "(", "m", ")", ":", "seasons", "=", "m", ".", "get", "(", "'episodes'", ",", "{", "}", ")", ".", "keys", "(", ")", "seasons", ".", "sort", "(", ")", "return", "seasons" ]
return a sorted list of seasons of the given series .
train
false
34,422
def cgsnapshot_update(context, cgsnapshot_id, values): return IMPL.cgsnapshot_update(context, cgsnapshot_id, values)
[ "def", "cgsnapshot_update", "(", "context", ",", "cgsnapshot_id", ",", "values", ")", ":", "return", "IMPL", ".", "cgsnapshot_update", "(", "context", ",", "cgsnapshot_id", ",", "values", ")" ]
set the given properties on a cgsnapshot and update it .
train
false
34,423
def test_concentration(): dense = np.random.randn(5, 10).astype('float32') sparse = np.random.randn(5, 10).astype('float32') sparse[:, 1:] /= 100000.0 weights = Variable(dense) dhl_dense_10 = dirichlet_likelihood(weights, alpha=10.0).data dhl_dense_01 = dirichlet_likelihood(weights, alpha=0.1).data weights = Variable(sparse) dhl_sparse_10 = dirichlet_likelihood(weights, alpha=10.0).data dhl_sparse_01 = dirichlet_likelihood(weights, alpha=0.1).data msg = 'Sparse vector has higher likelihood than dense with alpha=0.1' assert (dhl_sparse_01 > dhl_dense_01), msg msg = 'Dense vector has higher likelihood than sparse with alpha=10.0' assert (dhl_dense_10 > dhl_sparse_10), msg
[ "def", "test_concentration", "(", ")", ":", "dense", "=", "np", ".", "random", ".", "randn", "(", "5", ",", "10", ")", ".", "astype", "(", "'float32'", ")", "sparse", "=", "np", ".", "random", ".", "randn", "(", "5", ",", "10", ")", ".", "astype"...
test that alpha > 1 .
train
false
34,424
def expired(certificate): ret = {} if os.path.isfile(certificate): try: ret['path'] = certificate cert = _get_certificate_obj(certificate) _now = datetime.datetime.utcnow() _expiration_date = cert.get_not_after().get_datetime() ret['cn'] = _parse_subject(cert.get_subject())['CN'] if (_expiration_date.strftime('%Y-%m-%d %H:%M:%S') <= _now.strftime('%Y-%m-%d %H:%M:%S')): ret['expired'] = True else: ret['expired'] = False except ValueError: pass return ret
[ "def", "expired", "(", "certificate", ")", ":", "ret", "=", "{", "}", "if", "os", ".", "path", ".", "isfile", "(", "certificate", ")", ":", "try", ":", "ret", "[", "'path'", "]", "=", "certificate", "cert", "=", "_get_certificate_obj", "(", "certificat...
returns a dict containing limited details of a certificate and whether the certificate has expired .
train
true
34,425
def quaternion_about_axis(angle, axis): q = numpy.array([0.0, axis[0], axis[1], axis[2]]) qlen = vector_norm(q) if (qlen > _EPS): q *= (math.sin((angle / 2.0)) / qlen) q[0] = math.cos((angle / 2.0)) return q
[ "def", "quaternion_about_axis", "(", "angle", ",", "axis", ")", ":", "q", "=", "numpy", ".", "array", "(", "[", "0.0", ",", "axis", "[", "0", "]", ",", "axis", "[", "1", "]", ",", "axis", "[", "2", "]", "]", ")", "qlen", "=", "vector_norm", "("...
return quaternion for rotation about axis .
train
true
34,426
@pytest.mark.parametrize('text, expected', [('f<oo>bar', 'foob|ar'), ('foobar|', 'foobar|')]) def test_rl_forward_char(text, expected, lineedit, bridge): lineedit.set_aug_text(text) bridge.rl_forward_char() assert (lineedit.aug_text() == expected)
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'text, expected'", ",", "[", "(", "'f<oo>bar'", ",", "'foob|ar'", ")", ",", "(", "'foobar|'", ",", "'foobar|'", ")", "]", ")", "def", "test_rl_forward_char", "(", "text", ",", "expected", ",", "lineedit...
test rl_forward_char .
train
false
34,427
def should_include(path, exclude_patterns, include_patterns): for pattern in exclude_patterns: if match_path(path, pattern): for pattern in include_patterns: if match_path(path, pattern): return True return False return True
[ "def", "should_include", "(", "path", ",", "exclude_patterns", ",", "include_patterns", ")", ":", "for", "pattern", "in", "exclude_patterns", ":", "if", "match_path", "(", "path", ",", "pattern", ")", ":", "for", "pattern", "in", "include_patterns", ":", "if",...
given a path .
train
false
34,428
def _clean_credentials(credentials): SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I) CLEANSED_SUBSTITUTE = '********************' for key in credentials: if SENSITIVE_CREDENTIALS.search(key): credentials[key] = CLEANSED_SUBSTITUTE return credentials
[ "def", "_clean_credentials", "(", "credentials", ")", ":", "SENSITIVE_CREDENTIALS", "=", "re", ".", "compile", "(", "'api|token|key|secret|password|signature'", ",", "re", ".", "I", ")", "CLEANSED_SUBSTITUTE", "=", "'********************'", "for", "key", "in", "creden...
cleans a dictionary of credentials of potentially sensitive info before sending to less secure functions .
train
false
34,429
def require_moderator_email_prereqs_are_satisfied(): if (not feconf.REQUIRE_EMAIL_ON_MODERATOR_ACTION): raise Exception('For moderator emails to be sent, please ensure that REQUIRE_EMAIL_ON_MODERATOR_ACTION is set to True.') if (not feconf.CAN_SEND_EMAILS): raise Exception('For moderator emails to be sent, please ensure that CAN_SEND_EMAILS is set to True.')
[ "def", "require_moderator_email_prereqs_are_satisfied", "(", ")", ":", "if", "(", "not", "feconf", ".", "REQUIRE_EMAIL_ON_MODERATOR_ACTION", ")", ":", "raise", "Exception", "(", "'For moderator emails to be sent, please ensure that REQUIRE_EMAIL_ON_MODERATOR_ACTION is set to True.'",...
raises an exception if .
train
false
34,430
def dump_certificate_request(type, req): bio = _new_mem_buf() if (type == FILETYPE_PEM): result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req) elif (type == FILETYPE_ASN1): result_code = _lib.i2d_X509_REQ_bio(bio, req._req) elif (type == FILETYPE_TEXT): result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0) else: raise ValueError('type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT') _openssl_assert((result_code != 0)) return _bio_to_string(bio)
[ "def", "dump_certificate_request", "(", "type", ",", "req", ")", ":", "bio", "=", "_new_mem_buf", "(", ")", "if", "(", "type", "==", "FILETYPE_PEM", ")", ":", "result_code", "=", "_lib", ".", "PEM_write_bio_X509_REQ", "(", "bio", ",", "req", ".", "_req", ...
dump a certificate request to a buffer .
train
true
34,431
def adaptiveDetrend(data, x=None, threshold=3.0): try: import scipy.signal except ImportError: raise Exception('adaptiveDetrend() requires the package scipy.signal.') if (x is None): x = data.xvals(0) d = data.view(np.ndarray) d2 = scipy.signal.detrend(d) stdev = d2.std() mask = (abs(d2) < (stdev * threshold)) lr = scipy.stats.linregress(x[mask], d[mask]) base = (lr[1] + (lr[0] * x)) d4 = (d - base) if (hasattr(data, 'implements') and data.implements('MetaArray')): return MetaArray(d4, info=data.infoCopy()) return d4
[ "def", "adaptiveDetrend", "(", "data", ",", "x", "=", "None", ",", "threshold", "=", "3.0", ")", ":", "try", ":", "import", "scipy", ".", "signal", "except", "ImportError", ":", "raise", "Exception", "(", "'adaptiveDetrend() requires the package scipy.signal.'", ...
return the signal with baseline removed .
train
false
34,433
def install_importhook(config): if (sys.platform.startswith('java') or (sys.version_info[:3] == (2, 6, 0))): raise SystemError('rewrite not supported') config._assertstate = AssertionState(config, 'rewrite') config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config) sys.meta_path.insert(0, hook) config._assertstate.trace('installed rewrite import hook') def undo(): hook = config._assertstate.hook if ((hook is not None) and (hook in sys.meta_path)): sys.meta_path.remove(hook) config.add_cleanup(undo) return hook
[ "def", "install_importhook", "(", "config", ")", ":", "if", "(", "sys", ".", "platform", ".", "startswith", "(", "'java'", ")", "or", "(", "sys", ".", "version_info", "[", ":", "3", "]", "==", "(", "2", ",", "6", ",", "0", ")", ")", ")", ":", "...
try to install the rewrite hook .
train
false
34,434
def pause_int(): global __PAUSE_END if (__PAUSE_END is None): return '0' else: val = (__PAUSE_END - time.time()) if (val < 0): sign = '-' val = abs(val) else: sign = '' min = int((val / 60L)) sec = int((val - (min * 60))) return ('%s%d:%02d' % (sign, min, sec))
[ "def", "pause_int", "(", ")", ":", "global", "__PAUSE_END", "if", "(", "__PAUSE_END", "is", "None", ")", ":", "return", "'0'", "else", ":", "val", "=", "(", "__PAUSE_END", "-", "time", ".", "time", "(", ")", ")", "if", "(", "val", "<", "0", ")", ...
return minutes:seconds until pause ends .
train
false
34,435
def _pad_bytes(name, length): return (name + ('\x00' * (length - len(name))))
[ "def", "_pad_bytes", "(", "name", ",", "length", ")", ":", "return", "(", "name", "+", "(", "'\\x00'", "*", "(", "length", "-", "len", "(", "name", ")", ")", ")", ")" ]
takes a char string and pads it with null bytes until its length chars .
train
false