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
41,581
def truncateletters(value, arg): from django_extensions.utils.text import truncate_letters try: length = int(arg) except ValueError: return value return truncate_letters(value, length)
[ "def", "truncateletters", "(", "value", ",", "arg", ")", ":", "from", "django_extensions", ".", "utils", ".", "text", "import", "truncate_letters", "try", ":", "length", "=", "int", "(", "arg", ")", "except", "ValueError", ":", "return", "value", "return", "truncate_letters", "(", "value", ",", "length", ")" ]
truncates a string after a certain number of letters argument: number of letters to truncate after .
train
false
41,583
def create_rule_instance(rule): return SecurityRule(rule['protocol'], rule['source_address_prefix'], rule['destination_address_prefix'], rule['access'], rule['direction'], id=rule.get('id', None), description=rule.get('description', None), source_port_range=rule.get('source_port_range', None), destination_port_range=rule.get('destination_port_range', None), priority=rule.get('priority', None), provisioning_state=rule.get('provisioning_state', None), name=rule.get('name', None), etag=rule.get('etag', None))
[ "def", "create_rule_instance", "(", "rule", ")", ":", "return", "SecurityRule", "(", "rule", "[", "'protocol'", "]", ",", "rule", "[", "'source_address_prefix'", "]", ",", "rule", "[", "'destination_address_prefix'", "]", ",", "rule", "[", "'access'", "]", ",", "rule", "[", "'direction'", "]", ",", "id", "=", "rule", ".", "get", "(", "'id'", ",", "None", ")", ",", "description", "=", "rule", ".", "get", "(", "'description'", ",", "None", ")", ",", "source_port_range", "=", "rule", ".", "get", "(", "'source_port_range'", ",", "None", ")", ",", "destination_port_range", "=", "rule", ".", "get", "(", "'destination_port_range'", ",", "None", ")", ",", "priority", "=", "rule", ".", "get", "(", "'priority'", ",", "None", ")", ",", "provisioning_state", "=", "rule", ".", "get", "(", "'provisioning_state'", ",", "None", ")", ",", "name", "=", "rule", ".", "get", "(", "'name'", ",", "None", ")", ",", "etag", "=", "rule", ".", "get", "(", "'etag'", ",", "None", ")", ")" ]
create an instance of securityrule from a dict .
train
false
41,584
def erfcinv(y): return ((- ndtri((0.5 * y))) / sqrt(2))
[ "def", "erfcinv", "(", "y", ")", ":", "return", "(", "(", "-", "ndtri", "(", "(", "0.5", "*", "y", ")", ")", ")", "/", "sqrt", "(", "2", ")", ")" ]
inverse function for erfc .
train
false
41,587
def snapshot_update(context, snapshot_id, values): return IMPL.snapshot_update(context, snapshot_id, values)
[ "def", "snapshot_update", "(", "context", ",", "snapshot_id", ",", "values", ")", ":", "return", "IMPL", ".", "snapshot_update", "(", "context", ",", "snapshot_id", ",", "values", ")" ]
set the given properties on an snapshot and update it .
train
false
41,588
def get_installed_carousel(shop): return configuration.get(shop, SAMPLE_CAROUSEL_KEY)
[ "def", "get_installed_carousel", "(", "shop", ")", ":", "return", "configuration", ".", "get", "(", "shop", ",", "SAMPLE_CAROUSEL_KEY", ")" ]
returns the installed sample carousel .
train
false
41,589
def read_png(filename): x = Reader(filename) try: alpha = x.asDirect()[3]['alpha'] if alpha: y = x.asRGBA8()[2] n = 4 else: y = x.asRGB8()[2] n = 3 y = np.array([yy for yy in y], np.uint8) finally: x.file.close() y.shape = (y.shape[0], (y.shape[1] // n), n) return y
[ "def", "read_png", "(", "filename", ")", ":", "x", "=", "Reader", "(", "filename", ")", "try", ":", "alpha", "=", "x", ".", "asDirect", "(", ")", "[", "3", "]", "[", "'alpha'", "]", "if", "alpha", ":", "y", "=", "x", ".", "asRGBA8", "(", ")", "[", "2", "]", "n", "=", "4", "else", ":", "y", "=", "x", ".", "asRGB8", "(", ")", "[", "2", "]", "n", "=", "3", "y", "=", "np", ".", "array", "(", "[", "yy", "for", "yy", "in", "y", "]", ",", "np", ".", "uint8", ")", "finally", ":", "x", ".", "file", ".", "close", "(", ")", "y", ".", "shape", "=", "(", "y", ".", "shape", "[", "0", "]", ",", "(", "y", ".", "shape", "[", "1", "]", "//", "n", ")", ",", "n", ")", "return", "y" ]
read a png file to rgb8 or rgba8 unlike imread .
train
true
41,590
def _request_defaults(kwargs): request_defaults = {'timeout': 5.0, 'headers': {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-us,en;q=0.5', 'Connection': 'keep-alive'}, 'user_agent': USER_AGENT, 'follow_robots': False} request_defaults.update(kwargs) return request_defaults
[ "def", "_request_defaults", "(", "kwargs", ")", ":", "request_defaults", "=", "{", "'timeout'", ":", "5.0", ",", "'headers'", ":", "{", "'Accept'", ":", "'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'", ",", "'Accept-Encoding'", ":", "'gzip, deflate'", ",", "'Accept-Language'", ":", "'en-us,en;q=0.5'", ",", "'Connection'", ":", "'keep-alive'", "}", ",", "'user_agent'", ":", "USER_AGENT", ",", "'follow_robots'", ":", "False", "}", "request_defaults", ".", "update", "(", "kwargs", ")", "return", "request_defaults" ]
return defaults for a requests session .
train
false
41,591
def was_modified_since(header=None, mtime=0, size=0): try: if (header is None): raise ValueError matches = re.match('^([^;]+)(; length=([0-9]+))?$', header, re.IGNORECASE) header_mtime = parse_http_date(matches.group(1)) header_len = matches.group(3) if (header_len and (int(header_len) != size)): raise ValueError if (mtime > header_mtime): raise ValueError except (AttributeError, ValueError, OverflowError): return True return False
[ "def", "was_modified_since", "(", "header", "=", "None", ",", "mtime", "=", "0", ",", "size", "=", "0", ")", ":", "try", ":", "if", "(", "header", "is", "None", ")", ":", "raise", "ValueError", "matches", "=", "re", ".", "match", "(", "'^([^;]+)(; length=([0-9]+))?$'", ",", "header", ",", "re", ".", "IGNORECASE", ")", "header_mtime", "=", "parse_http_date", "(", "matches", ".", "group", "(", "1", ")", ")", "header_len", "=", "matches", ".", "group", "(", "3", ")", "if", "(", "header_len", "and", "(", "int", "(", "header_len", ")", "!=", "size", ")", ")", ":", "raise", "ValueError", "if", "(", "mtime", ">", "header_mtime", ")", ":", "raise", "ValueError", "except", "(", "AttributeError", ",", "ValueError", ",", "OverflowError", ")", ":", "return", "True", "return", "False" ]
was something modified since the user last downloaded it? header this is the value of the if-modified-since header .
train
true
41,594
def get_cached_clients(): if (OAuth.state_key not in current_app.extensions): raise RuntimeError(('%r is not initialized.' % current_app)) state = current_app.extensions[OAuth.state_key] return state.cached_clients
[ "def", "get_cached_clients", "(", ")", ":", "if", "(", "OAuth", ".", "state_key", "not", "in", "current_app", ".", "extensions", ")", ":", "raise", "RuntimeError", "(", "(", "'%r is not initialized.'", "%", "current_app", ")", ")", "state", "=", "current_app", ".", "extensions", "[", "OAuth", ".", "state_key", "]", "return", "state", ".", "cached_clients" ]
gets the cached clients dictionary in current context .
train
true
41,595
def _group_by_sample_metadata(collapsed_md, sample_id_field='SampleID'): new_index_to_group = {} old_index_to_new_index = {} for i in collapsed_md.index: old_indices = collapsed_md[sample_id_field][i] if isinstance(i, tuple): new_index = i else: new_index = (i,) new_index_to_group[new_index] = set(old_indices) for old_index in old_indices: old_index_to_new_index[old_index] = new_index return (new_index_to_group, old_index_to_new_index)
[ "def", "_group_by_sample_metadata", "(", "collapsed_md", ",", "sample_id_field", "=", "'SampleID'", ")", ":", "new_index_to_group", "=", "{", "}", "old_index_to_new_index", "=", "{", "}", "for", "i", "in", "collapsed_md", ".", "index", ":", "old_indices", "=", "collapsed_md", "[", "sample_id_field", "]", "[", "i", "]", "if", "isinstance", "(", "i", ",", "tuple", ")", ":", "new_index", "=", "i", "else", ":", "new_index", "=", "(", "i", ",", ")", "new_index_to_group", "[", "new_index", "]", "=", "set", "(", "old_indices", ")", "for", "old_index", "in", "old_indices", ":", "old_index_to_new_index", "[", "old_index", "]", "=", "new_index", "return", "(", "new_index_to_group", ",", "old_index_to_new_index", ")" ]
group sample identifiers by one or more metadata fields parameters collapsed_md : pd .
train
false
41,596
def parse_branch_site_a(foreground, line_floats, site_classes): if ((not site_classes) or (len(line_floats) == 0)): return for n in range(len(line_floats)): if (site_classes[n].get('branch types') is None): site_classes[n]['branch types'] = {} if foreground: site_classes[n]['branch types']['foreground'] = line_floats[n] else: site_classes[n]['branch types']['background'] = line_floats[n] return site_classes
[ "def", "parse_branch_site_a", "(", "foreground", ",", "line_floats", ",", "site_classes", ")", ":", "if", "(", "(", "not", "site_classes", ")", "or", "(", "len", "(", "line_floats", ")", "==", "0", ")", ")", ":", "return", "for", "n", "in", "range", "(", "len", "(", "line_floats", ")", ")", ":", "if", "(", "site_classes", "[", "n", "]", ".", "get", "(", "'branch types'", ")", "is", "None", ")", ":", "site_classes", "[", "n", "]", "[", "'branch types'", "]", "=", "{", "}", "if", "foreground", ":", "site_classes", "[", "n", "]", "[", "'branch types'", "]", "[", "'foreground'", "]", "=", "line_floats", "[", "n", "]", "else", ":", "site_classes", "[", "n", "]", "[", "'branch types'", "]", "[", "'background'", "]", "=", "line_floats", "[", "n", "]", "return", "site_classes" ]
parse results specific to the branch site a model .
train
false
41,598
@translations.command('update') @click.option('is_all', '--all', '-a', default=True, is_flag=True, help='Updates the plugin translations as well.') @click.option('--plugin', '-p', type=click.STRING, help='Updates the language of the given plugin.') def update_translation(is_all, plugin): if (plugin is not None): validate_plugin(plugin) click.secho('[+] Updating language files for plugin {}...'.format(plugin), fg='cyan') update_plugin_translations(plugin) else: click.secho('[+] Updating language files...', fg='cyan') update_translations(include_plugins=is_all)
[ "@", "translations", ".", "command", "(", "'update'", ")", "@", "click", ".", "option", "(", "'is_all'", ",", "'--all'", ",", "'-a'", ",", "default", "=", "True", ",", "is_flag", "=", "True", ",", "help", "=", "'Updates the plugin translations as well.'", ")", "@", "click", ".", "option", "(", "'--plugin'", ",", "'-p'", ",", "type", "=", "click", ".", "STRING", ",", "help", "=", "'Updates the language of the given plugin.'", ")", "def", "update_translation", "(", "is_all", ",", "plugin", ")", ":", "if", "(", "plugin", "is", "not", "None", ")", ":", "validate_plugin", "(", "plugin", ")", "click", ".", "secho", "(", "'[+] Updating language files for plugin {}...'", ".", "format", "(", "plugin", ")", ",", "fg", "=", "'cyan'", ")", "update_plugin_translations", "(", "plugin", ")", "else", ":", "click", ".", "secho", "(", "'[+] Updating language files...'", ",", "fg", "=", "'cyan'", ")", "update_translations", "(", "include_plugins", "=", "is_all", ")" ]
updates all translations .
train
false
41,599
def aggregate_tests(registry, xml_parent, data): agg = XML.SubElement(xml_parent, 'hudson.tasks.test.AggregatedTestResultPublisher') XML.SubElement(agg, 'includeFailedBuilds').text = str(data.get('include-failed-builds', False)).lower()
[ "def", "aggregate_tests", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "agg", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.tasks.test.AggregatedTestResultPublisher'", ")", "XML", ".", "SubElement", "(", "agg", ",", "'includeFailedBuilds'", ")", ".", "text", "=", "str", "(", "data", ".", "get", "(", "'include-failed-builds'", ",", "False", ")", ")", ".", "lower", "(", ")" ]
yaml: aggregate-tests aggregate downstream test results :arg bool include-failed-builds: whether to include failed builds example: .
train
false
41,600
def get_device_mac(device_name, namespace=None): return IPDevice(device_name, namespace=namespace).link.address
[ "def", "get_device_mac", "(", "device_name", ",", "namespace", "=", "None", ")", ":", "return", "IPDevice", "(", "device_name", ",", "namespace", "=", "namespace", ")", ".", "link", ".", "address" ]
return the mac address of the device .
train
false
41,603
@cli.command(name=u'serve') @click.option(u'-f', u'--config-file', type=click.File(u'rb'), help=config_help) @click.option(u'-a', u'--dev-addr', help=dev_addr_help, metavar=u'<IP:PORT>') @click.option(u'-s', u'--strict', is_flag=True, help=strict_help) @click.option(u'-t', u'--theme', type=click.Choice(theme_choices), help=theme_help) @click.option(u'-e', u'--theme-dir', type=click.Path(), help=theme_dir_help) @click.option(u'--livereload', u'livereload', flag_value=u'livereload', help=reload_help, default=True) @click.option(u'--no-livereload', u'livereload', flag_value=u'no-livereload', help=no_reload_help) @click.option(u'--dirtyreload', u'livereload', flag_value=u'dirty', help=dirty_reload_help) @common_options def serve_command(dev_addr, config_file, strict, theme, theme_dir, livereload): logging.getLogger(u'tornado').setLevel(logging.WARNING) strict = (strict or None) try: serve.serve(config_file=config_file, dev_addr=dev_addr, strict=strict, theme=theme, theme_dir=theme_dir, livereload=livereload) except (exceptions.ConfigurationError, socket.error) as e: raise SystemExit((u'\n' + str(e)))
[ "@", "cli", ".", "command", "(", "name", "=", "u'serve'", ")", "@", "click", ".", "option", "(", "u'-f'", ",", "u'--config-file'", ",", "type", "=", "click", ".", "File", "(", "u'rb'", ")", ",", "help", "=", "config_help", ")", "@", "click", ".", "option", "(", "u'-a'", ",", "u'--dev-addr'", ",", "help", "=", "dev_addr_help", ",", "metavar", "=", "u'<IP:PORT>'", ")", "@", "click", ".", "option", "(", "u'-s'", ",", "u'--strict'", ",", "is_flag", "=", "True", ",", "help", "=", "strict_help", ")", "@", "click", ".", "option", "(", "u'-t'", ",", "u'--theme'", ",", "type", "=", "click", ".", "Choice", "(", "theme_choices", ")", ",", "help", "=", "theme_help", ")", "@", "click", ".", "option", "(", "u'-e'", ",", "u'--theme-dir'", ",", "type", "=", "click", ".", "Path", "(", ")", ",", "help", "=", "theme_dir_help", ")", "@", "click", ".", "option", "(", "u'--livereload'", ",", "u'livereload'", ",", "flag_value", "=", "u'livereload'", ",", "help", "=", "reload_help", ",", "default", "=", "True", ")", "@", "click", ".", "option", "(", "u'--no-livereload'", ",", "u'livereload'", ",", "flag_value", "=", "u'no-livereload'", ",", "help", "=", "no_reload_help", ")", "@", "click", ".", "option", "(", "u'--dirtyreload'", ",", "u'livereload'", ",", "flag_value", "=", "u'dirty'", ",", "help", "=", "dirty_reload_help", ")", "@", "common_options", "def", "serve_command", "(", "dev_addr", ",", "config_file", ",", "strict", ",", "theme", ",", "theme_dir", ",", "livereload", ")", ":", "logging", ".", "getLogger", "(", "u'tornado'", ")", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "strict", "=", "(", "strict", "or", "None", ")", "try", ":", "serve", ".", "serve", "(", "config_file", "=", "config_file", ",", "dev_addr", "=", "dev_addr", ",", "strict", "=", "strict", ",", "theme", "=", "theme", ",", "theme_dir", "=", "theme_dir", ",", "livereload", "=", "livereload", ")", "except", "(", "exceptions", ".", "ConfigurationError", ",", "socket", ".", "error", ")", "as", "e", ":", "raise", "SystemExit", "(", "(", "u'\\n'", "+", "str", "(", "e", ")", ")", ")" ]
serve a single command .
train
false
41,605
def py_egg(name, srcs=[], deps=[], prebuilt=False, **kwargs): target = PythonEgg(name, srcs, deps, prebuilt, blade.blade, kwargs) blade.blade.register_target(target)
[ "def", "py_egg", "(", "name", ",", "srcs", "=", "[", "]", ",", "deps", "=", "[", "]", ",", "prebuilt", "=", "False", ",", "**", "kwargs", ")", ":", "target", "=", "PythonEgg", "(", "name", ",", "srcs", ",", "deps", ",", "prebuilt", ",", "blade", ".", "blade", ",", "kwargs", ")", "blade", ".", "blade", ".", "register_target", "(", "target", ")" ]
python egg .
train
false
41,606
def _threaded_method(method_name, sync_name, reactor_name, threadpool_name): def _run_in_thread(self, *args, **kwargs): reactor = getattr(self, reactor_name) sync = getattr(self, sync_name) threadpool = getattr(self, threadpool_name) original = getattr(sync, method_name) return deferToThreadPool(reactor, threadpool, preserve_context(original), *args, **kwargs) return _run_in_thread
[ "def", "_threaded_method", "(", "method_name", ",", "sync_name", ",", "reactor_name", ",", "threadpool_name", ")", ":", "def", "_run_in_thread", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "reactor", "=", "getattr", "(", "self", ",", "reactor_name", ")", "sync", "=", "getattr", "(", "self", ",", "sync_name", ")", "threadpool", "=", "getattr", "(", "self", ",", "threadpool_name", ")", "original", "=", "getattr", "(", "sync", ",", "method_name", ")", "return", "deferToThreadPool", "(", "reactor", ",", "threadpool", ",", "preserve_context", "(", "original", ")", ",", "*", "args", ",", "**", "kwargs", ")", "return", "_run_in_thread" ]
create a method that calls another method in a threadpool .
train
false
41,607
def data_to_lambda(data): return (lambda *args, **kwargs: copy.deepcopy(data))
[ "def", "data_to_lambda", "(", "data", ")", ":", "return", "(", "lambda", "*", "args", ",", "**", "kwargs", ":", "copy", ".", "deepcopy", "(", "data", ")", ")" ]
create a lambda function that takes arbitrary arguments and returns a deep copy of the passed data .
train
false
41,608
def is_matrix(iterable): if (is_iterable(iterable) and (len(iterable) > 0)): return all(imap((lambda x: (is_iterable(x) and (len(iterable[0]) == len(x)) and (len(x) > 0))), iterable)) else: return False
[ "def", "is_matrix", "(", "iterable", ")", ":", "if", "(", "is_iterable", "(", "iterable", ")", "and", "(", "len", "(", "iterable", ")", ">", "0", ")", ")", ":", "return", "all", "(", "imap", "(", "(", "lambda", "x", ":", "(", "is_iterable", "(", "x", ")", "and", "(", "len", "(", "iterable", "[", "0", "]", ")", "==", "len", "(", "x", ")", ")", "and", "(", "len", "(", "x", ")", ">", "0", ")", ")", ")", ",", "iterable", ")", ")", "else", ":", "return", "False" ]
returns true if iterable is a two dimensional iterable where each iterable is not empty .
train
false
41,609
def NotUnicode(string): if isinstance(string, unicode): string = string.encode('utf-8') if (not isinstance(string, str)): return str(string) return string
[ "def", "NotUnicode", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "string", "=", "string", ".", "encode", "(", "'utf-8'", ")", "if", "(", "not", "isinstance", "(", "string", ",", "str", ")", ")", ":", "return", "str", "(", "string", ")", "return", "string" ]
make sure a string is not unicode .
train
false
41,610
def hash_password(password): return hash_password_PBKDF2(password)
[ "def", "hash_password", "(", "password", ")", ":", "return", "hash_password_PBKDF2", "(", "password", ")" ]
hash a password .
train
false
41,613
def require_user_id_else_redirect_to_homepage(handler): def test_login(self, **kwargs): 'Checks if the user for the current session is logged in.\n\n If not, redirects the user to the home page.\n ' if (not self.user_id): self.redirect('/') return return handler(self, **kwargs) return test_login
[ "def", "require_user_id_else_redirect_to_homepage", "(", "handler", ")", ":", "def", "test_login", "(", "self", ",", "**", "kwargs", ")", ":", "if", "(", "not", "self", ".", "user_id", ")", ":", "self", ".", "redirect", "(", "'/'", ")", "return", "return", "handler", "(", "self", ",", "**", "kwargs", ")", "return", "test_login" ]
decorator that checks if a user_id is associated to the current session .
train
false
41,614
@pytest.mark.parametrize('str_prefix', ['u', '']) def test_pytest_fail_notrace_non_ascii(testdir, str_prefix): testdir.makepyfile((u"\n # coding: utf-8\n import pytest\n\n def test_hello():\n pytest.fail(%s'oh oh: \u263a', pytrace=False)\n " % str_prefix)) result = testdir.runpytest() if (sys.version_info[0] >= 3): result.stdout.fnmatch_lines(['*test_hello*', 'oh oh: \xe2\x98\xba']) else: result.stdout.fnmatch_lines(['*test_hello*', 'oh oh: *']) assert ('def test_hello' not in result.stdout.str())
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'str_prefix'", ",", "[", "'u'", ",", "''", "]", ")", "def", "test_pytest_fail_notrace_non_ascii", "(", "testdir", ",", "str_prefix", ")", ":", "testdir", ".", "makepyfile", "(", "(", "u\"\\n # coding: utf-8\\n import pytest\\n\\n def test_hello():\\n pytest.fail(%s'oh oh: \\u263a', pytrace=False)\\n \"", "%", "str_prefix", ")", ")", "result", "=", "testdir", ".", "runpytest", "(", ")", "if", "(", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ")", ":", "result", ".", "stdout", ".", "fnmatch_lines", "(", "[", "'*test_hello*'", ",", "'oh oh: \\xe2\\x98\\xba'", "]", ")", "else", ":", "result", ".", "stdout", ".", "fnmatch_lines", "(", "[", "'*test_hello*'", ",", "'oh oh: *'", "]", ")", "assert", "(", "'def test_hello'", "not", "in", "result", ".", "stdout", ".", "str", "(", ")", ")" ]
fix pytest .
train
false
41,615
def schema_exists(dbname, name, db_user=None, db_password=None, db_host=None, db_port=None): return bool(schema_get(dbname, name, db_user=db_user, db_host=db_host, db_port=db_port, db_password=db_password))
[ "def", "schema_exists", "(", "dbname", ",", "name", ",", "db_user", "=", "None", ",", "db_password", "=", "None", ",", "db_host", "=", "None", ",", "db_port", "=", "None", ")", ":", "return", "bool", "(", "schema_get", "(", "dbname", ",", "name", ",", "db_user", "=", "db_user", ",", "db_host", "=", "db_host", ",", "db_port", "=", "db_port", ",", "db_password", "=", "db_password", ")", ")" ]
checks if a schema exists on the postgres server .
train
true
41,616
def _dexp(c, e, p): p += 2 extra = max(0, ((e + len(str(c))) - 1)) q = (p + extra) shift = (e + q) if (shift >= 0): cshift = (c * (10 ** shift)) else: cshift = (c // (10 ** (- shift))) (quot, rem) = divmod(cshift, _log10_digits(q)) rem = _div_nearest(rem, (10 ** extra)) return (_div_nearest(_iexp(rem, (10 ** p)), 1000), ((quot - p) + 3))
[ "def", "_dexp", "(", "c", ",", "e", ",", "p", ")", ":", "p", "+=", "2", "extra", "=", "max", "(", "0", ",", "(", "(", "e", "+", "len", "(", "str", "(", "c", ")", ")", ")", "-", "1", ")", ")", "q", "=", "(", "p", "+", "extra", ")", "shift", "=", "(", "e", "+", "q", ")", "if", "(", "shift", ">=", "0", ")", ":", "cshift", "=", "(", "c", "*", "(", "10", "**", "shift", ")", ")", "else", ":", "cshift", "=", "(", "c", "//", "(", "10", "**", "(", "-", "shift", ")", ")", ")", "(", "quot", ",", "rem", ")", "=", "divmod", "(", "cshift", ",", "_log10_digits", "(", "q", ")", ")", "rem", "=", "_div_nearest", "(", "rem", ",", "(", "10", "**", "extra", ")", ")", "return", "(", "_div_nearest", "(", "_iexp", "(", "rem", ",", "(", "10", "**", "p", ")", ")", ",", "1000", ")", ",", "(", "(", "quot", "-", "p", ")", "+", "3", ")", ")" ]
compute an approximation to exp .
train
false
41,617
def check_requirements(): if ((sys.version_info < (3, 3)) and (sys.version_info[:2] != (2, 7))): raise SystemExit('PyInstaller requires at least Python 2.7 or 3.3+.') if is_win: try: from PyInstaller.utils.win32 import winutils pywintypes = winutils.import_pywin32_module('pywintypes') except ImportError: raise SystemExit('PyInstaller cannot check for assembly dependencies.\nPlease install PyWin32.\n\npip install pypiwin32\n')
[ "def", "check_requirements", "(", ")", ":", "if", "(", "(", "sys", ".", "version_info", "<", "(", "3", ",", "3", ")", ")", "and", "(", "sys", ".", "version_info", "[", ":", "2", "]", "!=", "(", "2", ",", "7", ")", ")", ")", ":", "raise", "SystemExit", "(", "'PyInstaller requires at least Python 2.7 or 3.3+.'", ")", "if", "is_win", ":", "try", ":", "from", "PyInstaller", ".", "utils", ".", "win32", "import", "winutils", "pywintypes", "=", "winutils", ".", "import_pywin32_module", "(", "'pywintypes'", ")", "except", "ImportError", ":", "raise", "SystemExit", "(", "'PyInstaller cannot check for assembly dependencies.\\nPlease install PyWin32.\\n\\npip install pypiwin32\\n'", ")" ]
verify that all requirements to run pyinstaller are met .
train
false
41,620
def findMultipartPostBoundary(post): retVal = None done = set() candidates = [] for match in re.finditer('(?m)^--(.+?)(--)?$', (post or '')): _ = match.group(1).strip().strip('-') if (_ in done): continue else: candidates.append((post.count(_), _)) done.add(_) if candidates: candidates.sort(key=(lambda _: _[0]), reverse=True) retVal = candidates[0][1] return retVal
[ "def", "findMultipartPostBoundary", "(", "post", ")", ":", "retVal", "=", "None", "done", "=", "set", "(", ")", "candidates", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "'(?m)^--(.+?)(--)?$'", ",", "(", "post", "or", "''", ")", ")", ":", "_", "=", "match", ".", "group", "(", "1", ")", ".", "strip", "(", ")", ".", "strip", "(", "'-'", ")", "if", "(", "_", "in", "done", ")", ":", "continue", "else", ":", "candidates", ".", "append", "(", "(", "post", ".", "count", "(", "_", ")", ",", "_", ")", ")", "done", ".", "add", "(", "_", ")", "if", "candidates", ":", "candidates", ".", "sort", "(", "key", "=", "(", "lambda", "_", ":", "_", "[", "0", "]", ")", ",", "reverse", "=", "True", ")", "retVal", "=", "candidates", "[", "0", "]", "[", "1", "]", "return", "retVal" ]
finds value for a boundary parameter in given multipart post body .
train
false
41,623
def check_cs_get(result, func, cargs): check_cs_op(result, func, cargs) return last_arg_byref(cargs)
[ "def", "check_cs_get", "(", "result", ",", "func", ",", "cargs", ")", ":", "check_cs_op", "(", "result", ",", "func", ",", "cargs", ")", "return", "last_arg_byref", "(", "cargs", ")" ]
checking the coordinate sequence retrieval .
train
false
41,624
def test_md5sum(): tempdir = _TempDir() fname1 = op.join(tempdir, 'foo') fname2 = op.join(tempdir, 'bar') with open(fname1, 'wb') as fid: fid.write('abcd') with open(fname2, 'wb') as fid: fid.write('efgh') assert_equal(md5sum(fname1), md5sum(fname1, 1)) assert_equal(md5sum(fname2), md5sum(fname2, 1024)) assert_true((md5sum(fname1) != md5sum(fname2)))
[ "def", "test_md5sum", "(", ")", ":", "tempdir", "=", "_TempDir", "(", ")", "fname1", "=", "op", ".", "join", "(", "tempdir", ",", "'foo'", ")", "fname2", "=", "op", ".", "join", "(", "tempdir", ",", "'bar'", ")", "with", "open", "(", "fname1", ",", "'wb'", ")", "as", "fid", ":", "fid", ".", "write", "(", "'abcd'", ")", "with", "open", "(", "fname2", ",", "'wb'", ")", "as", "fid", ":", "fid", ".", "write", "(", "'efgh'", ")", "assert_equal", "(", "md5sum", "(", "fname1", ")", ",", "md5sum", "(", "fname1", ",", "1", ")", ")", "assert_equal", "(", "md5sum", "(", "fname2", ")", ",", "md5sum", "(", "fname2", ",", "1024", ")", ")", "assert_true", "(", "(", "md5sum", "(", "fname1", ")", "!=", "md5sum", "(", "fname2", ")", ")", ")" ]
test md5sum calculation .
train
false
41,626
def get_nav_grading(fund_type='all', sub_type='all'): ct._write_head() nums = _get_fund_num((ct.SINA_NAV_COUNT_URL % (ct.P_TYPE['http'], ct.DOMAINS['vsf'], ct.NAV_GRADING_KEY, ct.NAV_GRADING_API, ct.NAV_GRADING_T2[fund_type], ct.NAV_GRADING_T3[sub_type]))) fund_df = _parse_fund_data((ct.SINA_NAV_DATA_URL % (ct.P_TYPE['http'], ct.DOMAINS['vsf'], ct.NAV_GRADING_KEY, ct.NAV_GRADING_API, nums, ct.NAV_GRADING_T2[fund_type], ct.NAV_GRADING_T3[sub_type])), 'grading') return fund_df
[ "def", "get_nav_grading", "(", "fund_type", "=", "'all'", ",", "sub_type", "=", "'all'", ")", ":", "ct", ".", "_write_head", "(", ")", "nums", "=", "_get_fund_num", "(", "(", "ct", ".", "SINA_NAV_COUNT_URL", "%", "(", "ct", ".", "P_TYPE", "[", "'http'", "]", ",", "ct", ".", "DOMAINS", "[", "'vsf'", "]", ",", "ct", ".", "NAV_GRADING_KEY", ",", "ct", ".", "NAV_GRADING_API", ",", "ct", ".", "NAV_GRADING_T2", "[", "fund_type", "]", ",", "ct", ".", "NAV_GRADING_T3", "[", "sub_type", "]", ")", ")", ")", "fund_df", "=", "_parse_fund_data", "(", "(", "ct", ".", "SINA_NAV_DATA_URL", "%", "(", "ct", ".", "P_TYPE", "[", "'http'", "]", ",", "ct", ".", "DOMAINS", "[", "'vsf'", "]", ",", "ct", ".", "NAV_GRADING_KEY", ",", "ct", ".", "NAV_GRADING_API", ",", "nums", ",", "ct", ".", "NAV_GRADING_T2", "[", "fund_type", "]", ",", "ct", ".", "NAV_GRADING_T3", "[", "sub_type", "]", ")", ")", ",", "'grading'", ")", "return", "fund_df" ]
parameters type:string 1 .
train
false
41,628
@constructor def var(input, axis=None, ddof=0, keepdims=False, corrected=False): if isinstance(ddof, bool): raise ValueError('Parameter keepdims is now at index 3: (input, axis=None, ddof=0, keepdims=False, corrected=False)') input_ndim = input.type.ndim if (axis is None): axis = list(range(input_ndim)) elif isinstance(axis, (integer_types, numpy.integer)): axis = [axis] elif (isinstance(axis, numpy.ndarray) and (axis.ndim == 0)): axis = [int(axis)] else: axis = [int(a) for a in axis] mean_input = mean(input, axis, keepdims=True) centered_input = (input - mean_input) two = constant(2, dtype=centered_input.dtype) if (ddof == 0): v = mean((centered_input ** two), axis, keepdims=keepdims) else: shp = (shape(input) - ddof) v = sum((centered_input ** two), axis=axis, keepdims=keepdims) for i in axis: v = true_div(v, shp[i]) if corrected: if (ddof == 0): error = (mean(centered_input, axis, keepdims=keepdims) ** 2) else: shp = (shape(input) - ddof) shp_inp = shape(input) error = (sum(centered_input, axis=axis, keepdims=keepdims) ** 2) for i in axis: error = true_div(error, (shp[i] * shp_inp[i])) v = (v - error) v.name = 'var' return v
[ "@", "constructor", "def", "var", "(", "input", ",", "axis", "=", "None", ",", "ddof", "=", "0", ",", "keepdims", "=", "False", ",", "corrected", "=", "False", ")", ":", "if", "isinstance", "(", "ddof", ",", "bool", ")", ":", "raise", "ValueError", "(", "'Parameter keepdims is now at index 3: (input, axis=None, ddof=0, keepdims=False, corrected=False)'", ")", "input_ndim", "=", "input", ".", "type", ".", "ndim", "if", "(", "axis", "is", "None", ")", ":", "axis", "=", "list", "(", "range", "(", "input_ndim", ")", ")", "elif", "isinstance", "(", "axis", ",", "(", "integer_types", ",", "numpy", ".", "integer", ")", ")", ":", "axis", "=", "[", "axis", "]", "elif", "(", "isinstance", "(", "axis", ",", "numpy", ".", "ndarray", ")", "and", "(", "axis", ".", "ndim", "==", "0", ")", ")", ":", "axis", "=", "[", "int", "(", "axis", ")", "]", "else", ":", "axis", "=", "[", "int", "(", "a", ")", "for", "a", "in", "axis", "]", "mean_input", "=", "mean", "(", "input", ",", "axis", ",", "keepdims", "=", "True", ")", "centered_input", "=", "(", "input", "-", "mean_input", ")", "two", "=", "constant", "(", "2", ",", "dtype", "=", "centered_input", ".", "dtype", ")", "if", "(", "ddof", "==", "0", ")", ":", "v", "=", "mean", "(", "(", "centered_input", "**", "two", ")", ",", "axis", ",", "keepdims", "=", "keepdims", ")", "else", ":", "shp", "=", "(", "shape", "(", "input", ")", "-", "ddof", ")", "v", "=", "sum", "(", "(", "centered_input", "**", "two", ")", ",", "axis", "=", "axis", ",", "keepdims", "=", "keepdims", ")", "for", "i", "in", "axis", ":", "v", "=", "true_div", "(", "v", ",", "shp", "[", "i", "]", ")", "if", "corrected", ":", "if", "(", "ddof", "==", "0", ")", ":", "error", "=", "(", "mean", "(", "centered_input", ",", "axis", ",", "keepdims", "=", "keepdims", ")", "**", "2", ")", "else", ":", "shp", "=", "(", "shape", "(", "input", ")", "-", "ddof", ")", "shp_inp", "=", "shape", "(", "input", ")", "error", "=", "(", "sum", "(", "centered_input", ",", "axis", "=", "axis", ",", "keepdims", "=", "keepdims", ")", "**", "2", ")", "for", "i", "in", "axis", ":", "error", "=", "true_div", "(", "error", ",", "(", "shp", "[", "i", "]", "*", "shp_inp", "[", "i", "]", ")", ")", "v", "=", "(", "v", "-", "error", ")", "v", ".", "name", "=", "'var'", "return", "v" ]
variance of a tensor .
train
false
41,629
def _set_dev_port(port, backend, instance=None, env=os.environ): env[_get_dev_port_var(backend, instance)] = str(port)
[ "def", "_set_dev_port", "(", "port", ",", "backend", ",", "instance", "=", "None", ",", "env", "=", "os", ".", "environ", ")", ":", "env", "[", "_get_dev_port_var", "(", "backend", ",", "instance", ")", "]", "=", "str", "(", "port", ")" ]
sets the port for a backend [instance] in the dev_appserver .
train
false
41,630
def p_number_signed(p): p[0] = eval(('-' + p[2]))
[ "def", "p_number_signed", "(", "p", ")", ":", "p", "[", "0", "]", "=", "eval", "(", "(", "'-'", "+", "p", "[", "2", "]", ")", ")" ]
number : minus integer | minus float .
train
false
41,631
def _get_join_indexers(left_keys, right_keys, sort=False, how='inner', **kwargs): from functools import partial assert (len(left_keys) == len(right_keys)), 'left_key and right_keys must be the same length' fkeys = partial(_factorize_keys, sort=sort) (llab, rlab, shape) = map(list, zip(*map(fkeys, left_keys, right_keys))) (lkey, rkey) = _get_join_keys(llab, rlab, shape, sort) (lkey, rkey, count) = fkeys(lkey, rkey) kwargs = copy.copy(kwargs) if (how == 'left'): kwargs['sort'] = sort join_func = _join_functions[how] return join_func(lkey, rkey, count, **kwargs)
[ "def", "_get_join_indexers", "(", "left_keys", ",", "right_keys", ",", "sort", "=", "False", ",", "how", "=", "'inner'", ",", "**", "kwargs", ")", ":", "from", "functools", "import", "partial", "assert", "(", "len", "(", "left_keys", ")", "==", "len", "(", "right_keys", ")", ")", ",", "'left_key and right_keys must be the same length'", "fkeys", "=", "partial", "(", "_factorize_keys", ",", "sort", "=", "sort", ")", "(", "llab", ",", "rlab", ",", "shape", ")", "=", "map", "(", "list", ",", "zip", "(", "*", "map", "(", "fkeys", ",", "left_keys", ",", "right_keys", ")", ")", ")", "(", "lkey", ",", "rkey", ")", "=", "_get_join_keys", "(", "llab", ",", "rlab", ",", "shape", ",", "sort", ")", "(", "lkey", ",", "rkey", ",", "count", ")", "=", "fkeys", "(", "lkey", ",", "rkey", ")", "kwargs", "=", "copy", ".", "copy", "(", "kwargs", ")", "if", "(", "how", "==", "'left'", ")", ":", "kwargs", "[", "'sort'", "]", "=", "sort", "join_func", "=", "_join_functions", "[", "how", "]", "return", "join_func", "(", "lkey", ",", "rkey", ",", "count", ",", "**", "kwargs", ")" ]
parameters returns .
train
true
41,632
def _has_dctrl_tools(): try: return __context__['pkg._has_dctrl_tools'] except KeyError: __context__['pkg._has_dctrl_tools'] = __salt__['cmd.has_exec']('grep-available') return __context__['pkg._has_dctrl_tools']
[ "def", "_has_dctrl_tools", "(", ")", ":", "try", ":", "return", "__context__", "[", "'pkg._has_dctrl_tools'", "]", "except", "KeyError", ":", "__context__", "[", "'pkg._has_dctrl_tools'", "]", "=", "__salt__", "[", "'cmd.has_exec'", "]", "(", "'grep-available'", ")", "return", "__context__", "[", "'pkg._has_dctrl_tools'", "]" ]
return a boolean depending on whether or not dctrl-tools was installed .
train
false
41,633
def dict_to_xml_schema(data): for (key, value) in data.items(): root = _add_element_attrs(ET.Element(key), value.get('attrs', {})) children = value.get('children', None) if isinstance(children, dict): _add_sub_elements_from_dict(root, children) return root
[ "def", "dict_to_xml_schema", "(", "data", ")", ":", "for", "(", "key", ",", "value", ")", "in", "data", ".", "items", "(", ")", ":", "root", "=", "_add_element_attrs", "(", "ET", ".", "Element", "(", "key", ")", ",", "value", ".", "get", "(", "'attrs'", ",", "{", "}", ")", ")", "children", "=", "value", ".", "get", "(", "'children'", ",", "None", ")", "if", "isinstance", "(", "children", ",", "dict", ")", ":", "_add_sub_elements_from_dict", "(", "root", ",", "children", ")", "return", "root" ]
input a dictionary to be converted to xml .
train
false
41,636
@pytest.mark.network def test_uninstall_easy_install_after_import(script): result = script.run('easy_install', 'INITools==0.2', expect_stderr=True) script.run('python', '-c', 'import initools') result2 = script.pip('uninstall', 'INITools', '-y') assert_all_changes(result, result2, [(script.venv / 'build'), 'cache', (script.site_packages / 'easy-install.pth')])
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_uninstall_easy_install_after_import", "(", "script", ")", ":", "result", "=", "script", ".", "run", "(", "'easy_install'", ",", "'INITools==0.2'", ",", "expect_stderr", "=", "True", ")", "script", ".", "run", "(", "'python'", ",", "'-c'", ",", "'import initools'", ")", "result2", "=", "script", ".", "pip", "(", "'uninstall'", ",", "'INITools'", ",", "'-y'", ")", "assert_all_changes", "(", "result", ",", "result2", ",", "[", "(", "script", ".", "venv", "/", "'build'", ")", ",", "'cache'", ",", "(", "script", ".", "site_packages", "/", "'easy-install.pth'", ")", "]", ")" ]
uninstall an easy_installed package after its been imported .
train
false
41,637
def _dict_from_expr_if_gens(expr, opt): ((poly,), gens) = _parallel_dict_from_expr_if_gens((expr,), opt) return (poly, gens)
[ "def", "_dict_from_expr_if_gens", "(", "expr", ",", "opt", ")", ":", "(", "(", "poly", ",", ")", ",", "gens", ")", "=", "_parallel_dict_from_expr_if_gens", "(", "(", "expr", ",", ")", ",", "opt", ")", "return", "(", "poly", ",", "gens", ")" ]
transform an expression into a multinomial form given generators .
train
false
41,638
def dumpGpsTracker(): global TRACES return TRACES
[ "def", "dumpGpsTracker", "(", ")", ":", "global", "TRACES", "return", "TRACES" ]
when inmeory is enabled .
train
false
41,640
def format_dt(dt): value = dt.strftime('%a, %d %b %Y %H:%M:%S %Z') return value
[ "def", "format_dt", "(", "dt", ")", ":", "value", "=", "dt", ".", "strftime", "(", "'%a, %d %b %Y %H:%M:%S %Z'", ")", "return", "value" ]
format datetime object for human friendly representation .
train
false
41,642
def _color(color, msg): return ((_proc((MAGIC + color)) + msg) + _proc((MAGIC + 'reset')).lower())
[ "def", "_color", "(", "color", ",", "msg", ")", ":", "return", "(", "(", "_proc", "(", "(", "MAGIC", "+", "color", ")", ")", "+", "msg", ")", "+", "_proc", "(", "(", "MAGIC", "+", "'reset'", ")", ")", ".", "lower", "(", ")", ")" ]
colorizes the given text .
train
false
41,644
def const_factory(value): assert (not isinstance(value, NodeNG)) try: return CONST_CLS[value.__class__](value) except (KeyError, AttributeError): node = EmptyNode() node.object = value return node
[ "def", "const_factory", "(", "value", ")", ":", "assert", "(", "not", "isinstance", "(", "value", ",", "NodeNG", ")", ")", "try", ":", "return", "CONST_CLS", "[", "value", ".", "__class__", "]", "(", "value", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "node", "=", "EmptyNode", "(", ")", "node", ".", "object", "=", "value", "return", "node" ]
return an astroid node for a python value .
train
false
41,646
def dup_sqr(f, K): (df, h) = ((len(f) - 1), []) for i in range(0, ((2 * df) + 1)): c = K.zero jmin = max(0, (i - df)) jmax = min(i, df) n = ((jmax - jmin) + 1) jmax = ((jmin + (n // 2)) - 1) for j in range(jmin, (jmax + 1)): c += (f[j] * f[(i - j)]) c += c if (n & 1): elem = f[(jmax + 1)] c += (elem ** 2) h.append(c) return dup_strip(h)
[ "def", "dup_sqr", "(", "f", ",", "K", ")", ":", "(", "df", ",", "h", ")", "=", "(", "(", "len", "(", "f", ")", "-", "1", ")", ",", "[", "]", ")", "for", "i", "in", "range", "(", "0", ",", "(", "(", "2", "*", "df", ")", "+", "1", ")", ")", ":", "c", "=", "K", ".", "zero", "jmin", "=", "max", "(", "0", ",", "(", "i", "-", "df", ")", ")", "jmax", "=", "min", "(", "i", ",", "df", ")", "n", "=", "(", "(", "jmax", "-", "jmin", ")", "+", "1", ")", "jmax", "=", "(", "(", "jmin", "+", "(", "n", "//", "2", ")", ")", "-", "1", ")", "for", "j", "in", "range", "(", "jmin", ",", "(", "jmax", "+", "1", ")", ")", ":", "c", "+=", "(", "f", "[", "j", "]", "*", "f", "[", "(", "i", "-", "j", ")", "]", ")", "c", "+=", "c", "if", "(", "n", "&", "1", ")", ":", "elem", "=", "f", "[", "(", "jmax", "+", "1", ")", "]", "c", "+=", "(", "elem", "**", "2", ")", "h", ".", "append", "(", "c", ")", "return", "dup_strip", "(", "h", ")" ]
square dense polynomials in k[x] .
train
false
41,647
def qurl_from_user_input(urlstr): match = re.match('\\[?([0-9a-fA-F:.]+)\\]?(.*)', urlstr.strip()) if match: (ipstr, rest) = match.groups() else: ipstr = urlstr.strip() rest = '' try: ipaddress.IPv6Address(ipstr) except ipaddress.AddressValueError: return QUrl.fromUserInput(urlstr) else: return QUrl('http://[{}]{}'.format(ipstr, rest))
[ "def", "qurl_from_user_input", "(", "urlstr", ")", ":", "match", "=", "re", ".", "match", "(", "'\\\\[?([0-9a-fA-F:.]+)\\\\]?(.*)'", ",", "urlstr", ".", "strip", "(", ")", ")", "if", "match", ":", "(", "ipstr", ",", "rest", ")", "=", "match", ".", "groups", "(", ")", "else", ":", "ipstr", "=", "urlstr", ".", "strip", "(", ")", "rest", "=", "''", "try", ":", "ipaddress", ".", "IPv6Address", "(", "ipstr", ")", "except", "ipaddress", ".", "AddressValueError", ":", "return", "QUrl", ".", "fromUserInput", "(", "urlstr", ")", "else", ":", "return", "QUrl", "(", "'http://[{}]{}'", ".", "format", "(", "ipstr", ",", "rest", ")", ")" ]
get a qurl based on a user input .
train
false
41,649
def get_ordered_locations(locations, **kwargs): return locations
[ "def", "get_ordered_locations", "(", "locations", ",", "**", "kwargs", ")", ":", "return", "locations" ]
order image location list .
train
false
41,650
def test_indexing_on_class(): g = Gaussian1D(1, 2, 3, name=u'g') p = Polynomial1D(2, name=u'p') M = (Gaussian1D + Const1D) assert (M[0] is Gaussian1D) assert (M[1] is Const1D) assert (M[u'Gaussian1D'] is M[0]) assert (M[u'Const1D'] is M[1]) M = (Gaussian1D + p) assert (M[0] is Gaussian1D) assert (M[1] is p) assert (M[u'Gaussian1D'] is M[0]) assert (M[u'p'] is M[1]) m = (g + p) assert isinstance(m[0], Gaussian1D) assert isinstance(m[1], Polynomial1D) assert isinstance(m[u'g'], Gaussian1D) assert isinstance(m[u'p'], Polynomial1D) assert isinstance(m[(-1)], Polynomial1D) assert isinstance(m[(-2)], Gaussian1D) with pytest.raises(IndexError): m[42] with pytest.raises(IndexError): m[u'foobar']
[ "def", "test_indexing_on_class", "(", ")", ":", "g", "=", "Gaussian1D", "(", "1", ",", "2", ",", "3", ",", "name", "=", "u'g'", ")", "p", "=", "Polynomial1D", "(", "2", ",", "name", "=", "u'p'", ")", "M", "=", "(", "Gaussian1D", "+", "Const1D", ")", "assert", "(", "M", "[", "0", "]", "is", "Gaussian1D", ")", "assert", "(", "M", "[", "1", "]", "is", "Const1D", ")", "assert", "(", "M", "[", "u'Gaussian1D'", "]", "is", "M", "[", "0", "]", ")", "assert", "(", "M", "[", "u'Const1D'", "]", "is", "M", "[", "1", "]", ")", "M", "=", "(", "Gaussian1D", "+", "p", ")", "assert", "(", "M", "[", "0", "]", "is", "Gaussian1D", ")", "assert", "(", "M", "[", "1", "]", "is", "p", ")", "assert", "(", "M", "[", "u'Gaussian1D'", "]", "is", "M", "[", "0", "]", ")", "assert", "(", "M", "[", "u'p'", "]", "is", "M", "[", "1", "]", ")", "m", "=", "(", "g", "+", "p", ")", "assert", "isinstance", "(", "m", "[", "0", "]", ",", "Gaussian1D", ")", "assert", "isinstance", "(", "m", "[", "1", "]", ",", "Polynomial1D", ")", "assert", "isinstance", "(", "m", "[", "u'g'", "]", ",", "Gaussian1D", ")", "assert", "isinstance", "(", "m", "[", "u'p'", "]", ",", "Polynomial1D", ")", "assert", "isinstance", "(", "m", "[", "(", "-", "1", ")", "]", ",", "Polynomial1D", ")", "assert", "isinstance", "(", "m", "[", "(", "-", "2", ")", "]", ",", "Gaussian1D", ")", "with", "pytest", ".", "raises", "(", "IndexError", ")", ":", "m", "[", "42", "]", "with", "pytest", ".", "raises", "(", "IndexError", ")", ":", "m", "[", "u'foobar'", "]" ]
test indexing on compound model class objects .
train
false
41,651
def ismethod(object): return isinstance(object, types.MethodType)
[ "def", "ismethod", "(", "object", ")", ":", "return", "isinstance", "(", "object", ",", "types", ".", "MethodType", ")" ]
return true if the object is an instance method .
train
false
41,652
def describe_file(module): from . import remote descriptor = FileDescriptor() descriptor.package = util.get_package_for_module(module) if (not descriptor.package): descriptor.package = None message_descriptors = [] enum_descriptors = [] service_descriptors = [] for name in sorted(dir(module)): value = getattr(module, name) if isinstance(value, type): if issubclass(value, messages.Message): message_descriptors.append(describe_message(value)) elif issubclass(value, messages.Enum): enum_descriptors.append(describe_enum(value)) elif issubclass(value, remote.Service): service_descriptors.append(describe_service(value)) if message_descriptors: descriptor.message_types = message_descriptors if enum_descriptors: descriptor.enum_types = enum_descriptors if service_descriptors: descriptor.service_types = service_descriptors return descriptor
[ "def", "describe_file", "(", "module", ")", ":", "from", ".", "import", "remote", "descriptor", "=", "FileDescriptor", "(", ")", "descriptor", ".", "package", "=", "util", ".", "get_package_for_module", "(", "module", ")", "if", "(", "not", "descriptor", ".", "package", ")", ":", "descriptor", ".", "package", "=", "None", "message_descriptors", "=", "[", "]", "enum_descriptors", "=", "[", "]", "service_descriptors", "=", "[", "]", "for", "name", "in", "sorted", "(", "dir", "(", "module", ")", ")", ":", "value", "=", "getattr", "(", "module", ",", "name", ")", "if", "isinstance", "(", "value", ",", "type", ")", ":", "if", "issubclass", "(", "value", ",", "messages", ".", "Message", ")", ":", "message_descriptors", ".", "append", "(", "describe_message", "(", "value", ")", ")", "elif", "issubclass", "(", "value", ",", "messages", ".", "Enum", ")", ":", "enum_descriptors", ".", "append", "(", "describe_enum", "(", "value", ")", ")", "elif", "issubclass", "(", "value", ",", "remote", ".", "Service", ")", ":", "service_descriptors", ".", "append", "(", "describe_service", "(", "value", ")", ")", "if", "message_descriptors", ":", "descriptor", ".", "message_types", "=", "message_descriptors", "if", "enum_descriptors", ":", "descriptor", ".", "enum_types", "=", "enum_descriptors", "if", "service_descriptors", ":", "descriptor", ".", "service_types", "=", "service_descriptors", "return", "descriptor" ]
build a file from a specified python module .
train
true
41,653
def execute_get_output(*command): devnull = open(os.devnull, 'w') command = map(str, command) proc = subprocess.Popen(command, close_fds=True, stdout=subprocess.PIPE, stderr=devnull) devnull.close() return proc.stdout.read().strip()
[ "def", "execute_get_output", "(", "*", "command", ")", ":", "devnull", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "command", "=", "map", "(", "str", ",", "command", ")", "proc", "=", "subprocess", ".", "Popen", "(", "command", ",", "close_fds", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "devnull", ")", "devnull", ".", "close", "(", ")", "return", "proc", ".", "stdout", ".", "read", "(", ")", ".", "strip", "(", ")" ]
execute and return stdout .
train
false
41,654
def get_query_for_ids(modelquery, model, ids): if has_multiple_pks(model): decoded_ids = [iterdecode(v) for v in ids] model_pk = [getattr(model, name) for name in get_primary_key(model)] try: query = modelquery.filter(tuple_(*model_pk).in_(decoded_ids)) query.all() except DBAPIError: query = modelquery.filter(tuple_operator_in(model_pk, decoded_ids)) else: model_pk = getattr(model, get_primary_key(model)) query = modelquery.filter(model_pk.in_(ids)) return query
[ "def", "get_query_for_ids", "(", "modelquery", ",", "model", ",", "ids", ")", ":", "if", "has_multiple_pks", "(", "model", ")", ":", "decoded_ids", "=", "[", "iterdecode", "(", "v", ")", "for", "v", "in", "ids", "]", "model_pk", "=", "[", "getattr", "(", "model", ",", "name", ")", "for", "name", "in", "get_primary_key", "(", "model", ")", "]", "try", ":", "query", "=", "modelquery", ".", "filter", "(", "tuple_", "(", "*", "model_pk", ")", ".", "in_", "(", "decoded_ids", ")", ")", "query", ".", "all", "(", ")", "except", "DBAPIError", ":", "query", "=", "modelquery", ".", "filter", "(", "tuple_operator_in", "(", "model_pk", ",", "decoded_ids", ")", ")", "else", ":", "model_pk", "=", "getattr", "(", "model", ",", "get_primary_key", "(", "model", ")", ")", "query", "=", "modelquery", ".", "filter", "(", "model_pk", ".", "in_", "(", "ids", ")", ")", "return", "query" ]
return a query object filtered by primary key values passed in ids argument .
train
false
41,655
def qualifying_prefix(modname, qualname): return ('{}.{}'.format(modname, qualname) if modname else qualname)
[ "def", "qualifying_prefix", "(", "modname", ",", "qualname", ")", ":", "return", "(", "'{}.{}'", ".", "format", "(", "modname", ",", "qualname", ")", "if", "modname", "else", "qualname", ")" ]
returns a new string that is used for the first half of the mangled name .
train
false
41,656
@require_POST @login_required @permitted def create_sub_comment(request, course_id, comment_id): if is_comment_too_deep(parent=cc.Comment(comment_id)): return JsonError(_('Comment level too deep')) return _create_comment(request, CourseKey.from_string(course_id), parent_id=comment_id)
[ "@", "require_POST", "@", "login_required", "@", "permitted", "def", "create_sub_comment", "(", "request", ",", "course_id", ",", "comment_id", ")", ":", "if", "is_comment_too_deep", "(", "parent", "=", "cc", ".", "Comment", "(", "comment_id", ")", ")", ":", "return", "JsonError", "(", "_", "(", "'Comment level too deep'", ")", ")", "return", "_create_comment", "(", "request", ",", "CourseKey", ".", "from_string", "(", "course_id", ")", ",", "parent_id", "=", "comment_id", ")" ]
given a course_id and comment_id .
train
false
41,658
def getPointMaximum(firstPoint, secondPoint): return Vector3(max(firstPoint.x, secondPoint.x), max(firstPoint.y, secondPoint.y), max(firstPoint.z, secondPoint.z))
[ "def", "getPointMaximum", "(", "firstPoint", ",", "secondPoint", ")", ":", "return", "Vector3", "(", "max", "(", "firstPoint", ".", "x", ",", "secondPoint", ".", "x", ")", ",", "max", "(", "firstPoint", ".", "y", ",", "secondPoint", ".", "y", ")", ",", "max", "(", "firstPoint", ".", "z", ",", "secondPoint", ".", "z", ")", ")" ]
get a point with each component the maximum of the respective components of a pair of vector3s .
train
false
41,660
def assemble_option_dict(option_list, options_spec): options = {} for (name, value) in option_list: convertor = options_spec[name] if (convertor is None): raise KeyError(name) if (name in options): raise DuplicateOptionError(('duplicate option "%s"' % name)) try: options[name] = convertor(value) except (ValueError, TypeError) as detail: raise detail.__class__(('(option: "%s"; value: %r)\n%s' % (name, value, ' '.join(detail.args)))) return options
[ "def", "assemble_option_dict", "(", "option_list", ",", "options_spec", ")", ":", "options", "=", "{", "}", "for", "(", "name", ",", "value", ")", "in", "option_list", ":", "convertor", "=", "options_spec", "[", "name", "]", "if", "(", "convertor", "is", "None", ")", ":", "raise", "KeyError", "(", "name", ")", "if", "(", "name", "in", "options", ")", ":", "raise", "DuplicateOptionError", "(", "(", "'duplicate option \"%s\"'", "%", "name", ")", ")", "try", ":", "options", "[", "name", "]", "=", "convertor", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "detail", ":", "raise", "detail", ".", "__class__", "(", "(", "'(option: \"%s\"; value: %r)\\n%s'", "%", "(", "name", ",", "value", ",", "' '", ".", "join", "(", "detail", ".", "args", ")", ")", ")", ")", "return", "options" ]
return a mapping of option names to values .
train
false
41,661
def getSegmentFromPoints(begin, end): endpointFirst = Endpoint() endpointSecond = Endpoint().getFromOtherPoint(endpointFirst, end) endpointFirst.getFromOtherPoint(endpointSecond, begin) return (endpointFirst, endpointSecond)
[ "def", "getSegmentFromPoints", "(", "begin", ",", "end", ")", ":", "endpointFirst", "=", "Endpoint", "(", ")", "endpointSecond", "=", "Endpoint", "(", ")", ".", "getFromOtherPoint", "(", "endpointFirst", ",", "end", ")", "endpointFirst", ".", "getFromOtherPoint", "(", "endpointSecond", ",", "begin", ")", "return", "(", "endpointFirst", ",", "endpointSecond", ")" ]
get endpoint segment from a pair of points .
train
false
41,662
def usingCurl(): return isinstance(getDefaultFetcher(), CurlHTTPFetcher)
[ "def", "usingCurl", "(", ")", ":", "return", "isinstance", "(", "getDefaultFetcher", "(", ")", ",", "CurlHTTPFetcher", ")" ]
whether the currently set http fetcher is a curl http fetcher .
train
false
41,663
def test_subtract_evoked(): (raw, events, picks) = _get_data() epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks) assert_raises(ValueError, epochs.subtract_evoked, epochs.average(picks[:5])) epochs.subtract_evoked() epochs.apply_proj() epochs2 = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, preload=True) evoked = epochs2.average() epochs2.subtract_evoked(evoked) assert_allclose(epochs.get_data(), epochs2.get_data()) zero_evoked = epochs.average() data = zero_evoked.data assert_allclose(data, np.zeros_like(data), atol=1e-15)
[ "def", "test_subtract_evoked", "(", ")", ":", "(", "raw", ",", "events", ",", "picks", ")", "=", "_get_data", "(", ")", "epochs", "=", "Epochs", "(", "raw", ",", "events", "[", ":", "10", "]", ",", "event_id", ",", "tmin", ",", "tmax", ",", "picks", "=", "picks", ")", "assert_raises", "(", "ValueError", ",", "epochs", ".", "subtract_evoked", ",", "epochs", ".", "average", "(", "picks", "[", ":", "5", "]", ")", ")", "epochs", ".", "subtract_evoked", "(", ")", "epochs", ".", "apply_proj", "(", ")", "epochs2", "=", "Epochs", "(", "raw", ",", "events", "[", ":", "10", "]", ",", "event_id", ",", "tmin", ",", "tmax", ",", "picks", "=", "picks", ",", "preload", "=", "True", ")", "evoked", "=", "epochs2", ".", "average", "(", ")", "epochs2", ".", "subtract_evoked", "(", "evoked", ")", "assert_allclose", "(", "epochs", ".", "get_data", "(", ")", ",", "epochs2", ".", "get_data", "(", ")", ")", "zero_evoked", "=", "epochs", ".", "average", "(", ")", "data", "=", "zero_evoked", ".", "data", "assert_allclose", "(", "data", ",", "np", ".", "zeros_like", "(", "data", ")", ",", "atol", "=", "1e-15", ")" ]
test subtraction of evoked from epochs .
train
false
41,664
def copy_files_from(address, client, username, password, port, remote_path, local_path, limit='', log_filename=None, verbose=False, timeout=600, interface=None): if (client == 'scp'): scp_from_remote(address, port, username, password, remote_path, local_path, limit, log_filename, timeout, interface=interface) elif (client == 'rss'): log_func = None if verbose: log_func = logging.debug c = rss_client.FileDownloadClient(address, port, log_func) c.download(remote_path, local_path, timeout) c.close()
[ "def", "copy_files_from", "(", "address", ",", "client", ",", "username", ",", "password", ",", "port", ",", "remote_path", ",", "local_path", ",", "limit", "=", "''", ",", "log_filename", "=", "None", ",", "verbose", "=", "False", ",", "timeout", "=", "600", ",", "interface", "=", "None", ")", ":", "if", "(", "client", "==", "'scp'", ")", ":", "scp_from_remote", "(", "address", ",", "port", ",", "username", ",", "password", ",", "remote_path", ",", "local_path", ",", "limit", ",", "log_filename", ",", "timeout", ",", "interface", "=", "interface", ")", "elif", "(", "client", "==", "'rss'", ")", ":", "log_func", "=", "None", "if", "verbose", ":", "log_func", "=", "logging", ".", "debug", "c", "=", "rss_client", ".", "FileDownloadClient", "(", "address", ",", "port", ",", "log_func", ")", "c", ".", "download", "(", "remote_path", ",", "local_path", ",", "timeout", ")", "c", ".", "close", "(", ")" ]
copy files from a remote host using the selected client .
train
false
41,665
def find_plugins(): load_plugins() plugins = [] for cls in _classes: if (cls not in _instances): _instances[cls] = cls() plugins.append(_instances[cls]) return plugins
[ "def", "find_plugins", "(", ")", ":", "load_plugins", "(", ")", "plugins", "=", "[", "]", "for", "cls", "in", "_classes", ":", "if", "(", "cls", "not", "in", "_instances", ")", ":", "_instances", "[", "cls", "]", "=", "cls", "(", ")", "plugins", ".", "append", "(", "_instances", "[", "cls", "]", ")", "return", "plugins" ]
returns a list of beetsplugin subclass instances from all currently loaded beets plugins .
train
false
41,666
def get_valuation_rate(): item_val_rate_map = {} for d in frappe.db.sql(u'select item_code,\n DCTB DCTB sum(actual_qty*valuation_rate)/sum(actual_qty) as val_rate\n DCTB DCTB from tabBin where actual_qty > 0 group by item_code', as_dict=1): item_val_rate_map.setdefault(d.item_code, d.val_rate) return item_val_rate_map
[ "def", "get_valuation_rate", "(", ")", ":", "item_val_rate_map", "=", "{", "}", "for", "d", "in", "frappe", ".", "db", ".", "sql", "(", "u'select item_code,\\n DCTB DCTB sum(actual_qty*valuation_rate)/sum(actual_qty) as val_rate\\n DCTB DCTB from tabBin where actual_qty > 0 group by item_code'", ",", "as_dict", "=", "1", ")", ":", "item_val_rate_map", ".", "setdefault", "(", "d", ".", "item_code", ",", "d", ".", "val_rate", ")", "return", "item_val_rate_map" ]
get an average valuation rate of an item from all warehouses .
train
false
41,667
def has_level_label(label_flags, vmin): if ((label_flags.size == 0) or ((label_flags.size == 1) and (label_flags[0] == 0) and ((vmin % 1) > 0.0))): return False else: return True
[ "def", "has_level_label", "(", "label_flags", ",", "vmin", ")", ":", "if", "(", "(", "label_flags", ".", "size", "==", "0", ")", "or", "(", "(", "label_flags", ".", "size", "==", "1", ")", "and", "(", "label_flags", "[", "0", "]", "==", "0", ")", "and", "(", "(", "vmin", "%", "1", ")", ">", "0.0", ")", ")", ")", ":", "return", "False", "else", ":", "return", "True" ]
returns true if the label_flags indicate there is at least one label for this level .
train
true
41,668
def test_commandline_explicit_interp(tmpdir): subprocess.check_call([sys.executable, VIRTUALENV_SCRIPT, '-p', sys.executable, str(tmpdir.join('venv'))])
[ "def", "test_commandline_explicit_interp", "(", "tmpdir", ")", ":", "subprocess", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "VIRTUALENV_SCRIPT", ",", "'-p'", ",", "sys", ".", "executable", ",", "str", "(", "tmpdir", ".", "join", "(", "'venv'", ")", ")", "]", ")" ]
specifying the python interpreter should work .
train
false
41,669
def _dtype_to_default_stata_fmt(dtype): if (dtype.type == np.string_): return (('%' + str(dtype.itemsize)) + 's') elif (dtype.type == np.object_): return '%244s' elif (dtype == np.float64): return '%10.0g' elif (dtype == np.float32): return '%9.0g' elif (dtype == np.int64): return '%9.0g' elif (dtype == np.int32): return '%8.0g' elif ((dtype == np.int8) or (dtype == np.int16)): return '%8.0g' else: raise ValueError(('Data type %s not currently understood. Please report an error to the developers.' % dtype))
[ "def", "_dtype_to_default_stata_fmt", "(", "dtype", ")", ":", "if", "(", "dtype", ".", "type", "==", "np", ".", "string_", ")", ":", "return", "(", "(", "'%'", "+", "str", "(", "dtype", ".", "itemsize", ")", ")", "+", "'s'", ")", "elif", "(", "dtype", ".", "type", "==", "np", ".", "object_", ")", ":", "return", "'%244s'", "elif", "(", "dtype", "==", "np", ".", "float64", ")", ":", "return", "'%10.0g'", "elif", "(", "dtype", "==", "np", ".", "float32", ")", ":", "return", "'%9.0g'", "elif", "(", "dtype", "==", "np", ".", "int64", ")", ":", "return", "'%9.0g'", "elif", "(", "dtype", "==", "np", ".", "int32", ")", ":", "return", "'%8.0g'", "elif", "(", "(", "dtype", "==", "np", ".", "int8", ")", "or", "(", "dtype", "==", "np", ".", "int16", ")", ")", ":", "return", "'%8.0g'", "else", ":", "raise", "ValueError", "(", "(", "'Data type %s not currently understood. Please report an error to the developers.'", "%", "dtype", ")", ")" ]
maps numpy dtype to statas default format for this type .
train
false
41,670
@_api_version(1.21) @_client_version('1.5.0') def inspect_volume(name): response = _client_wrapper('inspect_volume', name) _clear_context() return response
[ "@", "_api_version", "(", "1.21", ")", "@", "_client_version", "(", "'1.5.0'", ")", "def", "inspect_volume", "(", "name", ")", ":", "response", "=", "_client_wrapper", "(", "'inspect_volume'", ",", "name", ")", "_clear_context", "(", ")", "return", "response" ]
inspect volume .
train
false
41,671
def getHexagonalGrid(diameter, loopsComplex, maximumComplex, minimumComplex, zigzag): diameter = complex(diameter.real, (math.sqrt(0.75) * diameter.imag)) demiradius = (0.25 * diameter) xRadius = (0.5 * diameter.real) xStart = (minimumComplex.real - demiradius.real) y = (minimumComplex.imag - demiradius.imag) gridPath = [] rowIndex = 0 while (y < maximumComplex.imag): x = xStart if ((rowIndex % 2) == 1): x -= xRadius addGridRow(diameter, gridPath, loopsComplex, maximumComplex, rowIndex, x, y, zigzag) y += diameter.imag rowIndex += 1 return gridPath
[ "def", "getHexagonalGrid", "(", "diameter", ",", "loopsComplex", ",", "maximumComplex", ",", "minimumComplex", ",", "zigzag", ")", ":", "diameter", "=", "complex", "(", "diameter", ".", "real", ",", "(", "math", ".", "sqrt", "(", "0.75", ")", "*", "diameter", ".", "imag", ")", ")", "demiradius", "=", "(", "0.25", "*", "diameter", ")", "xRadius", "=", "(", "0.5", "*", "diameter", ".", "real", ")", "xStart", "=", "(", "minimumComplex", ".", "real", "-", "demiradius", ".", "real", ")", "y", "=", "(", "minimumComplex", ".", "imag", "-", "demiradius", ".", "imag", ")", "gridPath", "=", "[", "]", "rowIndex", "=", "0", "while", "(", "y", "<", "maximumComplex", ".", "imag", ")", ":", "x", "=", "xStart", "if", "(", "(", "rowIndex", "%", "2", ")", "==", "1", ")", ":", "x", "-=", "xRadius", "addGridRow", "(", "diameter", ",", "gridPath", ",", "loopsComplex", ",", "maximumComplex", ",", "rowIndex", ",", "x", ",", "y", ",", "zigzag", ")", "y", "+=", "diameter", ".", "imag", "rowIndex", "+=", "1", "return", "gridPath" ]
get hexagonal grid .
train
false
41,673
def list_permissions(vhost, runas=None): if ((runas is None) and (not salt.utils.is_windows())): runas = salt.utils.get_user() res = __salt__['cmd.run_all']([__context__['rabbitmqctl'], 'list_permissions', '-q', '-p', vhost], runas=runas, python_shell=False) return _output_to_dict(res)
[ "def", "list_permissions", "(", "vhost", ",", "runas", "=", "None", ")", ":", "if", "(", "(", "runas", "is", "None", ")", "and", "(", "not", "salt", ".", "utils", ".", "is_windows", "(", ")", ")", ")", ":", "runas", "=", "salt", ".", "utils", ".", "get_user", "(", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "[", "__context__", "[", "'rabbitmqctl'", "]", ",", "'list_permissions'", ",", "'-q'", ",", "'-p'", ",", "vhost", "]", ",", "runas", "=", "runas", ",", "python_shell", "=", "False", ")", "return", "_output_to_dict", "(", "res", ")" ]
lists permissions for vhost via rabbitmqctl list_permissions cli example: .
train
false
41,674
def get_fallback_avatar_url(size): return os.path.join(settings.STATIC_URL, u'weblate-{0}.png'.format(size))
[ "def", "get_fallback_avatar_url", "(", "size", ")", ":", "return", "os", ".", "path", ".", "join", "(", "settings", ".", "STATIC_URL", ",", "u'weblate-{0}.png'", ".", "format", "(", "size", ")", ")" ]
returns url of fallback avatar .
train
false
41,675
def are_not_nat(builder, vals): assert (len(vals) >= 1) pred = is_not_nat(builder, vals[0]) for val in vals[1:]: pred = builder.and_(pred, is_not_nat(builder, val)) return pred
[ "def", "are_not_nat", "(", "builder", ",", "vals", ")", ":", "assert", "(", "len", "(", "vals", ")", ">=", "1", ")", "pred", "=", "is_not_nat", "(", "builder", ",", "vals", "[", "0", "]", ")", "for", "val", "in", "vals", "[", "1", ":", "]", ":", "pred", "=", "builder", ".", "and_", "(", "pred", ",", "is_not_nat", "(", "builder", ",", "val", ")", ")", "return", "pred" ]
return a predicate which is true if all of *vals* are not nat .
train
false
41,678
def test_sun(): from ..funcs import get_sun northern_summer_solstice = Time(u'2010-6-21') northern_winter_solstice = Time(u'2010-12-21') equinox_1 = Time(u'2010-3-21') equinox_2 = Time(u'2010-9-21') gcrs1 = get_sun(equinox_1) assert (np.abs(gcrs1.dec.deg) < 1) gcrs2 = get_sun(Time([northern_summer_solstice, equinox_2, northern_winter_solstice])) assert np.all((np.abs((gcrs2.dec - ([23.5, 0, (-23.5)] * u.deg))) < (1 * u.deg)))
[ "def", "test_sun", "(", ")", ":", "from", ".", ".", "funcs", "import", "get_sun", "northern_summer_solstice", "=", "Time", "(", "u'2010-6-21'", ")", "northern_winter_solstice", "=", "Time", "(", "u'2010-12-21'", ")", "equinox_1", "=", "Time", "(", "u'2010-3-21'", ")", "equinox_2", "=", "Time", "(", "u'2010-9-21'", ")", "gcrs1", "=", "get_sun", "(", "equinox_1", ")", "assert", "(", "np", ".", "abs", "(", "gcrs1", ".", "dec", ".", "deg", ")", "<", "1", ")", "gcrs2", "=", "get_sun", "(", "Time", "(", "[", "northern_summer_solstice", ",", "equinox_2", ",", "northern_winter_solstice", "]", ")", ")", "assert", "np", ".", "all", "(", "(", "np", ".", "abs", "(", "(", "gcrs2", ".", "dec", "-", "(", "[", "23.5", ",", "0", ",", "(", "-", "23.5", ")", "]", "*", "u", ".", "deg", ")", ")", ")", "<", "(", "1", "*", "u", ".", "deg", ")", ")", ")" ]
test that get_sun works and it behaves roughly as it should .
train
false
41,679
def get_injected_files(personality): injected_files = [] for item in personality: injected_files.append((item['path'], item['contents'])) return injected_files
[ "def", "get_injected_files", "(", "personality", ")", ":", "injected_files", "=", "[", "]", "for", "item", "in", "personality", ":", "injected_files", ".", "append", "(", "(", "item", "[", "'path'", "]", ",", "item", "[", "'contents'", "]", ")", ")", "return", "injected_files" ]
create a list of injected files from the personality attribute .
train
false
41,682
def _reduce_memmap_backed(a, m): (a_start, a_end) = np.byte_bounds(a) m_start = np.byte_bounds(m)[0] offset = (a_start - m_start) offset += m.offset if m.flags['F_CONTIGUOUS']: order = 'F' else: order = 'C' if (a.flags['F_CONTIGUOUS'] or a.flags['C_CONTIGUOUS']): strides = None total_buffer_len = None else: strides = a.strides total_buffer_len = ((a_end - a_start) // a.itemsize) return (_strided_from_memmap, (m.filename, a.dtype, m.mode, offset, order, a.shape, strides, total_buffer_len))
[ "def", "_reduce_memmap_backed", "(", "a", ",", "m", ")", ":", "(", "a_start", ",", "a_end", ")", "=", "np", ".", "byte_bounds", "(", "a", ")", "m_start", "=", "np", ".", "byte_bounds", "(", "m", ")", "[", "0", "]", "offset", "=", "(", "a_start", "-", "m_start", ")", "offset", "+=", "m", ".", "offset", "if", "m", ".", "flags", "[", "'F_CONTIGUOUS'", "]", ":", "order", "=", "'F'", "else", ":", "order", "=", "'C'", "if", "(", "a", ".", "flags", "[", "'F_CONTIGUOUS'", "]", "or", "a", ".", "flags", "[", "'C_CONTIGUOUS'", "]", ")", ":", "strides", "=", "None", "total_buffer_len", "=", "None", "else", ":", "strides", "=", "a", ".", "strides", "total_buffer_len", "=", "(", "(", "a_end", "-", "a_start", ")", "//", "a", ".", "itemsize", ")", "return", "(", "_strided_from_memmap", ",", "(", "m", ".", "filename", ",", "a", ".", "dtype", ",", "m", ".", "mode", ",", "offset", ",", "order", ",", "a", ".", "shape", ",", "strides", ",", "total_buffer_len", ")", ")" ]
pickling reduction for memmap backed arrays .
train
false
41,684
def show_master(path=MASTER_CF): (conf_dict, conf_list) = _parse_master(path) return conf_dict
[ "def", "show_master", "(", "path", "=", "MASTER_CF", ")", ":", "(", "conf_dict", ",", "conf_list", ")", "=", "_parse_master", "(", "path", ")", "return", "conf_dict" ]
return a dict of active config values .
train
false
41,685
@task @needs('pavelib.prereqs.install_prereqs') @consume_args @timed def check_settings(args): parser = argparse.ArgumentParser(prog='paver check_settings') parser.add_argument('system', type=str, nargs=1, help='lms or studio') parser.add_argument('settings', type=str, nargs=1, help='Django settings') args = parser.parse_args(args) system = args.system[0] settings = args.settings[0] try: import_cmd = "echo 'import {system}.envs.{settings}'".format(system=system, settings=settings) django_shell_cmd = django_cmd(system, settings, 'shell', '--plain', '--pythonpath=.') sh('{import_cmd} | {shell_cmd}'.format(import_cmd=import_cmd, shell_cmd=django_shell_cmd)) except: print('Failed to import settings', file=sys.stderr)
[ "@", "task", "@", "needs", "(", "'pavelib.prereqs.install_prereqs'", ")", "@", "consume_args", "@", "timed", "def", "check_settings", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'paver check_settings'", ")", "parser", ".", "add_argument", "(", "'system'", ",", "type", "=", "str", ",", "nargs", "=", "1", ",", "help", "=", "'lms or studio'", ")", "parser", ".", "add_argument", "(", "'settings'", ",", "type", "=", "str", ",", "nargs", "=", "1", ",", "help", "=", "'Django settings'", ")", "args", "=", "parser", ".", "parse_args", "(", "args", ")", "system", "=", "args", ".", "system", "[", "0", "]", "settings", "=", "args", ".", "settings", "[", "0", "]", "try", ":", "import_cmd", "=", "\"echo 'import {system}.envs.{settings}'\"", ".", "format", "(", "system", "=", "system", ",", "settings", "=", "settings", ")", "django_shell_cmd", "=", "django_cmd", "(", "system", ",", "settings", ",", "'shell'", ",", "'--plain'", ",", "'--pythonpath=.'", ")", "sh", "(", "'{import_cmd} | {shell_cmd}'", ".", "format", "(", "import_cmd", "=", "import_cmd", ",", "shell_cmd", "=", "django_shell_cmd", ")", ")", "except", ":", "print", "(", "'Failed to import settings'", ",", "file", "=", "sys", ".", "stderr", ")" ]
show the settings as redash sees them .
train
false
41,686
def get_cart_from_request(request, cart_queryset=Cart.objects.all()): discounts = request.discounts if request.user.is_authenticated(): cart = get_user_cart(request.user, cart_queryset) user = request.user else: token = request.get_signed_cookie(Cart.COOKIE_NAME, default=None) cart = get_anonymous_cart_from_token(token, cart_queryset) user = None if (cart is not None): cart.discounts = discounts return cart else: return Cart(user=user, discounts=discounts)
[ "def", "get_cart_from_request", "(", "request", ",", "cart_queryset", "=", "Cart", ".", "objects", ".", "all", "(", ")", ")", ":", "discounts", "=", "request", ".", "discounts", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "cart", "=", "get_user_cart", "(", "request", ".", "user", ",", "cart_queryset", ")", "user", "=", "request", ".", "user", "else", ":", "token", "=", "request", ".", "get_signed_cookie", "(", "Cart", ".", "COOKIE_NAME", ",", "default", "=", "None", ")", "cart", "=", "get_anonymous_cart_from_token", "(", "token", ",", "cart_queryset", ")", "user", "=", "None", "if", "(", "cart", "is", "not", "None", ")", ":", "cart", ".", "discounts", "=", "discounts", "return", "cart", "else", ":", "return", "Cart", "(", "user", "=", "user", ",", "discounts", "=", "discounts", ")" ]
get cart from database or return unsaved cart :type cart_queryset: saleor .
train
false
41,688
def _SharedPrefix(pattern1, pattern2): first_star1 = (pattern1 + '*').find('*') first_star2 = (pattern2 + '*').find('*') if ((first_star1, first_star2) != (len(pattern1), len(pattern2))): min_star = min(first_star1, first_star2) if (min_star and (pattern1[:min_star] == pattern2[:min_star])): return pattern1[:min_star] return ''
[ "def", "_SharedPrefix", "(", "pattern1", ",", "pattern2", ")", ":", "first_star1", "=", "(", "pattern1", "+", "'*'", ")", ".", "find", "(", "'*'", ")", "first_star2", "=", "(", "pattern2", "+", "'*'", ")", ".", "find", "(", "'*'", ")", "if", "(", "(", "first_star1", ",", "first_star2", ")", "!=", "(", "len", "(", "pattern1", ")", ",", "len", "(", "pattern2", ")", ")", ")", ":", "min_star", "=", "min", "(", "first_star1", ",", "first_star2", ")", "if", "(", "min_star", "and", "(", "pattern1", "[", ":", "min_star", "]", "==", "pattern2", "[", ":", "min_star", "]", ")", ")", ":", "return", "pattern1", "[", ":", "min_star", "]", "return", "''" ]
returns the shared prefix of two patterns .
train
false
41,689
def fingerprint_task(log, task, session): items = (task.items if task.is_album else [task.item]) for item in items: acoustid_match(log, item.path)
[ "def", "fingerprint_task", "(", "log", ",", "task", ",", "session", ")", ":", "items", "=", "(", "task", ".", "items", "if", "task", ".", "is_album", "else", "[", "task", ".", "item", "]", ")", "for", "item", "in", "items", ":", "acoustid_match", "(", "log", ",", "item", ".", "path", ")" ]
fingerprint each item in the task for later use during the autotagging candidate search .
train
false
41,690
def serverinfo(url='http://localhost:8080/manager', timeout=180): data = _wget('serverinfo', {}, url, timeout=timeout) if (data['res'] is False): return {'error': data['msg']} ret = {} data['msg'].pop(0) for line in data['msg']: tmp = line.split(':') ret[tmp[0].strip()] = tmp[1].strip() return ret
[ "def", "serverinfo", "(", "url", "=", "'http://localhost:8080/manager'", ",", "timeout", "=", "180", ")", ":", "data", "=", "_wget", "(", "'serverinfo'", ",", "{", "}", ",", "url", ",", "timeout", "=", "timeout", ")", "if", "(", "data", "[", "'res'", "]", "is", "False", ")", ":", "return", "{", "'error'", ":", "data", "[", "'msg'", "]", "}", "ret", "=", "{", "}", "data", "[", "'msg'", "]", ".", "pop", "(", "0", ")", "for", "line", "in", "data", "[", "'msg'", "]", ":", "tmp", "=", "line", ".", "split", "(", "':'", ")", "ret", "[", "tmp", "[", "0", "]", ".", "strip", "(", ")", "]", "=", "tmp", "[", "1", "]", ".", "strip", "(", ")", "return", "ret" ]
return details about the server url : URL the url of the server manager webapp timeout : 180 timeout for http request cli examples: .
train
true
41,692
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) def do_resume(cs, args): _find_server(cs, args.server).resume()
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "def", "do_resume", "(", "cs", ",", "args", ")", ":", "_find_server", "(", "cs", ",", "args", ".", "server", ")", ".", "resume", "(", ")" ]
resume a server .
train
false
41,693
def start_version_async(module, version): def _ResultHook(rpc): mapped_errors = [modules_service_pb.ModulesServiceError.INVALID_VERSION, modules_service_pb.ModulesServiceError.TRANSIENT_ERROR] expected_errors = {modules_service_pb.ModulesServiceError.UNEXPECTED_STATE: ('The specified module: %s, version: %s is already started.' % (module, version))} _CheckAsyncResult(rpc, mapped_errors, expected_errors) request = modules_service_pb.StartModuleRequest() request.set_module(module) request.set_version(version) response = modules_service_pb.StartModuleResponse() return _MakeAsyncCall('StartModule', request, response, _ResultHook)
[ "def", "start_version_async", "(", "module", ",", "version", ")", ":", "def", "_ResultHook", "(", "rpc", ")", ":", "mapped_errors", "=", "[", "modules_service_pb", ".", "ModulesServiceError", ".", "INVALID_VERSION", ",", "modules_service_pb", ".", "ModulesServiceError", ".", "TRANSIENT_ERROR", "]", "expected_errors", "=", "{", "modules_service_pb", ".", "ModulesServiceError", ".", "UNEXPECTED_STATE", ":", "(", "'The specified module: %s, version: %s is already started.'", "%", "(", "module", ",", "version", ")", ")", "}", "_CheckAsyncResult", "(", "rpc", ",", "mapped_errors", ",", "expected_errors", ")", "request", "=", "modules_service_pb", ".", "StartModuleRequest", "(", ")", "request", ".", "set_module", "(", "module", ")", "request", ".", "set_version", "(", "version", ")", "response", "=", "modules_service_pb", ".", "StartModuleResponse", "(", ")", "return", "_MakeAsyncCall", "(", "'StartModule'", ",", "request", ",", "response", ",", "_ResultHook", ")" ]
returns a userrpc to start all instances for the given module version .
train
false
41,696
def refine_abs(expr, assumptions): from sympy.core.logic import fuzzy_not arg = expr.args[0] if (ask(Q.real(arg), assumptions) and fuzzy_not(ask(Q.negative(arg), assumptions))): return arg if ask(Q.negative(arg), assumptions): return (- arg)
[ "def", "refine_abs", "(", "expr", ",", "assumptions", ")", ":", "from", "sympy", ".", "core", ".", "logic", "import", "fuzzy_not", "arg", "=", "expr", ".", "args", "[", "0", "]", "if", "(", "ask", "(", "Q", ".", "real", "(", "arg", ")", ",", "assumptions", ")", "and", "fuzzy_not", "(", "ask", "(", "Q", ".", "negative", "(", "arg", ")", ",", "assumptions", ")", ")", ")", ":", "return", "arg", "if", "ask", "(", "Q", ".", "negative", "(", "arg", ")", ",", "assumptions", ")", ":", "return", "(", "-", "arg", ")" ]
handler for the absolute value .
train
false
41,698
def unlock_objects(bus, paths, callback=None): service_obj = bus_get_object(bus, SS_PATH) service_iface = InterfaceWrapper(service_obj, SERVICE_IFACE) (unlocked_paths, prompt) = service_iface.Unlock(paths, signature='ao') unlocked_paths = list(unlocked_paths) if (len(prompt) > 1): if callback: exec_prompt(bus, prompt, callback) else: return exec_prompt_glib(bus, prompt)[0] elif callback: callback(False, unlocked_paths)
[ "def", "unlock_objects", "(", "bus", ",", "paths", ",", "callback", "=", "None", ")", ":", "service_obj", "=", "bus_get_object", "(", "bus", ",", "SS_PATH", ")", "service_iface", "=", "InterfaceWrapper", "(", "service_obj", ",", "SERVICE_IFACE", ")", "(", "unlocked_paths", ",", "prompt", ")", "=", "service_iface", ".", "Unlock", "(", "paths", ",", "signature", "=", "'ao'", ")", "unlocked_paths", "=", "list", "(", "unlocked_paths", ")", "if", "(", "len", "(", "prompt", ")", ">", "1", ")", ":", "if", "callback", ":", "exec_prompt", "(", "bus", ",", "prompt", ",", "callback", ")", "else", ":", "return", "exec_prompt_glib", "(", "bus", ",", "prompt", ")", "[", "0", "]", "elif", "callback", ":", "callback", "(", "False", ",", "unlocked_paths", ")" ]
requests unlocking objects specified in paths .
train
false
41,700
def link_cohort_to_partition_group(cohort, partition_id, group_id): CourseUserGroupPartitionGroup(course_user_group=cohort, partition_id=partition_id, group_id=group_id).save()
[ "def", "link_cohort_to_partition_group", "(", "cohort", ",", "partition_id", ",", "group_id", ")", ":", "CourseUserGroupPartitionGroup", "(", "course_user_group", "=", "cohort", ",", "partition_id", "=", "partition_id", ",", "group_id", "=", "group_id", ")", ".", "save", "(", ")" ]
create cohort to partition_id/group_id link .
train
false
41,702
def is_request_from_mobile_app(request): if is_request_from_mobile_web_view(request): return True if getattr(settings, 'MOBILE_APP_USER_AGENT_REGEXES', None): user_agent = request.META.get('HTTP_USER_AGENT') if user_agent: for user_agent_regex in settings.MOBILE_APP_USER_AGENT_REGEXES: if re.search(user_agent_regex, user_agent): return True return False
[ "def", "is_request_from_mobile_app", "(", "request", ")", ":", "if", "is_request_from_mobile_web_view", "(", "request", ")", ":", "return", "True", "if", "getattr", "(", "settings", ",", "'MOBILE_APP_USER_AGENT_REGEXES'", ",", "None", ")", ":", "user_agent", "=", "request", ".", "META", ".", "get", "(", "'HTTP_USER_AGENT'", ")", "if", "user_agent", ":", "for", "user_agent_regex", "in", "settings", ".", "MOBILE_APP_USER_AGENT_REGEXES", ":", "if", "re", ".", "search", "(", "user_agent_regex", ",", "user_agent", ")", ":", "return", "True", "return", "False" ]
returns whether the given request was made by an open edx mobile app .
train
false
41,703
def local_resource_url(block, uri): return xblock_local_resource_url(block, uri)
[ "def", "local_resource_url", "(", "block", ",", "uri", ")", ":", "return", "xblock_local_resource_url", "(", "block", ",", "uri", ")" ]
local_resource_url for studio .
train
false
41,704
@skipif_not_matplotlib def test_latex_to_png_mpl_runs(): def mock_kpsewhich(filename): nt.assert_equal(filename, 'breqn.sty') return None for (s, wrap) in [('$x^2$', False), ('x^2', True)]: (yield (latextools.latex_to_png_mpl, s, wrap)) with patch.object(latextools, 'kpsewhich', mock_kpsewhich): (yield (latextools.latex_to_png_mpl, s, wrap))
[ "@", "skipif_not_matplotlib", "def", "test_latex_to_png_mpl_runs", "(", ")", ":", "def", "mock_kpsewhich", "(", "filename", ")", ":", "nt", ".", "assert_equal", "(", "filename", ",", "'breqn.sty'", ")", "return", "None", "for", "(", "s", ",", "wrap", ")", "in", "[", "(", "'$x^2$'", ",", "False", ")", ",", "(", "'x^2'", ",", "True", ")", "]", ":", "(", "yield", "(", "latextools", ".", "latex_to_png_mpl", ",", "s", ",", "wrap", ")", ")", "with", "patch", ".", "object", "(", "latextools", ",", "'kpsewhich'", ",", "mock_kpsewhich", ")", ":", "(", "yield", "(", "latextools", ".", "latex_to_png_mpl", ",", "s", ",", "wrap", ")", ")" ]
test that latex_to_png_mpl just runs without error .
train
false
41,706
def rolling_quantile(arg, window, quantile, min_periods=None, freq=None, center=False): return ensure_compat('rolling', 'quantile', arg, window=window, freq=freq, center=center, min_periods=min_periods, func_kw=['quantile'], quantile=quantile)
[ "def", "rolling_quantile", "(", "arg", ",", "window", ",", "quantile", ",", "min_periods", "=", "None", ",", "freq", "=", "None", ",", "center", "=", "False", ")", ":", "return", "ensure_compat", "(", "'rolling'", ",", "'quantile'", ",", "arg", ",", "window", "=", "window", ",", "freq", "=", "freq", ",", "center", "=", "center", ",", "min_periods", "=", "min_periods", ",", "func_kw", "=", "[", "'quantile'", "]", ",", "quantile", "=", "quantile", ")" ]
moving quantile .
train
false
41,708
def minify_css(css): remove_next_comment = 1 for css_comment in css_comments.findall(css): if (css_comment[(-3):] == '\\*/'): remove_next_comment = 0 continue if remove_next_comment: css = css.replace(css_comment, '') else: remove_next_comment = 1 css = re.sub('\\s\\s+', ' ', css) css = re.sub('\\s+\\n', '', css) for char in ('{', '}', ':', ';', ','): css = re.sub((char + '\\s'), char, css) css = re.sub(('\\s' + char), char, css) css = re.sub('}\\s(#|\\w)', '}\\1', css) css = re.sub(';}', '}', css) css = re.sub('}//-->', '}\\n//-->', css) return css.strip()
[ "def", "minify_css", "(", "css", ")", ":", "remove_next_comment", "=", "1", "for", "css_comment", "in", "css_comments", ".", "findall", "(", "css", ")", ":", "if", "(", "css_comment", "[", "(", "-", "3", ")", ":", "]", "==", "'\\\\*/'", ")", ":", "remove_next_comment", "=", "0", "continue", "if", "remove_next_comment", ":", "css", "=", "css", ".", "replace", "(", "css_comment", ",", "''", ")", "else", ":", "remove_next_comment", "=", "1", "css", "=", "re", ".", "sub", "(", "'\\\\s\\\\s+'", ",", "' '", ",", "css", ")", "css", "=", "re", ".", "sub", "(", "'\\\\s+\\\\n'", ",", "''", ",", "css", ")", "for", "char", "in", "(", "'{'", ",", "'}'", ",", "':'", ",", "';'", ",", "','", ")", ":", "css", "=", "re", ".", "sub", "(", "(", "char", "+", "'\\\\s'", ")", ",", "char", ",", "css", ")", "css", "=", "re", ".", "sub", "(", "(", "'\\\\s'", "+", "char", ")", ",", "char", ",", "css", ")", "css", "=", "re", ".", "sub", "(", "'}\\\\s(#|\\\\w)'", ",", "'}\\\\1'", ",", "css", ")", "css", "=", "re", ".", "sub", "(", "';}'", ",", "'}'", ",", "css", ")", "css", "=", "re", ".", "sub", "(", "'}//-->'", ",", "'}\\\\n//-->'", ",", "css", ")", "return", "css", ".", "strip", "(", ")" ]
little css minifier .
train
false
41,709
def getPackages(dname, pkgname=None, results=None, ignore=None, parent=None): parent = (parent or '') prefix = [] if parent: prefix = [parent] bname = os.path.basename(dname) ignore = (ignore or []) if (bname in ignore): return [] if (results is None): results = [] if (pkgname is None): pkgname = [] subfiles = os.listdir(dname) abssubfiles = [os.path.join(dname, x) for x in subfiles] if ('__init__.py' in subfiles): results.append(((prefix + pkgname) + [bname])) for subdir in filter(os.path.isdir, abssubfiles): getPackages(subdir, pkgname=(pkgname + [bname]), results=results, ignore=ignore, parent=parent) res = ['.'.join(result) for result in results] return res
[ "def", "getPackages", "(", "dname", ",", "pkgname", "=", "None", ",", "results", "=", "None", ",", "ignore", "=", "None", ",", "parent", "=", "None", ")", ":", "parent", "=", "(", "parent", "or", "''", ")", "prefix", "=", "[", "]", "if", "parent", ":", "prefix", "=", "[", "parent", "]", "bname", "=", "os", ".", "path", ".", "basename", "(", "dname", ")", "ignore", "=", "(", "ignore", "or", "[", "]", ")", "if", "(", "bname", "in", "ignore", ")", ":", "return", "[", "]", "if", "(", "results", "is", "None", ")", ":", "results", "=", "[", "]", "if", "(", "pkgname", "is", "None", ")", ":", "pkgname", "=", "[", "]", "subfiles", "=", "os", ".", "listdir", "(", "dname", ")", "abssubfiles", "=", "[", "os", ".", "path", ".", "join", "(", "dname", ",", "x", ")", "for", "x", "in", "subfiles", "]", "if", "(", "'__init__.py'", "in", "subfiles", ")", ":", "results", ".", "append", "(", "(", "(", "prefix", "+", "pkgname", ")", "+", "[", "bname", "]", ")", ")", "for", "subdir", "in", "filter", "(", "os", ".", "path", ".", "isdir", ",", "abssubfiles", ")", ":", "getPackages", "(", "subdir", ",", "pkgname", "=", "(", "pkgname", "+", "[", "bname", "]", ")", ",", "results", "=", "results", ",", "ignore", "=", "ignore", ",", "parent", "=", "parent", ")", "res", "=", "[", "'.'", ".", "join", "(", "result", ")", "for", "result", "in", "results", "]", "return", "res" ]
get all packages which are under dname .
train
true
41,710
def _re_flatten(p): if ('(' not in p): return p return re.sub('(\\\\*)(\\(\\?P<[^>]+>|\\((?!\\?))', (lambda m: (m.group(0) if (len(m.group(1)) % 2) else (m.group(1) + '(?:'))), p)
[ "def", "_re_flatten", "(", "p", ")", ":", "if", "(", "'('", "not", "in", "p", ")", ":", "return", "p", "return", "re", ".", "sub", "(", "'(\\\\\\\\*)(\\\\(\\\\?P<[^>]+>|\\\\((?!\\\\?))'", ",", "(", "lambda", "m", ":", "(", "m", ".", "group", "(", "0", ")", "if", "(", "len", "(", "m", ".", "group", "(", "1", ")", ")", "%", "2", ")", "else", "(", "m", ".", "group", "(", "1", ")", "+", "'(?:'", ")", ")", ")", ",", "p", ")" ]
turn all capturing groups in a regular expression pattern into non-capturing groups .
train
true
41,712
def _get_unique_table_field_values(model, field, sort_field): if ((field not in model.all_keys()) or (sort_field not in model.all_keys())): raise KeyError with g.lib.transaction() as tx: rows = tx.query('SELECT DISTINCT "{0}" FROM "{1}" ORDER BY "{2}"'.format(field, model._table, sort_field)) return [row[0] for row in rows]
[ "def", "_get_unique_table_field_values", "(", "model", ",", "field", ",", "sort_field", ")", ":", "if", "(", "(", "field", "not", "in", "model", ".", "all_keys", "(", ")", ")", "or", "(", "sort_field", "not", "in", "model", ".", "all_keys", "(", ")", ")", ")", ":", "raise", "KeyError", "with", "g", ".", "lib", ".", "transaction", "(", ")", "as", "tx", ":", "rows", "=", "tx", ".", "query", "(", "'SELECT DISTINCT \"{0}\" FROM \"{1}\" ORDER BY \"{2}\"'", ".", "format", "(", "field", ",", "model", ".", "_table", ",", "sort_field", ")", ")", "return", "[", "row", "[", "0", "]", "for", "row", "in", "rows", "]" ]
retrieve all unique values belonging to a key from a model .
train
false
41,713
def _tgrep_node_label_pred_use_action(_s, _l, tokens): assert (len(tokens) == 1) assert tokens[0].startswith(u'=') node_label = tokens[0][1:] def node_label_use_pred(n, m=None, l=None): if ((l is None) or (node_label not in l)): raise TgrepException(u'node_label ={0} not bound in pattern'.format(node_label)) node = l[node_label] return (n is node) return node_label_use_pred
[ "def", "_tgrep_node_label_pred_use_action", "(", "_s", ",", "_l", ",", "tokens", ")", ":", "assert", "(", "len", "(", "tokens", ")", "==", "1", ")", "assert", "tokens", "[", "0", "]", ".", "startswith", "(", "u'='", ")", "node_label", "=", "tokens", "[", "0", "]", "[", "1", ":", "]", "def", "node_label_use_pred", "(", "n", ",", "m", "=", "None", ",", "l", "=", "None", ")", ":", "if", "(", "(", "l", "is", "None", ")", "or", "(", "node_label", "not", "in", "l", ")", ")", ":", "raise", "TgrepException", "(", "u'node_label ={0} not bound in pattern'", ".", "format", "(", "node_label", ")", ")", "node", "=", "l", "[", "node_label", "]", "return", "(", "n", "is", "node", ")", "return", "node_label_use_pred" ]
builds a lambda function representing a predicate on a tree node which describes the use of a previously bound node label .
train
false
41,714
def check_method_name(name): if regex_private.match(name): raise AccessError((_('Private methods (such as %s) cannot be called remotely.') % (name,)))
[ "def", "check_method_name", "(", "name", ")", ":", "if", "regex_private", ".", "match", "(", "name", ")", ":", "raise", "AccessError", "(", "(", "_", "(", "'Private methods (such as %s) cannot be called remotely.'", ")", "%", "(", "name", ",", ")", ")", ")" ]
raise an accesserror if name is a private method name .
train
false
41,715
def get_time_info(layer): layer = gs_catalog.get_layer(layer.name) if (layer is None): raise ValueError(('no such layer: %s' % layer.name)) resource = layer.resource info = (resource.metadata.get('time', None) if resource.metadata else None) vals = None if info: value = step = None resolution = info.resolution_str() if resolution: (value, step) = resolution.split() vals = dict(enabled=info.enabled, attribute=info.attribute, end_attribute=info.end_attribute, presentation=info.presentation, precision_value=value, precision_step=step) return vals
[ "def", "get_time_info", "(", "layer", ")", ":", "layer", "=", "gs_catalog", ".", "get_layer", "(", "layer", ".", "name", ")", "if", "(", "layer", "is", "None", ")", ":", "raise", "ValueError", "(", "(", "'no such layer: %s'", "%", "layer", ".", "name", ")", ")", "resource", "=", "layer", ".", "resource", "info", "=", "(", "resource", ".", "metadata", ".", "get", "(", "'time'", ",", "None", ")", "if", "resource", ".", "metadata", "else", "None", ")", "vals", "=", "None", "if", "info", ":", "value", "=", "step", "=", "None", "resolution", "=", "info", ".", "resolution_str", "(", ")", "if", "resolution", ":", "(", "value", ",", "step", ")", "=", "resolution", ".", "split", "(", ")", "vals", "=", "dict", "(", "enabled", "=", "info", ".", "enabled", ",", "attribute", "=", "info", ".", "attribute", ",", "end_attribute", "=", "info", ".", "end_attribute", ",", "presentation", "=", "info", ".", "presentation", ",", "precision_value", "=", "value", ",", "precision_step", "=", "step", ")", "return", "vals" ]
get the configured time dimension metadata for the layer as a dict .
train
false
41,716
def untag(tagged_sentence): return [w for (w, t) in tagged_sentence]
[ "def", "untag", "(", "tagged_sentence", ")", ":", "return", "[", "w", "for", "(", "w", ",", "t", ")", "in", "tagged_sentence", "]" ]
make the post-tag back to dev commit .
train
false
41,718
def in_subnet(cidr, addr=None): try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error("Invalid CIDR '{0}'".format(cidr)) return False if (addr is None): addr = ip_addrs() addr.extend(ip_addrs6()) elif isinstance(addr, six.string_types): return (ipaddress.ip_address(addr) in cidr) for ip_addr in addr: if (ipaddress.ip_address(ip_addr) in cidr): return True return False
[ "def", "in_subnet", "(", "cidr", ",", "addr", "=", "None", ")", ":", "try", ":", "cidr", "=", "ipaddress", ".", "ip_network", "(", "cidr", ")", "except", "ValueError", ":", "log", ".", "error", "(", "\"Invalid CIDR '{0}'\"", ".", "format", "(", "cidr", ")", ")", "return", "False", "if", "(", "addr", "is", "None", ")", ":", "addr", "=", "ip_addrs", "(", ")", "addr", ".", "extend", "(", "ip_addrs6", "(", ")", ")", "elif", "isinstance", "(", "addr", ",", "six", ".", "string_types", ")", ":", "return", "(", "ipaddress", ".", "ip_address", "(", "addr", ")", "in", "cidr", ")", "for", "ip_addr", "in", "addr", ":", "if", "(", "ipaddress", ".", "ip_address", "(", "ip_addr", ")", "in", "cidr", ")", ":", "return", "True", "return", "False" ]
returns true if host is within specified subnet .
train
false
41,719
def setPrefixLimit(limit): global _PREFIX_LIMIT _PREFIX_LIMIT = limit
[ "def", "setPrefixLimit", "(", "limit", ")", ":", "global", "_PREFIX_LIMIT", "_PREFIX_LIMIT", "=", "limit" ]
set the limit on the prefix length for all banana connections established after this call .
train
false
41,720
def parse_qiime_parameters(lines): result = defaultdict(dict) for line in lines: line = line.strip() if (line and (not line.startswith('#'))): pound_pos = line.find('#') if ((pound_pos > 0) and line[(pound_pos - 1)].isspace()): line = line[:pound_pos].rstrip() fields = line.split(None, 1) (script_id, parameter_id) = fields[0].split(':') try: value = fields[1] except IndexError: continue if ((value.upper() == 'FALSE') or (value.upper() == 'NONE')): continue elif (value.upper() == 'TRUE'): value = None else: pass result[script_id][parameter_id] = value return result
[ "def", "parse_qiime_parameters", "(", "lines", ")", ":", "result", "=", "defaultdict", "(", "dict", ")", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "(", "line", "and", "(", "not", "line", ".", "startswith", "(", "'#'", ")", ")", ")", ":", "pound_pos", "=", "line", ".", "find", "(", "'#'", ")", "if", "(", "(", "pound_pos", ">", "0", ")", "and", "line", "[", "(", "pound_pos", "-", "1", ")", "]", ".", "isspace", "(", ")", ")", ":", "line", "=", "line", "[", ":", "pound_pos", "]", ".", "rstrip", "(", ")", "fields", "=", "line", ".", "split", "(", "None", ",", "1", ")", "(", "script_id", ",", "parameter_id", ")", "=", "fields", "[", "0", "]", ".", "split", "(", "':'", ")", "try", ":", "value", "=", "fields", "[", "1", "]", "except", "IndexError", ":", "continue", "if", "(", "(", "value", ".", "upper", "(", ")", "==", "'FALSE'", ")", "or", "(", "value", ".", "upper", "(", ")", "==", "'NONE'", ")", ")", ":", "continue", "elif", "(", "value", ".", "upper", "(", ")", "==", "'TRUE'", ")", ":", "value", "=", "None", "else", ":", "pass", "result", "[", "script_id", "]", "[", "parameter_id", "]", "=", "value", "return", "result" ]
return 2d dict of params which should be on .
train
false
41,721
def todict(db, row): d = {} for (i, field) in enumerate(db.cursor.description): column = field[0].lower() d[column] = row[i] return d
[ "def", "todict", "(", "db", ",", "row", ")", ":", "d", "=", "{", "}", "for", "(", "i", ",", "field", ")", "in", "enumerate", "(", "db", ".", "cursor", ".", "description", ")", ":", "column", "=", "field", "[", "0", "]", ".", "lower", "(", ")", "d", "[", "column", "]", "=", "row", "[", "i", "]", "return", "d" ]
transforms a row into a dict keyed by column names .
train
false
41,723
def convert_sv_text(text): ret_lines = [] for line in text.splitlines(): line = convert_sv_line(line) if ('DCDCDC' not in line): ret_lines.append(line) return ret_lines
[ "def", "convert_sv_text", "(", "text", ")", ":", "ret_lines", "=", "[", "]", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "line", "=", "convert_sv_line", "(", "line", ")", "if", "(", "'DCDCDC'", "not", "in", "line", ")", ":", "ret_lines", ".", "append", "(", "line", ")", "return", "ret_lines" ]
normalize senate vote text from pdftotext senate votes come out of pdftotext with characters shifted in weird way convert_sv_text converts that text to a readable format with junk stripped example after decoding: officialrollcall newmexicostatesenate fiftiethlegislature .
train
false
41,724
def last_two_blanks(src): if (not src): return False new_src = '\n'.join((['###\n'] + src.splitlines()[(-2):])) return (bool(last_two_blanks_re.match(new_src)) or bool(last_two_blanks_re2.match(new_src)))
[ "def", "last_two_blanks", "(", "src", ")", ":", "if", "(", "not", "src", ")", ":", "return", "False", "new_src", "=", "'\\n'", ".", "join", "(", "(", "[", "'###\\n'", "]", "+", "src", ".", "splitlines", "(", ")", "[", "(", "-", "2", ")", ":", "]", ")", ")", "return", "(", "bool", "(", "last_two_blanks_re", ".", "match", "(", "new_src", ")", ")", "or", "bool", "(", "last_two_blanks_re2", ".", "match", "(", "new_src", ")", ")", ")" ]
determine if the input source ends in two blanks .
train
true