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 |
|---|---|---|---|---|---|
29,437 | def sizeof(object):
return sys.getsizeof(object)
| [
"def",
"sizeof",
"(",
"object",
")",
":",
"return",
"sys",
".",
"getsizeof",
"(",
"object",
")"
] | return the size of an object when packed . | train | false |
29,438 | def gradient1(f, v):
return tt.flatten(tt.grad(f, v, disconnected_inputs='warn'))
| [
"def",
"gradient1",
"(",
"f",
",",
"v",
")",
":",
"return",
"tt",
".",
"flatten",
"(",
"tt",
".",
"grad",
"(",
"f",
",",
"v",
",",
"disconnected_inputs",
"=",
"'warn'",
")",
")"
] | flat gradient of f wrt v . | train | false |
29,439 | def showerror(title=None, message=None, **options):
return _show(title, message, ERROR, OK, **options)
| [
"def",
"showerror",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"**",
"options",
")",
":",
"return",
"_show",
"(",
"title",
",",
"message",
",",
"ERROR",
",",
"OK",
",",
"**",
"options",
")"
] | show an error message . | train | false |
29,440 | def _run_wsgi_app(*args):
global _run_wsgi_app
from werkzeug.test import run_wsgi_app as _run_wsgi_app
return _run_wsgi_app(*args)
| [
"def",
"_run_wsgi_app",
"(",
"*",
"args",
")",
":",
"global",
"_run_wsgi_app",
"from",
"werkzeug",
".",
"test",
"import",
"run_wsgi_app",
"as",
"_run_wsgi_app",
"return",
"_run_wsgi_app",
"(",
"*",
"args",
")"
] | this function replaces itself to ensure that the test module is not imported unless required . | train | false |
29,441 | def load_ancestors(pages):
pages_by_id = dict(((page.pk, page) for page in pages))
pages_list = list(pages)
missing = list(pages)
while missing:
page = missing.pop()
page.ancestors_descending = []
page._cached_descendants = []
if (page.parent_id and (page.parent_id not in pages_by_id)):
pages_list.append(page.parent)
pages_by_id[page.parent_id] = page.parent
missing.append(page.parent)
pages_list.sort(key=(lambda page: page.path))
for page in pages_list:
if page.parent_id:
parent = pages_by_id[page.parent_id]
page.ancestors_descending = (parent.ancestors_descending + [parent])
for ancestor in page.ancestors_descending:
ancestor._cached_descendants.append(page)
else:
page.ancestors_descending = []
page.ancestors_ascending = list(reversed(page.ancestors_descending))
return pages_list
| [
"def",
"load_ancestors",
"(",
"pages",
")",
":",
"pages_by_id",
"=",
"dict",
"(",
"(",
"(",
"page",
".",
"pk",
",",
"page",
")",
"for",
"page",
"in",
"pages",
")",
")",
"pages_list",
"=",
"list",
"(",
"pages",
")",
"missing",
"=",
"list",
"(",
"pag... | loads the ancestors . | train | false |
29,442 | @then(u'the command output should contain "{text}"')
def step_command_output_should_contain_text(context, text):
expected_text = text
if (('{__WORKDIR__}' in expected_text) or ('{__CWD__}' in expected_text)):
expected_text = textutil.template_substitute(text, __WORKDIR__=posixpath_normpath(context.workdir), __CWD__=posixpath_normpath(os.getcwd()))
actual_output = context.command_result.output
with on_assert_failed_print_details(actual_output, expected_text):
textutil.assert_normtext_should_contain(actual_output, expected_text)
| [
"@",
"then",
"(",
"u'the command output should contain \"{text}\"'",
")",
"def",
"step_command_output_should_contain_text",
"(",
"context",
",",
"text",
")",
":",
"expected_text",
"=",
"text",
"if",
"(",
"(",
"'{__WORKDIR__}'",
"in",
"expected_text",
")",
"or",
"(",
... | example: then the command output should contain "text" . | train | true |
29,443 | def NoCallback(*args, **kwargs):
pass
| [
"def",
"NoCallback",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"pass"
] | used where the conclusion of an asynchronous operation can be ignored . | train | false |
29,444 | def _add_step(emr_connection, step, jobflow_name, **jobflow_kw):
running = get_live_clusters(emr_connection)
for cluster in running:
if (cluster.name == jobflow_name):
jobflowid = cluster.id
emr_connection.add_jobflow_steps(jobflowid, step)
print ('Added %s to jobflow %s' % (step.name, jobflowid))
break
else:
base = TrafficBase(emr_connection, jobflow_name, steps=[step], **jobflow_kw)
base.run()
jobflowid = base.jobflowid
print ('Added %s to new jobflow %s' % (step.name, jobflowid))
return jobflowid
| [
"def",
"_add_step",
"(",
"emr_connection",
",",
"step",
",",
"jobflow_name",
",",
"**",
"jobflow_kw",
")",
":",
"running",
"=",
"get_live_clusters",
"(",
"emr_connection",
")",
"for",
"cluster",
"in",
"running",
":",
"if",
"(",
"cluster",
".",
"name",
"==",
... | add step to a running jobflow . | train | false |
29,445 | def dup_zz_mignotte_bound(f, K):
a = dup_max_norm(f, K)
b = abs(dup_LC(f, K))
n = dup_degree(f)
return (((K.sqrt(K((n + 1))) * (2 ** n)) * a) * b)
| [
"def",
"dup_zz_mignotte_bound",
"(",
"f",
",",
"K",
")",
":",
"a",
"=",
"dup_max_norm",
"(",
"f",
",",
"K",
")",
"b",
"=",
"abs",
"(",
"dup_LC",
"(",
"f",
",",
"K",
")",
")",
"n",
"=",
"dup_degree",
"(",
"f",
")",
"return",
"(",
"(",
"(",
"K"... | mignotte bound for univariate polynomials in k[x] . | train | false |
29,446 | def decompogen(f, symbol):
f = sympify(f)
result = []
if isinstance(f, (Function, Pow)):
if (f.args[0] == symbol):
return [f]
result += ([f.subs(f.args[0], symbol)] + decompogen(f.args[0], symbol))
return result
fp = Poly(f)
gens = list(filter((lambda x: (symbol in x.free_symbols)), fp.gens))
if ((len(gens) == 1) and (gens[0] != symbol)):
f1 = f.subs(gens[0], symbol)
f2 = gens[0]
result += ([f1] + decompogen(f2, symbol))
return result
try:
result += decompose(f)
return result
except ValueError:
return [f]
| [
"def",
"decompogen",
"(",
"f",
",",
"symbol",
")",
":",
"f",
"=",
"sympify",
"(",
"f",
")",
"result",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"f",
",",
"(",
"Function",
",",
"Pow",
")",
")",
":",
"if",
"(",
"f",
".",
"args",
"[",
"0",
"]",
... | computes general functional decomposition of f . | train | false |
29,447 | def configure_follower(follower_ident):
from sqlalchemy.testing import provision
provision.FOLLOWER_IDENT = follower_ident
| [
"def",
"configure_follower",
"(",
"follower_ident",
")",
":",
"from",
"sqlalchemy",
".",
"testing",
"import",
"provision",
"provision",
".",
"FOLLOWER_IDENT",
"=",
"follower_ident"
] | configure required state for a follower . | train | false |
29,449 | def find_git():
if (not utils.is_win32()):
return None
git_bindir = os.path.expanduser(os.path.join(u'~', u'.config', u'git-cola', u'git-bindir'))
if core.exists(git_bindir):
custom_path = core.read(git_bindir).strip()
if (custom_path and core.exists(custom_path)):
return custom_path
pf = os.environ.get(u'ProgramFiles', u'C:\\Program Files')
pf32 = os.environ.get(u'ProgramFiles(x86)', u'C:\\Program Files (x86)')
for p in [pf32, pf, u'C:\\']:
candidate = os.path.join(p, u'Git\\bin')
if os.path.isdir(candidate):
return candidate
return None
| [
"def",
"find_git",
"(",
")",
":",
"if",
"(",
"not",
"utils",
".",
"is_win32",
"(",
")",
")",
":",
"return",
"None",
"git_bindir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"u'~'",
",",
"u'.config'",
",",
... | return the path of git . | train | false |
29,450 | def update_configuration(lineagename, archive_dir, target, cli_config):
config_filename = renewal_filename_for_lineagename(cli_config, lineagename)
temp_filename = (config_filename + '.new')
if os.path.exists(temp_filename):
os.unlink(temp_filename)
values = relevant_values(vars(cli_config.namespace))
write_renewal_config(config_filename, temp_filename, archive_dir, target, values)
os.rename(temp_filename, config_filename)
return configobj.ConfigObj(config_filename)
| [
"def",
"update_configuration",
"(",
"lineagename",
",",
"archive_dir",
",",
"target",
",",
"cli_config",
")",
":",
"config_filename",
"=",
"renewal_filename_for_lineagename",
"(",
"cli_config",
",",
"lineagename",
")",
"temp_filename",
"=",
"(",
"config_filename",
"+"... | modifies lineagenames config to contain the specified values . | train | false |
29,451 | def get_vmdk_name_from_ovf(xmlstr):
ovf = etree.fromstring(encodeutils.safe_encode(xmlstr))
nsovf = ('{%s}' % ovf.nsmap['ovf'])
disk = ovf.find(('./%sDiskSection/%sDisk' % (nsovf, nsovf)))
file_id = disk.get(('%sfileRef' % nsovf))
file = ovf.find(('./%sReferences/%sFile[@%sid="%s"]' % (nsovf, nsovf, nsovf, file_id)))
vmdk_name = file.get(('%shref' % nsovf))
return vmdk_name
| [
"def",
"get_vmdk_name_from_ovf",
"(",
"xmlstr",
")",
":",
"ovf",
"=",
"etree",
".",
"fromstring",
"(",
"encodeutils",
".",
"safe_encode",
"(",
"xmlstr",
")",
")",
"nsovf",
"=",
"(",
"'{%s}'",
"%",
"ovf",
".",
"nsmap",
"[",
"'ovf'",
"]",
")",
"disk",
"=... | parse the ova descriptor to extract the vmdk name . | train | false |
29,452 | def test_probable_prime(candidate, randfunc=None):
if (randfunc is None):
randfunc = Random.new().read
if (not isinstance(candidate, Integer)):
candidate = Integer(candidate)
try:
map(candidate.fail_if_divisible_by, _sieve_base)
except ValueError:
return False
mr_ranges = ((220, 30), (280, 20), (390, 15), (512, 10), (620, 7), (740, 6), (890, 5), (1200, 4), (1700, 3), (3700, 2))
bit_size = candidate.size_in_bits()
try:
mr_iterations = list(filter((lambda x: (bit_size < x[0])), mr_ranges))[0][1]
except IndexError:
mr_iterations = 1
if (miller_rabin_test(candidate, mr_iterations, randfunc=randfunc) == COMPOSITE):
return COMPOSITE
if (lucas_test(candidate) == COMPOSITE):
return COMPOSITE
return PROBABLY_PRIME
| [
"def",
"test_probable_prime",
"(",
"candidate",
",",
"randfunc",
"=",
"None",
")",
":",
"if",
"(",
"randfunc",
"is",
"None",
")",
":",
"randfunc",
"=",
"Random",
".",
"new",
"(",
")",
".",
"read",
"if",
"(",
"not",
"isinstance",
"(",
"candidate",
",",
... | test if a number is prime . | train | false |
29,453 | def decode_morse(msg, sep='|', mapping=None):
mapping = (mapping or morse_char)
word_sep = (2 * sep)
characterstring = []
words = msg.strip(word_sep).split(word_sep)
for word in words:
letters = word.split(sep)
chars = [mapping[c] for c in letters]
word = ''.join(chars)
characterstring.append(word)
rv = ' '.join(characterstring)
return rv
| [
"def",
"decode_morse",
"(",
"msg",
",",
"sep",
"=",
"'|'",
",",
"mapping",
"=",
"None",
")",
":",
"mapping",
"=",
"(",
"mapping",
"or",
"morse_char",
")",
"word_sep",
"=",
"(",
"2",
"*",
"sep",
")",
"characterstring",
"=",
"[",
"]",
"words",
"=",
"... | decodes a morse code with letters separated by sep and words by word_sep into plaintext . | train | false |
29,454 | def read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None):
pandas_sql = pandasSQL_builder(con)
return pandas_sql.read_query(sql, index_col=index_col, params=params, coerce_float=coerce_float, parse_dates=parse_dates, chunksize=chunksize)
| [
"def",
"read_sql_query",
"(",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
... | read sql query into a dataframe . | train | true |
29,455 | def to_key_val_list(value):
if (value is None):
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
if isinstance(value, collections.Mapping):
value = value.items()
return list(value)
| [
"def",
"to_key_val_list",
"(",
"value",
")",
":",
"if",
"(",
"value",
"is",
"None",
")",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"bytes",
",",
"bool",
",",
"int",
")",
")",
":",
"raise",
"ValueError",
"(",
"'c... | take an object and test to see if it can be represented as a dictionary . | train | true |
29,456 | @pytest.fixture(params=[0, 1, (-1)])
def pickle_protocol(request):
return request.param
| [
"@",
"pytest",
".",
"fixture",
"(",
"params",
"=",
"[",
"0",
",",
"1",
",",
"(",
"-",
"1",
")",
"]",
")",
"def",
"pickle_protocol",
"(",
"request",
")",
":",
"return",
"request",
".",
"param"
] | fixture to run all the tests for protocols 0 and 1 . | train | false |
29,457 | def search_dict_list(l, key, value):
for i in l:
if (i.get(key) == value):
return i
| [
"def",
"search_dict_list",
"(",
"l",
",",
"key",
",",
"value",
")",
":",
"for",
"i",
"in",
"l",
":",
"if",
"(",
"i",
".",
"get",
"(",
"key",
")",
"==",
"value",
")",
":",
"return",
"i"
] | search a list of dict * return dict with specific value & key . | train | false |
29,458 | def is_builtin_object(node):
return (node and (node.root().name == BUILTINS_NAME))
| [
"def",
"is_builtin_object",
"(",
"node",
")",
":",
"return",
"(",
"node",
"and",
"(",
"node",
".",
"root",
"(",
")",
".",
"name",
"==",
"BUILTINS_NAME",
")",
")"
] | returns true if the given node is an object from the __builtin__ module . | train | false |
29,460 | def l1_min_c(X, y, loss='squared_hinge', fit_intercept=True, intercept_scaling=1.0):
if (loss not in ('squared_hinge', 'log')):
raise ValueError('loss type not in ("squared_hinge", "log", "l2")')
X = check_array(X, accept_sparse='csc')
check_consistent_length(X, y)
Y = LabelBinarizer(neg_label=(-1)).fit_transform(y).T
den = np.max(np.abs(safe_sparse_dot(Y, X)))
if fit_intercept:
bias = (intercept_scaling * np.ones((np.size(y), 1)))
den = max(den, abs(np.dot(Y, bias)).max())
if (den == 0.0):
raise ValueError('Ill-posed l1_min_c calculation: l1 will always select zero coefficients for this data')
if (loss == 'squared_hinge'):
return (0.5 / den)
else:
return (2.0 / den)
| [
"def",
"l1_min_c",
"(",
"X",
",",
"y",
",",
"loss",
"=",
"'squared_hinge'",
",",
"fit_intercept",
"=",
"True",
",",
"intercept_scaling",
"=",
"1.0",
")",
":",
"if",
"(",
"loss",
"not",
"in",
"(",
"'squared_hinge'",
",",
"'log'",
")",
")",
":",
"raise",... | return the lowest bound for c such that for c in the model is guaranteed not to be empty . | train | false |
29,461 | def kit():
if (len(request.args) == 2):
s3db.configure('budget_kit', update_next=URL(f='kit_item', args=request.args[1]))
return s3_rest_controller(rheader=s3db.budget_rheader, main='code')
| [
"def",
"kit",
"(",
")",
":",
"if",
"(",
"len",
"(",
"request",
".",
"args",
")",
"==",
"2",
")",
":",
"s3db",
".",
"configure",
"(",
"'budget_kit'",
",",
"update_next",
"=",
"URL",
"(",
"f",
"=",
"'kit_item'",
",",
"args",
"=",
"request",
".",
"a... | rest controller for kits . | train | false |
29,462 | def get_dir_pkg(d):
parent = os.path.dirname(os.path.realpath(d))
while ((not os.path.exists(os.path.join(d, MANIFEST_FILE))) and (not os.path.exists(os.path.join(d, PACKAGE_FILE))) and (parent != d)):
d = parent
parent = os.path.dirname(d)
if (os.path.exists(os.path.join(d, MANIFEST_FILE)) or os.path.exists(os.path.join(d, PACKAGE_FILE))):
pkg = os.path.basename(os.path.abspath(d))
return (d, pkg)
return (None, None)
| [
"def",
"get_dir_pkg",
"(",
"d",
")",
":",
"parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"d",
")",
")",
"while",
"(",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
... | get the package that the directory is contained within . | train | false |
29,463 | @jingo.register.filter
def locale_html(translatedfield):
if (not translatedfield):
return ''
site_locale = translation.to_locale(translation.get_language())
locale = translation.to_locale(translatedfield.locale)
if (locale == site_locale):
return ''
else:
rtl_locales = map(translation.to_locale, settings.RTL_LANGUAGES)
textdir = ('rtl' if (locale in rtl_locales) else 'ltr')
return jinja2.Markup((' lang="%s" dir="%s"' % (jinja2.escape(translatedfield.locale), textdir)))
| [
"@",
"jingo",
".",
"register",
".",
"filter",
"def",
"locale_html",
"(",
"translatedfield",
")",
":",
"if",
"(",
"not",
"translatedfield",
")",
":",
"return",
"''",
"site_locale",
"=",
"translation",
".",
"to_locale",
"(",
"translation",
".",
"get_language",
... | html attributes for languages different than the site language . | train | false |
29,464 | def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
testdir = findtestdir(testdir)
names = os.listdir(testdir)
tests = []
others = (set(stdtests) | nottests)
for name in names:
(modname, ext) = os.path.splitext(name)
if ((modname[:5] == 'test_') and (ext == '.py') and (modname not in others)):
tests.append(modname)
return (stdtests + sorted(tests))
| [
"def",
"findtests",
"(",
"testdir",
"=",
"None",
",",
"stdtests",
"=",
"STDTESTS",
",",
"nottests",
"=",
"NOTTESTS",
")",
":",
"testdir",
"=",
"findtestdir",
"(",
"testdir",
")",
"names",
"=",
"os",
".",
"listdir",
"(",
"testdir",
")",
"tests",
"=",
"[... | return a list of all applicable test modules . | train | false |
29,466 | def abspath_listdir(path):
path = abspath(path)
return [join(path, filename) for filename in listdir(path)]
| [
"def",
"abspath_listdir",
"(",
"path",
")",
":",
"path",
"=",
"abspath",
"(",
"path",
")",
"return",
"[",
"join",
"(",
"path",
",",
"filename",
")",
"for",
"filename",
"in",
"listdir",
"(",
"path",
")",
"]"
] | lists paths content using absolute paths . | train | false |
29,468 | def pipe_wait(popens):
popens = copy.copy(popens)
results = ([0] * len(popens))
while popens:
last = popens.pop((-1))
results[len(popens)] = last.wait()
return results
| [
"def",
"pipe_wait",
"(",
"popens",
")",
":",
"popens",
"=",
"copy",
".",
"copy",
"(",
"popens",
")",
"results",
"=",
"(",
"[",
"0",
"]",
"*",
"len",
"(",
"popens",
")",
")",
"while",
"popens",
":",
"last",
"=",
"popens",
".",
"pop",
"(",
"(",
"... | given an array of popen objects returned by the pipe method . | train | true |
29,469 | def _ScoreRequested(params):
return (params.has_scorer_spec() and params.scorer_spec().has_scorer())
| [
"def",
"_ScoreRequested",
"(",
"params",
")",
":",
"return",
"(",
"params",
".",
"has_scorer_spec",
"(",
")",
"and",
"params",
".",
"scorer_spec",
"(",
")",
".",
"has_scorer",
"(",
")",
")"
] | returns true if match scoring requested . | train | false |
29,470 | def get_quarter_names(width='wide', context='format', locale=LC_TIME):
return Locale.parse(locale).quarters[context][width]
| [
"def",
"get_quarter_names",
"(",
"width",
"=",
"'wide'",
",",
"context",
"=",
"'format'",
",",
"locale",
"=",
"LC_TIME",
")",
":",
"return",
"Locale",
".",
"parse",
"(",
"locale",
")",
".",
"quarters",
"[",
"context",
"]",
"[",
"width",
"]"
] | return the quarter names used by the locale for the specified format . | train | false |
29,472 | def send_args_to_spyder(args):
port = CONF.get('main', 'open_files_port')
for _x in range(200):
try:
for arg in args:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
client.connect(('127.0.0.1', port))
if is_unicode(arg):
arg = arg.encode('utf-8')
client.send(osp.abspath(arg))
client.close()
except socket.error:
time.sleep(0.25)
continue
break
| [
"def",
"send_args_to_spyder",
"(",
"args",
")",
":",
"port",
"=",
"CONF",
".",
"get",
"(",
"'main'",
",",
"'open_files_port'",
")",
"for",
"_x",
"in",
"range",
"(",
"200",
")",
":",
"try",
":",
"for",
"arg",
"in",
"args",
":",
"client",
"=",
"socket"... | simple socket client used to send the args passed to the spyder executable to an already running instance . | train | true |
29,474 | def split_slug(slug):
slug_split = slug.split('/')
length = len(slug_split)
root = None
seo_root = ''
bad_seo_roots = ['Web']
if (length > 1):
root = slug_split[0]
if (root in bad_seo_roots):
if (length > 2):
seo_root = ((root + '/') + slug_split[1])
else:
seo_root = root
specific = slug_split.pop()
parent = '/'.join(slug_split)
return {'specific': specific, 'parent': parent, 'full': slug, 'parent_split': slug_split, 'length': length, 'root': root, 'seo_root': seo_root}
| [
"def",
"split_slug",
"(",
"slug",
")",
":",
"slug_split",
"=",
"slug",
".",
"split",
"(",
"'/'",
")",
"length",
"=",
"len",
"(",
"slug_split",
")",
"root",
"=",
"None",
"seo_root",
"=",
"''",
"bad_seo_roots",
"=",
"[",
"'Web'",
"]",
"if",
"(",
"lengt... | utility function to do basic slug splitting . | train | false |
29,475 | def _collapse_addresses_internal(addresses):
to_merge = list(addresses)
subnets = {}
while to_merge:
net = to_merge.pop()
supernet = net.supernet()
existing = subnets.get(supernet)
if (existing is None):
subnets[supernet] = net
elif (existing != net):
del subnets[supernet]
to_merge.append(supernet)
last = None
for net in sorted(subnets.values()):
if (last is not None):
if (last.broadcast_address >= net.broadcast_address):
continue
(yield net)
last = net
| [
"def",
"_collapse_addresses_internal",
"(",
"addresses",
")",
":",
"to_merge",
"=",
"list",
"(",
"addresses",
")",
"subnets",
"=",
"{",
"}",
"while",
"to_merge",
":",
"net",
"=",
"to_merge",
".",
"pop",
"(",
")",
"supernet",
"=",
"net",
".",
"supernet",
... | loops through the addresses . | train | true |
29,478 | def demographic():
return s3_rest_controller('stats', 'demographic')
| [
"def",
"demographic",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
"'stats'",
",",
"'demographic'",
")"
] | rest controller . | train | false |
29,480 | def copystat(src, dst):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
if hasattr(os, 'utime'):
os.utime(dst, (st.st_atime, st.st_mtime))
if hasattr(os, 'chmod'):
os.chmod(dst, mode)
if (hasattr(os, 'chflags') and hasattr(st, 'st_flags')):
os.chflags(dst, st.st_flags)
| [
"def",
"copystat",
"(",
"src",
",",
"dst",
")",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"src",
")",
"mode",
"=",
"stat",
".",
"S_IMODE",
"(",
"st",
".",
"st_mode",
")",
"if",
"hasattr",
"(",
"os",
",",
"'utime'",
")",
":",
"os",
".",
"utime",
... | copy all stat info from src to dst . | train | true |
29,481 | def doc_wraps(func):
def _(func2):
if (func.__doc__ is not None):
func2.__doc__ = func.__doc__.replace('>>>', '>>').replace('...', '..')
return func2
return _
| [
"def",
"doc_wraps",
"(",
"func",
")",
":",
"def",
"_",
"(",
"func2",
")",
":",
"if",
"(",
"func",
".",
"__doc__",
"is",
"not",
"None",
")",
":",
"func2",
".",
"__doc__",
"=",
"func",
".",
"__doc__",
".",
"replace",
"(",
"'>>>'",
",",
"'>>'",
")",... | copy docstring from one function to another . | train | false |
29,482 | def test_http_invalid_response_header():
mocked_socket = mock.MagicMock()
mocked_socket.sendall = mock.MagicMock()
mocked_request = mock.MagicMock()
response = Response(mocked_request, mocked_socket, None)
with pytest.raises(InvalidHeader):
response.start_response('200 OK', [('foo', 'essai\r\n')])
response = Response(mocked_request, mocked_socket, None)
with pytest.raises(InvalidHeaderName):
response.start_response('200 OK', [('foo\r\n', 'essai')])
| [
"def",
"test_http_invalid_response_header",
"(",
")",
":",
"mocked_socket",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"mocked_socket",
".",
"sendall",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"mocked_request",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"response"... | tests whether http response headers are contains control chars . | train | false |
29,483 | def bootstrap2(value, distr, args=(), nobs=200, nrep=100):
count = 0
for irep in range(nrep):
rvs = distr.rvs(args, **{'size': nobs})
params = distr.fit_vec(rvs)
cdfvals = np.sort(distr.cdf(rvs, params))
stat = asquare(cdfvals, axis=0)
count += (stat >= value)
return ((count * 1.0) / nrep)
| [
"def",
"bootstrap2",
"(",
"value",
",",
"distr",
",",
"args",
"=",
"(",
")",
",",
"nobs",
"=",
"200",
",",
"nrep",
"=",
"100",
")",
":",
"count",
"=",
"0",
"for",
"irep",
"in",
"range",
"(",
"nrep",
")",
":",
"rvs",
"=",
"distr",
".",
"rvs",
... | monte carlo p-values for gof currently hardcoded for a^2 only non vectorized . | train | false |
29,484 | def _get_local_rev_and_branch(target, user, password):
log.info('Checking local revision for {0}'.format(target))
try:
local_rev = __salt__['git.revision'](target, user=user, password=password, ignore_retcode=True)
except CommandExecutionError:
log.info('No local revision for {0}'.format(target))
local_rev = None
log.info('Checking local branch for {0}'.format(target))
try:
local_branch = __salt__['git.current_branch'](target, user=user, password=password, ignore_retcode=True)
except CommandExecutionError:
log.info('No local branch for {0}'.format(target))
local_branch = None
return (local_rev, local_branch)
| [
"def",
"_get_local_rev_and_branch",
"(",
"target",
",",
"user",
",",
"password",
")",
":",
"log",
".",
"info",
"(",
"'Checking local revision for {0}'",
".",
"format",
"(",
"target",
")",
")",
"try",
":",
"local_rev",
"=",
"__salt__",
"[",
"'git.revision'",
"]... | return the local revision for before/after comparisons . | train | true |
29,486 | def get_sosfiltfilt():
try:
from scipy.signal import sosfiltfilt
except ImportError:
sosfiltfilt = _sosfiltfilt
return sosfiltfilt
| [
"def",
"get_sosfiltfilt",
"(",
")",
":",
"try",
":",
"from",
"scipy",
".",
"signal",
"import",
"sosfiltfilt",
"except",
"ImportError",
":",
"sosfiltfilt",
"=",
"_sosfiltfilt",
"return",
"sosfiltfilt"
] | helper to get sosfiltfilt from scipy . | train | false |
29,487 | def ihilbert(x):
return (- hilbert(x))
| [
"def",
"ihilbert",
"(",
"x",
")",
":",
"return",
"(",
"-",
"hilbert",
"(",
"x",
")",
")"
] | return inverse hilbert transform of a periodic sequence x . | train | false |
29,488 | @register(u'clear-screen')
def clear_screen(event):
event.cli.renderer.clear()
| [
"@",
"register",
"(",
"u'clear-screen'",
")",
"def",
"clear_screen",
"(",
"event",
")",
":",
"event",
".",
"cli",
".",
"renderer",
".",
"clear",
"(",
")"
] | clear the screen and redraw everything at the top of the screen . | train | false |
29,489 | def Semaphore(*args, **kwargs):
return _Semaphore(*args, **kwargs)
| [
"def",
"Semaphore",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"_Semaphore",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | a factory function that returns a new semaphore . | train | false |
29,490 | def output_json(data, code, headers=None):
settings = current_app.config.get('RESTFUL_JSON', {})
if current_app.debug:
settings.setdefault('indent', 4)
settings.setdefault('sort_keys', True)
dumped = (dumps(data, **settings) + '\n')
resp = make_response(dumped, code)
resp.headers.extend((headers or {}))
return resp
| [
"def",
"output_json",
"(",
"data",
",",
"code",
",",
"headers",
"=",
"None",
")",
":",
"settings",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'RESTFUL_JSON'",
",",
"{",
"}",
")",
"if",
"current_app",
".",
"debug",
":",
"settings",
".",
"setde... | makes a flask response with a json encoded body . | train | true |
29,494 | def smart_split(text):
text = force_unicode(text)
for bit in smart_split_re.finditer(text):
(yield bit.group(0))
| [
"def",
"smart_split",
"(",
"text",
")",
":",
"text",
"=",
"force_unicode",
"(",
"text",
")",
"for",
"bit",
"in",
"smart_split_re",
".",
"finditer",
"(",
"text",
")",
":",
"(",
"yield",
"bit",
".",
"group",
"(",
"0",
")",
")"
] | generator that splits a string by spaces . | train | false |
29,495 | def paths_from_indexes(model, indexes, item_type=TreeWidgetItem.TYPE, item_filter=None):
items = [model.itemFromIndex(i) for i in indexes]
return paths_from_items(items, item_type=item_type, item_filter=item_filter)
| [
"def",
"paths_from_indexes",
"(",
"model",
",",
"indexes",
",",
"item_type",
"=",
"TreeWidgetItem",
".",
"TYPE",
",",
"item_filter",
"=",
"None",
")",
":",
"items",
"=",
"[",
"model",
".",
"itemFromIndex",
"(",
"i",
")",
"for",
"i",
"in",
"indexes",
"]",... | return paths from a list of qstandarditemmodel indexes . | train | false |
29,496 | def kerp_zeros(nt):
if ((not isscalar(nt)) or (floor(nt) != nt) or (nt <= 0)):
raise ValueError('nt must be positive integer scalar.')
return specfun.klvnzo(nt, 7)
| [
"def",
"kerp_zeros",
"(",
"nt",
")",
":",
"if",
"(",
"(",
"not",
"isscalar",
"(",
"nt",
")",
")",
"or",
"(",
"floor",
"(",
"nt",
")",
"!=",
"nt",
")",
"or",
"(",
"nt",
"<=",
"0",
")",
")",
":",
"raise",
"ValueError",
"(",
"'nt must be positive in... | compute nt zeros of the kelvin function ker(x) . | train | false |
29,497 | def buildMixedNestedNetwork():
N = RecurrentNetwork('outer')
a = LinearLayer(1, name='a')
b = LinearLayer(2, name='b')
c = buildNetwork(2, 3, 1)
c.name = 'inner'
N.addInputModule(a)
N.addModule(c)
N.addOutputModule(b)
N.addConnection(FullConnection(a, b))
N.addConnection(FullConnection(b, c))
N.addRecurrentConnection(FullConnection(c, c))
N.sortModules()
return N
| [
"def",
"buildMixedNestedNetwork",
"(",
")",
":",
"N",
"=",
"RecurrentNetwork",
"(",
"'outer'",
")",
"a",
"=",
"LinearLayer",
"(",
"1",
",",
"name",
"=",
"'a'",
")",
"b",
"=",
"LinearLayer",
"(",
"2",
",",
"name",
"=",
"'b'",
")",
"c",
"=",
"buildNetw... | build a nested network with the inner one being a ffn and the outer one being recurrent . | train | false |
29,500 | def get_checkers_for(lang=u'python'):
global NOTIFICATIONS_CHECKERS
return NOTIFICATIONS_CHECKERS.get(lang, [])
| [
"def",
"get_checkers_for",
"(",
"lang",
"=",
"u'python'",
")",
":",
"global",
"NOTIFICATIONS_CHECKERS",
"return",
"NOTIFICATIONS_CHECKERS",
".",
"get",
"(",
"lang",
",",
"[",
"]",
")"
] | get a registered checker for some language . | train | false |
29,501 | def linear_interpolate(p, x, y):
return LinearInterpolate()(p, x, y)
| [
"def",
"linear_interpolate",
"(",
"p",
",",
"x",
",",
"y",
")",
":",
"return",
"LinearInterpolate",
"(",
")",
"(",
"p",
",",
"x",
",",
"y",
")"
] | elementwise linear-interpolation function . | train | false |
29,502 | def _get_subgraph(codons, G):
subgraph = {}
for i in codons:
subgraph[i] = {}
for j in codons:
if (i != j):
subgraph[i][j] = G[i][j]
return subgraph
| [
"def",
"_get_subgraph",
"(",
"codons",
",",
"G",
")",
":",
"subgraph",
"=",
"{",
"}",
"for",
"i",
"in",
"codons",
":",
"subgraph",
"[",
"i",
"]",
"=",
"{",
"}",
"for",
"j",
"in",
"codons",
":",
"if",
"(",
"i",
"!=",
"j",
")",
":",
"subgraph",
... | get the subgraph that contains all codons in list . | train | false |
29,503 | def _prefix(subject):
if email().prefix:
return '{} {}'.format(email().prefix, subject)
else:
return subject
| [
"def",
"_prefix",
"(",
"subject",
")",
":",
"if",
"email",
"(",
")",
".",
"prefix",
":",
"return",
"'{} {}'",
".",
"format",
"(",
"email",
"(",
")",
".",
"prefix",
",",
"subject",
")",
"else",
":",
"return",
"subject"
] | if the config has a special prefix for emails then this function adds this prefix . | train | false |
29,504 | def store_outcome_parameters(request_params, user, lti_consumer):
result_id = request_params.get('lis_result_sourcedid', None)
if result_id:
result_service = request_params.get('lis_outcome_service_url', None)
if (not result_service):
log.warn('Outcome Service: lis_outcome_service_url parameter missing from scored assignment; we will be unable to return a score. Request parameters: %s', request_params)
return
usage_key = request_params['usage_key']
course_key = request_params['course_key']
(outcomes, __) = OutcomeService.objects.get_or_create(lis_outcome_service_url=result_service, lti_consumer=lti_consumer)
GradedAssignment.objects.get_or_create(lis_result_sourcedid=result_id, course_key=course_key, usage_key=usage_key, user=user, outcome_service=outcomes)
| [
"def",
"store_outcome_parameters",
"(",
"request_params",
",",
"user",
",",
"lti_consumer",
")",
":",
"result_id",
"=",
"request_params",
".",
"get",
"(",
"'lis_result_sourcedid'",
",",
"None",
")",
"if",
"result_id",
":",
"result_service",
"=",
"request_params",
... | determine whether a set of lti launch parameters contains information about an expected score . | train | false |
29,505 | def is_global(name):
return (name and (name[0] == SEP))
| [
"def",
"is_global",
"(",
"name",
")",
":",
"return",
"(",
"name",
"and",
"(",
"name",
"[",
"0",
"]",
"==",
"SEP",
")",
")"
] | test if name is a global graph resource name . | train | false |
29,506 | def _split_left_right(name):
parts = name.split(None, 1)
(lhs, rhs) = [parts[0], (parts[1] if (len(parts) > 1) else u'')]
return (lhs, rhs)
| [
"def",
"_split_left_right",
"(",
"name",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"None",
",",
"1",
")",
"(",
"lhs",
",",
"rhs",
")",
"=",
"[",
"parts",
"[",
"0",
"]",
",",
"(",
"parts",
"[",
"1",
"]",
"if",
"(",
"len",
"(",
"parts"... | split record name at the first whitespace and return both parts . | train | false |
29,509 | def tokenMap(func, *args):
def pa(s, l, t):
return [func(tokn, *args) for tokn in t]
try:
func_name = getattr(func, '__name__', getattr(func, '__class__').__name__)
except Exception:
func_name = str(func)
pa.__name__ = func_name
return pa
| [
"def",
"tokenMap",
"(",
"func",
",",
"*",
"args",
")",
":",
"def",
"pa",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"return",
"[",
"func",
"(",
"tokn",
",",
"*",
"args",
")",
"for",
"tokn",
"in",
"t",
"]",
"try",
":",
"func_name",
"=",
"getattr"... | helper to define a parse action by mapping a function to all elements of a parseresults list . | train | true |
29,512 | def getFilesWithFileTypesWithoutWordsRecursively(fileTypes, words=[], fileInDirectory=''):
filesWithFileTypesRecursively = []
for filePath in getFilePathsRecursively(fileInDirectory):
for fileType in fileTypes:
if isFileWithFileTypeWithoutWords(fileType, filePath, words):
filesWithFileTypesRecursively.append(filePath)
filesWithFileTypesRecursively.sort()
return filesWithFileTypesRecursively
| [
"def",
"getFilesWithFileTypesWithoutWordsRecursively",
"(",
"fileTypes",
",",
"words",
"=",
"[",
"]",
",",
"fileInDirectory",
"=",
"''",
")",
":",
"filesWithFileTypesRecursively",
"=",
"[",
"]",
"for",
"filePath",
"in",
"getFilePathsRecursively",
"(",
"fileInDirectory... | get files recursively which have a given file type . | train | false |
29,514 | def test_line_endings():
tempdir = _TempDir()
with open(op.join(tempdir, 'foo'), 'wb') as fid:
fid.write('bad\r\ngood\n'.encode('ascii'))
_assert_line_endings(tempdir)
with open(op.join(tempdir, 'bad.py'), 'wb') as fid:
fid.write('\x97')
assert_raises(AssertionError, _assert_line_endings, tempdir)
with open(op.join(tempdir, 'bad.py'), 'wb') as fid:
fid.write('bad\r\ngood\n'.encode('ascii'))
assert_raises(AssertionError, _assert_line_endings, tempdir)
_assert_line_endings(_get_root_dir())
| [
"def",
"test_line_endings",
"(",
")",
":",
"tempdir",
"=",
"_TempDir",
"(",
")",
"with",
"open",
"(",
"op",
".",
"join",
"(",
"tempdir",
",",
"'foo'",
")",
",",
"'wb'",
")",
"as",
"fid",
":",
"fid",
".",
"write",
"(",
"'bad\\r\\ngood\\n'",
".",
"enco... | test line endings of mne-python . | train | false |
29,515 | def parse_contributions_calendar(contributions_calendar):
for line in contributions_calendar.splitlines():
for day in line.split():
if ('data-count=' in day):
commit = day.split('=')[1]
commit = commit.strip('"')
(yield int(commit))
| [
"def",
"parse_contributions_calendar",
"(",
"contributions_calendar",
")",
":",
"for",
"line",
"in",
"contributions_calendar",
".",
"splitlines",
"(",
")",
":",
"for",
"day",
"in",
"line",
".",
"split",
"(",
")",
":",
"if",
"(",
"'data-count='",
"in",
"day",
... | yield daily counts extracted from the contributions svg . | train | false |
29,516 | def replay():
g['pause'] = False
printNicely(green('Stream is running back now'))
| [
"def",
"replay",
"(",
")",
":",
"g",
"[",
"'pause'",
"]",
"=",
"False",
"printNicely",
"(",
"green",
"(",
"'Stream is running back now'",
")",
")"
] | a simple context manager for using the httreplay library . | train | false |
29,517 | def filter_docker_plays(plays, repo_path):
items = set()
for play in plays:
dockerfile = pathlib2.Path(DOCKER_PATH_ROOT, play, 'Dockerfile')
if dockerfile.exists():
items.add(play)
else:
LOGGER.warning(("covered playbook '%s' does not have Dockerfile." % play))
return items
| [
"def",
"filter_docker_plays",
"(",
"plays",
",",
"repo_path",
")",
":",
"items",
"=",
"set",
"(",
")",
"for",
"play",
"in",
"plays",
":",
"dockerfile",
"=",
"pathlib2",
".",
"Path",
"(",
"DOCKER_PATH_ROOT",
",",
"play",
",",
"'Dockerfile'",
")",
"if",
"d... | filters out docker plays that do not have a dockerfile . | train | false |
29,518 | def db_check(name, table=None, **connection_args):
ret = []
if (table is None):
tables = db_tables(name, **connection_args)
for table in tables:
log.info("Checking table '{0}' in db '{1}'..".format(name, table))
ret.append(__check_table(name, table, **connection_args))
else:
log.info("Checking table '{0}' in db '{1}'..".format(name, table))
ret = __check_table(name, table, **connection_args)
return ret
| [
"def",
"db_check",
"(",
"name",
",",
"table",
"=",
"None",
",",
"**",
"connection_args",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"(",
"table",
"is",
"None",
")",
":",
"tables",
"=",
"db_tables",
"(",
"name",
",",
"**",
"connection_args",
")",
"for",
... | repairs the full database or just a given table cli example: . | train | true |
29,519 | def setup_test():
warnings.simplefilter('default')
from scipy import signal, ndimage, special, optimize, linalg
from scipy.io import loadmat
from skimage import viewer
np.random.seed(0)
warnings.simplefilter('error')
| [
"def",
"setup_test",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"'default'",
")",
"from",
"scipy",
"import",
"signal",
",",
"ndimage",
",",
"special",
",",
"optimize",
",",
"linalg",
"from",
"scipy",
".",
"io",
"import",
"loadmat",
"from",
"skima... | direct invoke test . | train | false |
29,520 | def ffi_callback(signature, name, **kwargs):
def wrapper(func):
if lib.Cryptography_STATIC_CALLBACKS:
ffi.def_extern(name=name, **kwargs)(func)
callback = getattr(lib, name)
else:
callback = ffi.callback(signature, **kwargs)(func)
return callback
return wrapper
| [
"def",
"ffi_callback",
"(",
"signature",
",",
"name",
",",
"**",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"if",
"lib",
".",
"Cryptography_STATIC_CALLBACKS",
":",
"ffi",
".",
"def_extern",
"(",
"name",
"=",
"name",
",",
"**",
"kwargs",... | callback dispatcher the ffi_callback() dispatcher keeps callbacks compatible between dynamic and static callbacks . | train | false |
29,521 | def get_property(obj, name, old_name, default=None):
if hasattr(obj, old_name):
warnings.warn(('Property %s is obsolete, please use %s instead' % (old_name, name)), stacklevel=2)
return getattr(obj, old_name)
return getattr(obj, name, default)
| [
"def",
"get_property",
"(",
"obj",
",",
"name",
",",
"old_name",
",",
"default",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"old_name",
")",
":",
"warnings",
".",
"warn",
"(",
"(",
"'Property %s is obsolete, please use %s instead'",
"%",
"(",
... | check if old property name exists and if it does - show warning message and return value . | train | false |
29,522 | def raise_if_reindex_in_progress(site):
already_reindexing = Reindexing.objects._is_reindexing(site)
if (already_reindexing and ('FORCE_INDEXING' not in os.environ)):
raise CommandError('Indexation already occurring. Add a FORCE_INDEXING variable in the environ to force it')
| [
"def",
"raise_if_reindex_in_progress",
"(",
"site",
")",
":",
"already_reindexing",
"=",
"Reindexing",
".",
"objects",
".",
"_is_reindexing",
"(",
"site",
")",
"if",
"(",
"already_reindexing",
"and",
"(",
"'FORCE_INDEXING'",
"not",
"in",
"os",
".",
"environ",
")... | checks if the database indexation flag is on for the given site . | train | false |
29,524 | def do_indent(s, width=4, indentfirst=False):
indention = (u' ' * width)
rv = (u'\n' + indention).join(s.splitlines())
if indentfirst:
rv = (indention + rv)
return rv
| [
"def",
"do_indent",
"(",
"s",
",",
"width",
"=",
"4",
",",
"indentfirst",
"=",
"False",
")",
":",
"indention",
"=",
"(",
"u' '",
"*",
"width",
")",
"rv",
"=",
"(",
"u'\\n'",
"+",
"indention",
")",
".",
"join",
"(",
"s",
".",
"splitlines",
"(",
")... | return a copy of the passed string . | train | true |
29,525 | def manage_changed(wrapped):
def changed(session, *arg, **kw):
session.accessed = int(time.time())
session.changed()
return wrapped(session, *arg, **kw)
changed.__doc__ = wrapped.__doc__
return changed
| [
"def",
"manage_changed",
"(",
"wrapped",
")",
":",
"def",
"changed",
"(",
"session",
",",
"*",
"arg",
",",
"**",
"kw",
")",
":",
"session",
".",
"accessed",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"session",
".",
"changed",
"(",
")",
... | decorator which causes a cookie to be set when a setter method is called . | train | false |
29,526 | def whitespace_before_parameters(logical_line, tokens):
(prev_type, prev_text, __, prev_end, __) = tokens[0]
for index in range(1, len(tokens)):
(token_type, text, start, end, __) = tokens[index]
if ((token_type == tokenize.OP) and (text in '([') and (start != prev_end) and ((prev_type == tokenize.NAME) or (prev_text in '}])')) and ((index < 2) or (tokens[(index - 2)][1] != 'class')) and (not keyword.iskeyword(prev_text))):
(yield (prev_end, ("E211 whitespace before '%s'" % text)))
prev_type = token_type
prev_text = text
prev_end = end
| [
"def",
"whitespace_before_parameters",
"(",
"logical_line",
",",
"tokens",
")",
":",
"(",
"prev_type",
",",
"prev_text",
",",
"__",
",",
"prev_end",
",",
"__",
")",
"=",
"tokens",
"[",
"0",
"]",
"for",
"index",
"in",
"range",
"(",
"1",
",",
"len",
"(",... | avoid extraneous whitespace in the following situations: - immediately before the open parenthesis that starts the argument list of a function call . | train | true |
29,527 | def safe_mask(X, mask):
mask = np.asarray(mask)
if np.issubdtype(mask.dtype, np.int):
return mask
if hasattr(X, 'toarray'):
ind = np.arange(mask.shape[0])
mask = ind[mask]
return mask
| [
"def",
"safe_mask",
"(",
"X",
",",
"mask",
")",
":",
"mask",
"=",
"np",
".",
"asarray",
"(",
"mask",
")",
"if",
"np",
".",
"issubdtype",
"(",
"mask",
".",
"dtype",
",",
"np",
".",
"int",
")",
":",
"return",
"mask",
"if",
"hasattr",
"(",
"X",
",... | return a mask which is safe to use on x . | train | false |
29,529 | def mail_admins(subject, message, fail_silently=False, connection=None, html_message=None):
if (not settings.ADMINS):
return
mail = EmailMultiAlternatives(('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently)
| [
"def",
"mail_admins",
"(",
"subject",
",",
"message",
",",
"fail_silently",
"=",
"False",
",",
"connection",
"=",
"None",
",",
"html_message",
"=",
"None",
")",
":",
"if",
"(",
"not",
"settings",
".",
"ADMINS",
")",
":",
"return",
"mail",
"=",
"EmailMult... | sends a message to the admins . | train | true |
29,531 | def _gen_random_array(n):
randArray = [random.random() for i in range(n)]
total = sum(randArray)
normalizedRandArray = [(x / total) for x in randArray]
return normalizedRandArray
| [
"def",
"_gen_random_array",
"(",
"n",
")",
":",
"randArray",
"=",
"[",
"random",
".",
"random",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"total",
"=",
"sum",
"(",
"randArray",
")",
"normalizedRandArray",
"=",
"[",
"(",
"x",
"/",
"to... | return an array of n random numbers . | train | false |
29,532 | def _format_syslog_config(cmd_ret):
ret_dict = {'success': (cmd_ret['retcode'] == 0)}
if (cmd_ret['retcode'] != 0):
ret_dict['message'] = cmd_ret['stdout']
else:
for line in cmd_ret['stdout'].splitlines():
line = line.strip()
cfgvars = line.split(': ')
key = cfgvars[0].strip()
value = cfgvars[1].strip()
ret_dict[key] = value
return ret_dict
| [
"def",
"_format_syslog_config",
"(",
"cmd_ret",
")",
":",
"ret_dict",
"=",
"{",
"'success'",
":",
"(",
"cmd_ret",
"[",
"'retcode'",
"]",
"==",
"0",
")",
"}",
"if",
"(",
"cmd_ret",
"[",
"'retcode'",
"]",
"!=",
"0",
")",
":",
"ret_dict",
"[",
"'message'"... | helper function to format the stdout from the get_syslog_config function . | train | true |
29,533 | def group_snapshot_creating_from_src():
return IMPL.group_snapshot_creating_from_src()
| [
"def",
"group_snapshot_creating_from_src",
"(",
")",
":",
"return",
"IMPL",
".",
"group_snapshot_creating_from_src",
"(",
")"
] | get a filter to check if a grp snapshot is being created from a grp . | train | false |
29,534 | def reconnect(hass):
hass.services.call(DOMAIN, SERVICE_RECONNECT, {})
| [
"def",
"reconnect",
"(",
"hass",
")",
":",
"hass",
".",
"services",
".",
"call",
"(",
"DOMAIN",
",",
"SERVICE_RECONNECT",
",",
"{",
"}",
")"
] | reconnects before running . | train | false |
29,535 | def _sort_possible_cpu_topologies(possible, wanttopology):
scores = collections.defaultdict(list)
for topology in possible:
score = _score_cpu_topology(topology, wanttopology)
scores[score].append(topology)
desired = []
desired.extend(scores[3])
desired.extend(scores[2])
desired.extend(scores[1])
desired.extend(scores[0])
return desired
| [
"def",
"_sort_possible_cpu_topologies",
"(",
"possible",
",",
"wanttopology",
")",
":",
"scores",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"topology",
"in",
"possible",
":",
"score",
"=",
"_score_cpu_topology",
"(",
"topology",
",",
"want... | sort the topologies in order of preference . | train | false |
29,536 | def _get_picks(raw):
return [0, 1, 2, 6, 7, 8, 306, 340, 341, 342]
| [
"def",
"_get_picks",
"(",
"raw",
")",
":",
"return",
"[",
"0",
",",
"1",
",",
"2",
",",
"6",
",",
"7",
",",
"8",
",",
"306",
",",
"340",
",",
"341",
",",
"342",
"]"
] | get picks . | train | false |
29,539 | def clean_symbols(text):
result = text
if isinstance(result, str):
result = normalize(u'NFKD', result)
result = re.sub(u'[ \\(\\)\\-_\\[\\]\\.]+', u' ', result).lower()
result = re.sub(u'[^a-zA-Z0-9 ]', u'', result)
return result
| [
"def",
"clean_symbols",
"(",
"text",
")",
":",
"result",
"=",
"text",
"if",
"isinstance",
"(",
"result",
",",
"str",
")",
":",
"result",
"=",
"normalize",
"(",
"u'NFKD'",
",",
"result",
")",
"result",
"=",
"re",
".",
"sub",
"(",
"u'[ \\\\(\\\\)\\\\-_\\\\... | replaces common symbols with spaces . | train | false |
29,540 | def traverse_post_order(start_node, get_children, filter_func=None):
class _Node(object, ):
'\n Wrapper node class to keep an active children iterator.\n An active iterator is needed in order to determine when all\n children are visited and so the node itself should be visited.\n '
def __init__(self, node, get_children):
self.node = node
self.children = iter(get_children(node))
filter_func = (filter_func or (lambda __: True))
stack = deque([_Node(start_node, get_children)])
visited = set()
while stack:
current = stack[(-1)]
if ((current.node in visited) or (not filter_func(current.node))):
stack.pop()
continue
try:
next_child = current.children.next()
except StopIteration:
(yield current.node)
visited.add(current.node)
stack.pop()
else:
stack.append(_Node(next_child, get_children))
| [
"def",
"traverse_post_order",
"(",
"start_node",
",",
"get_children",
",",
"filter_func",
"=",
"None",
")",
":",
"class",
"_Node",
"(",
"object",
",",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"node",
",",
"get_children",
")",
":",
"self",
".",
"nod... | generator for yielding nodes of a tree in a post-order sort . | train | false |
29,541 | def gather(reference, indices):
return tf.gather(reference, indices)
| [
"def",
"gather",
"(",
"reference",
",",
"indices",
")",
":",
"return",
"tf",
".",
"gather",
"(",
"reference",
",",
"indices",
")"
] | gathers variables from different gpus on a specified device . | train | false |
29,542 | def test_inverse_deriv():
np.random.seed(24235)
for link in Links:
for k in range(10):
z = (- np.log(np.random.uniform()))
d = link.inverse_deriv(z)
f = (1 / link.deriv(link.inverse(z)))
assert_allclose(d, f, rtol=1e-08, atol=1e-10, err_msg=str(link))
| [
"def",
"test_inverse_deriv",
"(",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"24235",
")",
"for",
"link",
"in",
"Links",
":",
"for",
"k",
"in",
"range",
"(",
"10",
")",
":",
"z",
"=",
"(",
"-",
"np",
".",
"log",
"(",
"np",
".",
"random",
... | logic check that inverse_deriv equals 1/link . | train | false |
29,543 | def register_unpack_format(name, extensions, function, extra_args=None, description=''):
if (extra_args is None):
extra_args = []
_check_unpack_options(extensions, function, extra_args)
_UNPACK_FORMATS[name] = (extensions, function, extra_args, description)
| [
"def",
"register_unpack_format",
"(",
"name",
",",
"extensions",
",",
"function",
",",
"extra_args",
"=",
"None",
",",
"description",
"=",
"''",
")",
":",
"if",
"(",
"extra_args",
"is",
"None",
")",
":",
"extra_args",
"=",
"[",
"]",
"_check_unpack_options",
... | registers an unpack format . | train | true |
29,544 | def _unlock_cache(w_lock):
if (not os.path.exists(w_lock)):
return
try:
if os.path.isdir(w_lock):
os.rmdir(w_lock)
elif os.path.isfile(w_lock):
os.unlink(w_lock)
except (OSError, IOError) as exc:
log.trace('Error removing lockfile {0}: {1}'.format(w_lock, exc))
| [
"def",
"_unlock_cache",
"(",
"w_lock",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"w_lock",
")",
")",
":",
"return",
"try",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"w_lock",
")",
":",
"os",
".",
"rmdir",
"(",
"w... | unlock a fs file/dir based lock . | train | true |
29,545 | @verbose
def twitterclass_demo():
tw = Twitter()
print('Track from the public stream\n')
tw.tweets(keywords='love, hate', limit=10)
print(SPACER)
print('Search past Tweets\n')
tw = Twitter()
tw.tweets(keywords='love, hate', stream=False, limit=10)
print(SPACER)
print(('Follow two accounts in the public stream' + ' -- be prepared to wait a few minutes\n'))
tw = Twitter()
tw.tweets(follow=['759251', '6017542'], stream=True, limit=5)
| [
"@",
"verbose",
"def",
"twitterclass_demo",
"(",
")",
":",
"tw",
"=",
"Twitter",
"(",
")",
"print",
"(",
"'Track from the public stream\\n'",
")",
"tw",
".",
"tweets",
"(",
"keywords",
"=",
"'love, hate'",
",",
"limit",
"=",
"10",
")",
"print",
"(",
"SPACE... | use the simplified :class:twitter class to write some tweets to a file . | train | false |
29,546 | def Area(data=None, x=None, y=None, **kws):
kws['x'] = x
kws['y'] = y
return create_and_build(AreaBuilder, data, **kws)
| [
"def",
"Area",
"(",
"data",
"=",
"None",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"**",
"kws",
")",
":",
"kws",
"[",
"'x'",
"]",
"=",
"x",
"kws",
"[",
"'y'",
"]",
"=",
"y",
"return",
"create_and_build",
"(",
"AreaBuilder",
",",
"data"... | create an area chart using :class:areabuilder <bokeh . | train | false |
29,547 | def readline_generator(f):
line = f.readline()
while line:
(yield line)
line = f.readline()
| [
"def",
"readline_generator",
"(",
"f",
")",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"while",
"line",
":",
"(",
"yield",
"line",
")",
"line",
"=",
"f",
".",
"readline",
"(",
")"
] | as advised in doc/library/configparser . | train | false |
29,549 | def column_has_value(data, fieldname):
has_value = False
for row in data:
value = row.get(fieldname)
if value:
if isinstance(value, basestring):
if strip_html(value).strip():
has_value = True
break
else:
has_value = True
break
return has_value
| [
"def",
"column_has_value",
"(",
"data",
",",
"fieldname",
")",
":",
"has_value",
"=",
"False",
"for",
"row",
"in",
"data",
":",
"value",
"=",
"row",
".",
"get",
"(",
"fieldname",
")",
"if",
"value",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestri... | check if at least one cell in column has non-zero and non-blank value . | train | false |
29,550 | def test_save(config_stub, fake_save_manager, monkeypatch, qapp):
monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub)
jar = cookies.CookieJar()
jar._lineparser.data = [COOKIE1, COOKIE2, SESSION_COOKIE, EXPIRED_COOKIE]
jar.parse_cookies()
jar.save()
saved_cookies = [cookie.data() for cookie in jar._lineparser.saved]
assert (saved_cookies == [COOKIE1, COOKIE2])
| [
"def",
"test_save",
"(",
"config_stub",
",",
"fake_save_manager",
",",
"monkeypatch",
",",
"qapp",
")",
":",
"monkeypatch",
".",
"setattr",
"(",
"lineparser",
",",
"'LineParser'",
",",
"LineparserSaveStub",
")",
"jar",
"=",
"cookies",
".",
"CookieJar",
"(",
")... | test %save . | train | false |
29,551 | def _inherited_panel(panel, base_panels_from_pillar, ret):
base_panels = []
for base_panel_from_pillar in base_panels_from_pillar:
base_panel = __salt__['pillar.get'](base_panel_from_pillar)
if base_panel:
base_panels.append(base_panel)
elif (base_panel_from_pillar != _DEFAULT_PANEL_PILLAR):
ret.setdefault('warnings', [])
warning_message = 'Cannot find panel pillar "{0}".'.format(base_panel_from_pillar)
if (warning_message not in ret['warnings']):
ret['warnings'].append(warning_message)
base_panels.append(panel)
result_panel = {}
for panel in base_panels:
result_panel.update(panel)
return result_panel
| [
"def",
"_inherited_panel",
"(",
"panel",
",",
"base_panels_from_pillar",
",",
"ret",
")",
":",
"base_panels",
"=",
"[",
"]",
"for",
"base_panel_from_pillar",
"in",
"base_panels_from_pillar",
":",
"base_panel",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"base_... | return a panel with properties from parents . | train | true |
29,553 | def load_linker_sequences(linker_fname):
global linkerlengths
if (not os.path.getsize(linker_fname)):
raise RuntimeError((("File empty? '" + linker_fname) + "'"))
fh = open(linker_fname, 'r')
linkerseqs = read_fasta(fh)
if (len(linkerseqs) == 0):
raise RuntimeError((linker_fname + ': no sequence found?'))
for i in linkerseqs:
if (i.name in linkerlengths):
raise RuntimeError((((linker_fname + ": sequence '") + i.name) + "' present multiple times. Aborting."))
linkerlengths[i.name] = len(i.sequence)
fh.close()
| [
"def",
"load_linker_sequences",
"(",
"linker_fname",
")",
":",
"global",
"linkerlengths",
"if",
"(",
"not",
"os",
".",
"path",
".",
"getsize",
"(",
"linker_fname",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"(",
"(",
"\"File empty? '\"",
"+",
"linker_fname",... | loads all linker sequences into memory . | train | false |
29,556 | def stop_version_async(module=None, version=None):
def _ResultHook(rpc):
mapped_errors = [modules_service_pb.ModulesServiceError.INVALID_VERSION, modules_service_pb.ModulesServiceError.TRANSIENT_ERROR]
expected_errors = {modules_service_pb.ModulesServiceError.UNEXPECTED_STATE: ('The specified module: %s, version: %s is already stopped.' % (module, version))}
_CheckAsyncResult(rpc, mapped_errors, expected_errors)
request = modules_service_pb.StopModuleRequest()
if module:
request.set_module(module)
if version:
request.set_version(version)
response = modules_service_pb.StopModuleResponse()
return _MakeAsyncCall('StopModule', request, response, _ResultHook)
| [
"def",
"stop_version_async",
"(",
"module",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"def",
"_ResultHook",
"(",
"rpc",
")",
":",
"mapped_errors",
"=",
"[",
"modules_service_pb",
".",
"ModulesServiceError",
".",
"INVALID_VERSION",
",",
"modules_service... | returns a userrpc to stop all instances for the given module version . | train | false |
29,557 | def contextualize_text(text, context):
if (not text):
return text
for key in sorted(context, (lambda x, y: cmp(len(y), len(x)))):
if (('$' + key) in text):
try:
s = str(context[key])
except UnicodeEncodeError:
s = context[key].encode('utf8', errors='ignore')
text = text.replace(('$' + key), s)
return text
| [
"def",
"contextualize_text",
"(",
"text",
",",
"context",
")",
":",
"if",
"(",
"not",
"text",
")",
":",
"return",
"text",
"for",
"key",
"in",
"sorted",
"(",
"context",
",",
"(",
"lambda",
"x",
",",
"y",
":",
"cmp",
"(",
"len",
"(",
"y",
")",
",",... | takes a string with variables . | train | false |
29,558 | def LoadSingleCron(cron_info, open_fn=None):
builder = yaml_object.ObjectBuilder(CronInfoExternal)
handler = yaml_builder.BuilderHandler(builder)
listener = yaml_listener.EventListener(handler)
listener.Parse(cron_info)
cron_info = handler.GetResults()
if (len(cron_info) < 1):
raise MalformedCronfigurationFile('Empty cron configuration.')
if (len(cron_info) > 1):
raise MalformedCronfigurationFile('Multiple cron sections in configuration.')
return cron_info[0]
| [
"def",
"LoadSingleCron",
"(",
"cron_info",
",",
"open_fn",
"=",
"None",
")",
":",
"builder",
"=",
"yaml_object",
".",
"ObjectBuilder",
"(",
"CronInfoExternal",
")",
"handler",
"=",
"yaml_builder",
".",
"BuilderHandler",
"(",
"builder",
")",
"listener",
"=",
"y... | load a cron . | train | false |
29,559 | def _platform(*args):
platform = '-'.join((x.strip() for x in filter(len, args)))
platform = platform.replace(' ', '_')
platform = platform.replace('/', '-')
platform = platform.replace('\\', '-')
platform = platform.replace(':', '-')
platform = platform.replace(';', '-')
platform = platform.replace('"', '-')
platform = platform.replace('(', '-')
platform = platform.replace(')', '-')
platform = platform.replace('unknown', '')
while 1:
cleaned = platform.replace('--', '-')
if (cleaned == platform):
break
platform = cleaned
while (platform[(-1)] == '-'):
platform = platform[:(-1)]
return platform
| [
"def",
"_platform",
"(",
"*",
"args",
")",
":",
"platform",
"=",
"'-'",
".",
"join",
"(",
"(",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"filter",
"(",
"len",
",",
"args",
")",
")",
")",
"platform",
"=",
"platform",
".",
"replace",
"(",
"'... | helper to format the platform string in a filename compatible format e . | train | false |
29,562 | def BoundedSemaphore(value=1):
from multiprocessing.synchronize import BoundedSemaphore
return BoundedSemaphore(value)
| [
"def",
"BoundedSemaphore",
"(",
"value",
"=",
"1",
")",
":",
"from",
"multiprocessing",
".",
"synchronize",
"import",
"BoundedSemaphore",
"return",
"BoundedSemaphore",
"(",
"value",
")"
] | a factory function that returns a new bounded semaphore . | train | false |
29,564 | def _has_init(directory):
mod_or_pack = join(directory, '__init__')
for ext in (PY_SOURCE_EXTS + ('pyc', 'pyo')):
if exists(((mod_or_pack + '.') + ext)):
return ((mod_or_pack + '.') + ext)
return None
| [
"def",
"_has_init",
"(",
"directory",
")",
":",
"mod_or_pack",
"=",
"join",
"(",
"directory",
",",
"'__init__'",
")",
"for",
"ext",
"in",
"(",
"PY_SOURCE_EXTS",
"+",
"(",
"'pyc'",
",",
"'pyo'",
")",
")",
":",
"if",
"exists",
"(",
"(",
"(",
"mod_or_pack... | if the given directory has a valid __init__ file . | train | false |
29,566 | def create_slices(start, stop, step=None, length=1):
if (step is None):
step = length
slices = [slice(t, (t + length), 1) for t in range(start, ((stop - length) + 1), step)]
return slices
| [
"def",
"create_slices",
"(",
"start",
",",
"stop",
",",
"step",
"=",
"None",
",",
"length",
"=",
"1",
")",
":",
"if",
"(",
"step",
"is",
"None",
")",
":",
"step",
"=",
"length",
"slices",
"=",
"[",
"slice",
"(",
"t",
",",
"(",
"t",
"+",
"length... | generate slices of time indexes . | train | false |
29,568 | def inverse_fisher_z_transform(z):
return (((e ** (2 * z)) - 1.0) / ((e ** (2 * z)) + 1.0))
| [
"def",
"inverse_fisher_z_transform",
"(",
"z",
")",
":",
"return",
"(",
"(",
"(",
"e",
"**",
"(",
"2",
"*",
"z",
")",
")",
"-",
"1.0",
")",
"/",
"(",
"(",
"e",
"**",
"(",
"2",
"*",
"z",
")",
")",
"+",
"1.0",
")",
")"
] | calculate the inverse of the fisher z transform on a z value . | train | false |
29,569 | def AddErrors(counts1, counts2):
return ErrorCounts((counts1.fn + counts2.fn), (counts1.fp + counts2.fp), (counts1.truth_count + counts2.truth_count), (counts1.test_count + counts2.test_count))
| [
"def",
"AddErrors",
"(",
"counts1",
",",
"counts2",
")",
":",
"return",
"ErrorCounts",
"(",
"(",
"counts1",
".",
"fn",
"+",
"counts2",
".",
"fn",
")",
",",
"(",
"counts1",
".",
"fp",
"+",
"counts2",
".",
"fp",
")",
",",
"(",
"counts1",
".",
"truth_... | adds the counts and returns a new sum tuple . | train | false |
29,570 | def setup_formatters():
_registry.register_formats(_BUILTIN_FORMATS)
| [
"def",
"setup_formatters",
"(",
")",
":",
"_registry",
".",
"register_formats",
"(",
"_BUILTIN_FORMATS",
")"
] | register all built-in formatters . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.