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", ...
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=r...
[ "def", "create_rule_instance", "(", "rule", ")", ":", "return", "SecurityRule", "(", "rule", "[", "'protocol'", "]", ",", "rule", "[", "'source_address_prefix'", "]", ",", "rule", "[", "'destination_address_prefix'", "]", ",", "rule", "[", "'access'", "]", ","...
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", "(", ")", ...
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_de...
[ "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'", ...
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...
[ "def", "was_modified_since", "(", "header", "=", "None", ",", "mtime", "=", "0", ",", "size", "=", "0", ")", ":", "try", ":", "if", "(", "header", "is", "None", ")", ":", "raise", "ValueError", "matches", "=", "re", ".", "match", "(", "'^([^;]+)(; le...
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",...
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_...
[ "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", "=", "...
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'] =...
[ "def", "parse_branch_site_a", "(", "foreground", ",", "line_floats", ",", "site_classes", ")", ":", "if", "(", "(", "not", "site_classes", ")", "or", "(", "len", "(", "line_floats", ")", "==", "0", ")", ")", ":", "return", "for", "n", "in", "range", "(...
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): val...
[ "@", "translations", ".", "command", "(", "'update'", ")", "@", "click", ".", "option", "(", "'is_all'", ",", "'--all'", ",", "'-a'", ",", "default", "=", "True", ",", "is_flag", "=", "True", ",", "help", "=", "'Updates the plugin translations as well.'", ")...
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", ",", "'includeFailedB...
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), ...
[ "@", "cli", ".", "command", "(", "name", "=", "u'serve'", ")", "@", "click", ".", "option", "(", "u'-f'", ",", "u'--config-file'", ",", "type", "=", "click", ".", "File", "(", "u'rb'", ")", ",", "help", "=", "config_help", ")", "@", "click", ".", "...
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", ...
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, thr...
[ "def", "_threaded_method", "(", "method_name", ",", "sync_name", ",", "reactor_name", ",", "threadpool_name", ")", ":", "def", "_run_in_thread", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "reactor", "=", "getattr", "(", "self", ",", "rea...
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", "(", ...
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"...
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_l...
[ "def", "require_user_id_else_redirect_to_homepage", "(", "handler", ")", ":", "def", "test_login", "(", "self", ",", "**", "kwargs", ")", ":", "if", "(", "not", "self", ".", "user_id", ")", ":", "self", ".", "redirect", "(", "'/'", ")", "return", "return",...
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...
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'str_prefix'", ",", "[", "'u'", ",", "''", "]", ")", "def", "test_pytest_fail_notrace_non_ascii", "(", "testdir", ",", "str_prefix", ")", ":", "testdir", ".", "makepyfile", "(", "(", "u\"\\n # coding...
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", ",", ...
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 ...
[ "def", "_dexp", "(", "c", ",", "e", ",", "p", ")", ":", "p", "+=", "2", "extra", "=", "max", "(", "0", ",", "(", "(", "e", "+", "len", "(", "str", "(", "c", ")", ")", ")", "-", "1", ")", ")", "q", "=", "(", "p", "+", "extra", ")", "...
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: ...
[ "def", "check_requirements", "(", ")", ":", "if", "(", "(", "sys", ".", "version_info", "<", "(", "3", ",", "3", ")", ")", "and", "(", "sys", ".", "version_info", "[", ":", "2", "]", "!=", "(", "2", ",", "7", ")", ")", ")", ":", "raise", "Sys...
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=(l...
[ "def", "findMultipartPostBoundary", "(", "post", ")", ":", "retVal", "=", "None", "done", "=", "set", "(", ")", "candidates", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "'(?m)^--(.+?)(--)?$'", ",", "(", "post", "or", "''", ")", ")...
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)) ass...
[ "def", "test_md5sum", "(", ")", ":", "tempdir", "=", "_TempDir", "(", ")", "fname1", "=", "op", ".", "join", "(", "tempdir", ",", "'foo'", ")", "fname2", "=", "op", ".", "join", "(", "tempdir", ",", "'bar'", ")", "with", "open", "(", "fname1", ",",...
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_TYP...
[ "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'", ...
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(r...
[ "@", "constructor", "def", "var", "(", "input", ",", "axis", "=", "None", ",", "ddof", "=", "0", ",", "keepdims", "=", "False", ",", "corrected", "=", "False", ")", ":", "if", "isinstance", "(", "ddof", ",", "bool", ")", ":", "raise", "ValueError", ...
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_k...
[ "def", "_get_join_indexers", "(", "left_keys", ",", "right_keys", ",", "sort", "=", "False", ",", "how", "=", "'inner'", ",", "**", "kwargs", ")", ":", "from", "functools", "import", "partial", "assert", "(", "len", "(", "left_keys", ")", "==", "len", "(...
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 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", "(", "'att...
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',...
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_uninstall_easy_install_after_import", "(", "script", ")", ":", "result", "=", "script", ".", "run", "(", "'easy_install'", ",", "'INITools==0.2'", ",", "expect_stderr", "=", "True", ")", "script", ".", "...
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", ",", "Attri...
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 +...
[ "def", "dup_sqr", "(", "f", ",", "K", ")", ":", "(", "df", ",", "h", ")", "=", "(", "(", "len", "(", "f", ")", "-", "1", ")", ",", "[", "]", ")", "for", "i", "in", "range", "(", "0", ",", "(", "(", "2", "*", "df", ")", "+", "1", ")"...
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('...
[ "def", "qurl_from_user_input", "(", "urlstr", ")", ":", "match", "=", "re", ".", "match", "(", "'\\\\[?([0-9a-fA-F:.]+)\\\\]?(.*)'", ",", "urlstr", ".", "strip", "(", ")", ")", "if", "match", ":", "(", "ipstr", ",", "rest", ")", "=", "match", ".", "group...
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) ...
[ "def", "test_indexing_on_class", "(", ")", ":", "g", "=", "Gaussian1D", "(", "1", ",", "2", ",", "3", ",", "name", "=", "u'g'", ")", "p", "=", "Polynomial1D", "(", "2", ",", "name", "=", "u'p'", ")", "M", "=", "(", "Gaussian1D", "+", "Const1D", "...
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 = getat...
[ "def", "describe_file", "(", "module", ")", ":", "from", ".", "import", "remote", "descriptor", "=", "FileDescriptor", "(", ")", "descriptor", ".", "package", "=", "util", ".", "get_package_for_module", "(", "module", ")", "if", "(", "not", "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", ",", "clo...
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 = modelquer...
[ "def", "get_query_for_ids", "(", "modelquery", ",", "model", ",", "ids", ")", ":", "if", "has_multiple_pks", "(", "model", ")", ":", "decoded_ids", "=", "[", "iterdecode", "(", "v", ")", "for", "v", "in", "ids", "]", "model_pk", "=", "[", "getattr", "(...
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", ")", ")", ":", ...
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", ")", ",",...
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) ex...
[ "def", "assemble_option_dict", "(", "option_list", ",", "options_spec", ")", ":", "options", "=", "{", "}", "for", "(", "name", ",", "value", ")", "in", "option_list", ":", "convertor", "=", "options_spec", "[", "name", "]", "if", "(", "convertor", "is", ...
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"...
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, pic...
[ "def", "test_subtract_evoked", "(", ")", ":", "(", "raw", ",", "events", ",", "picks", ")", "=", "_get_data", "(", ")", "epochs", "=", "Epochs", "(", "raw", ",", "events", "[", ":", "10", "]", ",", "event_id", ",", "tmin", ",", "tmax", ",", "picks"...
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 ...
[ "def", "copy_files_from", "(", "address", ",", "client", ",", "username", ",", "password", ",", "port", ",", "remote_path", ",", "local_path", ",", "limit", "=", "''", ",", "log_filename", "=", "None", ",", "verbose", "=", "False", ",", "timeout", "=", "...
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", "....
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_ra...
[ "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 gro...
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", ")", ...
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 ==...
[ "def", "_dtype_to_default_stata_fmt", "(", "dtype", ")", ":", "if", "(", "dtype", ".", "type", "==", "np", ".", "string_", ")", ":", "return", "(", "(", "'%'", "+", "str", "(", "dtype", ".", "itemsize", ")", ")", "+", "'s'", ")", "elif", "(", "dtyp...
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) gri...
[ "def", "getHexagonalGrid", "(", "diameter", ",", "loopsComplex", ",", "maximumComplex", ",", "minimumComplex", ",", "zigzag", ")", ":", "diameter", "=", "complex", "(", "diameter", ".", "real", ",", "(", "math", ".", "sqrt", "(", "0.75", ")", "*", "diamete...
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", "."...
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", ":", "]", ":"...
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, equ...
[ "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'"...
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'", "]", ")", ")", "re...
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 e...
[ "def", "_reduce_memmap_backed", "(", "a", ",", "m", ")", ":", "(", "a_start", ",", "a_end", ")", "=", "np", ".", "byte_bounds", "(", "a", ")", "m_start", "=", "np", ".", "byte_bounds", "(", "m", ")", "[", "0", "]", "offset", "=", "(", "a_start", ...
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...
[ "@", "task", "@", "needs", "(", "'pavelib.prereqs.install_prereqs'", ")", "@", "consume_args", "@", "timed", "def", "check_settings", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'paver check_settings'", ")", "parse...
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_...
[ "def", "get_cart_from_request", "(", "request", ",", "cart_queryset", "=", "Cart", ".", "objects", ".", "all", "(", ")", ")", ":", "discounts", "=", "request", ".", "discounts", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "cart", ...
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[:...
[ "def", "_SharedPrefix", "(", "pattern1", ",", "pattern2", ")", ":", "first_star1", "=", "(", "pattern1", "+", "'*'", ")", ".", "find", "(", "'*'", ")", "first_star2", "=", "(", "pattern2", "+", "'*'", ")", ".", "find", "(", "'*'", ")", "if", "(", "...
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", "("...
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'", "...
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 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 alr...
[ "def", "start_version_async", "(", "module", ",", "version", ")", ":", "def", "_ResultHook", "(", "rpc", ")", ":", "mapped_errors", "=", "[", "modules_service_pb", ".", "ModulesServiceError", ".", "INVALID_VERSION", ",", "modules_service_pb", ".", "ModulesServiceErr...
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", ")", ",", "ass...
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...
[ "def", "unlock_objects", "(", "bus", ",", "paths", ",", "callback", "=", "None", ")", ":", "service_obj", "=", "bus_get_object", "(", "bus", ",", "SS_PATH", ")", "service_iface", "=", "InterfaceWrapper", "(", "service_obj", ",", "SERVICE_IFACE", ")", "(", "u...
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", ")", ".", "s...
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_...
[ "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", "=", ...
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 (la...
[ "@", "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", ")", "i...
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", ",", "win...
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('\\...
[ "def", "minify_css", "(", "css", ")", ":", "remove_next_comment", "=", "1", "for", "css_comment", "in", "css_comments", ".", "findall", "(", "css", ")", ":", "if", "(", "css_comment", "[", "(", "-", "3", ")", ":", "]", "==", "'\\\\*/'", ")", ":", "re...
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 = [] su...
[ "def", "getPackages", "(", "dname", ",", "pkgname", "=", "None", ",", "results", "=", "None", ",", "ignore", "=", "None", ",", "parent", "=", "None", ")", ":", "parent", "=", "(", "parent", "or", "''", ")", "prefix", "=", "[", "]", "if", "parent", ...
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", ...
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 ...
[ "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", "(", ")", "...
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)) ...
[ "def", "_tgrep_node_label_pred_use_action", "(", "_s", ",", "_l", ",", "tokens", ")", ":", "assert", "(", "len", "(", "tokens", ")", "==", "1", ")", "assert", "tokens", "[", "0", "]", ".", "startswith", "(", "u'='", ")", "node_label", "=", "tokens", "[...
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.resolut...
[ "def", "get_time_info", "(", "layer", ")", ":", "layer", "=", "gs_catalog", ".", "get_layer", "(", "layer", ".", "name", ")", "if", "(", "layer", "is", "None", ")", ":", "raise", "ValueError", "(", "(", "'no such layer: %s'", "%", "layer", ".", "name", ...
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_a...
[ "def", "in_subnet", "(", "cidr", ",", "addr", "=", "None", ")", ":", "try", ":", "cidr", "=", "ipaddress", ".", "ip_network", "(", "cidr", ")", "except", "ValueError", ":", "log", ".", "error", "(", "\"Invalid CIDR '{0}'\"", ".", "format", "(", "cidr", ...
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_...
[ "def", "parse_qiime_parameters", "(", "lines", ")", ":", "result", "=", "defaultdict", "(", "dict", ")", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "(", "line", "and", "(", "not", "line", ".", "startswith", ...
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", "(", ")"...
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_l...
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", ")", ":", "...
determine if the input source ends in two blanks .
train
true