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 |
|---|---|---|---|---|---|
39,854 | def _key_value_callback(option, opt_str, value, parser):
try:
(k, v) = value.split('=', 1)
except ValueError:
parser.error(('%s argument %r is not of the form KEY=VALUE' % (opt_str, value)))
_default_to(parser, option.dest, {})
getattr(parser.values, option.dest)[k] = v
| [
"def",
"_key_value_callback",
"(",
"option",
",",
"opt_str",
",",
"value",
",",
"parser",
")",
":",
"try",
":",
"(",
"k",
",",
"v",
")",
"=",
"value",
".",
"split",
"(",
"'='",
",",
"1",
")",
"except",
"ValueError",
":",
"parser",
".",
"error",
"("... | callback for key=value pairs . | train | false |
39,855 | def upcharge(amount):
typecheck(amount, Decimal)
charge_amount = ((amount + FEE_CHARGE[0]) / (1 - FEE_CHARGE[1]))
charge_amount = charge_amount.quantize(FEE_CHARGE[0], rounding=ROUND_UP)
return (charge_amount, (charge_amount - amount))
| [
"def",
"upcharge",
"(",
"amount",
")",
":",
"typecheck",
"(",
"amount",
",",
"Decimal",
")",
"charge_amount",
"=",
"(",
"(",
"amount",
"+",
"FEE_CHARGE",
"[",
"0",
"]",
")",
"/",
"(",
"1",
"-",
"FEE_CHARGE",
"[",
"1",
"]",
")",
")",
"charge_amount",
... | given an amount . | train | false |
39,856 | def _to_datetime(iso8601_time):
if (iso8601_time is None):
return None
return iso8601_to_datetime(iso8601_time)
| [
"def",
"_to_datetime",
"(",
"iso8601_time",
")",
":",
"if",
"(",
"iso8601_time",
"is",
"None",
")",
":",
"return",
"None",
"return",
"iso8601_to_datetime",
"(",
"iso8601_time",
")"
] | convert a iso8601-formatted datetime to a :py:class:datetime . | train | false |
39,857 | @then(u'an undefined-step snippet should not exist for "{step}"')
def step_undefined_step_snippet_should_not_exist_for(context, step):
undefined_step_snippet = make_undefined_step_snippet(step)
context.execute_steps(u'Then the command output should not contain:\n """\n {undefined_step_snippet}\n """\n '.f... | [
"@",
"then",
"(",
"u'an undefined-step snippet should not exist for \"{step}\"'",
")",
"def",
"step_undefined_step_snippet_should_not_exist_for",
"(",
"context",
",",
"step",
")",
":",
"undefined_step_snippet",
"=",
"make_undefined_step_snippet",
"(",
"step",
")",
"context",
... | checks if an undefined-step snippet is provided for a step in behave command output . | train | false |
39,858 | def create_ipsecpolicy(name, profile=None, **kwargs):
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
| [
"def",
"create_ipsecpolicy",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"create_ipsecpolicy",
"(",
"name",
",",
"**",
"kwargs",
")"
] | creates a new ipsecpolicy cli example: . | train | true |
39,860 | def generate_datafile(number_items=20000):
from utils import generate_dataset_shelve
filename = 'samples.shelve'
dataset = generate_dataset_shelve(filename, number_items)
print ('%s generated with %d samples' % (filename, number_items))
| [
"def",
"generate_datafile",
"(",
"number_items",
"=",
"20000",
")",
":",
"from",
"utils",
"import",
"generate_dataset_shelve",
"filename",
"=",
"'samples.shelve'",
"dataset",
"=",
"generate_dataset_shelve",
"(",
"filename",
",",
"number_items",
")",
"print",
"(",
"'... | create the samples . | train | true |
39,861 | def benchmark_command(command, benchmark_script, summarize_script, output_dir, num_iterations, dry_run, upkeep=None, cleanup=None):
performance_dir = os.path.join(output_dir, 'performance')
if os.path.exists(performance_dir):
shutil.rmtree(performance_dir)
os.makedirs(performance_dir)
try:
for i in range(num_it... | [
"def",
"benchmark_command",
"(",
"command",
",",
"benchmark_script",
",",
"summarize_script",
",",
"output_dir",
",",
"num_iterations",
",",
"dry_run",
",",
"upkeep",
"=",
"None",
",",
"cleanup",
"=",
"None",
")",
":",
"performance_dir",
"=",
"os",
".",
"path"... | benchmark several runs of a long-running command . | train | false |
39,862 | def unary_predicate(func):
func.argtypes = [GEOM_PTR]
func.restype = c_char
func.errcheck = check_predicate
return func
| [
"def",
"unary_predicate",
"(",
"func",
")",
":",
"func",
".",
"argtypes",
"=",
"[",
"GEOM_PTR",
"]",
"func",
".",
"restype",
"=",
"c_char",
"func",
".",
"errcheck",
"=",
"check_predicate",
"return",
"func"
] | for geos unary predicate functions . | train | false |
39,863 | def stack_size(size=None):
if (size is not None):
raise error('setting thread stack size not supported')
return 0
| [
"def",
"stack_size",
"(",
"size",
"=",
"None",
")",
":",
"if",
"(",
"size",
"is",
"not",
"None",
")",
":",
"raise",
"error",
"(",
"'setting thread stack size not supported'",
")",
"return",
"0"
] | dummy implementation of thread . | train | false |
39,864 | def report_test_tree(output, flaky_tests):
reporter = TreeReporter(output)
for (test, flaky) in flaky_tests:
new_test = clone_test_with_new_id(test, '{}({})'.format(test.id(), ', '.join(flaky.jira_keys)))
reporter.startTest(new_test)
reporter.addSuccess(new_test)
reporter.stopTest(new_test)
reporter.done()
| [
"def",
"report_test_tree",
"(",
"output",
",",
"flaky_tests",
")",
":",
"reporter",
"=",
"TreeReporter",
"(",
"output",
")",
"for",
"(",
"test",
",",
"flaky",
")",
"in",
"flaky_tests",
":",
"new_test",
"=",
"clone_test_with_new_id",
"(",
"test",
",",
"'{}({}... | print all flaky tests as a tree . | train | false |
39,865 | def check_optional(name, allowXHTML=False, merge_multiple=False):
def check(n, filename):
n = get_nodes_by_name(n, name)
if ((len(n) > 1) and (not merge_multiple)):
raise ManifestException(("Invalid manifest file: must have a single '%s' element" % name))
if n:
values = []
for child in n:
if allowXH... | [
"def",
"check_optional",
"(",
"name",
",",
"allowXHTML",
"=",
"False",
",",
"merge_multiple",
"=",
"False",
")",
":",
"def",
"check",
"(",
"n",
",",
"filename",
")",
":",
"n",
"=",
"get_nodes_by_name",
"(",
"n",
",",
"name",
")",
"if",
"(",
"(",
"len... | validator for optional elements . | train | false |
39,867 | def get_by_name_or_id(context, identity):
if (not uuidutils.is_uuid_like(identity)):
return get_volume_type_by_name(context, identity)
return get_volume_type(context, identity)
| [
"def",
"get_by_name_or_id",
"(",
"context",
",",
"identity",
")",
":",
"if",
"(",
"not",
"uuidutils",
".",
"is_uuid_like",
"(",
"identity",
")",
")",
":",
"return",
"get_volume_type_by_name",
"(",
"context",
",",
"identity",
")",
"return",
"get_volume_type",
"... | retrieves volume type by id or name . | train | false |
39,869 | def _get_image_blob(im):
im_orig = im.astype(np.float32, copy=True)
im_orig -= cfg.PIXEL_MEANS
im_shape = im_orig.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
processed_ims = []
im_scale_factors = []
for target_size in cfg.TEST.SCALES:
im_scale = (float(target_size) / float(im... | [
"def",
"_get_image_blob",
"(",
"im",
")",
":",
"im_orig",
"=",
"im",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"copy",
"=",
"True",
")",
"im_orig",
"-=",
"cfg",
".",
"PIXEL_MEANS",
"im_shape",
"=",
"im_orig",
".",
"shape",
"im_size_min",
"=",
"np"... | converts an image into a network input . | train | false |
39,870 | def _lookup_error(number):
return_values = {2: 'Invalid OU or specifying OU is not supported', 5: 'Access is denied', 53: 'The network path was not found', 87: 'The parameter is incorrect', 110: 'The system cannot open the specified object', 1323: 'Unable to update the password', 1326: 'Logon failure: unknown username... | [
"def",
"_lookup_error",
"(",
"number",
")",
":",
"return_values",
"=",
"{",
"2",
":",
"'Invalid OU or specifying OU is not supported'",
",",
"5",
":",
"'Access is denied'",
",",
"53",
":",
"'The network path was not found'",
",",
"87",
":",
"'The parameter is incorrect'... | lookup the error based on the passed number . | train | false |
39,871 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | return a fresh instance of the hash object . | train | false |
39,872 | def filter_headers(headers, remove_headers):
remove_headers = [((h, None) if isinstance(h, basestring) else h) for h in remove_headers]
remove_headers = dict(((h.lower(), v) for (h, v) in remove_headers))
headers = dict(((h, remove_headers.get(h.lower(), v)) for (h, v) in headers.items()))
headers = dict(((h, v) fo... | [
"def",
"filter_headers",
"(",
"headers",
",",
"remove_headers",
")",
":",
"remove_headers",
"=",
"[",
"(",
"(",
"h",
",",
"None",
")",
"if",
"isinstance",
"(",
"h",
",",
"basestring",
")",
"else",
"h",
")",
"for",
"h",
"in",
"remove_headers",
"]",
"rem... | remove undesired headers from the provided headers dict . | train | false |
39,873 | def p_equality_expression_2(t):
pass
| [
"def",
"p_equality_expression_2",
"(",
"t",
")",
":",
"pass"
] | equality_expression : equality_expression eq relational_expression . | train | false |
39,874 | def loopbackTCP(server, client, port=0, noisy=True):
from twisted.internet import reactor
f = policies.WrappingFactory(protocol.Factory())
serverWrapper = _FireOnClose(f, server)
f.noisy = noisy
f.buildProtocol = (lambda addr: serverWrapper)
serverPort = reactor.listenTCP(port, f, interface='127.0.0.1')
clientF ... | [
"def",
"loopbackTCP",
"(",
"server",
",",
"client",
",",
"port",
"=",
"0",
",",
"noisy",
"=",
"True",
")",
":",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"f",
"=",
"policies",
".",
"WrappingFactory",
"(",
"protocol",
".",
"Factory",
"(",
... | run session between server and client protocol instances over tcp . | train | false |
39,875 | def _is_scaled_mri_subject(subject, subjects_dir=None):
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
if (not _is_mri_subject(subject, subjects_dir)):
return False
fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg')
return os.path.exists(fname)
| [
"def",
"_is_scaled_mri_subject",
"(",
"subject",
",",
"subjects_dir",
"=",
"None",
")",
":",
"subjects_dir",
"=",
"get_subjects_dir",
"(",
"subjects_dir",
",",
"raise_error",
"=",
"True",
")",
"if",
"(",
"not",
"_is_mri_subject",
"(",
"subject",
",",
"subjects_d... | check whether a directory in subjects_dir is a scaled mri subject . | train | false |
39,876 | @utils.arg('flavor', metavar='<flavor>', help=_('Flavor name or ID to add access for the given tenant.'))
@utils.arg('tenant', metavar='<tenant_id>', help=_('Tenant ID to add flavor access for.'))
def do_flavor_access_add(cs, args):
flavor = _find_flavor(cs, args.flavor)
access_list = cs.flavor_access.add_tenant_acce... | [
"@",
"utils",
".",
"arg",
"(",
"'flavor'",
",",
"metavar",
"=",
"'<flavor>'",
",",
"help",
"=",
"_",
"(",
"'Flavor name or ID to add access for the given tenant.'",
")",
")",
"@",
"utils",
".",
"arg",
"(",
"'tenant'",
",",
"metavar",
"=",
"'<tenant_id>'",
",",... | add flavor access for the given tenant . | train | false |
39,877 | def _setHTTPTimeout():
if conf.timeout:
infoMsg = 'setting the HTTP timeout'
logger.log(CUSTOM_LOGGING.SYSINFO, infoMsg)
conf.timeout = float(conf.timeout)
if (conf.timeout < 3.0):
warnMsg = 'the minimum HTTP timeout is 3 seconds, pocsuite will going to reset it'
logger.log(CUSTOM_LOGGING.WARNING, warnMs... | [
"def",
"_setHTTPTimeout",
"(",
")",
":",
"if",
"conf",
".",
"timeout",
":",
"infoMsg",
"=",
"'setting the HTTP timeout'",
"logger",
".",
"log",
"(",
"CUSTOM_LOGGING",
".",
"SYSINFO",
",",
"infoMsg",
")",
"conf",
".",
"timeout",
"=",
"float",
"(",
"conf",
"... | set the http timeout . | train | false |
39,878 | def dmp_l1_norm(f, u, K):
if (not u):
return dup_l1_norm(f, K)
v = (u - 1)
return sum([dmp_l1_norm(c, v, K) for c in f])
| [
"def",
"dmp_l1_norm",
"(",
"f",
",",
"u",
",",
"K",
")",
":",
"if",
"(",
"not",
"u",
")",
":",
"return",
"dup_l1_norm",
"(",
"f",
",",
"K",
")",
"v",
"=",
"(",
"u",
"-",
"1",
")",
"return",
"sum",
"(",
"[",
"dmp_l1_norm",
"(",
"c",
",",
"v"... | returns l1 norm of a polynomial in k[x] . | train | false |
39,879 | def default_request_ip_resolver(request):
return (real_ip(request) or x_forwarded_ip(request) or remote_addr_ip(request))
| [
"def",
"default_request_ip_resolver",
"(",
"request",
")",
":",
"return",
"(",
"real_ip",
"(",
"request",
")",
"or",
"x_forwarded_ip",
"(",
"request",
")",
"or",
"remote_addr_ip",
"(",
"request",
")",
")"
] | this is a hybrid request ip resolver that attempts should address most cases . | train | false |
39,880 | def PackString(name, value, pbvalue):
pbvalue.set_stringvalue(unicode(value).encode('utf-8'))
| [
"def",
"PackString",
"(",
"name",
",",
"value",
",",
"pbvalue",
")",
":",
"pbvalue",
".",
"set_stringvalue",
"(",
"unicode",
"(",
"value",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | packs a string-typed property into a entity_pb . | train | false |
39,881 | @click.command(u'purge-jobs')
@click.option(u'--site', help=u'site name')
@click.option(u'--queue', default=None, help=u'one of "low", "default", "high')
@click.option(u'--event', default=None, help=u'one of "all", "weekly", "monthly", "hourly", "daily", "weekly_long", "daily_long"')
def purge_jobs(site=None, queue=Non... | [
"@",
"click",
".",
"command",
"(",
"u'purge-jobs'",
")",
"@",
"click",
".",
"option",
"(",
"u'--site'",
",",
"help",
"=",
"u'site name'",
")",
"@",
"click",
".",
"option",
"(",
"u'--queue'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"u'one of \"low\... | purge any pending periodic tasks . | train | false |
39,882 | def Channel(n):
rv = channels.get(n, None)
if (rv is None):
rv = ChannelImpl(n)
channels[n] = rv
return rv
| [
"def",
"Channel",
"(",
"n",
")",
":",
"rv",
"=",
"channels",
".",
"get",
"(",
"n",
",",
"None",
")",
"if",
"(",
"rv",
"is",
"None",
")",
":",
"rv",
"=",
"ChannelImpl",
"(",
"n",
")",
"channels",
"[",
"n",
"]",
"=",
"rv",
"return",
"rv"
] | gets the channel with the given number . | train | true |
39,883 | @cache_page(3600, key_prefix=('js18n-%s' % get_language()))
def javascript_catalog_all(request, domain='djangojs'):
all_apps = [x.name for x in apps.get_app_configs()]
return javascript_catalog(request, domain, all_apps)
| [
"@",
"cache_page",
"(",
"3600",
",",
"key_prefix",
"=",
"(",
"'js18n-%s'",
"%",
"get_language",
"(",
")",
")",
")",
"def",
"javascript_catalog_all",
"(",
"request",
",",
"domain",
"=",
"'djangojs'",
")",
":",
"all_apps",
"=",
"[",
"x",
".",
"name",
"for"... | get javascript message catalog for all apps in installed_apps . | train | false |
39,884 | def test_significant():
f = formatters.significant
assert (f(1) == '1')
assert (f(1.0) == '1')
assert (f((-1.0)) == '-1')
assert (f(10) == '10')
assert (f(10000000000) == '1e+10')
assert (f(100000000000) == '1e+11')
assert (f(120000000000) == '1.2e+11')
assert (f(0.1) == '0.1')
assert (f(0.01) == '0.01')
ass... | [
"def",
"test_significant",
"(",
")",
":",
"f",
"=",
"formatters",
".",
"significant",
"assert",
"(",
"f",
"(",
"1",
")",
"==",
"'1'",
")",
"assert",
"(",
"f",
"(",
"1.0",
")",
"==",
"'1'",
")",
"assert",
"(",
"f",
"(",
"(",
"-",
"1.0",
")",
")"... | test significant formatter . | train | false |
39,885 | @default_selem
def black_tophat(image, selem=None, out=None):
if (out is image):
original = image.copy()
else:
original = image
out = closing(image, selem, out=out)
out -= original
return out
| [
"@",
"default_selem",
"def",
"black_tophat",
"(",
"image",
",",
"selem",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"if",
"(",
"out",
"is",
"image",
")",
":",
"original",
"=",
"image",
".",
"copy",
"(",
")",
"else",
":",
"original",
"=",
"imag... | return black top hat of an image . | train | false |
39,886 | def get_outgoing_url(url):
if (not settings.REDIRECT_URL):
return url
parsed_url = urlparse(url)
url_netloc = parsed_url.netloc
if (parsed_url.scheme not in ['http', 'https']):
return '/'
if ((url_netloc == urlparse(settings.REDIRECT_URL).netloc) or (url_netloc in settings.REDIRECT_URL_ALLOW_LIST)):
return u... | [
"def",
"get_outgoing_url",
"(",
"url",
")",
":",
"if",
"(",
"not",
"settings",
".",
"REDIRECT_URL",
")",
":",
"return",
"url",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"url_netloc",
"=",
"parsed_url",
".",
"netloc",
"if",
"(",
"parsed_url",
".",
"... | bounce a url off an outgoing url redirector . | train | false |
39,889 | def send_draft_copy(account, draft, custom_body, recipient):
response_on_success = encode(draft)
response_on_success['body'] = custom_body
response_on_success = APIEncoder().jsonify(response_on_success)
try:
sendmail_client = get_sendmail_client(account)
sendmail_client.send_custom(draft, custom_body, [recipien... | [
"def",
"send_draft_copy",
"(",
"account",
",",
"draft",
",",
"custom_body",
",",
"recipient",
")",
":",
"response_on_success",
"=",
"encode",
"(",
"draft",
")",
"response_on_success",
"[",
"'body'",
"]",
"=",
"custom_body",
"response_on_success",
"=",
"APIEncoder"... | sends a copy of this draft to the recipient . | train | false |
39,891 | def const_non_dominated_sort(iterable, key=(lambda x: x), allowequality=True):
items = set(iterable)
fronts = []
while items:
front = const_non_dominated_front(items, key, allowequality)
items -= front
fronts.append(front)
return fronts
| [
"def",
"const_non_dominated_sort",
"(",
"iterable",
",",
"key",
"=",
"(",
"lambda",
"x",
":",
"x",
")",
",",
"allowequality",
"=",
"True",
")",
":",
"items",
"=",
"set",
"(",
"iterable",
")",
"fronts",
"=",
"[",
"]",
"while",
"items",
":",
"front",
"... | return a list that is sorted in a non-dominating fashion . | train | false |
39,892 | def number_of_nodes(G):
return G.number_of_nodes()
| [
"def",
"number_of_nodes",
"(",
"G",
")",
":",
"return",
"G",
".",
"number_of_nodes",
"(",
")"
] | return the number of nodes in the graph . | train | false |
39,893 | def test_group_column_from_table(T1):
cg = T1['c'].group_by(np.array(T1['a']))
assert np.all((cg.groups.keys == np.array([0, 1, 2])))
assert np.all((cg.groups.indices == np.array([0, 1, 4, 8])))
| [
"def",
"test_group_column_from_table",
"(",
"T1",
")",
":",
"cg",
"=",
"T1",
"[",
"'c'",
"]",
".",
"group_by",
"(",
"np",
".",
"array",
"(",
"T1",
"[",
"'a'",
"]",
")",
")",
"assert",
"np",
".",
"all",
"(",
"(",
"cg",
".",
"groups",
".",
"keys",
... | group a column that is part of a table . | train | false |
39,894 | def tar(file, filelist, expression='^.+$'):
tar = tarfile.TarFile(file, 'w')
try:
for element in filelist:
try:
for file in listdir(element, expression, add_dirs=True):
tar.add(os.path.join(element, file), file, False)
except:
tar.add(element)
finally:
tar.close()
| [
"def",
"tar",
"(",
"file",
",",
"filelist",
",",
"expression",
"=",
"'^.+$'",
")",
":",
"tar",
"=",
"tarfile",
".",
"TarFile",
"(",
"file",
",",
"'w'",
")",
"try",
":",
"for",
"element",
"in",
"filelist",
":",
"try",
":",
"for",
"file",
"in",
"list... | tars dir into file . | train | false |
39,896 | def saltpath():
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
| [
"def",
"saltpath",
"(",
")",
":",
"salt_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"os",
".",
"path",
".",
"pardir",
")",
")",
"return",
"{",
"'saltpath'",
":",
"os",
".",
"path",
"."... | return the path of the salt module . | train | true |
39,898 | def install_cygwin(name, install_args=None, override_args=False):
return install(name, source='cygwin', install_args=install_args, override_args=override_args)
| [
"def",
"install_cygwin",
"(",
"name",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"return",
"install",
"(",
"name",
",",
"source",
"=",
"'cygwin'",
",",
"install_args",
"=",
"install_args",
",",
"override_args",
"=",
"over... | instructs chocolatey to install a package via cygwin . | train | true |
39,899 | def get_blas_funcs(names, arrays=(), dtype=None):
return _get_funcs(names, arrays, dtype, 'BLAS', _fblas, _cblas, 'fblas', 'cblas', _blas_alias)
| [
"def",
"get_blas_funcs",
"(",
"names",
",",
"arrays",
"=",
"(",
")",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"_get_funcs",
"(",
"names",
",",
"arrays",
",",
"dtype",
",",
"'BLAS'",
",",
"_fblas",
",",
"_cblas",
",",
"'fblas'",
",",
"'cblas'",
... | return available blas function objects from names . | train | false |
39,900 | def get_theme_dir(name):
theme = get_themes()[name]
return os.path.dirname(os.path.abspath(theme.load().__file__))
| [
"def",
"get_theme_dir",
"(",
"name",
")",
":",
"theme",
"=",
"get_themes",
"(",
")",
"[",
"name",
"]",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"theme",
".",
"load",
"(",
")",
".",
"__file__",
")",
... | return the directory of an installed theme by name . | train | false |
39,901 | def index_alt():
s3_redirect_default(URL(f='person'))
| [
"def",
"index_alt",
"(",
")",
":",
"s3_redirect_default",
"(",
"URL",
"(",
"f",
"=",
"'person'",
")",
")"
] | module homepage for non-admin users when no cms content found . | train | false |
39,902 | def create_client_from_parsed_globals(session, service_name, parsed_globals, overrides=None):
client_args = {}
if ('region' in parsed_globals):
client_args['region_name'] = parsed_globals.region
if ('endpoint_url' in parsed_globals):
client_args['endpoint_url'] = parsed_globals.endpoint_url
if ('verify_ssl' in ... | [
"def",
"create_client_from_parsed_globals",
"(",
"session",
",",
"service_name",
",",
"parsed_globals",
",",
"overrides",
"=",
"None",
")",
":",
"client_args",
"=",
"{",
"}",
"if",
"(",
"'region'",
"in",
"parsed_globals",
")",
":",
"client_args",
"[",
"'region_n... | creates a service client . | train | false |
39,905 | def test_ast_good_drop():
can_compile(u'(drop 1 [2 3])')
| [
"def",
"test_ast_good_drop",
"(",
")",
":",
"can_compile",
"(",
"u'(drop 1 [2 3])'",
")"
] | make sure ast can compile valid drop . | train | false |
39,908 | def installPexpect(vm, prompt=Prompt):
vm.sendline('sudo -n apt-get -qy install python-pexpect')
vm.expect(prompt)
| [
"def",
"installPexpect",
"(",
"vm",
",",
"prompt",
"=",
"Prompt",
")",
":",
"vm",
".",
"sendline",
"(",
"'sudo -n apt-get -qy install python-pexpect'",
")",
"vm",
".",
"expect",
"(",
"prompt",
")"
] | install pexpect . | train | false |
39,909 | def is_app_name_valid(app_name):
if re.match(VALID_APP_NAME_CHARS_REGEX, app_name):
return True
else:
return False
| [
"def",
"is_app_name_valid",
"(",
"app_name",
")",
":",
"if",
"re",
".",
"match",
"(",
"VALID_APP_NAME_CHARS_REGEX",
",",
"app_name",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | validates an application by checking if it contains certain characters . | train | false |
39,910 | def _count_syllables(word):
n = 0
p = False
for ch in ((word.endswith('e') and word[:(-1)]) or word):
v = (ch in VOWELS)
n += int((v and (not p)))
p = v
return n
| [
"def",
"_count_syllables",
"(",
"word",
")",
":",
"n",
"=",
"0",
"p",
"=",
"False",
"for",
"ch",
"in",
"(",
"(",
"word",
".",
"endswith",
"(",
"'e'",
")",
"and",
"word",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
"or",
"word",
")",
":",
"v",
"... | returns the estimated number of syllables in the word by counting vowel-groups . | train | false |
39,911 | @library.filter
def entity_decode(str):
return htmlparser.unescape(str)
| [
"@",
"library",
".",
"filter",
"def",
"entity_decode",
"(",
"str",
")",
":",
"return",
"htmlparser",
".",
"unescape",
"(",
"str",
")"
] | turn html entities in a string into unicode . | train | false |
39,913 | def Linkable(filename):
return filename.endswith('.o')
| [
"def",
"Linkable",
"(",
"filename",
")",
":",
"return",
"filename",
".",
"endswith",
"(",
"'.o'",
")"
] | return true if the file is linkable . | train | false |
39,914 | @bdd.then(bdd.parsers.parse('{path} should be requested'))
def path_should_be_requested(httpbin, path):
httpbin.wait_for(verb='GET', path=('/' + path))
| [
"@",
"bdd",
".",
"then",
"(",
"bdd",
".",
"parsers",
".",
"parse",
"(",
"'{path} should be requested'",
")",
")",
"def",
"path_should_be_requested",
"(",
"httpbin",
",",
"path",
")",
":",
"httpbin",
".",
"wait_for",
"(",
"verb",
"=",
"'GET'",
",",
"path",
... | make sure the given path was loaded from the webserver . | train | false |
39,919 | def unicode_from_os(e):
if (sys.version_info >= (3,)):
return str(e)
try:
if isinstance(e, Exception):
e = e.args[0]
if isinstance(e, str_cls):
return e
if isinstance(e, int):
e = str(e)
return str_cls(e, _encoding)
except UnicodeDecodeError:
for encoding in _fallback_encodings:
try:
retu... | [
"def",
"unicode_from_os",
"(",
"e",
")",
":",
"if",
"(",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
")",
")",
":",
"return",
"str",
"(",
"e",
")",
"try",
":",
"if",
"isinstance",
"(",
"e",
",",
"Exception",
")",
":",
"e",
"=",
"e",
".",
... | this is needed as some exceptions coming from the os are already encoded and so just calling unicode(e) will result in an unicodedecodeerror as the string isnt in ascii form . | train | false |
39,920 | def rotation3d(x=0, y=0, z=0):
cos_x = cos(x)
cos_y = cos(y)
cos_z = cos(z)
sin_x = sin(x)
sin_y = sin(y)
sin_z = sin(z)
r = np.array([[(cos_y * cos_z), (((- cos_x) * sin_z) + ((sin_x * sin_y) * cos_z)), ((sin_x * sin_z) + ((cos_x * sin_y) * cos_z))], [(cos_y * sin_z), ((cos_x * cos_z) + ((sin_x * sin_y) * sin_z... | [
"def",
"rotation3d",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"z",
"=",
"0",
")",
":",
"cos_x",
"=",
"cos",
"(",
"x",
")",
"cos_y",
"=",
"cos",
"(",
"y",
")",
"cos_z",
"=",
"cos",
"(",
"z",
")",
"sin_x",
"=",
"sin",
"(",
"x",
")",
"... | create an array with a 3 dimensional rotation matrix . | train | false |
39,921 | def print_headers_as_table(args):
tables = []
for filename in args.filename:
try:
formatter = TableHeaderFormatter(filename)
tbl = formatter.parse(args.extensions, args.keywords, args.compressed)
if tbl:
tables.append(tbl)
except IOError as e:
log.error(str(e))
if (len(tables) == 0):
return Fal... | [
"def",
"print_headers_as_table",
"(",
"args",
")",
":",
"tables",
"=",
"[",
"]",
"for",
"filename",
"in",
"args",
".",
"filename",
":",
"try",
":",
"formatter",
"=",
"TableHeaderFormatter",
"(",
"filename",
")",
"tbl",
"=",
"formatter",
".",
"parse",
"(",
... | prints fits header(s) in a machine-readable table format . | train | false |
39,922 | def header_quopri_check(c):
return bool(hqre.match(c))
| [
"def",
"header_quopri_check",
"(",
"c",
")",
":",
"return",
"bool",
"(",
"hqre",
".",
"match",
"(",
"c",
")",
")"
] | return true if the character should be escaped with header quopri . | train | false |
39,923 | def parse_coverage(report_dir, coveragerc):
report_dir.makedirs_p()
msg = colorize('green', 'Combining coverage reports')
print msg
sh('coverage combine --rcfile={}'.format(coveragerc))
msg = colorize('green', 'Generating coverage reports')
print msg
sh('coverage html --rcfile={}'.format(coveragerc))
sh('covera... | [
"def",
"parse_coverage",
"(",
"report_dir",
",",
"coveragerc",
")",
":",
"report_dir",
".",
"makedirs_p",
"(",
")",
"msg",
"=",
"colorize",
"(",
"'green'",
",",
"'Combining coverage reports'",
")",
"print",
"msg",
"sh",
"(",
"'coverage combine --rcfile={}'",
".",
... | generate coverage reports for bok-choy or a11y tests . | train | false |
39,924 | @require_POST
def ajax_enable(request):
if (not request.user.is_authenticated()):
raise PermissionDenied
enable_notifications(request.user)
return HttpResponse(status=204)
| [
"@",
"require_POST",
"def",
"ajax_enable",
"(",
"request",
")",
":",
"if",
"(",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
")",
":",
"raise",
"PermissionDenied",
"enable_notifications",
"(",
"request",
".",
"user",
")",
"return",
"Http... | a view that enables notifications for the authenticated user this view should be invoked by an ajax post call . | train | false |
39,925 | def compile_views(folder, skip_failed_views=False):
path = pjoin(folder, 'views')
failed_views = []
for fname in listdir(path, '^[\\w/\\-]+(\\.\\w+)*$'):
try:
data = parse_template(fname, path)
except Exception as e:
if skip_failed_views:
failed_views.append(fname)
else:
raise Exception(('%s in ... | [
"def",
"compile_views",
"(",
"folder",
",",
"skip_failed_views",
"=",
"False",
")",
":",
"path",
"=",
"pjoin",
"(",
"folder",
",",
"'views'",
")",
"failed_views",
"=",
"[",
"]",
"for",
"fname",
"in",
"listdir",
"(",
"path",
",",
"'^[\\\\w/\\\\-]+(\\\\.\\\\w+... | compiles all the views in the application specified by folder . | train | false |
39,926 | def makeData(amount=10000):
center = array([0.5, 0.5])
def makePoint():
"Return a random point and its satellite information.\n\n Satellite is 'blue' if point is in the circle, else 'red'."
point = (random.random((2,)) * 10)
vectorLength = (lambda x: dot(x.T, x))
return (point, ('blue' if (vectorLength... | [
"def",
"makeData",
"(",
"amount",
"=",
"10000",
")",
":",
"center",
"=",
"array",
"(",
"[",
"0.5",
",",
"0.5",
"]",
")",
"def",
"makePoint",
"(",
")",
":",
"point",
"=",
"(",
"random",
".",
"random",
"(",
"(",
"2",
",",
")",
")",
"*",
"10",
"... | return 2d dataset of points in where points in a circle of radius . | train | false |
39,927 | def get_latest_changelog():
started = False
lines = []
with open(CHANGELOG) as f:
for line in f:
if re.match('^--+$', line.strip()):
if started:
del lines[(-1)]
break
else:
started = True
elif started:
lines.append(line)
return ''.join(lines).strip()
| [
"def",
"get_latest_changelog",
"(",
")",
":",
"started",
"=",
"False",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"CHANGELOG",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"re",
".",
"match",
"(",
"'^--+$'",
",",
"line",
".",
"strip"... | extract the first section of the changelog . | train | false |
39,928 | def get_indexer_numbering(indexer_id, indexer, sceneSeason, sceneEpisode, fallback_to_xem=True):
if ((indexer_id is None) or (sceneSeason is None) or (sceneEpisode is None)):
return (sceneSeason, sceneEpisode)
indexer_id = int(indexer_id)
indexer = int(indexer)
main_db_con = db.DBConnection()
rows = main_db_con.... | [
"def",
"get_indexer_numbering",
"(",
"indexer_id",
",",
"indexer",
",",
"sceneSeason",
",",
"sceneEpisode",
",",
"fallback_to_xem",
"=",
"True",
")",
":",
"if",
"(",
"(",
"indexer_id",
"is",
"None",
")",
"or",
"(",
"sceneSeason",
"is",
"None",
")",
"or",
"... | returns a tuple . | train | false |
39,929 | @ignore_warnings
def check_estimators_pickle(name, Estimator):
check_methods = ['predict', 'transform', 'decision_function', 'predict_proba']
(X, y) = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], random_state=0, n_features=2, cluster_std=0.1)
X -= X.min()
y = multioutput_estimator_convert_y_2d(name, y)
... | [
"@",
"ignore_warnings",
"def",
"check_estimators_pickle",
"(",
"name",
",",
"Estimator",
")",
":",
"check_methods",
"=",
"[",
"'predict'",
",",
"'transform'",
",",
"'decision_function'",
",",
"'predict_proba'",
"]",
"(",
"X",
",",
"y",
")",
"=",
"make_blobs",
... | test that we can pickle all estimators . | train | false |
39,930 | def get_model_front_url(request, object):
if (not object.pk):
return None
if (u'shuup.front' in settings.INSTALLED_APPS):
try:
from shuup.front.template_helpers.urls import model_url
return model_url({u'request': request}, object)
except (ValueError, NoReverseMatch):
pass
return None
| [
"def",
"get_model_front_url",
"(",
"request",
",",
"object",
")",
":",
"if",
"(",
"not",
"object",
".",
"pk",
")",
":",
"return",
"None",
"if",
"(",
"u'shuup.front'",
"in",
"settings",
".",
"INSTALLED_APPS",
")",
":",
"try",
":",
"from",
"shuup",
".",
... | get a frontend url for an object . | train | false |
39,931 | def GC_skew(seq, window=100):
values = []
for i in range(0, len(seq), window):
s = seq[i:(i + window)]
g = (s.count('G') + s.count('g'))
c = (s.count('C') + s.count('c'))
skew = ((g - c) / float((g + c)))
values.append(skew)
return values
| [
"def",
"GC_skew",
"(",
"seq",
",",
"window",
"=",
"100",
")",
":",
"values",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"seq",
")",
",",
"window",
")",
":",
"s",
"=",
"seq",
"[",
"i",
":",
"(",
"i",
"+",
"window",
... | calculates gc skew / for multiple windows along the sequence . | train | false |
39,932 | def run_example(example, reporter=None):
if reporter:
reporter.write(example)
else:
print(('=' * 79))
print('Running: ', example)
try:
mod = load_example_module(example)
if reporter:
suppress_output(mod.main)
reporter.write('[PASS]', 'Green', align='right')
else:
mod.main()
return True
except... | [
"def",
"run_example",
"(",
"example",
",",
"reporter",
"=",
"None",
")",
":",
"if",
"reporter",
":",
"reporter",
".",
"write",
"(",
"example",
")",
"else",
":",
"print",
"(",
"(",
"'='",
"*",
"79",
")",
")",
"print",
"(",
"'Running: '",
",",
"example... | run a specific example . | train | false |
39,934 | @deprecated.Callable(deprecation=u'4.0', removal=u'5.0', alternative=u'Please use celery.app.backends.by_url')
def get_backend_cls(backend=None, loader=None, **kwargs):
return _backends.by_name(backend=backend, loader=loader, **kwargs)
| [
"@",
"deprecated",
".",
"Callable",
"(",
"deprecation",
"=",
"u'4.0'",
",",
"removal",
"=",
"u'5.0'",
",",
"alternative",
"=",
"u'Please use celery.app.backends.by_url'",
")",
"def",
"get_backend_cls",
"(",
"backend",
"=",
"None",
",",
"loader",
"=",
"None",
","... | get backend class by name/alias . | train | false |
39,935 | def scan_directory(project_tree, directory):
try:
return DirectoryListing(directory, tuple(project_tree.scandir(directory.path)), exists=True)
except (IOError, OSError) as e:
if (e.errno == errno.ENOENT):
return DirectoryListing(directory, tuple(), exists=False)
else:
raise e
| [
"def",
"scan_directory",
"(",
"project_tree",
",",
"directory",
")",
":",
"try",
":",
"return",
"DirectoryListing",
"(",
"directory",
",",
"tuple",
"(",
"project_tree",
".",
"scandir",
"(",
"directory",
".",
"path",
")",
")",
",",
"exists",
"=",
"True",
")... | list stat objects directly below the given path . | train | false |
39,937 | def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='simplex', callback=None, options=None):
meth = method.lower()
if (options is None):
options = {}
if (meth == 'simplex'):
return _linprog_simplex(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, callback=callback, **optio... | [
"def",
"linprog",
"(",
"c",
",",
"A_ub",
"=",
"None",
",",
"b_ub",
"=",
"None",
",",
"A_eq",
"=",
"None",
",",
"b_eq",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"method",
"=",
"'simplex'",
",",
"callback",
"=",
"None",
",",
"options",
"=",
"N... | minimize a linear objective function subject to linear equality and inequality constraints . | train | false |
39,938 | @pytest.fixture
def tutorial(english, settings):
import pytest_pootle
shutil.copytree(os.path.join(os.path.dirname(pytest_pootle.__file__), 'data', 'po', 'tutorial'), os.path.join(settings.POOTLE_TRANSLATION_DIRECTORY, 'tutorial'))
return _require_project('tutorial', 'Tutorial', english)
| [
"@",
"pytest",
".",
"fixture",
"def",
"tutorial",
"(",
"english",
",",
"settings",
")",
":",
"import",
"pytest_pootle",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"pytest_pootle",
".",
"... | require tutorial test project . | train | false |
39,939 | def _tessellate_sphere_surf(level, rad=1.0):
(rr, tris) = _tessellate_sphere(level)
npt = len(rr)
ntri = len(tris)
nn = rr.copy()
rr *= rad
s = dict(rr=rr, np=npt, tris=tris, use_tris=tris, ntri=ntri, nuse=np, nn=nn, inuse=np.ones(npt, int))
return s
| [
"def",
"_tessellate_sphere_surf",
"(",
"level",
",",
"rad",
"=",
"1.0",
")",
":",
"(",
"rr",
",",
"tris",
")",
"=",
"_tessellate_sphere",
"(",
"level",
")",
"npt",
"=",
"len",
"(",
"rr",
")",
"ntri",
"=",
"len",
"(",
"tris",
")",
"nn",
"=",
"rr",
... | return a surface structure instead of the details . | train | false |
39,940 | def p_list_type(p):
p[0] = (TType.LIST, p[3])
| [
"def",
"p_list_type",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"TType",
".",
"LIST",
",",
"p",
"[",
"3",
"]",
")"
] | list_type : list < field_type > . | train | false |
39,941 | @receiver(post_save, sender=CourseTeam)
def team_post_save_callback(sender, instance, **kwargs):
changed_fields = instance.field_tracker.changed()
if (not kwargs['created']):
for field in changed_fields:
if (field not in instance.FIELD_BLACKLIST):
truncated_fields = truncate_fields(unicode(changed_fields[fie... | [
"@",
"receiver",
"(",
"post_save",
",",
"sender",
"=",
"CourseTeam",
")",
"def",
"team_post_save_callback",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"changed_fields",
"=",
"instance",
".",
"field_tracker",
".",
"changed",
"(",
")",
"if"... | emits signal after the team is saved . | train | false |
39,942 | @handle_response_format
@treeio_login_required
def file_delete(request, file_id, response_format='html'):
file = get_object_or_404(File, pk=file_id)
if (not request.user.profile.has_permission(file, mode='w')):
return user_denied(request, message="You don't have access to this File")
if request.POST:
if ('delete... | [
"@",
"handle_response_format",
"@",
"treeio_login_required",
"def",
"file_delete",
"(",
"request",
",",
"file_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"file",
"=",
"get_object_or_404",
"(",
"File",
",",
"pk",
"=",
"file_id",
")",
"if",
"(",
"not",... | file delete . | train | false |
39,943 | def path_to_local_directory_uri(relpath):
if isinstance(relpath, compat.text_type):
relpath = relpath.encode(u'utf-8')
return (u'local:directory:%s' % urllib.quote(relpath))
| [
"def",
"path_to_local_directory_uri",
"(",
"relpath",
")",
":",
"if",
"isinstance",
"(",
"relpath",
",",
"compat",
".",
"text_type",
")",
":",
"relpath",
"=",
"relpath",
".",
"encode",
"(",
"u'utf-8'",
")",
"return",
"(",
"u'local:directory:%s'",
"%",
"urllib"... | convert path relative to :confval:local/media_dir to directory uri . | train | false |
39,945 | def group_show(context, data_dict):
return _group_or_org_show(context, data_dict)
| [
"def",
"group_show",
"(",
"context",
",",
"data_dict",
")",
":",
"return",
"_group_or_org_show",
"(",
"context",
",",
"data_dict",
")"
] | return the details of a group . | train | false |
39,947 | def stop_tuning(step):
if hasattr(step, 'tune'):
step.tune = False
elif hasattr(step, 'methods'):
step.methods = [stop_tuning(s) for s in step.methods]
return step
| [
"def",
"stop_tuning",
"(",
"step",
")",
":",
"if",
"hasattr",
"(",
"step",
",",
"'tune'",
")",
":",
"step",
".",
"tune",
"=",
"False",
"elif",
"hasattr",
"(",
"step",
",",
"'methods'",
")",
":",
"step",
".",
"methods",
"=",
"[",
"stop_tuning",
"(",
... | stop tuning the current step method . | train | false |
39,948 | def rid():
return (struct.unpack('@Q', os.urandom(8))[0] & _WAMP_ID_MASK)
| [
"def",
"rid",
"(",
")",
":",
"return",
"(",
"struct",
".",
"unpack",
"(",
"'@Q'",
",",
"os",
".",
"urandom",
"(",
"8",
")",
")",
"[",
"0",
"]",
"&",
"_WAMP_ID_MASK",
")"
] | generate a new random integer id from range **[0 . | train | false |
39,949 | def clear_mappers():
mapperlib._CONFIGURE_MUTEX.acquire()
try:
while _mapper_registry:
try:
(mapper, b) = _mapper_registry.popitem()
mapper.dispose()
except KeyError:
pass
finally:
mapperlib._CONFIGURE_MUTEX.release()
| [
"def",
"clear_mappers",
"(",
")",
":",
"mapperlib",
".",
"_CONFIGURE_MUTEX",
".",
"acquire",
"(",
")",
"try",
":",
"while",
"_mapper_registry",
":",
"try",
":",
"(",
"mapper",
",",
"b",
")",
"=",
"_mapper_registry",
".",
"popitem",
"(",
")",
"mapper",
".... | remove all mappers from all classes . | train | false |
39,950 | def _statsmodels_bivariate_kde(x, y, bw, gridsize, cut, clip):
if isinstance(bw, string_types):
bw_func = getattr(smnp.bandwidths, ('bw_' + bw))
x_bw = bw_func(x)
y_bw = bw_func(y)
bw = [x_bw, y_bw]
elif np.isscalar(bw):
bw = [bw, bw]
if isinstance(x, pd.Series):
x = x.values
if isinstance(y, pd.Series)... | [
"def",
"_statsmodels_bivariate_kde",
"(",
"x",
",",
"y",
",",
"bw",
",",
"gridsize",
",",
"cut",
",",
"clip",
")",
":",
"if",
"isinstance",
"(",
"bw",
",",
"string_types",
")",
":",
"bw_func",
"=",
"getattr",
"(",
"smnp",
".",
"bandwidths",
",",
"(",
... | compute a bivariate kde using statsmodels . | train | false |
39,951 | def create_anonymous_user(sender, **kwargs):
User = get_user_model()
try:
lookup = {User.USERNAME_FIELD: guardian_settings.ANONYMOUS_USER_NAME}
User.objects.get(**lookup)
except User.DoesNotExist:
retrieve_anonymous_function = import_string(guardian_settings.GET_INIT_ANONYMOUS_USER)
user = retrieve_anonymous... | [
"def",
"create_anonymous_user",
"(",
"sender",
",",
"**",
"kwargs",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"try",
":",
"lookup",
"=",
"{",
"User",
".",
"USERNAME_FIELD",
":",
"guardian_settings",
".",
"ANONYMOUS_USER_NAME",
"}",
"User",
".",
"obj... | creates anonymous user instance with id and username from settings . | train | false |
39,952 | def create_replicated_mapping_file(map_f, num_replicates, sample_ids):
if (num_replicates < 1):
raise ValueError(('Must specify at least one sample replicate (was provided %d).' % num_replicates))
(map_data, header, comments) = parse_mapping_file(map_f)
rep_map_data = []
for row in map_data:
if (row[0] in sampl... | [
"def",
"create_replicated_mapping_file",
"(",
"map_f",
",",
"num_replicates",
",",
"sample_ids",
")",
":",
"if",
"(",
"num_replicates",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Must specify at least one sample replicate (was provided %d).'",
"%",
"num_repl... | returns a formatted mapping file with replicated sample ids . | train | false |
39,953 | def median_absolute_deviation(x):
x = asarray(x)
median_x = median(x)
median_abs_deviation = median(abs((x - median_x)))
return (median_abs_deviation, median_x)
| [
"def",
"median_absolute_deviation",
"(",
"x",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"median_x",
"=",
"median",
"(",
"x",
")",
"median_abs_deviation",
"=",
"median",
"(",
"abs",
"(",
"(",
"x",
"-",
"median_x",
")",
")",
")",
"return",
"(",
"me... | compute the median of the absolute deviations from the median . | train | false |
39,955 | def sync_ldap_users(connection, failed_users=None):
users = User.objects.filter(userprofile__creation_method=str(UserProfile.CreationMethod.EXTERNAL)).all()
for user in users:
_import_ldap_users(connection, user.username, failed_users=failed_users)
return users
| [
"def",
"sync_ldap_users",
"(",
"connection",
",",
"failed_users",
"=",
"None",
")",
":",
"users",
"=",
"User",
".",
"objects",
".",
"filter",
"(",
"userprofile__creation_method",
"=",
"str",
"(",
"UserProfile",
".",
"CreationMethod",
".",
"EXTERNAL",
")",
")",... | syncs ldap user information . | train | false |
39,956 | def test_defn():
cant_compile(u'(defn if* [] 1)')
cant_compile(u'(defn "hy" [] 1)')
cant_compile(u'(defn :hy [] 1)')
can_compile(u'(defn &hy [] 1)')
| [
"def",
"test_defn",
"(",
")",
":",
"cant_compile",
"(",
"u'(defn if* [] 1)'",
")",
"cant_compile",
"(",
"u'(defn \"hy\" [] 1)'",
")",
"cant_compile",
"(",
"u'(defn :hy [] 1)'",
")",
"can_compile",
"(",
"u'(defn &hy [] 1)'",
")"
] | ensure that defn works correctly in various corner cases . | train | false |
39,957 | def create_folder(name, location='\\'):
if (name in list_folders(location)):
return '{0} already exists'.format(name)
pythoncom.CoInitialize()
task_service = win32com.client.Dispatch('Schedule.Service')
task_service.Connect()
task_folder = task_service.GetFolder(location)
task_folder.CreateFolder(name)
if (nam... | [
"def",
"create_folder",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"if",
"(",
"name",
"in",
"list_folders",
"(",
"location",
")",
")",
":",
"return",
"'{0} already exists'",
".",
"format",
"(",
"name",
")",
"pythoncom",
".",
"CoInitialize",
"("... | create a new folder inside the one received as a param . | train | false |
39,958 | def pportTristate(state):
global ctrlReg
if (state == 0):
ctrlReg = (ctrlReg & (~ 16))
else:
ctrlReg = (ctrlReg | 16)
port.DlPortWritePortUchar(ctrlRegAdrs, ctrlReg)
| [
"def",
"pportTristate",
"(",
"state",
")",
":",
"global",
"ctrlReg",
"if",
"(",
"state",
"==",
"0",
")",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"&",
"(",
"~",
"16",
")",
")",
"else",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"|",
"16",
")",
"port",
".",... | toggle tristate output bit . | train | false |
39,959 | def force_unicode(s):
if (s is None):
return None
else:
return unicod(s)
| [
"def",
"force_unicode",
"(",
"s",
")",
":",
"if",
"(",
"s",
"is",
"None",
")",
":",
"return",
"None",
"else",
":",
"return",
"unicod",
"(",
"s",
")"
] | wrapper around djangos version . | train | false |
39,960 | def dynamicsymbols(names, level=0):
esses = symbols(names, cls=Function)
t = dynamicsymbols._t
if iterable(esses):
esses = [reduce(diff, ([t] * level), e(t)) for e in esses]
return esses
else:
return reduce(diff, ([t] * level), esses(t))
| [
"def",
"dynamicsymbols",
"(",
"names",
",",
"level",
"=",
"0",
")",
":",
"esses",
"=",
"symbols",
"(",
"names",
",",
"cls",
"=",
"Function",
")",
"t",
"=",
"dynamicsymbols",
".",
"_t",
"if",
"iterable",
"(",
"esses",
")",
":",
"esses",
"=",
"[",
"r... | uses symbols and function for functions of time . | train | false |
39,961 | def provide_fake_entries(group):
return _FAKE_ENTRIES.get(group, [])
| [
"def",
"provide_fake_entries",
"(",
"group",
")",
":",
"return",
"_FAKE_ENTRIES",
".",
"get",
"(",
"group",
",",
"[",
"]",
")"
] | give a set of fake entries for known groups . | train | false |
39,962 | @xfail_py3
@xfail(wxPython_fail, reason='PyInstaller does not support this wxPython version')
@importorskip('wx.lib.pubsub.core')
def test_wx_lib_pubsub_protocol_kwargs(pyi_builder):
pyi_builder.test_script('pyi_hooks/wx_lib_pubsub_setupkwargs.py')
| [
"@",
"xfail_py3",
"@",
"xfail",
"(",
"wxPython_fail",
",",
"reason",
"=",
"'PyInstaller does not support this wxPython version'",
")",
"@",
"importorskip",
"(",
"'wx.lib.pubsub.core'",
")",
"def",
"test_wx_lib_pubsub_protocol_kwargs",
"(",
"pyi_builder",
")",
":",
"pyi_bu... | functional test specific to version 3 of the pypubsub api . | train | false |
39,963 | def get_exc_from_name(name):
exc = None
try:
return rc_exc_cache[name]
except KeyError:
m = rc_exc_regex.match(name)
if m:
base = m.group(1)
rc_or_sig_name = m.group(2)
if (base == 'SignalException'):
try:
rc = (- int(rc_or_sig_name))
except ValueError:
rc = (- getattr(signal, rc_or_... | [
"def",
"get_exc_from_name",
"(",
"name",
")",
":",
"exc",
"=",
"None",
"try",
":",
"return",
"rc_exc_cache",
"[",
"name",
"]",
"except",
"KeyError",
":",
"m",
"=",
"rc_exc_regex",
".",
"match",
"(",
"name",
")",
"if",
"m",
":",
"base",
"=",
"m",
".",... | takes an exception name . | train | true |
39,964 | def set_sff_trimpoints(sff_dir, technical_lengths):
for (lib_id, sff_fp) in get_per_lib_sff_fps(sff_dir):
try:
readlength = technical_lengths[lib_id]
except KeyError:
continue
sff_data = parse_binary_sff(open(sff_fp), True)
(clipped_header, clipped_reads) = set_clip_qual_left(sff_data, readlength)
(fd,... | [
"def",
"set_sff_trimpoints",
"(",
"sff_dir",
",",
"technical_lengths",
")",
":",
"for",
"(",
"lib_id",
",",
"sff_fp",
")",
"in",
"get_per_lib_sff_fps",
"(",
"sff_dir",
")",
":",
"try",
":",
"readlength",
"=",
"technical_lengths",
"[",
"lib_id",
"]",
"except",
... | set trimpoints to end of technical read for all sff files in directory . | train | false |
39,965 | def _combine_similar_molecules(molecules_list):
new_guys_start_idx = 0
while (new_guys_start_idx < len(molecules_list)):
combined = ([False] * len(molecules_list))
new_guys = []
for j in xrange(new_guys_start_idx, len(molecules_list)):
for i in xrange(0, j):
if combined[i]:
continue
((g1, m1), (... | [
"def",
"_combine_similar_molecules",
"(",
"molecules_list",
")",
":",
"new_guys_start_idx",
"=",
"0",
"while",
"(",
"new_guys_start_idx",
"<",
"len",
"(",
"molecules_list",
")",
")",
":",
"combined",
"=",
"(",
"[",
"False",
"]",
"*",
"len",
"(",
"molecules_lis... | using a greedy approach here for speed . | train | false |
39,966 | def _tryint(v):
try:
return int(v)
except:
return 0
| [
"def",
"_tryint",
"(",
"v",
")",
":",
"try",
":",
"return",
"int",
"(",
"v",
")",
"except",
":",
"return",
"0"
] | tries to convert v to an integer . | train | false |
39,967 | def getDictionaryString(dictionary):
output = cStringIO.StringIO()
keys = dictionary.keys()
keys.sort()
for key in keys:
addValueToOutput(0, key, output, dictionary[key])
return output.getvalue()
| [
"def",
"getDictionaryString",
"(",
"dictionary",
")",
":",
"output",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"keys",
"=",
"dictionary",
".",
"keys",
"(",
")",
"keys",
".",
"sort",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"addValueToOutput",
"(",
... | get the dictionary string . | train | false |
39,968 | def getPythonContainers(meth):
containers = []
containers.append(meth.im_class)
moduleName = meth.im_class.__module__
while (moduleName is not None):
module = sys.modules.get(moduleName, None)
if (module is None):
module = __import__(moduleName)
containers.append(module)
moduleName = getattr(module, '__m... | [
"def",
"getPythonContainers",
"(",
"meth",
")",
":",
"containers",
"=",
"[",
"]",
"containers",
".",
"append",
"(",
"meth",
".",
"im_class",
")",
"moduleName",
"=",
"meth",
".",
"im_class",
".",
"__module__",
"while",
"(",
"moduleName",
"is",
"not",
"None"... | walk up the python tree from method meth . | train | false |
39,969 | def t_KEGG_Compound(testfiles):
for file in testfiles:
fh = open(os.path.join('KEGG', file))
print((('Testing Bio.KEGG.Compound on ' + file) + '\n\n'))
records = Compound.parse(fh)
for record in records:
print(record)
print('\n')
fh.close()
| [
"def",
"t_KEGG_Compound",
"(",
"testfiles",
")",
":",
"for",
"file",
"in",
"testfiles",
":",
"fh",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'KEGG'",
",",
"file",
")",
")",
"print",
"(",
"(",
"(",
"'Testing Bio.KEGG.Compound on '",
"+",
"... | tests bio . | train | false |
39,970 | def makelist(inlist, listchar='', stringify=False, escape=False, encoding=None):
if stringify:
inlist = list_stringify(inlist)
listdict = {'[': '[%s]', '(': '(%s)', '': '%s'}
outline = []
if (len(inlist) < 2):
listchar = (listchar or '[')
for item in inlist:
if (not isinstance(item, (list, tuple))):
if es... | [
"def",
"makelist",
"(",
"inlist",
",",
"listchar",
"=",
"''",
",",
"stringify",
"=",
"False",
",",
"escape",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"stringify",
":",
"inlist",
"=",
"list_stringify",
"(",
"inlist",
")",
"listdict",
... | given a list - turn it into a string that represents that list . | train | false |
39,971 | def get_urls_proxy(output_pipe=sys.stderr):
try:
from django.conf import settings
except Exception as e:
output_pipe.write((('\n\nWarning, exception fetching KA Lite settings module:\n\n' + str(e)) + '\n\n'))
return
if (hasattr(settings, 'USER_FACING_PORT') and settings.USER_FACING_PORT and hasattr(settings, '... | [
"def",
"get_urls_proxy",
"(",
"output_pipe",
"=",
"sys",
".",
"stderr",
")",
":",
"try",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"except",
"Exception",
"as",
"e",
":",
"output_pipe",
".",
"write",
"(",
"(",
"(",
"'\\n\\nWarning, exception f... | get addresses of the server if were using settings . | train | false |
39,972 | def db_optimize(name, table=None, **connection_args):
ret = []
if (table is None):
tables = db_tables(name, **connection_args)
for table in tables:
log.info("Optimizing table '{0}' in db '{1}'..".format(name, table))
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info("Optimizing ... | [
"def",
"db_optimize",
"(",
"name",
",",
"table",
"=",
"None",
",",
"**",
"connection_args",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"(",
"table",
"is",
"None",
")",
":",
"tables",
"=",
"db_tables",
"(",
"name",
",",
"**",
"connection_args",
")",
"for",... | optimizes the full database or just a given table cli example: . | train | true |
39,973 | def plugins_update():
for env in PluginGlobals.env_registry.values():
for service in env.services.copy():
if (service.__class__ not in _PLUGINS_CLASS):
service.deactivate()
import ckan.config.environment as environment
environment.update_config()
| [
"def",
"plugins_update",
"(",
")",
":",
"for",
"env",
"in",
"PluginGlobals",
".",
"env_registry",
".",
"values",
"(",
")",
":",
"for",
"service",
"in",
"env",
".",
"services",
".",
"copy",
"(",
")",
":",
"if",
"(",
"service",
".",
"__class__",
"not",
... | this is run when plugins have been loaded or unloaded and allows us to run any specific code to ensure that the new plugin setting are correctly setup . | train | false |
39,974 | def is_leap(year):
x = math.fmod(year, 4)
y = math.fmod(year, 100)
z = math.fmod(year, 400)
return ((not x) and (y or (not z)))
| [
"def",
"is_leap",
"(",
"year",
")",
":",
"x",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"4",
")",
"y",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"100",
")",
"z",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"400",
")",
"return",
"(",
"("... | leap year or not in the gregorian calendar . | train | true |
39,975 | def iso8601_from_timestamp(timestamp, microsecond=False):
return isotime(datetime.datetime.utcfromtimestamp(timestamp), microsecond)
| [
"def",
"iso8601_from_timestamp",
"(",
"timestamp",
",",
"microsecond",
"=",
"False",
")",
":",
"return",
"isotime",
"(",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"timestamp",
")",
",",
"microsecond",
")"
] | returns a iso8601 formated date from timestamp . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.