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
13,941
@docfiller def gaussian_laplace(input, sigma, output=None, mode='reflect', cval=0.0, **kwargs): input = numpy.asarray(input) def derivative2(input, axis, output, mode, cval, sigma, **kwargs): order = ([0] * input.ndim) order[axis] = 2 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) return generic_laplace(input, derivative2, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs)
[ "@", "docfiller", "def", "gaussian_laplace", "(", "input", ",", "sigma", ",", "output", "=", "None", ",", "mode", "=", "'reflect'", ",", "cval", "=", "0.0", ",", "**", "kwargs", ")", ":", "input", "=", "numpy", ".", "asarray", "(", "input", ")", "def...
multidimensional laplace filter using gaussian second derivatives .
train
false
13,942
def test_client_options(config): if config['use_ssl']: if (('certificate' in config) and config['certificate']): read_file(config['certificate']) if (('client_cert' in config) and config['client_cert']): read_file(config['client_cert']) if (('client_key' in config) and config['client_key']): read_file(config['client_key'])
[ "def", "test_client_options", "(", "config", ")", ":", "if", "config", "[", "'use_ssl'", "]", ":", "if", "(", "(", "'certificate'", "in", "config", ")", "and", "config", "[", "'certificate'", "]", ")", ":", "read_file", "(", "config", "[", "'certificate'",...
test whether a ssl/tls files exist .
train
false
13,943
def dmp_trial_division(f, factors, u, K): result = [] for factor in factors: k = 0 while True: (q, r) = dmp_div(f, factor, u, K) if dmp_zero_p(r, u): (f, k) = (q, (k + 1)) else: break result.append((factor, k)) return _sort_factors(result)
[ "def", "dmp_trial_division", "(", "f", ",", "factors", ",", "u", ",", "K", ")", ":", "result", "=", "[", "]", "for", "factor", "in", "factors", ":", "k", "=", "0", "while", "True", ":", "(", "q", ",", "r", ")", "=", "dmp_div", "(", "f", ",", ...
determine multiplicities of factors using trial division .
train
false
13,945
def load_svmlight_file(f, n_features=None, dtype=np.float64, multilabel=False, zero_based='auto', query_id=False): return tuple(load_svmlight_files([f], n_features, dtype, multilabel, zero_based, query_id))
[ "def", "load_svmlight_file", "(", "f", ",", "n_features", "=", "None", ",", "dtype", "=", "np", ".", "float64", ",", "multilabel", "=", "False", ",", "zero_based", "=", "'auto'", ",", "query_id", "=", "False", ")", ":", "return", "tuple", "(", "load_svml...
load datasets in the svmlight / libsvm format into sparse csr matrix this format is a text-based format .
train
false
13,947
@overload(np.trace) def matrix_trace_impl(a, offset=types.int_): _check_linalg_matrix(a, 'trace', la_prefix=False) if (not isinstance(offset, types.Integer)): raise TypeError(('integer argument expected, got %s' % offset)) def matrix_trace_impl(a, offset=0): (rows, cols) = a.shape k = offset if (k < 0): rows = (rows + k) if (k > 0): cols = (cols - k) n = max(min(rows, cols), 0) ret = 0 if (k >= 0): for i in range(n): ret += a[(i, (k + i))] else: for i in range(n): ret += a[((i - k), i)] return ret return matrix_trace_impl
[ "@", "overload", "(", "np", ".", "trace", ")", "def", "matrix_trace_impl", "(", "a", ",", "offset", "=", "types", ".", "int_", ")", ":", "_check_linalg_matrix", "(", "a", ",", "'trace'", ",", "la_prefix", "=", "False", ")", "if", "(", "not", "isinstanc...
computes the trace of an array .
train
false
13,948
def getsavefilename(parent=None, caption='', basedir='', filters='', selectedfilter='', options=None): return _qfiledialog_wrapper('getSaveFileName', parent=parent, caption=caption, basedir=basedir, filters=filters, selectedfilter=selectedfilter, options=options)
[ "def", "getsavefilename", "(", "parent", "=", "None", ",", "caption", "=", "''", ",", "basedir", "=", "''", ",", "filters", "=", "''", ",", "selectedfilter", "=", "''", ",", "options", "=", "None", ")", ":", "return", "_qfiledialog_wrapper", "(", "'getSa...
wrapper around qtgui .
train
true
13,949
def enable_theming(): if hasattr(settings, 'COMPREHENSIVE_THEME_DIR'): logger.warning('\x1b[93m \nDeprecated: \n DCTB COMPREHENSIVE_THEME_DIR setting has been deprecated in favor of COMPREHENSIVE_THEME_DIRS.\x1b[00m') for theme in get_themes(): if (theme.themes_base_dir not in settings.MAKO_TEMPLATES['main']): settings.MAKO_TEMPLATES['main'].insert(0, theme.themes_base_dir) _add_theming_locales()
[ "def", "enable_theming", "(", ")", ":", "if", "hasattr", "(", "settings", ",", "'COMPREHENSIVE_THEME_DIR'", ")", ":", "logger", ".", "warning", "(", "'\\x1b[93m \\nDeprecated: \\n DCTB COMPREHENSIVE_THEME_DIR setting has been deprecated in favor of COMPREHENSIVE_THEME_DIRS.\\x1b[00...
add directories and relevant paths to settings for comprehensive theming .
train
false
13,950
def wiki_to_html(wiki_markup, locale=settings.WIKI_DEFAULT_LANGUAGE, nofollow=True): return WikiParser().parse(wiki_markup, show_toc=False, locale=locale, nofollow=nofollow)
[ "def", "wiki_to_html", "(", "wiki_markup", ",", "locale", "=", "settings", ".", "WIKI_DEFAULT_LANGUAGE", ",", "nofollow", "=", "True", ")", ":", "return", "WikiParser", "(", ")", ".", "parse", "(", "wiki_markup", ",", "show_toc", "=", "False", ",", "locale",...
wiki markup -> html jinja2 .
train
false
13,952
@logit def addition_func(x): return (x + x)
[ "@", "logit", "def", "addition_func", "(", "x", ")", ":", "return", "(", "x", "+", "x", ")" ]
do some math .
train
false
13,953
def test_hsl_to_rgb_part_16(): assert (hsl_to_rgb(180, 100, 0) == (0, 0, 0)) assert (hsl_to_rgb(180, 100, 10) == (0, 51, 51)) assert (hsl_to_rgb(180, 100, 20) == (0, 102, 102)) assert (hsl_to_rgb(180, 100, 30) == (0, 153, 153)) assert (hsl_to_rgb(180, 100, 40) == (0, 204, 204)) assert (hsl_to_rgb(180, 100, 50) == (0, 255, 255)) assert (hsl_to_rgb(180, 100, 60) == (51, 255, 255)) assert (hsl_to_rgb(180, 100, 70) == (102, 255, 255)) assert (hsl_to_rgb(180, 100, 80) == (153, 255, 255)) assert (hsl_to_rgb(180, 100, 90) == (204, 255, 255)) assert (hsl_to_rgb(180, 100, 100) == (255, 255, 255))
[ "def", "test_hsl_to_rgb_part_16", "(", ")", ":", "assert", "(", "hsl_to_rgb", "(", "180", ",", "100", ",", "0", ")", "==", "(", "0", ",", "0", ",", "0", ")", ")", "assert", "(", "hsl_to_rgb", "(", "180", ",", "100", ",", "10", ")", "==", "(", "...
test hsl to rgb color function .
train
false
13,954
def platform_encode(p): if isinstance(p, str): try: return p.decode('utf-8') except: return p.decode(codepage, errors='replace').replace('?', '!') else: return p
[ "def", "platform_encode", "(", "p", ")", ":", "if", "isinstance", "(", "p", ",", "str", ")", ":", "try", ":", "return", "p", ".", "decode", "(", "'utf-8'", ")", "except", ":", "return", "p", ".", "decode", "(", "codepage", ",", "errors", "=", "'rep...
return unicode name .
train
false
13,956
def assignCrowdingDist(individuals): if (len(individuals) == 0): return distances = ([0.0] * len(individuals)) crowd = [(ind.fitness.values, i) for (i, ind) in enumerate(individuals)] nobj = len(individuals[0].fitness.values) for i in xrange(nobj): crowd.sort(key=(lambda element: element[0][i])) distances[crowd[0][1]] = float('inf') distances[crowd[(-1)][1]] = float('inf') if (crowd[(-1)][0][i] == crowd[0][0][i]): continue norm = (nobj * float((crowd[(-1)][0][i] - crowd[0][0][i]))) for (prev, cur, next) in zip(crowd[:(-2)], crowd[1:(-1)], crowd[2:]): distances[cur[1]] += ((next[0][i] - prev[0][i]) / norm) for (i, dist) in enumerate(distances): individuals[i].fitness.crowding_dist = dist
[ "def", "assignCrowdingDist", "(", "individuals", ")", ":", "if", "(", "len", "(", "individuals", ")", "==", "0", ")", ":", "return", "distances", "=", "(", "[", "0.0", "]", "*", "len", "(", "individuals", ")", ")", "crowd", "=", "[", "(", "ind", "....
assign a crowding distance to each individuals fitness .
train
false
13,957
def get_max_memberships_for_project(project): if (project.owner is None): return None if project.is_private: return project.owner.max_memberships_private_projects return project.owner.max_memberships_public_projects
[ "def", "get_max_memberships_for_project", "(", "project", ")", ":", "if", "(", "project", ".", "owner", "is", "None", ")", ":", "return", "None", "if", "project", ".", "is_private", ":", "return", "project", ".", "owner", ".", "max_memberships_private_projects",...
return tha maximun of membersh for a concrete project .
train
false
13,958
def _get_next_name(names, name): indexes = [int(a.group(2)) for x in names for a in re.finditer('(^{} \\()(\\d{{1,}})(\\)$)'.format(name), x)] if ((name not in names) and (not indexes)): return name return '{} ({})'.format(name, (max(indexes, default=1) + 1))
[ "def", "_get_next_name", "(", "names", ",", "name", ")", ":", "indexes", "=", "[", "int", "(", "a", ".", "group", "(", "2", ")", ")", "for", "x", "in", "names", "for", "a", "in", "re", ".", "finditer", "(", "'(^{} \\\\()(\\\\d{{1,}})(\\\\)$)'", ".", ...
returns next possible attribute name .
train
false
13,960
def _rewrite_saxena_1(fac, po, g, x): (_, s) = _get_coeff_exp(po, x) (a, b) = _get_coeff_exp(g.argument, x) period = g.get_period() a = _my_principal_branch(a, period) C = (fac / (abs(b) * (a ** (((s + 1) / b) - 1)))) def tr(l): return [((a + ((1 + s) / b)) - 1) for a in l] return (C, meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), (a * x)))
[ "def", "_rewrite_saxena_1", "(", "fac", ",", "po", ",", "g", ",", "x", ")", ":", "(", "_", ",", "s", ")", "=", "_get_coeff_exp", "(", "po", ",", "x", ")", "(", "a", ",", "b", ")", "=", "_get_coeff_exp", "(", "g", ".", "argument", ",", "x", ")...
rewrite the integral fac*po*g dx .
train
false
13,961
def normalizeNewline(text): text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') return NEWLINES_REGEX.sub('\n', text)
[ "def", "normalizeNewline", "(", "text", ")", ":", "text", "=", "text", ".", "replace", "(", "'\\r\\n'", ",", "'\\n'", ")", "text", "=", "text", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "return", "NEWLINES_REGEX", ".", "sub", "(", "'\\n'", ",", ...
replace windows and mac newlines with unix newlines .
train
false
13,963
@click.command(u'new-site') @click.argument(u'site') @click.option(u'--db-name', help=u'Database name') @click.option(u'--mariadb-root-username', default=u'root', help=u'Root username for MariaDB') @click.option(u'--mariadb-root-password', help=u'Root password for MariaDB') @click.option(u'--admin-password', help=u'Administrator password for new site', default=None) @click.option(u'--verbose', is_flag=True, default=False, help=u'Verbose') @click.option(u'--force', help=u'Force restore if site/database already exists', is_flag=True, default=False) @click.option(u'--source_sql', help=u'Initiate database with a SQL file') @click.option(u'--install-app', multiple=True, help=u'Install app after installation') def new_site(site, mariadb_root_username=None, mariadb_root_password=None, admin_password=None, verbose=False, install_apps=None, source_sql=None, force=None, install_app=None, db_name=None): frappe.init(site=site, new_site=True) _new_site(db_name, site, mariadb_root_username=mariadb_root_username, mariadb_root_password=mariadb_root_password, admin_password=admin_password, verbose=verbose, install_apps=install_app, source_sql=source_sql, force=force) if (len(frappe.utils.get_sites()) == 1): use(site)
[ "@", "click", ".", "command", "(", "u'new-site'", ")", "@", "click", ".", "argument", "(", "u'site'", ")", "@", "click", ".", "option", "(", "u'--db-name'", ",", "help", "=", "u'Database name'", ")", "@", "click", ".", "option", "(", "u'--mariadb-root-user...
create a new site in the bench .
train
false
13,964
def kernel_integrity(attrs=None, where=None): if (__grains__['os_family'] in ['RedHat', 'Debian']): return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where) return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
[ "def", "kernel_integrity", "(", "attrs", "=", "None", ",", "where", "=", "None", ")", ":", "if", "(", "__grains__", "[", "'os_family'", "]", "in", "[", "'RedHat'", ",", "'Debian'", "]", ")", ":", "return", "_osquery_cmd", "(", "table", "=", "'kernel_inte...
return kernel_integrity information from osquery cli example: .
train
true
13,965
@frappe.whitelist() def install_app(name): frappe.only_for(u'System Manager') if (name not in frappe.get_all_apps(True)): if (not frappe.conf.disallow_app_listing): get_app(name) frappe.cache().delete_value([u'app_hooks']) import site reload(site) else: frappe.throw(u'Listing app not allowed') app_hooks = frappe.get_hooks(app_name=name) if app_hooks.get(u'hide_in_installer'): frappe.throw(_(u'You cannot install this app')) enqueue(u'frappe.desk.page.applications.applications.start_install', name=name) frappe.msgprint(_(u'Queued for install'))
[ "@", "frappe", ".", "whitelist", "(", ")", "def", "install_app", "(", "name", ")", ":", "frappe", ".", "only_for", "(", "u'System Manager'", ")", "if", "(", "name", "not", "in", "frappe", ".", "get_all_apps", "(", "True", ")", ")", ":", "if", "(", "n...
install a new app to site .
train
false
13,967
def convert_time(time, result_format='number', exclude_millis=False): return Time(time).convert(result_format, millis=is_falsy(exclude_millis))
[ "def", "convert_time", "(", "time", ",", "result_format", "=", "'number'", ",", "exclude_millis", "=", "False", ")", ":", "return", "Time", "(", "time", ")", ".", "convert", "(", "result_format", ",", "millis", "=", "is_falsy", "(", "exclude_millis", ")", ...
convert a time in seconds into the biggest unit .
train
false
13,968
def AmericanDateToEpoch(date_str): try: epoch = time.strptime(date_str, '%m/%d/%Y') return (int(calendar.timegm(epoch)) * 1000000) except ValueError: return 0
[ "def", "AmericanDateToEpoch", "(", "date_str", ")", ":", "try", ":", "epoch", "=", "time", ".", "strptime", "(", "date_str", ",", "'%m/%d/%Y'", ")", "return", "(", "int", "(", "calendar", ".", "timegm", "(", "epoch", ")", ")", "*", "1000000", ")", "exc...
take a us format date and return epoch .
train
true
13,970
@_held_figure def delaunay_plot_2d(tri, ax=None): if (tri.points.shape[1] != 2): raise ValueError('Delaunay triangulation is not 2-D') ax.plot(tri.points[:, 0], tri.points[:, 1], 'o') ax.triplot(tri.points[:, 0], tri.points[:, 1], tri.simplices.copy()) _adjust_bounds(ax, tri.points) return ax.figure
[ "@", "_held_figure", "def", "delaunay_plot_2d", "(", "tri", ",", "ax", "=", "None", ")", ":", "if", "(", "tri", ".", "points", ".", "shape", "[", "1", "]", "!=", "2", ")", ":", "raise", "ValueError", "(", "'Delaunay triangulation is not 2-D'", ")", "ax",...
plot the given delaunay triangulation in 2-d parameters tri : scipy .
train
false
13,971
def test_scenario_ptbr_from_string(): ptbr = Language('pt-br') scenario = Scenario.from_string(SCENARIO, language=ptbr) assert_equals(scenario.name, u'Consolidar o banco de dados de cursos universit\xe1rios em arquivo texto') assert_equals(scenario.steps[0].hashes, [{'Nome': u'Ci\xeancia da Computa\xe7\xe3o', u'Dura\xe7\xe3o': '5 anos'}, {'Nome': u'Nutri\xe7\xe3o', u'Dura\xe7\xe3o': '4 anos'}])
[ "def", "test_scenario_ptbr_from_string", "(", ")", ":", "ptbr", "=", "Language", "(", "'pt-br'", ")", "scenario", "=", "Scenario", ".", "from_string", "(", "SCENARIO", ",", "language", "=", "ptbr", ")", "assert_equals", "(", "scenario", ".", "name", ",", "u'...
language: pt-br -> scenario .
train
false
13,972
def get_class_from_str(class_path): (module_path, klass_name) = class_path.rsplit(u'.', 1) module = import_module(module_path) return getattr(module, klass_name)
[ "def", "get_class_from_str", "(", "class_path", ")", ":", "(", "module_path", ",", "klass_name", ")", "=", "class_path", ".", "rsplit", "(", "u'.'", ",", "1", ")", "module", "=", "import_module", "(", "module_path", ")", "return", "getattr", "(", "module", ...
dynamically load a view class from a string path "myapp .
train
false
13,973
def test_float_range(): assert (0.5 == float_range('0.5'))
[ "def", "test_float_range", "(", ")", ":", "assert", "(", "0.5", "==", "float_range", "(", "'0.5'", ")", ")" ]
assert that the tpot cli interfaces float range returns a float with input is in 0 .
train
false
13,974
def floating_ip_deallocate(context, address): return IMPL.floating_ip_deallocate(context, address)
[ "def", "floating_ip_deallocate", "(", "context", ",", "address", ")", ":", "return", "IMPL", ".", "floating_ip_deallocate", "(", "context", ",", "address", ")" ]
deallocate a floating ip by address .
train
false
13,975
def _is_nthpow_residue_bign_prime_power(a, n, p, k): if (a % p): if (p != 2): return _is_nthpow_residue_bign(a, n, pow(p, k)) if (n & 1): return True c = trailing(n) return ((a % pow(2, min((c + 2), k))) == 1) else: a %= pow(p, k) if (not a): return True mu = multiplicity(p, a) if (mu % n): return False pm = pow(p, mu) return _is_nthpow_residue_bign_prime_power((a // pm), n, p, (k - mu))
[ "def", "_is_nthpow_residue_bign_prime_power", "(", "a", ",", "n", ",", "p", ",", "k", ")", ":", "if", "(", "a", "%", "p", ")", ":", "if", "(", "p", "!=", "2", ")", ":", "return", "_is_nthpow_residue_bign", "(", "a", ",", "n", ",", "pow", "(", "p"...
returns true/false if a solution for x**n == a (mod) does/doesnt exist .
train
false
13,976
@nottest def get_ignored_tests(): return _get_tests('ignored.xml', NOSE_IGNORE_SELECTOR, NOSE_COLLECT_IGNORE_PARAMS)
[ "@", "nottest", "def", "get_ignored_tests", "(", ")", ":", "return", "_get_tests", "(", "'ignored.xml'", ",", "NOSE_IGNORE_SELECTOR", ",", "NOSE_COLLECT_IGNORE_PARAMS", ")" ]
collect all ignored tests and return them :return: a test suite as returned by xunitparser with all the tests available in the w3af framework source code .
train
false
13,977
def _make_set(var): if (var is None): return set() if (not isinstance(var, list)): if isinstance(var, str): var = var.split() else: var = list(var) return set(var)
[ "def", "_make_set", "(", "var", ")", ":", "if", "(", "var", "is", "None", ")", ":", "return", "set", "(", ")", "if", "(", "not", "isinstance", "(", "var", ",", "list", ")", ")", ":", "if", "isinstance", "(", "var", ",", "str", ")", ":", "var", ...
force var to be a set .
train
false
13,978
def float_range(value): try: value = float(value) except: raise argparse.ArgumentTypeError("Invalid float value: '{}'".format(value)) if ((value < 0.0) or (value > 1.0)): raise argparse.ArgumentTypeError("Invalid float value: '{}'".format(value)) return value
[ "def", "float_range", "(", "value", ")", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"Invalid float value: '{}'\"", ".", "format", "(", "value", ")", ")", "if", "(", "(", ...
ensures that the provided value is a float integer in the range [0 .
train
true
13,979
def get_casava_version(fastq1): if isinstance(fastq1, list): fastq_read_f_line1 = fastq1[0] else: fastq_read_f_line1 = fastq1.readline() fastq1.seek(0) post_casava_v180 = is_casava_v180_or_later(fastq_read_f_line1) if post_casava_v180: check_header_match_f = check_header_match_180_or_later else: check_header_match_f = check_header_match_pre180 return check_header_match_f
[ "def", "get_casava_version", "(", "fastq1", ")", ":", "if", "isinstance", "(", "fastq1", ",", "list", ")", ":", "fastq_read_f_line1", "=", "fastq1", "[", "0", "]", "else", ":", "fastq_read_f_line1", "=", "fastq1", ".", "readline", "(", ")", "fastq1", ".", ...
determine the version of casava that was used to generate the fastq fastq1: open fastq file or list of lines .
train
false
13,981
def key_entry_name_order(entry): return entry[0]
[ "def", "key_entry_name_order", "(", "entry", ")", ":", "return", "entry", "[", "0", "]" ]
sort key for tree entry in name order .
train
false
13,982
def move_to_element(browser, css_selector, header_height=155): wait_until_condition(browser, (lambda x: x.is_element_present_by_css(css_selector))) element = browser.driver.find_element_by_css_selector(css_selector) y = (element.location['y'] - header_height) browser.execute_script(('window.scrollTo(0, %s)' % y))
[ "def", "move_to_element", "(", "browser", ",", "css_selector", ",", "header_height", "=", "155", ")", ":", "wait_until_condition", "(", "browser", ",", "(", "lambda", "x", ":", "x", ".", "is_element_present_by_css", "(", "css_selector", ")", ")", ")", "element...
scroll the browser window to the element .
train
false
13,983
def list_saml_providers(region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: providers = [] info = conn.list_saml_providers() for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']: providers.append(arn['arn'].rsplit('/', 1)[1]) return providers except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) msg = 'Failed to get list of SAML providers.' log.error(msg) return False
[ "def", "list_saml_providers", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", ...
list saml providers .
train
true
13,984
def _get_host_disks(host_reference): storage_system = host_reference.configManager.storageSystem disks = storage_system.storageDeviceInfo.scsiLun ssds = [] non_ssds = [] for disk in disks: try: has_ssd_attr = disk.ssd except AttributeError: has_ssd_attr = False if has_ssd_attr: ssds.append(disk) else: non_ssds.append(disk) return {'SSDs': ssds, 'Non-SSDs': non_ssds}
[ "def", "_get_host_disks", "(", "host_reference", ")", ":", "storage_system", "=", "host_reference", ".", "configManager", ".", "storageSystem", "disks", "=", "storage_system", ".", "storageDeviceInfo", ".", "scsiLun", "ssds", "=", "[", "]", "non_ssds", "=", "[", ...
helper function that returns a dictionary containing a list of ssd and non-ssd disks .
train
true
13,986
def _normalize_string(orig): return orig.replace('"', '').replace("'", '').strip()
[ "def", "_normalize_string", "(", "orig", ")", ":", "return", "orig", ".", "replace", "(", "'\"'", ",", "''", ")", ".", "replace", "(", "\"'\"", ",", "''", ")", ".", "strip", "(", ")" ]
helper function for _get_systemd_os_release_var() to remove quotes and whitespaces .
train
false
13,987
def host_subplot(*args, **kwargs): import matplotlib.pyplot as plt axes_class = kwargs.pop(u'axes_class', None) host_subplot_class = host_subplot_class_factory(axes_class) fig = kwargs.get(u'figure', None) if (fig is None): fig = plt.gcf() ax = host_subplot_class(fig, *args, **kwargs) fig.add_subplot(ax) plt.draw_if_interactive() return ax
[ "def", "host_subplot", "(", "*", "args", ",", "**", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "axes_class", "=", "kwargs", ".", "pop", "(", "u'axes_class'", ",", "None", ")", "host_subplot_class", "=", "host_subplot_class_factory"...
create a subplot that can act as a host to parasitic axes .
train
false
13,988
def post_view(request): if (request.method == 'POST'): if request.POST: t = Template('Data received: {{ data }} is the value.', name='POST Template') c = Context({'data': request.POST['value']}) else: t = Template('Viewing POST page.', name='Empty POST Template') c = Context() else: t = Template('Viewing GET page.', name='Empty GET Template') c = Context() return HttpResponse(t.render(c))
[ "def", "post_view", "(", "request", ")", ":", "if", "(", "request", ".", "method", "==", "'POST'", ")", ":", "if", "request", ".", "POST", ":", "t", "=", "Template", "(", "'Data received: {{ data }} is the value.'", ",", "name", "=", "'POST Template'", ")", ...
a view that expects a post .
train
false
13,990
def write_float_matrix(fid, kind, mat): FIFFT_MATRIX = (1 << 30) FIFFT_MATRIX_FLOAT = (FIFF.FIFFT_FLOAT | FIFFT_MATRIX) data_size = ((4 * mat.size) + (4 * (mat.ndim + 1))) fid.write(np.array(kind, dtype='>i4').tostring()) fid.write(np.array(FIFFT_MATRIX_FLOAT, dtype='>i4').tostring()) fid.write(np.array(data_size, dtype='>i4').tostring()) fid.write(np.array(FIFF.FIFFV_NEXT_SEQ, dtype='>i4').tostring()) fid.write(np.array(mat, dtype='>f4').tostring()) dims = np.empty((mat.ndim + 1), dtype=np.int32) dims[:mat.ndim] = mat.shape[::(-1)] dims[(-1)] = mat.ndim fid.write(np.array(dims, dtype='>i4').tostring()) check_fiff_length(fid)
[ "def", "write_float_matrix", "(", "fid", ",", "kind", ",", "mat", ")", ":", "FIFFT_MATRIX", "=", "(", "1", "<<", "30", ")", "FIFFT_MATRIX_FLOAT", "=", "(", "FIFF", ".", "FIFFT_FLOAT", "|", "FIFFT_MATRIX", ")", "data_size", "=", "(", "(", "4", "*", "mat...
write a single-precision floating-point matrix tag .
train
false
13,992
def _showwarning(message, category, filename, lineno, file=None, line=None): if (file is not None): if (_warnings_showwarning is not None): _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger('py.warnings') if (not logger.handlers): logger.addHandler(NullHandler()) logger.warning('%s', s)
[ "def", "_showwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "file", "=", "None", ",", "line", "=", "None", ")", ":", "if", "(", "file", "is", "not", "None", ")", ":", "if", "(", "_warnings_showwarning", "is", "not", "...
implementation of showwarnings which redirects to logging .
train
false
13,993
def test_half_pie(): pie = Pie() pie.add('IE', 19.5) pie.add('Firefox', 36.6) pie.add('Chrome', 36.3) pie.add('Safari', 4.5) pie.add('Opera', 2.3) half = Pie(half_pie=True) half.add('IE', 19.5) half.add('Firefox', 36.6) half.add('Chrome', 36.3) half.add('Safari', 4.5) half.add('Opera', 2.3) assert (pie.render() != half.render())
[ "def", "test_half_pie", "(", ")", ":", "pie", "=", "Pie", "(", ")", "pie", ".", "add", "(", "'IE'", ",", "19.5", ")", "pie", ".", "add", "(", "'Firefox'", ",", "36.6", ")", "pie", ".", "add", "(", "'Chrome'", ",", "36.3", ")", "pie", ".", "add"...
test a half pie chart .
train
false
13,994
def long_int(hash_key): if (sys.version_info < (3,)): return long(hash_key) else: return int(hash_key)
[ "def", "long_int", "(", "hash_key", ")", ":", "if", "(", "sys", ".", "version_info", "<", "(", "3", ",", ")", ")", ":", "return", "long", "(", "hash_key", ")", "else", ":", "return", "int", "(", "hash_key", ")" ]
the hash key is a 128-bit int .
train
false
13,995
@contextmanager def hard_exit_handler(): try: (yield) except HardSystemExit: os._exit(0)
[ "@", "contextmanager", "def", "hard_exit_handler", "(", ")", ":", "try", ":", "(", "yield", ")", "except", "HardSystemExit", ":", "os", ".", "_exit", "(", "0", ")" ]
an exit helper for the daemon/forkd context that provides for deferred os .
train
false
13,996
@task @needs('pavelib.prereqs.install_prereqs') @cmdopts([('settings=', 's', 'Django settings'), ('asset-settings=', 'a', ASSET_SETTINGS_HELP), ('port=', 'p', 'Port'), ('fast', 'f', 'Skip updating assets')]) def lms(options): settings = getattr(options, 'settings', DEFAULT_SETTINGS) asset_settings = getattr(options, 'asset-settings', settings) port = getattr(options, 'port', None) fast = getattr(options, 'fast', False) run_server('lms', fast=fast, settings=settings, asset_settings=asset_settings, port=port)
[ "@", "task", "@", "needs", "(", "'pavelib.prereqs.install_prereqs'", ")", "@", "cmdopts", "(", "[", "(", "'settings='", ",", "'s'", ",", "'Django settings'", ")", ",", "(", "'asset-settings='", ",", "'a'", ",", "ASSET_SETTINGS_HELP", ")", ",", "(", "'port='", ...
run the lms server .
train
false
13,997
def slice2gridspec(key): if ((len(key) != 2) or (not isinstance(key[0], slice)) or (not isinstance(key[1], slice))): raise ValueError('only 2-D slices, please') x0 = key[1].start x1 = key[1].stop xstep = key[1].step if ((not isinstance(xstep, complex)) or (int(xstep.real) != xstep.real)): raise ValueError('only the [start:stop:numsteps*1j] form supported') xstep = int(xstep.imag) y0 = key[0].start y1 = key[0].stop ystep = key[0].step if ((not isinstance(ystep, complex)) or (int(ystep.real) != ystep.real)): raise ValueError('only the [start:stop:numsteps*1j] form supported') ystep = int(ystep.imag) return (x0, x1, xstep, y0, y1, ystep)
[ "def", "slice2gridspec", "(", "key", ")", ":", "if", "(", "(", "len", "(", "key", ")", "!=", "2", ")", "or", "(", "not", "isinstance", "(", "key", "[", "0", "]", ",", "slice", ")", ")", "or", "(", "not", "isinstance", "(", "key", "[", "1", "]...
convert a 2-tuple of slices to start .
train
false
13,998
def _clean_win_chars(string): import urllib if hasattr(urllib, 'quote'): quote = urllib.quote else: import urllib.parse quote = urllib.parse.quote for char in ('<', '>', '!', ':', '\\'): string = string.replace(char, quote(char)) return string
[ "def", "_clean_win_chars", "(", "string", ")", ":", "import", "urllib", "if", "hasattr", "(", "urllib", ",", "'quote'", ")", ":", "quote", "=", "urllib", ".", "quote", "else", ":", "import", "urllib", ".", "parse", "quote", "=", "urllib", ".", "parse", ...
windows cannot encode some characters in filename .
train
false
14,001
def BFS(gr, s): if (not gr.has_node(s)): raise Exception(('Node %s not in graph' % s)) nodes_explored = set([s]) q = deque([s]) while (len(q) != 0): node = q.popleft() for each in gr.neighbors(node): if (each not in nodes_explored): nodes_explored.add(each) q.append(each) return nodes_explored
[ "def", "BFS", "(", "gr", ",", "s", ")", ":", "if", "(", "not", "gr", ".", "has_node", "(", "s", ")", ")", ":", "raise", "Exception", "(", "(", "'Node %s not in graph'", "%", "s", ")", ")", "nodes_explored", "=", "set", "(", "[", "s", "]", ")", ...
breadth first search returns a list of nodes that are "findable" from s .
train
false
14,003
def set_event_transaction_id(new_id): get_cache('event_transaction')['id'] = UUID(new_id)
[ "def", "set_event_transaction_id", "(", "new_id", ")", ":", "get_cache", "(", "'event_transaction'", ")", "[", "'id'", "]", "=", "UUID", "(", "new_id", ")" ]
sets the event transaction id to a uuid object generated from new_id .
train
false
14,004
def getNewDerivation(elementNode): return evaluate.EmptyObject(elementNode)
[ "def", "getNewDerivation", "(", "elementNode", ")", ":", "return", "evaluate", ".", "EmptyObject", "(", "elementNode", ")" ]
get new derivation .
train
false
14,005
def activity_age_group(): return s3_rest_controller()
[ "def", "activity_age_group", "(", ")", ":", "return", "s3_rest_controller", "(", ")" ]
activity age groups: restful crud controller .
train
false
14,006
def test_ast_bad_yield(): cant_compile(u'(yield 1 2)')
[ "def", "test_ast_bad_yield", "(", ")", ":", "cant_compile", "(", "u'(yield 1 2)'", ")" ]
make sure ast cant compile invalid yield .
train
false
14,007
def _api_queue_default(output, value, kwargs): sort = kwargs.get('sort') direction = kwargs.get('dir', '') start = int_conv(kwargs.get('start')) limit = int_conv(kwargs.get('limit')) trans = kwargs.get('trans') search = kwargs.get('search') if (output in ('xml', 'json')): if (sort and (sort != 'index')): reverse = (direction.lower() == 'desc') sort_queue(sort, reverse) (info, pnfo_list, bytespersec) = build_queue(start=start, limit=limit, output=output, trans=trans, search=search) info['categories'] = info.pop('cat_list') info['scripts'] = info.pop('script_list') return report(output, keyword='queue', data=remove_callable(info)) elif (output == 'rss'): return rss_qstatus() else: return report(output, _MSG_NOT_IMPLEMENTED)
[ "def", "_api_queue_default", "(", "output", ",", "value", ",", "kwargs", ")", ":", "sort", "=", "kwargs", ".", "get", "(", "'sort'", ")", "direction", "=", "kwargs", ".", "get", "(", "'dir'", ",", "''", ")", "start", "=", "int_conv", "(", "kwargs", "...
api: accepts output .
train
false
14,009
def _aslist(obj): if (obj is None): return [] elif isinstance(obj, (list, tuple)): return obj else: return [obj]
[ "def", "_aslist", "(", "obj", ")", ":", "if", "(", "obj", "is", "None", ")", ":", "return", "[", "]", "elif", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "obj", "else", ":", "return", "[", "obj", "]" ]
turn object into a list; lists and tuples are left as-is .
train
false
14,010
def disable_print(): sys.stdout = None sys.stderr = os.devnull
[ "def", "disable_print", "(", ")", ":", "sys", ".", "stdout", "=", "None", "sys", ".", "stderr", "=", "os", ".", "devnull" ]
disable console output .
train
false
14,011
def modal(image, selem, out=None, mask=None, shift_x=False, shift_y=False): return _apply_scalar_per_pixel(generic_cy._modal, image, selem, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y)
[ "def", "modal", "(", "image", ",", "selem", ",", "out", "=", "None", ",", "mask", "=", "None", ",", "shift_x", "=", "False", ",", "shift_y", "=", "False", ")", ":", "return", "_apply_scalar_per_pixel", "(", "generic_cy", ".", "_modal", ",", "image", ",...
return local mode of an image .
train
false
14,012
def condense_whitespace(css): return re.sub('\\s+', ' ', css)
[ "def", "condense_whitespace", "(", "css", ")", ":", "return", "re", ".", "sub", "(", "'\\\\s+'", ",", "' '", ",", "css", ")" ]
condense multiple adjacent whitespace characters into one .
train
false
14,013
def _set_persistent_module(mod): if ((not mod) or (mod in mod_list(True)) or (mod not in available())): return set() __salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod)) return set([mod])
[ "def", "_set_persistent_module", "(", "mod", ")", ":", "if", "(", "(", "not", "mod", ")", "or", "(", "mod", "in", "mod_list", "(", "True", ")", ")", "or", "(", "mod", "not", "in", "available", "(", ")", ")", ")", ":", "return", "set", "(", ")", ...
add module to configuration file to make it persistent .
train
true
14,014
def get_permission_labels(): for plugin in plugins.PluginImplementations(plugins.IPermissionLabels): return plugin return DefaultPermissionLabels()
[ "def", "get_permission_labels", "(", ")", ":", "for", "plugin", "in", "plugins", ".", "PluginImplementations", "(", "plugins", ".", "IPermissionLabels", ")", ":", "return", "plugin", "return", "DefaultPermissionLabels", "(", ")" ]
return the permission label plugin .
train
false
14,015
def _parseClientTCP(**kwargs): kwargs['port'] = int(kwargs['port']) try: kwargs['timeout'] = int(kwargs['timeout']) except KeyError: pass return kwargs
[ "def", "_parseClientTCP", "(", "**", "kwargs", ")", ":", "kwargs", "[", "'port'", "]", "=", "int", "(", "kwargs", "[", "'port'", "]", ")", "try", ":", "kwargs", "[", "'timeout'", "]", "=", "int", "(", "kwargs", "[", "'timeout'", "]", ")", "except", ...
perform any argument value coercion necessary for tcp client parameters .
train
false
14,016
def test_kmeans(): X = np.random.random(size=(100, 10)) Y = np.random.randint(5, size=(100, 1)) dataset = DenseDesignMatrix(X, y=Y) model = KMeans(k=5, nvis=10) train = Train(model=model, dataset=dataset) train.main_loop()
[ "def", "test_kmeans", "(", ")", ":", "X", "=", "np", ".", "random", ".", "random", "(", "size", "=", "(", "100", ",", "10", ")", ")", "Y", "=", "np", ".", "random", ".", "randint", "(", "5", ",", "size", "=", "(", "100", ",", "1", ")", ")",...
tests kmeans .
train
false
14,017
def remove_volumes(paths): errors = [] for path in paths: clear_volume(path) lvremove = ('lvremove', '-f', path) try: utils.execute(attempts=3, run_as_root=True, *lvremove) except processutils.ProcessExecutionError as exp: errors.append(six.text_type(exp)) if errors: raise exception.VolumesNotRemoved(reason=', '.join(errors))
[ "def", "remove_volumes", "(", "paths", ")", ":", "errors", "=", "[", "]", "for", "path", "in", "paths", ":", "clear_volume", "(", "path", ")", "lvremove", "=", "(", "'lvremove'", ",", "'-f'", ",", "path", ")", "try", ":", "utils", ".", "execute", "("...
remove one or more logical volume .
train
false
14,019
def sanitize_prefix(function): @functools.wraps(function) def wrapper(*args, **kwargs): args = list(args) offset = 1 if ('prefix' in kwargs): kwargs['prefix'] = name_or_value(kwargs['prefix']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) offset += 1 if ('key' in kwargs): kwargs['key'] = name_or_value(kwargs['key']) elif ((len(args) - 1) >= offset): args[offset] = name_or_value(args[offset]) return function(*tuple(args), **kwargs) return wrapper
[ "def", "sanitize_prefix", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "offset", "=", "1", "if", "(", "'pr...
automatically call name_or_value on the prefix passed in .
train
false
14,020
def version2float(s): s = s.split('-')[0] s = '.'.join(s.split('.')[:2]) s = ''.join((c for c in s if (c.isdigit() or (c == '.')))) return float(s)
[ "def", "version2float", "(", "s", ")", ":", "s", "=", "s", ".", "split", "(", "'-'", ")", "[", "0", "]", "s", "=", "'.'", ".", "join", "(", "s", ".", "split", "(", "'.'", ")", "[", ":", "2", "]", ")", "s", "=", "''", ".", "join", "(", "...
converts a version string to a float suitable for sorting .
train
false
14,021
def test_fnpickling_protocol(tmpdir): import pickle obj1 = 'astring' obj2 = ToBePickled(obj1) for p in range((pickle.HIGHEST_PROTOCOL + 1)): fn = str(tmpdir.join('testp{}.pickle'.format(p))) fnpickle(obj2, fn, protocol=p) res = fnunpickle(fn) assert (res == obj2)
[ "def", "test_fnpickling_protocol", "(", "tmpdir", ")", ":", "import", "pickle", "obj1", "=", "'astring'", "obj2", "=", "ToBePickled", "(", "obj1", ")", "for", "p", "in", "range", "(", "(", "pickle", ".", "HIGHEST_PROTOCOL", "+", "1", ")", ")", ":", "fn",...
tests the fnpickle and fnupickle functions ability to pickle and unpickle pickle files from all protcols .
train
false
14,022
def finish_fsdev(force_cleanup=False): if ((FSDEV_PREP_CNT == 1) or force_cleanup): restore_disks(job=FSDEV_JOB, restore=FSDEV_RESTORE, disk_list=FSDEV_DISKLIST)
[ "def", "finish_fsdev", "(", "force_cleanup", "=", "False", ")", ":", "if", "(", "(", "FSDEV_PREP_CNT", "==", "1", ")", "or", "force_cleanup", ")", ":", "restore_disks", "(", "job", "=", "FSDEV_JOB", ",", "restore", "=", "FSDEV_RESTORE", ",", "disk_list", "...
this method can be called from the test file to optionally restore all the drives used by the test to a standard ext2 format .
train
false
14,023
def isInsideOtherLoops(loopIndex, loops): return isPathInsideLoops((loops[:loopIndex] + loops[(loopIndex + 1):]), loops[loopIndex])
[ "def", "isInsideOtherLoops", "(", "loopIndex", ",", "loops", ")", ":", "return", "isPathInsideLoops", "(", "(", "loops", "[", ":", "loopIndex", "]", "+", "loops", "[", "(", "loopIndex", "+", "1", ")", ":", "]", ")", ",", "loops", "[", "loopIndex", "]",...
determine if a loop in a list is inside another loop in that list .
train
false
14,025
@contextlib.contextmanager def on_error_print_details(actual, expected): try: (yield) except Exception: diff = difflib.ndiff(expected.splitlines(), actual.splitlines()) diff_text = u'\n'.join(diff) print(u'DIFF (+ ACTUAL, - EXPECTED):\n{0}\n'.format(diff_text)) if DEBUG: print(u'expected:\n{0}\n'.format(expected)) print(u'actual:\n{0}'.format(actual)) raise
[ "@", "contextlib", ".", "contextmanager", "def", "on_error_print_details", "(", "actual", ",", "expected", ")", ":", "try", ":", "(", "yield", ")", "except", "Exception", ":", "diff", "=", "difflib", ".", "ndiff", "(", "expected", ".", "splitlines", "(", "...
print text details in case of assertation failed errors .
train
false
14,026
def granular_now(n=None, default_tz=None): if (n is None): n = timezone.now() if (default_tz is None): default_tz = n.tzinfo rounded_minute = ((n.minute // 5) * 5) d = datetime(n.year, n.month, n.day, n.hour, rounded_minute) try: retval = timezone.make_aware(d, default_tz) except AmbiguousTimeError: try: retval = timezone.make_aware(d, default_tz, is_dst=False) except TypeError: retval = timezone.make_aware(datetime(n.year, n.month, n.day, (n.hour + 1), rounded_minute), default_tz) return retval
[ "def", "granular_now", "(", "n", "=", "None", ",", "default_tz", "=", "None", ")", ":", "if", "(", "n", "is", "None", ")", ":", "n", "=", "timezone", ".", "now", "(", ")", "if", "(", "default_tz", "is", "None", ")", ":", "default_tz", "=", "n", ...
a datetime .
train
false
14,027
def test_page(): data.page()
[ "def", "test_page", "(", ")", ":", "data", ".", "page", "(", ")" ]
test that "page" image can be loaded .
train
false
14,028
def cidr_netmask(cidr): ips = netaddr.IPNetwork(cidr) return str(ips.netmask)
[ "def", "cidr_netmask", "(", "cidr", ")", ":", "ips", "=", "netaddr", ".", "IPNetwork", "(", "cidr", ")", "return", "str", "(", "ips", ".", "netmask", ")" ]
get the netmask address associated with a cidr address .
train
false
14,032
def yesterday(): date = datetime.datetime.now() date -= datetime.timedelta(days=1) date_tuple = date.timetuple()[:6] return date_tuple
[ "def", "yesterday", "(", ")", ":", "date", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "date", "-=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "date_tuple", "=", "date", ".", "timetuple", "(", ")", "[", ":", "6", "]", ...
get yesterdays datetime as a 5-tuple .
train
false
14,036
@commands(u'getchanneltimeformat', u'getctf') @example(u'.getctf [channel]') def get_channel_format(bot, trigger): channel = trigger.group(2) if (not channel): channel = trigger.sender channel = channel.strip() tformat = bot.db.get_channel_value(channel, u'time_format') if tformat: bot.say((u"%s's time format: %s" % (channel, tformat))) else: bot.say((u'%s has no preferred time format' % channel))
[ "@", "commands", "(", "u'getchanneltimeformat'", ",", "u'getctf'", ")", "@", "example", "(", "u'.getctf [channel]'", ")", "def", "get_channel_format", "(", "bot", ",", "trigger", ")", ":", "channel", "=", "trigger", ".", "group", "(", "2", ")", "if", "(", ...
gets the channels preferred time format .
train
false
14,037
def _dipole_forwards(fwd_data, whitener, rr, n_jobs=1): B = _compute_forwards_meeg(rr, fwd_data, n_jobs, verbose=False) B = np.concatenate(B, axis=1) B_orig = B.copy() B = np.dot(B, whitener.T) scales = np.ones(3) return (B, B_orig, scales)
[ "def", "_dipole_forwards", "(", "fwd_data", ",", "whitener", ",", "rr", ",", "n_jobs", "=", "1", ")", ":", "B", "=", "_compute_forwards_meeg", "(", "rr", ",", "fwd_data", ",", "n_jobs", ",", "verbose", "=", "False", ")", "B", "=", "np", ".", "concatena...
compute the forward solution and do other nice stuff .
train
false
14,039
def sinm(A): A = _asarray_square(A) if np.iscomplexobj(A): return ((-0.5j) * (expm((1j * A)) - expm(((-1j) * A)))) else: return expm((1j * A)).imag
[ "def", "sinm", "(", "A", ")", ":", "A", "=", "_asarray_square", "(", "A", ")", "if", "np", ".", "iscomplexobj", "(", "A", ")", ":", "return", "(", "(", "-", "0.5j", ")", "*", "(", "expm", "(", "(", "1j", "*", "A", ")", ")", "-", "expm", "("...
compute the matrix sine .
train
false
14,040
def _parse_template(tmpl_str): tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = json.loads(tmpl_str) else: try: tpl = yaml.load(tmpl_str, Loader=YamlLoader) except yaml.YAMLError: try: tpl = yaml.load(tmpl_str, Loader=yaml.SafeLoader) except yaml.YAMLError as yea: raise ValueError(yea) else: if (tpl is None): tpl = {} if (not (('HeatTemplateFormatVersion' in tpl) or ('heat_template_version' in tpl) or ('AWSTemplateFormatVersion' in tpl))): raise ValueError('Template format version not found.') return tpl
[ "def", "_parse_template", "(", "tmpl_str", ")", ":", "tmpl_str", "=", "tmpl_str", ".", "strip", "(", ")", "if", "tmpl_str", ".", "startswith", "(", "'{'", ")", ":", "tpl", "=", "json", ".", "loads", "(", "tmpl_str", ")", "else", ":", "try", ":", "tpl...
parsing template .
train
false
14,042
def wheel_delta(event): if PYQT4: delta = event.delta() else: angle = event.angleDelta() x = angle.x() y = angle.y() if (abs(x) > abs(y)): delta = x else: delta = y return delta
[ "def", "wheel_delta", "(", "event", ")", ":", "if", "PYQT4", ":", "delta", "=", "event", ".", "delta", "(", ")", "else", ":", "angle", "=", "event", ".", "angleDelta", "(", ")", "x", "=", "angle", ".", "x", "(", ")", "y", "=", "angle", ".", "y"...
return a single wheel delta .
train
false
14,044
def RemoveSubtypeAnnotation(node, value): attr = GetNodeAnnotation(node, Annotation.SUBTYPE) if (attr and (value in attr)): attr.remove(value) SetNodeAnnotation(node, Annotation.SUBTYPE, attr)
[ "def", "RemoveSubtypeAnnotation", "(", "node", ",", "value", ")", ":", "attr", "=", "GetNodeAnnotation", "(", "node", ",", "Annotation", ".", "SUBTYPE", ")", "if", "(", "attr", "and", "(", "value", "in", "attr", ")", ")", ":", "attr", ".", "remove", "(...
removes an annotation value from the subtype annotations on the node .
train
false
14,045
def parse_distmat_to_dict(table): (col_headers, row_headers, data) = parse_matrix(table) assert (col_headers == row_headers) result = defaultdict(dict) for (sample_id_x, row) in zip(col_headers, data): for (sample_id_y, value) in zip(row_headers, row): result[sample_id_x][sample_id_y] = value return result
[ "def", "parse_distmat_to_dict", "(", "table", ")", ":", "(", "col_headers", ",", "row_headers", ",", "data", ")", "=", "parse_matrix", "(", "table", ")", "assert", "(", "col_headers", "==", "row_headers", ")", "result", "=", "defaultdict", "(", "dict", ")", ...
parse a dist matrix into an 2d dict indexed by sample ids .
train
false
14,046
def collapseStrings(results): copy = [] begun = None listsList = [isinstance(s, list) for s in results] pred = (lambda e: isinstance(e, tuple)) tran = {0: (lambda e: splitQuoted(''.join(e))), 1: (lambda e: [''.join([i[0] for i in e])])} for (i, c, isList) in zip(list(range(len(results))), results, listsList): if isList: if (begun is not None): copy.extend(splitOn(results[begun:i], pred, tran)) begun = None copy.append(collapseStrings(c)) elif (begun is None): begun = i if (begun is not None): copy.extend(splitOn(results[begun:], pred, tran)) return copy
[ "def", "collapseStrings", "(", "results", ")", ":", "copy", "=", "[", "]", "begun", "=", "None", "listsList", "=", "[", "isinstance", "(", "s", ",", "list", ")", "for", "s", "in", "results", "]", "pred", "=", "(", "lambda", "e", ":", "isinstance", ...
turns a list of length-one strings and lists into a list of longer strings and lists .
train
false
14,047
def compile_(source, filename=None, mode='exec', flags=generators.compiler_flag, dont_inherit=0): if ((_ast is not None) and isinstance(source, _ast.AST)): return cpy_compile(source, filename, mode, flags, dont_inherit) _genframe = sys._getframe(1) s = Source(source) co = s.compile(filename, mode, flags, _genframe=_genframe) return co
[ "def", "compile_", "(", "source", ",", "filename", "=", "None", ",", "mode", "=", "'exec'", ",", "flags", "=", "generators", ".", "compiler_flag", ",", "dont_inherit", "=", "0", ")", ":", "if", "(", "(", "_ast", "is", "not", "None", ")", "and", "isin...
compile the given source to a raw code object .
train
false
14,048
def read_zfile(file_handle): file_handle.seek(0) header_length = (len(_ZFILE_PREFIX) + _MAX_LEN) length = file_handle.read(header_length) length = length[len(_ZFILE_PREFIX):] length = int(length, 16) next_byte = file_handle.read(1) if (next_byte != ' '): file_handle.seek(header_length) data = zlib.decompress(file_handle.read(), 15, length) assert (len(data) == length), ('Incorrect data length while decompressing %s.The file could be corrupted.' % file_handle) return data
[ "def", "read_zfile", "(", "file_handle", ")", ":", "file_handle", ".", "seek", "(", "0", ")", "header_length", "=", "(", "len", "(", "_ZFILE_PREFIX", ")", "+", "_MAX_LEN", ")", "length", "=", "file_handle", ".", "read", "(", "header_length", ")", "length",...
read the z-file and return the content as a string .
train
false
14,049
def as_op(itypes, otypes, infer_shape=None): if (not isinstance(itypes, (list, tuple))): itypes = [itypes] if any(((not isinstance(t, theano.Type)) for t in itypes)): raise TypeError('itypes has to be a list of Theano types') if (not isinstance(otypes, (list, tuple))): otypes = [otypes] if any(((not isinstance(t, theano.Type)) for t in otypes)): raise TypeError('otypes has to be a list of Theano types') itypes = list(itypes) otypes = list(otypes) if ((infer_shape is not None) and (not callable(infer_shape))): raise TypeError('infer_shape needs to be a callable') def make_op(fn): return FromFunctionOp(fn, itypes, otypes, infer_shape) return make_op
[ "def", "as_op", "(", "itypes", ",", "otypes", ",", "infer_shape", "=", "None", ")", ":", "if", "(", "not", "isinstance", "(", "itypes", ",", "(", "list", ",", "tuple", ")", ")", ")", ":", "itypes", "=", "[", "itypes", "]", "if", "any", "(", "(", ...
decorator that converts a function into a basic theano op that will call the supplied function as its implementation .
train
false
14,050
def metadef_resource_type_delete(context, resource_type_name, session=None): session = (session or get_session()) return metadef_resource_type_api.delete(context, resource_type_name, session)
[ "def", "metadef_resource_type_delete", "(", "context", ",", "resource_type_name", ",", "session", "=", "None", ")", ":", "session", "=", "(", "session", "or", "get_session", "(", ")", ")", "return", "metadef_resource_type_api", ".", "delete", "(", "context", ","...
get a resource_type .
train
false
14,051
def MakeExponentialPmf(lam, high, n=200): pmf = Pmf() for x in np.linspace(0, high, n): p = EvalExponentialPdf(x, lam) pmf.Set(x, p) pmf.Normalize() return pmf
[ "def", "MakeExponentialPmf", "(", "lam", ",", "high", ",", "n", "=", "200", ")", ":", "pmf", "=", "Pmf", "(", ")", "for", "x", "in", "np", ".", "linspace", "(", "0", ",", "high", ",", "n", ")", ":", "p", "=", "EvalExponentialPdf", "(", "x", ","...
makes a pmf discrete approx to an exponential distribution .
train
true
14,052
def line_select_callback(eclick, erelease): (x1, y1) = (eclick.xdata, eclick.ydata) (x2, y2) = (erelease.xdata, erelease.ydata) print(('(%3.2f, %3.2f) --> (%3.2f, %3.2f)' % (x1, y1, x2, y2))) print((' The button you used were: %s %s' % (eclick.button, erelease.button)))
[ "def", "line_select_callback", "(", "eclick", ",", "erelease", ")", ":", "(", "x1", ",", "y1", ")", "=", "(", "eclick", ".", "xdata", ",", "eclick", ".", "ydata", ")", "(", "x2", ",", "y2", ")", "=", "(", "erelease", ".", "xdata", ",", "erelease", ...
eclick and erelease are the press and release events .
train
false
14,054
def list_subscribers(t): (owner, slug) = get_slug() rel = {} next_cursor = (-1) while (next_cursor != 0): m = t.lists.subscribers(slug=slug, owner_screen_name=owner, cursor=next_cursor, include_entities=False) for u in m['users']: rel[u['name']] = ('@' + u['screen_name']) next_cursor = m['next_cursor'] printNicely((('All: ' + str(len(rel))) + ' subscribers.')) for name in rel: user = (' ' + cycle_color(name)) user += color_func(c['TWEET']['nick'])(((' ' + rel[name]) + ' ')) printNicely(user)
[ "def", "list_subscribers", "(", "t", ")", ":", "(", "owner", ",", "slug", ")", "=", "get_slug", "(", ")", "rel", "=", "{", "}", "next_cursor", "=", "(", "-", "1", ")", "while", "(", "next_cursor", "!=", "0", ")", ":", "m", "=", "t", ".", "lists...
list subscribers .
train
false
14,057
def read_bytes(urlpath, delimiter=None, not_zero=False, blocksize=(2 ** 27), sample=True, compression=None, **kwargs): (fs, paths, myopen) = get_fs_paths_myopen(urlpath, compression, 'rb', None, **kwargs) client = None if (len(paths) == 0): raise IOError(('%s resolved to no files' % urlpath)) (blocks, lengths, machines) = fs.get_block_locations(paths) if blocks: offsets = blocks elif (blocksize is None): offsets = ([[0]] * len(paths)) lengths = ([[None]] * len(offsets)) machines = ([[None]] * len(offsets)) else: offsets = [] lengths = [] for path in paths: try: size = fs.logical_size(path, compression) except KeyError: raise ValueError(('Cannot read compressed files (%s) in byte chunks,use blocksize=None' % infer_compression(urlpath))) off = list(range(0, size, blocksize)) length = ([blocksize] * len(off)) if not_zero: off[0] = 1 length[0] -= 1 offsets.append(off) lengths.append(length) machines = ([[None]] * len(offsets)) out = [] for (path, offset, length, machine) in zip(paths, offsets, lengths, machines): ukey = fs.ukey(path) keys = [('read-block-%s-%s' % (o, tokenize(path, compression, offset, ukey, kwargs, delimiter))) for o in offset] L = [delayed(read_block_from_file)(myopen(path, mode='rb'), o, l, delimiter, dask_key_name=key) for (o, key, l) in zip(offset, keys, length)] out.append(L) if (machine is not None): if (client is None): try: from distributed.client import default_client client = default_client() except (ImportError, ValueError): client = False if client: restrictions = {key: w for (key, w) in zip(keys, machine)} client._send_to_scheduler({'op': 'update-graph', 'tasks': {}, 'dependencies': [], 'keys': [], 'restrictions': restrictions, 'loose_restrictions': list(restrictions), 'client': client.id}) if (sample is not True): nbytes = sample else: nbytes = 10000 if sample: with myopen(paths[0], 'rb') as f: sample = read_block(f, 0, nbytes, delimiter) return (sample, out)
[ "def", "read_bytes", "(", "urlpath", ",", "delimiter", "=", "None", ",", "not_zero", "=", "False", ",", "blocksize", "=", "(", "2", "**", "27", ")", ",", "sample", "=", "True", ",", "compression", "=", "None", ",", "**", "kwargs", ")", ":", "(", "f...
read tag data from file and return as byte string .
train
false
14,058
def _GenerateAccessToken(action, tester, device_dict, auth_info_dict, user_cookie=None, use_short_token=True): version = (message.MAX_SUPPORTED_MESSAGE_VERSION if use_short_token else message.Message.SUPPRESS_AUTH_NAME) url = tester.GetUrl(('/%s/viewfinder' % action)) request_dict = auth_test._CreateRegisterRequest(device_dict, auth_info_dict, version=version) response = auth_test._SendAuthRequest(tester, url, 'POST', user_cookie=user_cookie, request_dict=request_dict) return json.loads(response.body)
[ "def", "_GenerateAccessToken", "(", "action", ",", "tester", ",", "device_dict", ",", "auth_info_dict", ",", "user_cookie", "=", "None", ",", "use_short_token", "=", "True", ")", ":", "version", "=", "(", "message", ".", "MAX_SUPPORTED_MESSAGE_VERSION", "if", "u...
sends a request to the viewfinder auth service .
train
false
14,059
def console_create(context, values): return IMPL.console_create(context, values)
[ "def", "console_create", "(", "context", ",", "values", ")", ":", "return", "IMPL", ".", "console_create", "(", "context", ",", "values", ")" ]
create a console .
train
false
14,060
def ADXR(barDs, count, timeperiod=(- (2 ** 31))): return call_talib_with_hlc(barDs, count, talib.ADXR, timeperiod)
[ "def", "ADXR", "(", "barDs", ",", "count", ",", "timeperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ")", ":", "return", "call_talib_with_hlc", "(", "barDs", ",", "count", ",", "talib", ".", "ADXR", ",", "timeperiod", ")" ]
average directional movement index rating .
train
false
14,061
def _hash_internal(method, salt, password): if (method == 'plain'): return password if salt: if (method not in _hash_mods): return None if isinstance(salt, unicode): salt = salt.encode('utf-8') h = hmac.new(salt, None, _hash_mods[method]) else: if (method not in _hash_funcs): return None h = _hash_funcs[method]() if isinstance(password, unicode): password = password.encode('utf-8') h.update(password) return h.hexdigest()
[ "def", "_hash_internal", "(", "method", ",", "salt", ",", "password", ")", ":", "if", "(", "method", "==", "'plain'", ")", ":", "return", "password", "if", "salt", ":", "if", "(", "method", "not", "in", "_hash_mods", ")", ":", "return", "None", "if", ...
internal password hash helper .
train
false
14,062
def polygonsOverlap(poly1, poly2): try: poly1 = poly1.verticesPix except Exception: pass try: poly2 = poly2.verticesPix except Exception: pass if haveMatplotlib: if (matplotlib.__version__ > '1.2'): if any(mplPath(poly1).contains_points(poly2)): return True return any(mplPath(poly2).contains_points(poly1)) else: try: if any(nxutils.points_inside_poly(poly1, poly2)): return True return any(nxutils.points_inside_poly(poly2, poly1)) except Exception: pass for p1 in poly1: if pointInPolygon(p1[0], p1[1], poly2): return True for p2 in poly2: if pointInPolygon(p2[0], p2[1], poly1): return True return False
[ "def", "polygonsOverlap", "(", "poly1", ",", "poly2", ")", ":", "try", ":", "poly1", "=", "poly1", ".", "verticesPix", "except", "Exception", ":", "pass", "try", ":", "poly2", "=", "poly2", ".", "verticesPix", "except", "Exception", ":", "pass", "if", "h...
determine if two polygons intersect; can fail for very pointy polygons .
train
false
14,064
def _Pluralize(value, unused_context, args): if (len(args) == 0): (s, p) = ('', 's') elif (len(args) == 1): (s, p) = ('', args[0]) elif (len(args) == 2): (s, p) = args else: raise AssertionError if (value > 1): return p else: return s
[ "def", "_Pluralize", "(", "value", ",", "unused_context", ",", "args", ")", ":", "if", "(", "len", "(", "args", ")", "==", "0", ")", ":", "(", "s", ",", "p", ")", "=", "(", "''", ",", "'s'", ")", "elif", "(", "len", "(", "args", ")", "==", ...
formatter to pluralize words .
train
true
14,068
def backward(variables, grad_variables, retain_variables=False): Variable._execution_engine.run_backward(tuple(variables), tuple(grad_variables), retain_variables)
[ "def", "backward", "(", "variables", ",", "grad_variables", ",", "retain_variables", "=", "False", ")", ":", "Variable", ".", "_execution_engine", ".", "run_backward", "(", "tuple", "(", "variables", ")", ",", "tuple", "(", "grad_variables", ")", ",", "retain_...
a generator returning lines from a file starting with the last line .
train
false
14,069
@pytest.fixture def app_stub(stubs): stub = stubs.ApplicationStub() objreg.register('app', stub) (yield stub) objreg.delete('app')
[ "@", "pytest", ".", "fixture", "def", "app_stub", "(", "stubs", ")", ":", "stub", "=", "stubs", ".", "ApplicationStub", "(", ")", "objreg", ".", "register", "(", "'app'", ",", "stub", ")", "(", "yield", "stub", ")", "objreg", ".", "delete", "(", "'ap...
fixture which provides a fake app object .
train
false
14,070
def requirement_args(argv, want_paths=False, want_other=False): was_r = False for arg in argv: if was_r: if want_paths: (yield arg) was_r = False elif (arg in ['-r', '--requirement']): was_r = True elif want_other: (yield arg)
[ "def", "requirement_args", "(", "argv", ",", "want_paths", "=", "False", ",", "want_other", "=", "False", ")", ":", "was_r", "=", "False", "for", "arg", "in", "argv", ":", "if", "was_r", ":", "if", "want_paths", ":", "(", "yield", "arg", ")", "was_r", ...
return an iterable of filtered arguments .
train
true
14,071
def generate_notification_email_unsubscribe_token(user_id36, user_email=None, user_password_hash=None): import hashlib import hmac if ((not user_email) or (not user_password_hash)): user = Account._byID36(user_id36, data=True) if (not user_email): user_email = user.email if (not user_password_hash): user_password_hash = user.password return hmac.new(g.secrets['email_notifications'], ((user_id36 + user_email) + user_password_hash), hashlib.sha256).hexdigest()
[ "def", "generate_notification_email_unsubscribe_token", "(", "user_id36", ",", "user_email", "=", "None", ",", "user_password_hash", "=", "None", ")", ":", "import", "hashlib", "import", "hmac", "if", "(", "(", "not", "user_email", ")", "or", "(", "not", "user_p...
generate a token used for one-click unsubscribe links for notification emails .
train
false
14,072
def test_no_targets(): skip_if_no_sklearn() trainer = yaml_parse.load(test_yaml_no_targets) trainer.main_loop()
[ "def", "test_no_targets", "(", ")", ":", "skip_if_no_sklearn", "(", ")", "trainer", "=", "yaml_parse", ".", "load", "(", "test_yaml_no_targets", ")", "trainer", ".", "main_loop", "(", ")" ]
test cross-validation without targets .
train
false
14,073
def dumpPacket(buffer): return repr([hex(x) for x in buffer])
[ "def", "dumpPacket", "(", "buffer", ")", ":", "return", "repr", "(", "[", "hex", "(", "x", ")", "for", "x", "in", "buffer", "]", ")" ]
name: dumppacket args: byte array desc: returns hex value of all bytes in the buffer .
train
false
14,074
@pytest.mark.django_db def test_image_plugin_choice_widget_get_object(): image = File.objects.create() widget = ImagePluginChoiceWidget() assert (widget.get_object(image.pk) == image) assert (widget.get_object(1000) == None)
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_image_plugin_choice_widget_get_object", "(", ")", ":", "image", "=", "File", ".", "objects", ".", "create", "(", ")", "widget", "=", "ImagePluginChoiceWidget", "(", ")", "assert", "(", "widget", ".", ...
test get_object method for imagepluginchoicewidget .
train
false