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 |
|---|---|---|---|---|---|
10,313
|
def needs_local_scope(func):
func.needs_local_scope = True
return func
|
[
"def",
"needs_local_scope",
"(",
"func",
")",
":",
"func",
".",
"needs_local_scope",
"=",
"True",
"return",
"func"
] |
decorator to mark magic functions which need to local scope to run .
|
train
| false
|
10,314
|
def _api_restart_repair(name, output, kwargs):
sabnzbd.request_repair()
sabnzbd.trigger_restart()
return report(output)
|
[
"def",
"_api_restart_repair",
"(",
"name",
",",
"output",
",",
"kwargs",
")",
":",
"sabnzbd",
".",
"request_repair",
"(",
")",
"sabnzbd",
".",
"trigger_restart",
"(",
")",
"return",
"report",
"(",
"output",
")"
] |
api: accepts output .
|
train
| false
|
10,315
|
@verbose
def followtoscreen_demo(limit=10):
oauth = credsfromfile()
client = Streamer(**oauth)
client.register(TweetViewer(limit=limit))
client.statuses.filter(follow=USERIDS)
|
[
"@",
"verbose",
"def",
"followtoscreen_demo",
"(",
"limit",
"=",
"10",
")",
":",
"oauth",
"=",
"credsfromfile",
"(",
")",
"client",
"=",
"Streamer",
"(",
"**",
"oauth",
")",
"client",
".",
"register",
"(",
"TweetViewer",
"(",
"limit",
"=",
"limit",
")",
")",
"client",
".",
"statuses",
".",
"filter",
"(",
"follow",
"=",
"USERIDS",
")"
] |
using the streaming api .
|
train
| false
|
10,318
|
def test_show_verbose_with_classifiers(script):
result = script.pip('show', 'pip', '--verbose')
lines = result.stdout.splitlines()
assert ('Name: pip' in lines)
assert re.search('Classifiers:\\n( .+\\n)+', result.stdout)
assert ('Intended Audience :: Developers' in result.stdout)
|
[
"def",
"test_show_verbose_with_classifiers",
"(",
"script",
")",
":",
"result",
"=",
"script",
".",
"pip",
"(",
"'show'",
",",
"'pip'",
",",
"'--verbose'",
")",
"lines",
"=",
"result",
".",
"stdout",
".",
"splitlines",
"(",
")",
"assert",
"(",
"'Name: pip'",
"in",
"lines",
")",
"assert",
"re",
".",
"search",
"(",
"'Classifiers:\\\\n( .+\\\\n)+'",
",",
"result",
".",
"stdout",
")",
"assert",
"(",
"'Intended Audience :: Developers'",
"in",
"result",
".",
"stdout",
")"
] |
test that classifiers can be listed .
|
train
| false
|
10,321
|
def worker_direct(hostname):
if isinstance(hostname, Queue):
return hostname
return Queue(WORKER_DIRECT_QUEUE_FORMAT.format(hostname=hostname), WORKER_DIRECT_EXCHANGE, hostname)
|
[
"def",
"worker_direct",
"(",
"hostname",
")",
":",
"if",
"isinstance",
"(",
"hostname",
",",
"Queue",
")",
":",
"return",
"hostname",
"return",
"Queue",
"(",
"WORKER_DIRECT_QUEUE_FORMAT",
".",
"format",
"(",
"hostname",
"=",
"hostname",
")",
",",
"WORKER_DIRECT_EXCHANGE",
",",
"hostname",
")"
] |
return the :class:kombu .
|
train
| false
|
10,322
|
def GetProgram(plist):
try:
return (("['%s']" % plist['Program']), HashFile(plist['Program']))
except KeyError:
return (plist['ProgramArguments'], HashFile(plist['ProgramArguments']))
|
[
"def",
"GetProgram",
"(",
"plist",
")",
":",
"try",
":",
"return",
"(",
"(",
"\"['%s']\"",
"%",
"plist",
"[",
"'Program'",
"]",
")",
",",
"HashFile",
"(",
"plist",
"[",
"'Program'",
"]",
")",
")",
"except",
"KeyError",
":",
"return",
"(",
"plist",
"[",
"'ProgramArguments'",
"]",
",",
"HashFile",
"(",
"plist",
"[",
"'ProgramArguments'",
"]",
")",
")"
] |
plists have either a program or programarguments key .
|
train
| false
|
10,324
|
def force_escape(value):
from django.utils.html import escape
return mark_safe(escape(value))
|
[
"def",
"force_escape",
"(",
"value",
")",
":",
"from",
"django",
".",
"utils",
".",
"html",
"import",
"escape",
"return",
"mark_safe",
"(",
"escape",
"(",
"value",
")",
")"
] |
escapes a strings html .
|
train
| false
|
10,325
|
def setClockFormat(clockFormat, **kwargs):
if ((clockFormat != '12h') and (clockFormat != '24h')):
return False
_gsession = _GSettings(user=kwargs.get('user'), schema='org.gnome.desktop.interface', key='clock-format')
return _gsession._set(clockFormat)
|
[
"def",
"setClockFormat",
"(",
"clockFormat",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"(",
"clockFormat",
"!=",
"'12h'",
")",
"and",
"(",
"clockFormat",
"!=",
"'24h'",
")",
")",
":",
"return",
"False",
"_gsession",
"=",
"_GSettings",
"(",
"user",
"=",
"kwargs",
".",
"get",
"(",
"'user'",
")",
",",
"schema",
"=",
"'org.gnome.desktop.interface'",
",",
"key",
"=",
"'clock-format'",
")",
"return",
"_gsession",
".",
"_set",
"(",
"clockFormat",
")"
] |
set the clock format .
|
train
| true
|
10,326
|
def wrap_neg_index(index, dim):
if ((index is not None) and (index < 0)):
index %= dim
return index
|
[
"def",
"wrap_neg_index",
"(",
"index",
",",
"dim",
")",
":",
"if",
"(",
"(",
"index",
"is",
"not",
"None",
")",
"and",
"(",
"index",
"<",
"0",
")",
")",
":",
"index",
"%=",
"dim",
"return",
"index"
] |
converts a negative index into a positive index .
|
train
| false
|
10,327
|
def s_hex_dump(data, addr=0):
dump = slice = ''
for byte in data:
if ((addr % 16) == 0):
dump += ' '
for char in slice:
if ((ord(char) >= 32) and (ord(char) <= 126)):
dump += char
else:
dump += '.'
dump += ('\n%04x: ' % addr)
slice = ''
dump += ('%02x ' % ord(byte))
slice += byte
addr += 1
remainder = (addr % 16)
if (remainder != 0):
dump += ((' ' * (16 - remainder)) + ' ')
for char in slice:
if ((ord(char) >= 32) and (ord(char) <= 126)):
dump += char
else:
dump += '.'
return (dump + '\n')
|
[
"def",
"s_hex_dump",
"(",
"data",
",",
"addr",
"=",
"0",
")",
":",
"dump",
"=",
"slice",
"=",
"''",
"for",
"byte",
"in",
"data",
":",
"if",
"(",
"(",
"addr",
"%",
"16",
")",
"==",
"0",
")",
":",
"dump",
"+=",
"' '",
"for",
"char",
"in",
"slice",
":",
"if",
"(",
"(",
"ord",
"(",
"char",
")",
">=",
"32",
")",
"and",
"(",
"ord",
"(",
"char",
")",
"<=",
"126",
")",
")",
":",
"dump",
"+=",
"char",
"else",
":",
"dump",
"+=",
"'.'",
"dump",
"+=",
"(",
"'\\n%04x: '",
"%",
"addr",
")",
"slice",
"=",
"''",
"dump",
"+=",
"(",
"'%02x '",
"%",
"ord",
"(",
"byte",
")",
")",
"slice",
"+=",
"byte",
"addr",
"+=",
"1",
"remainder",
"=",
"(",
"addr",
"%",
"16",
")",
"if",
"(",
"remainder",
"!=",
"0",
")",
":",
"dump",
"+=",
"(",
"(",
"' '",
"*",
"(",
"16",
"-",
"remainder",
")",
")",
"+",
"' '",
")",
"for",
"char",
"in",
"slice",
":",
"if",
"(",
"(",
"ord",
"(",
"char",
")",
">=",
"32",
")",
"and",
"(",
"ord",
"(",
"char",
")",
"<=",
"126",
")",
")",
":",
"dump",
"+=",
"char",
"else",
":",
"dump",
"+=",
"'.'",
"return",
"(",
"dump",
"+",
"'\\n'",
")"
] |
return the hex dump of the supplied data starting at the offset address specified .
|
train
| false
|
10,328
|
def get_empty_preference_message(preference_key):
return "Preference '{preference_key}' cannot be set to an empty value.".format(preference_key=preference_key)
|
[
"def",
"get_empty_preference_message",
"(",
"preference_key",
")",
":",
"return",
"\"Preference '{preference_key}' cannot be set to an empty value.\"",
".",
"format",
"(",
"preference_key",
"=",
"preference_key",
")"
] |
returns the validation message shown for an empty preference .
|
train
| false
|
10,329
|
@app.route('/account/<subscription_id>/providers/<provider_namespace>/register', methods=['POST'])
@auth.require_login
def provider_register_post(subscription_id, provider_namespace):
creds = _get_credentials()
models.register_provider(subscription_id, creds, provider_namespace)
return redirect(url_for('subscription_view', subscription_id=subscription_id))
|
[
"@",
"app",
".",
"route",
"(",
"'/account/<subscription_id>/providers/<provider_namespace>/register'",
",",
"methods",
"=",
"[",
"'POST'",
"]",
")",
"@",
"auth",
".",
"require_login",
"def",
"provider_register_post",
"(",
"subscription_id",
",",
"provider_namespace",
")",
":",
"creds",
"=",
"_get_credentials",
"(",
")",
"models",
".",
"register_provider",
"(",
"subscription_id",
",",
"creds",
",",
"provider_namespace",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'subscription_view'",
",",
"subscription_id",
"=",
"subscription_id",
")",
")"
] |
register provider request .
|
train
| false
|
10,332
|
def build_encoder(tparams, options):
opt_ret = dict()
trng = RandomStreams(1234)
x = tensor.matrix('x', dtype='int64')
x_mask = tensor.matrix('x_mask', dtype='float32')
n_timesteps = x.shape[0]
n_samples = x.shape[1]
emb = tparams['Wemb'][x.flatten()].reshape([n_timesteps, n_samples, options['dim_word']])
proj = get_layer(options['encoder'])[1](tparams, emb, None, options, prefix='encoder', mask=x_mask)
ctx = proj[0][(-1)]
return (trng, x, x_mask, ctx, emb)
|
[
"def",
"build_encoder",
"(",
"tparams",
",",
"options",
")",
":",
"opt_ret",
"=",
"dict",
"(",
")",
"trng",
"=",
"RandomStreams",
"(",
"1234",
")",
"x",
"=",
"tensor",
".",
"matrix",
"(",
"'x'",
",",
"dtype",
"=",
"'int64'",
")",
"x_mask",
"=",
"tensor",
".",
"matrix",
"(",
"'x_mask'",
",",
"dtype",
"=",
"'float32'",
")",
"n_timesteps",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"n_samples",
"=",
"x",
".",
"shape",
"[",
"1",
"]",
"emb",
"=",
"tparams",
"[",
"'Wemb'",
"]",
"[",
"x",
".",
"flatten",
"(",
")",
"]",
".",
"reshape",
"(",
"[",
"n_timesteps",
",",
"n_samples",
",",
"options",
"[",
"'dim_word'",
"]",
"]",
")",
"proj",
"=",
"get_layer",
"(",
"options",
"[",
"'encoder'",
"]",
")",
"[",
"1",
"]",
"(",
"tparams",
",",
"emb",
",",
"None",
",",
"options",
",",
"prefix",
"=",
"'encoder'",
",",
"mask",
"=",
"x_mask",
")",
"ctx",
"=",
"proj",
"[",
"0",
"]",
"[",
"(",
"-",
"1",
")",
"]",
"return",
"(",
"trng",
",",
"x",
",",
"x_mask",
",",
"ctx",
",",
"emb",
")"
] |
computation graph .
|
train
| false
|
10,334
|
def _shift_intercept(arr):
arr = np.asarray(arr)
side = int(np.sqrt(len(arr)))
return np.roll(np.roll(arr.reshape(side, side), (-1), axis=1), (-1), axis=0)
|
[
"def",
"_shift_intercept",
"(",
"arr",
")",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"arr",
")",
"side",
"=",
"int",
"(",
"np",
".",
"sqrt",
"(",
"len",
"(",
"arr",
")",
")",
")",
"return",
"np",
".",
"roll",
"(",
"np",
".",
"roll",
"(",
"arr",
".",
"reshape",
"(",
"side",
",",
"side",
")",
",",
"(",
"-",
"1",
")",
",",
"axis",
"=",
"1",
")",
",",
"(",
"-",
"1",
")",
",",
"axis",
"=",
"0",
")"
] |
a convenience function to make the sas covariance matrix compatible with statsmodels .
|
train
| false
|
10,335
|
def protected(callback=None):
def wrapper(f):
@functools.wraps(f)
def inner(self, request, *args, **kwargs):
request.assert_authenticated()
if request.context.is_admin:
LOG.warning(_LW('RBAC: Bypassing authorization'))
elif (callback is not None):
prep_info = {'f_name': f.__name__, 'input_attr': kwargs}
callback(self, request, prep_info, *args, **kwargs)
else:
action = ('identity:%s' % f.__name__)
creds = _build_policy_check_credentials(self, action, request.context_dict, kwargs)
policy_dict = {}
if (hasattr(self, 'get_member_from_driver') and (self.get_member_from_driver is not None)):
key = ('%s_id' % self.member_name)
if (key in kwargs):
ref = self.get_member_from_driver(kwargs[key])
policy_dict['target'] = {self.member_name: ref}
if (request.context_dict.get('subject_token_id') is not None):
window_seconds = self._token_validation_window(request)
token_ref = token_model.KeystoneToken(token_id=request.context_dict['subject_token_id'], token_data=self.token_provider_api.validate_token(request.context_dict['subject_token_id'], window_seconds=window_seconds))
policy_dict.setdefault('target', {})
policy_dict['target'].setdefault(self.member_name, {})
policy_dict['target'][self.member_name]['user_id'] = token_ref.user_id
try:
user_domain_id = token_ref.user_domain_id
except exception.UnexpectedError:
user_domain_id = None
if user_domain_id:
policy_dict['target'][self.member_name].setdefault('user', {})
policy_dict['target'][self.member_name]['user'].setdefault('domain', {})
policy_dict['target'][self.member_name]['user']['domain']['id'] = user_domain_id
policy_dict.update(kwargs)
self.policy_api.enforce(creds, action, utils.flatten_dict(policy_dict))
LOG.debug('RBAC: Authorization granted')
return f(self, request, *args, **kwargs)
return inner
return wrapper
|
[
"def",
"protected",
"(",
"callback",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"request",
".",
"assert_authenticated",
"(",
")",
"if",
"request",
".",
"context",
".",
"is_admin",
":",
"LOG",
".",
"warning",
"(",
"_LW",
"(",
"'RBAC: Bypassing authorization'",
")",
")",
"elif",
"(",
"callback",
"is",
"not",
"None",
")",
":",
"prep_info",
"=",
"{",
"'f_name'",
":",
"f",
".",
"__name__",
",",
"'input_attr'",
":",
"kwargs",
"}",
"callback",
"(",
"self",
",",
"request",
",",
"prep_info",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"else",
":",
"action",
"=",
"(",
"'identity:%s'",
"%",
"f",
".",
"__name__",
")",
"creds",
"=",
"_build_policy_check_credentials",
"(",
"self",
",",
"action",
",",
"request",
".",
"context_dict",
",",
"kwargs",
")",
"policy_dict",
"=",
"{",
"}",
"if",
"(",
"hasattr",
"(",
"self",
",",
"'get_member_from_driver'",
")",
"and",
"(",
"self",
".",
"get_member_from_driver",
"is",
"not",
"None",
")",
")",
":",
"key",
"=",
"(",
"'%s_id'",
"%",
"self",
".",
"member_name",
")",
"if",
"(",
"key",
"in",
"kwargs",
")",
":",
"ref",
"=",
"self",
".",
"get_member_from_driver",
"(",
"kwargs",
"[",
"key",
"]",
")",
"policy_dict",
"[",
"'target'",
"]",
"=",
"{",
"self",
".",
"member_name",
":",
"ref",
"}",
"if",
"(",
"request",
".",
"context_dict",
".",
"get",
"(",
"'subject_token_id'",
")",
"is",
"not",
"None",
")",
":",
"window_seconds",
"=",
"self",
".",
"_token_validation_window",
"(",
"request",
")",
"token_ref",
"=",
"token_model",
".",
"KeystoneToken",
"(",
"token_id",
"=",
"request",
".",
"context_dict",
"[",
"'subject_token_id'",
"]",
",",
"token_data",
"=",
"self",
".",
"token_provider_api",
".",
"validate_token",
"(",
"request",
".",
"context_dict",
"[",
"'subject_token_id'",
"]",
",",
"window_seconds",
"=",
"window_seconds",
")",
")",
"policy_dict",
".",
"setdefault",
"(",
"'target'",
",",
"{",
"}",
")",
"policy_dict",
"[",
"'target'",
"]",
".",
"setdefault",
"(",
"self",
".",
"member_name",
",",
"{",
"}",
")",
"policy_dict",
"[",
"'target'",
"]",
"[",
"self",
".",
"member_name",
"]",
"[",
"'user_id'",
"]",
"=",
"token_ref",
".",
"user_id",
"try",
":",
"user_domain_id",
"=",
"token_ref",
".",
"user_domain_id",
"except",
"exception",
".",
"UnexpectedError",
":",
"user_domain_id",
"=",
"None",
"if",
"user_domain_id",
":",
"policy_dict",
"[",
"'target'",
"]",
"[",
"self",
".",
"member_name",
"]",
".",
"setdefault",
"(",
"'user'",
",",
"{",
"}",
")",
"policy_dict",
"[",
"'target'",
"]",
"[",
"self",
".",
"member_name",
"]",
"[",
"'user'",
"]",
".",
"setdefault",
"(",
"'domain'",
",",
"{",
"}",
")",
"policy_dict",
"[",
"'target'",
"]",
"[",
"self",
".",
"member_name",
"]",
"[",
"'user'",
"]",
"[",
"'domain'",
"]",
"[",
"'id'",
"]",
"=",
"user_domain_id",
"policy_dict",
".",
"update",
"(",
"kwargs",
")",
"self",
".",
"policy_api",
".",
"enforce",
"(",
"creds",
",",
"action",
",",
"utils",
".",
"flatten_dict",
"(",
"policy_dict",
")",
")",
"LOG",
".",
"debug",
"(",
"'RBAC: Authorization granted'",
")",
"return",
"f",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"inner",
"return",
"wrapper"
] |
wraps api calls with role based access controls .
|
train
| false
|
10,336
|
def get_plugin_folders():
if (not sys.platform.startswith('win')):
return []
plugin_dir = os.path.join(distutils.sysconfig.get_python_lib(), 'PyQt5', 'plugins')
folders = ['audio', 'iconengines', 'mediaservice', 'printsupport']
return [os.path.join(plugin_dir, folder) for folder in folders]
|
[
"def",
"get_plugin_folders",
"(",
")",
":",
"if",
"(",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
")",
":",
"return",
"[",
"]",
"plugin_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"distutils",
".",
"sysconfig",
".",
"get_python_lib",
"(",
")",
",",
"'PyQt5'",
",",
"'plugins'",
")",
"folders",
"=",
"[",
"'audio'",
",",
"'iconengines'",
",",
"'mediaservice'",
",",
"'printsupport'",
"]",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"plugin_dir",
",",
"folder",
")",
"for",
"folder",
"in",
"folders",
"]"
] |
get the plugin folders to copy to the output .
|
train
| false
|
10,338
|
def _smooth(image, sigma, mode, cval):
smoothed = np.empty(image.shape, dtype=np.double)
if (image.ndim == 3):
for dim in range(image.shape[2]):
ndi.gaussian_filter(image[..., dim], sigma, output=smoothed[..., dim], mode=mode, cval=cval)
else:
ndi.gaussian_filter(image, sigma, output=smoothed, mode=mode, cval=cval)
return smoothed
|
[
"def",
"_smooth",
"(",
"image",
",",
"sigma",
",",
"mode",
",",
"cval",
")",
":",
"smoothed",
"=",
"np",
".",
"empty",
"(",
"image",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"double",
")",
"if",
"(",
"image",
".",
"ndim",
"==",
"3",
")",
":",
"for",
"dim",
"in",
"range",
"(",
"image",
".",
"shape",
"[",
"2",
"]",
")",
":",
"ndi",
".",
"gaussian_filter",
"(",
"image",
"[",
"...",
",",
"dim",
"]",
",",
"sigma",
",",
"output",
"=",
"smoothed",
"[",
"...",
",",
"dim",
"]",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
")",
"else",
":",
"ndi",
".",
"gaussian_filter",
"(",
"image",
",",
"sigma",
",",
"output",
"=",
"smoothed",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
")",
"return",
"smoothed"
] |
return image with each channel smoothed by the gaussian filter .
|
train
| false
|
10,340
|
def getPrecision(elementNode):
return getCascadeFloatWithoutSelf((0.2 * getLayerHeight(elementNode)), elementNode, 'precision')
|
[
"def",
"getPrecision",
"(",
"elementNode",
")",
":",
"return",
"getCascadeFloatWithoutSelf",
"(",
"(",
"0.2",
"*",
"getLayerHeight",
"(",
"elementNode",
")",
")",
",",
"elementNode",
",",
"'precision'",
")"
] |
get the cascade precision .
|
train
| false
|
10,341
|
def get_spider_list(project, runner=None, pythonpath=None, version=''):
if ('cache' not in get_spider_list.__dict__):
get_spider_list.cache = UtilsCache()
try:
return get_spider_list.cache[project][version]
except KeyError:
pass
if (runner is None):
runner = Config().get('runner')
env = os.environ.copy()
env['PYTHONIOENCODING'] = 'UTF-8'
env['SCRAPY_PROJECT'] = project
if pythonpath:
env['PYTHONPATH'] = pythonpath
if version:
env['SCRAPY_EGG_VERSION'] = version
pargs = [sys.executable, '-m', runner, 'list']
proc = Popen(pargs, stdout=PIPE, stderr=PIPE, env=env)
(out, err) = proc.communicate()
if proc.returncode:
msg = (err or out or '')
msg = msg.decode('utf8')
raise RuntimeError((msg.encode('unicode_escape') if six.PY2 else msg))
tmp = out.decode('utf-8').splitlines()
try:
project_cache = get_spider_list.cache[project]
project_cache[version] = tmp
except KeyError:
project_cache = {version: tmp}
get_spider_list.cache[project] = project_cache
return tmp
|
[
"def",
"get_spider_list",
"(",
"project",
",",
"runner",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"version",
"=",
"''",
")",
":",
"if",
"(",
"'cache'",
"not",
"in",
"get_spider_list",
".",
"__dict__",
")",
":",
"get_spider_list",
".",
"cache",
"=",
"UtilsCache",
"(",
")",
"try",
":",
"return",
"get_spider_list",
".",
"cache",
"[",
"project",
"]",
"[",
"version",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"(",
"runner",
"is",
"None",
")",
":",
"runner",
"=",
"Config",
"(",
")",
".",
"get",
"(",
"'runner'",
")",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
"[",
"'PYTHONIOENCODING'",
"]",
"=",
"'UTF-8'",
"env",
"[",
"'SCRAPY_PROJECT'",
"]",
"=",
"project",
"if",
"pythonpath",
":",
"env",
"[",
"'PYTHONPATH'",
"]",
"=",
"pythonpath",
"if",
"version",
":",
"env",
"[",
"'SCRAPY_EGG_VERSION'",
"]",
"=",
"version",
"pargs",
"=",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"runner",
",",
"'list'",
"]",
"proc",
"=",
"Popen",
"(",
"pargs",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"env",
"=",
"env",
")",
"(",
"out",
",",
"err",
")",
"=",
"proc",
".",
"communicate",
"(",
")",
"if",
"proc",
".",
"returncode",
":",
"msg",
"=",
"(",
"err",
"or",
"out",
"or",
"''",
")",
"msg",
"=",
"msg",
".",
"decode",
"(",
"'utf8'",
")",
"raise",
"RuntimeError",
"(",
"(",
"msg",
".",
"encode",
"(",
"'unicode_escape'",
")",
"if",
"six",
".",
"PY2",
"else",
"msg",
")",
")",
"tmp",
"=",
"out",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"splitlines",
"(",
")",
"try",
":",
"project_cache",
"=",
"get_spider_list",
".",
"cache",
"[",
"project",
"]",
"project_cache",
"[",
"version",
"]",
"=",
"tmp",
"except",
"KeyError",
":",
"project_cache",
"=",
"{",
"version",
":",
"tmp",
"}",
"get_spider_list",
".",
"cache",
"[",
"project",
"]",
"=",
"project_cache",
"return",
"tmp"
] |
return the spider list from the given project .
|
train
| false
|
10,342
|
def iddp_rsvd(eps, m, n, matvect, matvec):
(k, iU, iV, iS, w, ier) = _id.iddp_rsvd(eps, m, n, matvect, matvec)
if ier:
raise _RETCODE_ERROR
U = w[(iU - 1):((iU + (m * k)) - 1)].reshape((m, k), order='F')
V = w[(iV - 1):((iV + (n * k)) - 1)].reshape((n, k), order='F')
S = w[(iS - 1):((iS + k) - 1)]
return (U, V, S)
|
[
"def",
"iddp_rsvd",
"(",
"eps",
",",
"m",
",",
"n",
",",
"matvect",
",",
"matvec",
")",
":",
"(",
"k",
",",
"iU",
",",
"iV",
",",
"iS",
",",
"w",
",",
"ier",
")",
"=",
"_id",
".",
"iddp_rsvd",
"(",
"eps",
",",
"m",
",",
"n",
",",
"matvect",
",",
"matvec",
")",
"if",
"ier",
":",
"raise",
"_RETCODE_ERROR",
"U",
"=",
"w",
"[",
"(",
"iU",
"-",
"1",
")",
":",
"(",
"(",
"iU",
"+",
"(",
"m",
"*",
"k",
")",
")",
"-",
"1",
")",
"]",
".",
"reshape",
"(",
"(",
"m",
",",
"k",
")",
",",
"order",
"=",
"'F'",
")",
"V",
"=",
"w",
"[",
"(",
"iV",
"-",
"1",
")",
":",
"(",
"(",
"iV",
"+",
"(",
"n",
"*",
"k",
")",
")",
"-",
"1",
")",
"]",
".",
"reshape",
"(",
"(",
"n",
",",
"k",
")",
",",
"order",
"=",
"'F'",
")",
"S",
"=",
"w",
"[",
"(",
"iS",
"-",
"1",
")",
":",
"(",
"(",
"iS",
"+",
"k",
")",
"-",
"1",
")",
"]",
"return",
"(",
"U",
",",
"V",
",",
"S",
")"
] |
compute svd of a real matrix to a specified relative precision using random matrix-vector multiplication .
|
train
| false
|
10,343
|
def python_zip(file_list, gallery_path, extension='.py'):
zipname = gallery_path.replace(os.path.sep, '_')
zipname += ('_python' if (extension == '.py') else '_jupyter')
zipname = os.path.join(gallery_path, (zipname + '.zip'))
zipf = zipfile.ZipFile(zipname, mode='w')
for fname in file_list:
file_src = (os.path.splitext(fname)[0] + extension)
zipf.write(file_src)
zipf.close()
return zipname
|
[
"def",
"python_zip",
"(",
"file_list",
",",
"gallery_path",
",",
"extension",
"=",
"'.py'",
")",
":",
"zipname",
"=",
"gallery_path",
".",
"replace",
"(",
"os",
".",
"path",
".",
"sep",
",",
"'_'",
")",
"zipname",
"+=",
"(",
"'_python'",
"if",
"(",
"extension",
"==",
"'.py'",
")",
"else",
"'_jupyter'",
")",
"zipname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"gallery_path",
",",
"(",
"zipname",
"+",
"'.zip'",
")",
")",
"zipf",
"=",
"zipfile",
".",
"ZipFile",
"(",
"zipname",
",",
"mode",
"=",
"'w'",
")",
"for",
"fname",
"in",
"file_list",
":",
"file_src",
"=",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"[",
"0",
"]",
"+",
"extension",
")",
"zipf",
".",
"write",
"(",
"file_src",
")",
"zipf",
".",
"close",
"(",
")",
"return",
"zipname"
] |
stores all files in file_list into an zip file parameters file_list : list of strings holds all the file names to be included in zip file gallery_path : string path to where the zipfile is stored extension : str .
|
train
| false
|
10,345
|
def _parse_server_raw(server):
parsed_server = {'addrs': set(), 'ssl': False, 'names': set()}
apply_ssl_to_all_addrs = False
for directive in server:
if (not directive):
continue
if (directive[0] == 'listen'):
addr = obj.Addr.fromstring(directive[1])
parsed_server['addrs'].add(addr)
if addr.ssl:
parsed_server['ssl'] = True
elif (directive[0] == 'server_name'):
parsed_server['names'].update(_get_servernames(directive[1]))
elif ((directive[0] == 'ssl') and (directive[1] == 'on')):
parsed_server['ssl'] = True
apply_ssl_to_all_addrs = True
if apply_ssl_to_all_addrs:
for addr in parsed_server['addrs']:
addr.ssl = True
return parsed_server
|
[
"def",
"_parse_server_raw",
"(",
"server",
")",
":",
"parsed_server",
"=",
"{",
"'addrs'",
":",
"set",
"(",
")",
",",
"'ssl'",
":",
"False",
",",
"'names'",
":",
"set",
"(",
")",
"}",
"apply_ssl_to_all_addrs",
"=",
"False",
"for",
"directive",
"in",
"server",
":",
"if",
"(",
"not",
"directive",
")",
":",
"continue",
"if",
"(",
"directive",
"[",
"0",
"]",
"==",
"'listen'",
")",
":",
"addr",
"=",
"obj",
".",
"Addr",
".",
"fromstring",
"(",
"directive",
"[",
"1",
"]",
")",
"parsed_server",
"[",
"'addrs'",
"]",
".",
"add",
"(",
"addr",
")",
"if",
"addr",
".",
"ssl",
":",
"parsed_server",
"[",
"'ssl'",
"]",
"=",
"True",
"elif",
"(",
"directive",
"[",
"0",
"]",
"==",
"'server_name'",
")",
":",
"parsed_server",
"[",
"'names'",
"]",
".",
"update",
"(",
"_get_servernames",
"(",
"directive",
"[",
"1",
"]",
")",
")",
"elif",
"(",
"(",
"directive",
"[",
"0",
"]",
"==",
"'ssl'",
")",
"and",
"(",
"directive",
"[",
"1",
"]",
"==",
"'on'",
")",
")",
":",
"parsed_server",
"[",
"'ssl'",
"]",
"=",
"True",
"apply_ssl_to_all_addrs",
"=",
"True",
"if",
"apply_ssl_to_all_addrs",
":",
"for",
"addr",
"in",
"parsed_server",
"[",
"'addrs'",
"]",
":",
"addr",
".",
"ssl",
"=",
"True",
"return",
"parsed_server"
] |
parses a list of server directives .
|
train
| false
|
10,346
|
def gps_offset(lat, lon, east, north):
bearing = math.degrees(math.atan2(east, north))
distance = math.sqrt(((east ** 2) + (north ** 2)))
return gps_newpos(lat, lon, bearing, distance)
|
[
"def",
"gps_offset",
"(",
"lat",
",",
"lon",
",",
"east",
",",
"north",
")",
":",
"bearing",
"=",
"math",
".",
"degrees",
"(",
"math",
".",
"atan2",
"(",
"east",
",",
"north",
")",
")",
"distance",
"=",
"math",
".",
"sqrt",
"(",
"(",
"(",
"east",
"**",
"2",
")",
"+",
"(",
"north",
"**",
"2",
")",
")",
")",
"return",
"gps_newpos",
"(",
"lat",
",",
"lon",
",",
"bearing",
",",
"distance",
")"
] |
return new lat/lon after moving east/north by the given number of meters .
|
train
| true
|
10,348
|
def _clip_boxes(boxes, im_shape):
boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0)
boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0)
boxes[:, 2::4] = np.minimum(boxes[:, 2::4], (im_shape[1] - 1))
boxes[:, 3::4] = np.minimum(boxes[:, 3::4], (im_shape[0] - 1))
return boxes
|
[
"def",
"_clip_boxes",
"(",
"boxes",
",",
"im_shape",
")",
":",
"boxes",
"[",
":",
",",
"0",
":",
":",
"4",
"]",
"=",
"np",
".",
"maximum",
"(",
"boxes",
"[",
":",
",",
"0",
":",
":",
"4",
"]",
",",
"0",
")",
"boxes",
"[",
":",
",",
"1",
":",
":",
"4",
"]",
"=",
"np",
".",
"maximum",
"(",
"boxes",
"[",
":",
",",
"1",
":",
":",
"4",
"]",
",",
"0",
")",
"boxes",
"[",
":",
",",
"2",
":",
":",
"4",
"]",
"=",
"np",
".",
"minimum",
"(",
"boxes",
"[",
":",
",",
"2",
":",
":",
"4",
"]",
",",
"(",
"im_shape",
"[",
"1",
"]",
"-",
"1",
")",
")",
"boxes",
"[",
":",
",",
"3",
":",
":",
"4",
"]",
"=",
"np",
".",
"minimum",
"(",
"boxes",
"[",
":",
",",
"3",
":",
":",
"4",
"]",
",",
"(",
"im_shape",
"[",
"0",
"]",
"-",
"1",
")",
")",
"return",
"boxes"
] |
clip boxes to image boundaries .
|
train
| false
|
10,349
|
@blueprint.route('/extension-static/<extension_type>/<extension_id>/<path:filename>')
def extension_static(extension_type, extension_id, filename):
extension = None
if (extension_type == 'view'):
extension = extensions.view.get_extension(extension_id)
elif (extension_type == 'data'):
extension = extensions.data.get_extension(extension_id)
if (extension is None):
raise ValueError(("Unknown extension '%s'" % extension_id))
digits_root = os.path.dirname(os.path.abspath(digits.__file__))
rootdir = os.path.join(digits_root, *['extensions', 'view', extension.get_dirname(), 'static'])
return flask.send_from_directory(rootdir, filename)
|
[
"@",
"blueprint",
".",
"route",
"(",
"'/extension-static/<extension_type>/<extension_id>/<path:filename>'",
")",
"def",
"extension_static",
"(",
"extension_type",
",",
"extension_id",
",",
"filename",
")",
":",
"extension",
"=",
"None",
"if",
"(",
"extension_type",
"==",
"'view'",
")",
":",
"extension",
"=",
"extensions",
".",
"view",
".",
"get_extension",
"(",
"extension_id",
")",
"elif",
"(",
"extension_type",
"==",
"'data'",
")",
":",
"extension",
"=",
"extensions",
".",
"data",
".",
"get_extension",
"(",
"extension_id",
")",
"if",
"(",
"extension",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"Unknown extension '%s'\"",
"%",
"extension_id",
")",
")",
"digits_root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"digits",
".",
"__file__",
")",
")",
"rootdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"digits_root",
",",
"*",
"[",
"'extensions'",
",",
"'view'",
",",
"extension",
".",
"get_dirname",
"(",
")",
",",
"'static'",
"]",
")",
"return",
"flask",
".",
"send_from_directory",
"(",
"rootdir",
",",
"filename",
")"
] |
returns static files from an extensions static directory .
|
train
| false
|
10,350
|
def _find_method_hash(method_hash):
for (hashname, asn1code) in HASH_ASN1.items():
if (not method_hash.startswith(asn1code)):
continue
return (hashname, method_hash[len(asn1code):])
raise VerificationError('Verification failed')
|
[
"def",
"_find_method_hash",
"(",
"method_hash",
")",
":",
"for",
"(",
"hashname",
",",
"asn1code",
")",
"in",
"HASH_ASN1",
".",
"items",
"(",
")",
":",
"if",
"(",
"not",
"method_hash",
".",
"startswith",
"(",
"asn1code",
")",
")",
":",
"continue",
"return",
"(",
"hashname",
",",
"method_hash",
"[",
"len",
"(",
"asn1code",
")",
":",
"]",
")",
"raise",
"VerificationError",
"(",
"'Verification failed'",
")"
] |
finds the hash method and the hash itself .
|
train
| false
|
10,352
|
def change_SHOWUPDATE_HOUR(freq):
sickbeard.SHOWUPDATE_HOUR = try_int(freq, sickbeard.DEFAULT_SHOWUPDATE_HOUR)
if (sickbeard.SHOWUPDATE_HOUR > 23):
sickbeard.SHOWUPDATE_HOUR = 0
elif (sickbeard.SHOWUPDATE_HOUR < 0):
sickbeard.SHOWUPDATE_HOUR = 0
sickbeard.showUpdateScheduler.start_time = datetime.time(hour=sickbeard.SHOWUPDATE_HOUR)
|
[
"def",
"change_SHOWUPDATE_HOUR",
"(",
"freq",
")",
":",
"sickbeard",
".",
"SHOWUPDATE_HOUR",
"=",
"try_int",
"(",
"freq",
",",
"sickbeard",
".",
"DEFAULT_SHOWUPDATE_HOUR",
")",
"if",
"(",
"sickbeard",
".",
"SHOWUPDATE_HOUR",
">",
"23",
")",
":",
"sickbeard",
".",
"SHOWUPDATE_HOUR",
"=",
"0",
"elif",
"(",
"sickbeard",
".",
"SHOWUPDATE_HOUR",
"<",
"0",
")",
":",
"sickbeard",
".",
"SHOWUPDATE_HOUR",
"=",
"0",
"sickbeard",
".",
"showUpdateScheduler",
".",
"start_time",
"=",
"datetime",
".",
"time",
"(",
"hour",
"=",
"sickbeard",
".",
"SHOWUPDATE_HOUR",
")"
] |
change frequency of show updater thread .
|
train
| false
|
10,353
|
def show_progress(iteration, loglikelihood):
pass
|
[
"def",
"show_progress",
"(",
"iteration",
",",
"loglikelihood",
")",
":",
"pass"
] |
callback function to be used for training the model .
|
train
| false
|
10,354
|
def set_restart_power_failure(enabled):
state = salt.utils.mac_utils.validate_enabled(enabled)
cmd = 'systemsetup -setrestartpowerfailure {0}'.format(state)
salt.utils.mac_utils.execute_return_success(cmd)
return salt.utils.mac_utils.confirm_updated(state, get_restart_power_failure)
|
[
"def",
"set_restart_power_failure",
"(",
"enabled",
")",
":",
"state",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"validate_enabled",
"(",
"enabled",
")",
"cmd",
"=",
"'systemsetup -setrestartpowerfailure {0}'",
".",
"format",
"(",
"state",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"confirm_updated",
"(",
"state",
",",
"get_restart_power_failure",
")"
] |
set whether or not the computer will automatically restart after a power failure .
|
train
| true
|
10,356
|
def less_shitty_error_messages(func):
@wraps(func)
def inner(self, sql, *args, **kwargs):
try:
return func(self, sql, *args, **kwargs)
except Exception as e:
exc_info = sys.exc_info()
msg = '{}\nSQL: {}'.format(repr(e), sql)
six.reraise(exc_info[0], exc_info[0](msg), exc_info[2])
return inner
|
[
"def",
"less_shitty_error_messages",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"self",
",",
"sql",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"self",
",",
"sql",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{}\\nSQL: {}'",
".",
"format",
"(",
"repr",
"(",
"e",
")",
",",
"sql",
")",
"six",
".",
"reraise",
"(",
"exc_info",
"[",
"0",
"]",
",",
"exc_info",
"[",
"0",
"]",
"(",
"msg",
")",
",",
"exc_info",
"[",
"2",
"]",
")",
"return",
"inner"
] |
wraps functions where the first param is a sql statement and enforces any exceptions thrown will also contain the statement in the message .
|
train
| false
|
10,357
|
def cidr_to_netmask(bits):
v = ((1 << bits) - 1)
v = (v << (32 - bits))
return IPAddr(v, networkOrder=False)
|
[
"def",
"cidr_to_netmask",
"(",
"bits",
")",
":",
"v",
"=",
"(",
"(",
"1",
"<<",
"bits",
")",
"-",
"1",
")",
"v",
"=",
"(",
"v",
"<<",
"(",
"32",
"-",
"bits",
")",
")",
"return",
"IPAddr",
"(",
"v",
",",
"networkOrder",
"=",
"False",
")"
] |
takes a number of network bits .
|
train
| false
|
10,358
|
def RunDebugModbusFrontend(server, port=8080):
from bottle import run
application = build_application(server)
run(app=application, port=port)
|
[
"def",
"RunDebugModbusFrontend",
"(",
"server",
",",
"port",
"=",
"8080",
")",
":",
"from",
"bottle",
"import",
"run",
"application",
"=",
"build_application",
"(",
"server",
")",
"run",
"(",
"app",
"=",
"application",
",",
"port",
"=",
"port",
")"
] |
helper method to start the bottle server .
|
train
| false
|
10,359
|
def text_to_int(ip):
if (':' not in ip):
return ipv4_to_int(ip)
else:
return ipv6_to_int(ip)
|
[
"def",
"text_to_int",
"(",
"ip",
")",
":",
"if",
"(",
"':'",
"not",
"in",
"ip",
")",
":",
"return",
"ipv4_to_int",
"(",
"ip",
")",
"else",
":",
"return",
"ipv6_to_int",
"(",
"ip",
")"
] |
converts human readable ipv4 or ipv6 string to int type representation .
|
train
| false
|
10,360
|
def readFeatureFile(font, text, prepend=True):
writer = FilterFeatureWriter(set(font.keys()))
if prepend:
text += font.features.text
else:
text = (font.features.text + text)
parser.parseFeatures(writer, text)
font.features.text = writer.write()
|
[
"def",
"readFeatureFile",
"(",
"font",
",",
"text",
",",
"prepend",
"=",
"True",
")",
":",
"writer",
"=",
"FilterFeatureWriter",
"(",
"set",
"(",
"font",
".",
"keys",
"(",
")",
")",
")",
"if",
"prepend",
":",
"text",
"+=",
"font",
".",
"features",
".",
"text",
"else",
":",
"text",
"=",
"(",
"font",
".",
"features",
".",
"text",
"+",
"text",
")",
"parser",
".",
"parseFeatures",
"(",
"writer",
",",
"text",
")",
"font",
".",
"features",
".",
"text",
"=",
"writer",
".",
"write",
"(",
")"
] |
incorporate valid definitions from feature text into font .
|
train
| false
|
10,362
|
def meminfo():
def linux_meminfo():
'\n linux specific implementation of meminfo\n '
ret = {}
try:
with salt.utils.fopen('/proc/meminfo', 'r') as fp_:
stats = fp_.read()
except IOError:
pass
else:
for line in stats.splitlines():
if (not line):
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {'value': comps[1]}
if (len(comps) > 2):
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'\n freebsd specific implementation of meminfo\n '
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]]
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
get_version = {'Linux': linux_meminfo, 'FreeBSD': freebsd_meminfo}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], (lambda : errmsg))()
|
[
"def",
"meminfo",
"(",
")",
":",
"def",
"linux_meminfo",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"'/proc/meminfo'",
",",
"'r'",
")",
"as",
"fp_",
":",
"stats",
"=",
"fp_",
".",
"read",
"(",
")",
"except",
"IOError",
":",
"pass",
"else",
":",
"for",
"line",
"in",
"stats",
".",
"splitlines",
"(",
")",
":",
"if",
"(",
"not",
"line",
")",
":",
"continue",
"comps",
"=",
"line",
".",
"split",
"(",
")",
"comps",
"[",
"0",
"]",
"=",
"comps",
"[",
"0",
"]",
".",
"replace",
"(",
"':'",
",",
"''",
")",
"ret",
"[",
"comps",
"[",
"0",
"]",
"]",
"=",
"{",
"'value'",
":",
"comps",
"[",
"1",
"]",
"}",
"if",
"(",
"len",
"(",
"comps",
")",
">",
"2",
")",
":",
"ret",
"[",
"comps",
"[",
"0",
"]",
"]",
"[",
"'unit'",
"]",
"=",
"comps",
"[",
"2",
"]",
"return",
"ret",
"def",
"freebsd_meminfo",
"(",
")",
":",
"sysctlvm",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'sysctl vm'",
")",
".",
"splitlines",
"(",
")",
"sysctlvm",
"=",
"[",
"x",
"for",
"x",
"in",
"sysctlvm",
"if",
"x",
".",
"startswith",
"(",
"'vm'",
")",
"]",
"sysctlvm",
"=",
"[",
"x",
".",
"split",
"(",
"':'",
")",
"for",
"x",
"in",
"sysctlvm",
"]",
"sysctlvm",
"=",
"[",
"[",
"y",
".",
"strip",
"(",
")",
"for",
"y",
"in",
"x",
"]",
"for",
"x",
"in",
"sysctlvm",
"]",
"sysctlvm",
"=",
"[",
"x",
"for",
"x",
"in",
"sysctlvm",
"if",
"x",
"[",
"1",
"]",
"]",
"ret",
"=",
"{",
"}",
"for",
"line",
"in",
"sysctlvm",
":",
"ret",
"[",
"line",
"[",
"0",
"]",
"]",
"=",
"line",
"[",
"1",
"]",
"sysctlvmtot",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'sysctl -n vm.vmtotal'",
")",
".",
"splitlines",
"(",
")",
"sysctlvmtot",
"=",
"[",
"x",
"for",
"x",
"in",
"sysctlvmtot",
"if",
"x",
"]",
"ret",
"[",
"'vm.vmtotal'",
"]",
"=",
"sysctlvmtot",
"return",
"ret",
"get_version",
"=",
"{",
"'Linux'",
":",
"linux_meminfo",
",",
"'FreeBSD'",
":",
"freebsd_meminfo",
"}",
"errmsg",
"=",
"'This method is unsupported on the current operating system!'",
"return",
"get_version",
".",
"get",
"(",
"__grains__",
"[",
"'kernel'",
"]",
",",
"(",
"lambda",
":",
"errmsg",
")",
")",
"(",
")"
] |
get memory information from /proc/meminfo .
|
train
| false
|
10,363
|
def test_scenario_ru_from_string():
ru = Language('ru')
scenario = Scenario.from_string(SCENARIO, language=ru)
assert_equals(scenario.name, u'\u0421\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435 \u0431\u0430\u0437\u044b \u043a\u0443\u0440\u0441\u043e\u0432 \u0443\u043d\u0438\u0432\u0435\u0440\u0438\u0442\u0435\u0442\u0430 \u0432 \u0442\u0435\u043a\u0441\u0442\u043e\u0432\u044b\u0439 \u0444\u0430\u0439\u043b')
assert_equals(scenario.steps[0].hashes, [{u'\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435': u'\u041c\u0430\u0442\u0430\u043d', u'\u0414\u043b\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c': u'2 \u0433\u043e\u0434\u0430'}, {u'\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435': u'\u041e\u0441\u043d\u043e\u0432\u044b \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f', u'\u0414\u043b\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u044c': u'1 \u0433\u043e\u0434'}])
|
[
"def",
"test_scenario_ru_from_string",
"(",
")",
":",
"ru",
"=",
"Language",
"(",
"'ru'",
")",
"scenario",
"=",
"Scenario",
".",
"from_string",
"(",
"SCENARIO",
",",
"language",
"=",
"ru",
")",
"assert_equals",
"(",
"scenario",
".",
"name",
",",
"u'\\u0421\\u043e\\u0445\\u0440\\u0430\\u043d\\u0435\\u043d\\u0438\\u0435 \\u0431\\u0430\\u0437\\u044b \\u043a\\u0443\\u0440\\u0441\\u043e\\u0432 \\u0443\\u043d\\u0438\\u0432\\u0435\\u0440\\u0438\\u0442\\u0435\\u0442\\u0430 \\u0432 \\u0442\\u0435\\u043a\\u0441\\u0442\\u043e\\u0432\\u044b\\u0439 \\u0444\\u0430\\u0439\\u043b'",
")",
"assert_equals",
"(",
"scenario",
".",
"steps",
"[",
"0",
"]",
".",
"hashes",
",",
"[",
"{",
"u'\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435'",
":",
"u'\\u041c\\u0430\\u0442\\u0430\\u043d'",
",",
"u'\\u0414\\u043b\\u0438\\u0442\\u0435\\u043b\\u044c\\u043d\\u043e\\u0441\\u0442\\u044c'",
":",
"u'2 \\u0433\\u043e\\u0434\\u0430'",
"}",
",",
"{",
"u'\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435'",
":",
"u'\\u041e\\u0441\\u043d\\u043e\\u0432\\u044b \\u043f\\u0440\\u043e\\u0433\\u0440\\u0430\\u043c\\u043c\\u0438\\u0440\\u043e\\u0432\\u0430\\u043d\\u0438\\u044f'",
",",
"u'\\u0414\\u043b\\u0438\\u0442\\u0435\\u043b\\u044c\\u043d\\u043e\\u0441\\u0442\\u044c'",
":",
"u'1 \\u0433\\u043e\\u0434'",
"}",
"]",
")"
] |
language: ru -> scenario .
|
train
| false
|
10,364
|
def _block_size(sep):
return (BLOCK_SIZE + (len(sep) * ((BLOCK_SIZE // Card.length) - 1)))
|
[
"def",
"_block_size",
"(",
"sep",
")",
":",
"return",
"(",
"BLOCK_SIZE",
"+",
"(",
"len",
"(",
"sep",
")",
"*",
"(",
"(",
"BLOCK_SIZE",
"//",
"Card",
".",
"length",
")",
"-",
"1",
")",
")",
")"
] |
determine the size of a fits header block if a non-blank separator is used between cards .
|
train
| false
|
10,365
|
def setup_input(pin, pull_mode):
import Adafruit_BBIO.GPIO as GPIO
GPIO.setup(pin, GPIO.IN, (GPIO.PUD_DOWN if (pull_mode == 'DOWN') else GPIO.PUD_UP))
|
[
"def",
"setup_input",
"(",
"pin",
",",
"pull_mode",
")",
":",
"import",
"Adafruit_BBIO",
".",
"GPIO",
"as",
"GPIO",
"GPIO",
".",
"setup",
"(",
"pin",
",",
"GPIO",
".",
"IN",
",",
"(",
"GPIO",
".",
"PUD_DOWN",
"if",
"(",
"pull_mode",
"==",
"'DOWN'",
")",
"else",
"GPIO",
".",
"PUD_UP",
")",
")"
] |
setup a gpio as input .
|
train
| false
|
10,366
|
def Query(sorted=0, **kwarg):
cmd = []
keys = kwarg.keys()
if sorted:
keys.sort()
for k in keys:
v = kwarg[k]
k = k.upper()
if ((k in _SIMPLE_BOOL) and v):
cmd.append(k)
elif (k == 'HEADER'):
cmd.extend([k, v[0], ('"%s"' % (v[1],))])
elif (k not in _NO_QUOTES):
cmd.extend([k, ('"%s"' % (v,))])
else:
cmd.extend([k, ('%s' % (v,))])
if (len(cmd) > 1):
return ('(%s)' % ' '.join(cmd))
else:
return ' '.join(cmd)
|
[
"def",
"Query",
"(",
"sorted",
"=",
"0",
",",
"**",
"kwarg",
")",
":",
"cmd",
"=",
"[",
"]",
"keys",
"=",
"kwarg",
".",
"keys",
"(",
")",
"if",
"sorted",
":",
"keys",
".",
"sort",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"v",
"=",
"kwarg",
"[",
"k",
"]",
"k",
"=",
"k",
".",
"upper",
"(",
")",
"if",
"(",
"(",
"k",
"in",
"_SIMPLE_BOOL",
")",
"and",
"v",
")",
":",
"cmd",
".",
"append",
"(",
"k",
")",
"elif",
"(",
"k",
"==",
"'HEADER'",
")",
":",
"cmd",
".",
"extend",
"(",
"[",
"k",
",",
"v",
"[",
"0",
"]",
",",
"(",
"'\"%s\"'",
"%",
"(",
"v",
"[",
"1",
"]",
",",
")",
")",
"]",
")",
"elif",
"(",
"k",
"not",
"in",
"_NO_QUOTES",
")",
":",
"cmd",
".",
"extend",
"(",
"[",
"k",
",",
"(",
"'\"%s\"'",
"%",
"(",
"v",
",",
")",
")",
"]",
")",
"else",
":",
"cmd",
".",
"extend",
"(",
"[",
"k",
",",
"(",
"'%s'",
"%",
"(",
"v",
",",
")",
")",
"]",
")",
"if",
"(",
"len",
"(",
"cmd",
")",
">",
"1",
")",
":",
"return",
"(",
"'(%s)'",
"%",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"else",
":",
"return",
"' '",
".",
"join",
"(",
"cmd",
")"
] |
create a query string among the accepted keywords are:: all : if set to a true value .
|
train
| false
|
10,367
|
@lower_constant(types.EnumMember)
def enum_constant(context, builder, ty, pyval):
return context.get_constant_generic(builder, ty.dtype, pyval.value)
|
[
"@",
"lower_constant",
"(",
"types",
".",
"EnumMember",
")",
"def",
"enum_constant",
"(",
"context",
",",
"builder",
",",
"ty",
",",
"pyval",
")",
":",
"return",
"context",
".",
"get_constant_generic",
"(",
"builder",
",",
"ty",
".",
"dtype",
",",
"pyval",
".",
"value",
")"
] |
return a llvm constant representing enum member *pyval* .
|
train
| false
|
10,368
|
def file_html(models, resources, title=None, template=FILE, template_variables={}):
models = _check_models(models)
with _ModelInDocument(models):
(docs_json, render_items) = _standalone_docs_json_and_render_items(models)
title = _title_from_models(models, title)
bundle = _bundle_for_objs_and_resources(models, resources)
return _html_page_for_render_items(bundle, docs_json, render_items, title=title, template=template, template_variables=template_variables)
|
[
"def",
"file_html",
"(",
"models",
",",
"resources",
",",
"title",
"=",
"None",
",",
"template",
"=",
"FILE",
",",
"template_variables",
"=",
"{",
"}",
")",
":",
"models",
"=",
"_check_models",
"(",
"models",
")",
"with",
"_ModelInDocument",
"(",
"models",
")",
":",
"(",
"docs_json",
",",
"render_items",
")",
"=",
"_standalone_docs_json_and_render_items",
"(",
"models",
")",
"title",
"=",
"_title_from_models",
"(",
"models",
",",
"title",
")",
"bundle",
"=",
"_bundle_for_objs_and_resources",
"(",
"models",
",",
"resources",
")",
"return",
"_html_page_for_render_items",
"(",
"bundle",
",",
"docs_json",
",",
"render_items",
",",
"title",
"=",
"title",
",",
"template",
"=",
"template",
",",
"template_variables",
"=",
"template_variables",
")"
] |
return an html document that embeds bokeh model or document objects .
|
train
| false
|
10,369
|
def is_pre_release(version):
parsed_version = parse_version(version)
return ((parsed_version.pre_release is not None) and (parsed_version.weekly_release is None) and (parsed_version.commit_count is None) and (parsed_version.dirty is None))
|
[
"def",
"is_pre_release",
"(",
"version",
")",
":",
"parsed_version",
"=",
"parse_version",
"(",
"version",
")",
"return",
"(",
"(",
"parsed_version",
".",
"pre_release",
"is",
"not",
"None",
")",
"and",
"(",
"parsed_version",
".",
"weekly_release",
"is",
"None",
")",
"and",
"(",
"parsed_version",
".",
"commit_count",
"is",
"None",
")",
"and",
"(",
"parsed_version",
".",
"dirty",
"is",
"None",
")",
")"
] |
return whether the version corresponds to a pre-release .
|
train
| false
|
10,370
|
def decipher_elgamal(msg, key):
(p, r, d) = key
(c1, c2) = msg
u = igcdex((c1 ** d), p)[0]
return ((u * c2) % p)
|
[
"def",
"decipher_elgamal",
"(",
"msg",
",",
"key",
")",
":",
"(",
"p",
",",
"r",
",",
"d",
")",
"=",
"key",
"(",
"c1",
",",
"c2",
")",
"=",
"msg",
"u",
"=",
"igcdex",
"(",
"(",
"c1",
"**",
"d",
")",
",",
"p",
")",
"[",
"0",
"]",
"return",
"(",
"(",
"u",
"*",
"c2",
")",
"%",
"p",
")"
] |
decrypt message with private key msg = key = according to extended eucliden theorem .
|
train
| false
|
10,371
|
def exception_data(func, *args, **kwds):
try:
func(*args, **kwds)
except Exception as detail:
return (detail, detail.args, ('%s: %s' % (detail.__class__.__name__, detail)))
|
[
"def",
"exception_data",
"(",
"func",
",",
"*",
"args",
",",
"**",
"kwds",
")",
":",
"try",
":",
"func",
"(",
"*",
"args",
",",
"**",
"kwds",
")",
"except",
"Exception",
"as",
"detail",
":",
"return",
"(",
"detail",
",",
"detail",
".",
"args",
",",
"(",
"'%s: %s'",
"%",
"(",
"detail",
".",
"__class__",
".",
"__name__",
",",
"detail",
")",
")",
")"
] |
execute func and return the resulting exception .
|
train
| false
|
10,372
|
def _ImageProcessing(image_buffer, shape):
image = tf.image.decode_png(image_buffer, channels=shape.depth)
image.set_shape([shape.height, shape.width, shape.depth])
image = tf.cast(image, tf.float32)
image = tf.sub(image, 128.0)
image = tf.mul(image, (1 / 100.0))
return image
|
[
"def",
"_ImageProcessing",
"(",
"image_buffer",
",",
"shape",
")",
":",
"image",
"=",
"tf",
".",
"image",
".",
"decode_png",
"(",
"image_buffer",
",",
"channels",
"=",
"shape",
".",
"depth",
")",
"image",
".",
"set_shape",
"(",
"[",
"shape",
".",
"height",
",",
"shape",
".",
"width",
",",
"shape",
".",
"depth",
"]",
")",
"image",
"=",
"tf",
".",
"cast",
"(",
"image",
",",
"tf",
".",
"float32",
")",
"image",
"=",
"tf",
".",
"sub",
"(",
"image",
",",
"128.0",
")",
"image",
"=",
"tf",
".",
"mul",
"(",
"image",
",",
"(",
"1",
"/",
"100.0",
")",
")",
"return",
"image"
] |
convert a png string into an input tensor .
|
train
| false
|
10,373
|
def test_import_error_in_warning_logging():
class FakeModule(object, ):
def __getattr__(self, attr):
raise ImportError(u'_showwarning should ignore any exceptions here')
log.enable_warnings_logging()
sys.modules[u'<test fake module>'] = FakeModule()
try:
warnings.showwarning(AstropyWarning(u'Regression test for #2671'), AstropyWarning, u'<this is only a test>', 1)
finally:
del sys.modules[u'<test fake module>']
|
[
"def",
"test_import_error_in_warning_logging",
"(",
")",
":",
"class",
"FakeModule",
"(",
"object",
",",
")",
":",
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"raise",
"ImportError",
"(",
"u'_showwarning should ignore any exceptions here'",
")",
"log",
".",
"enable_warnings_logging",
"(",
")",
"sys",
".",
"modules",
"[",
"u'<test fake module>'",
"]",
"=",
"FakeModule",
"(",
")",
"try",
":",
"warnings",
".",
"showwarning",
"(",
"AstropyWarning",
"(",
"u'Regression test for #2671'",
")",
",",
"AstropyWarning",
",",
"u'<this is only a test>'",
",",
"1",
")",
"finally",
":",
"del",
"sys",
".",
"modules",
"[",
"u'<test fake module>'",
"]"
] |
regression test for URL this test actually puts a goofy fake module into sys .
|
train
| false
|
10,374
|
def _generate_states_report(sorted_data):
states = []
for (state, data) in sorted_data:
(module, stateid, name, function) = [x.rstrip('_').lstrip('-') for x in state.split('|')]
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [{'function': module_function}, {'name': name}, {'result': result}, {'duration': data.get('duration', 0.0)}, {'comment': data.get('comment', '')}]
if (not result):
style = 'failed'
else:
changes = data.get('changes', {})
if (changes and isinstance(changes, dict)):
single.append({'changes': _dict_to_name_value(changes)})
style = 'changed'
else:
style = 'unchanged'
started = data.get('start_time', '')
if started:
single.append({'started': started})
states.append({stateid: single, '__style__': style})
return states
|
[
"def",
"_generate_states_report",
"(",
"sorted_data",
")",
":",
"states",
"=",
"[",
"]",
"for",
"(",
"state",
",",
"data",
")",
"in",
"sorted_data",
":",
"(",
"module",
",",
"stateid",
",",
"name",
",",
"function",
")",
"=",
"[",
"x",
".",
"rstrip",
"(",
"'_'",
")",
".",
"lstrip",
"(",
"'-'",
")",
"for",
"x",
"in",
"state",
".",
"split",
"(",
"'|'",
")",
"]",
"module_function",
"=",
"'.'",
".",
"join",
"(",
"(",
"module",
",",
"function",
")",
")",
"result",
"=",
"data",
".",
"get",
"(",
"'result'",
",",
"''",
")",
"single",
"=",
"[",
"{",
"'function'",
":",
"module_function",
"}",
",",
"{",
"'name'",
":",
"name",
"}",
",",
"{",
"'result'",
":",
"result",
"}",
",",
"{",
"'duration'",
":",
"data",
".",
"get",
"(",
"'duration'",
",",
"0.0",
")",
"}",
",",
"{",
"'comment'",
":",
"data",
".",
"get",
"(",
"'comment'",
",",
"''",
")",
"}",
"]",
"if",
"(",
"not",
"result",
")",
":",
"style",
"=",
"'failed'",
"else",
":",
"changes",
"=",
"data",
".",
"get",
"(",
"'changes'",
",",
"{",
"}",
")",
"if",
"(",
"changes",
"and",
"isinstance",
"(",
"changes",
",",
"dict",
")",
")",
":",
"single",
".",
"append",
"(",
"{",
"'changes'",
":",
"_dict_to_name_value",
"(",
"changes",
")",
"}",
")",
"style",
"=",
"'changed'",
"else",
":",
"style",
"=",
"'unchanged'",
"started",
"=",
"data",
".",
"get",
"(",
"'start_time'",
",",
"''",
")",
"if",
"started",
":",
"single",
".",
"append",
"(",
"{",
"'started'",
":",
"started",
"}",
")",
"states",
".",
"append",
"(",
"{",
"stateid",
":",
"single",
",",
"'__style__'",
":",
"style",
"}",
")",
"return",
"states"
] |
generate states report .
|
train
| true
|
10,376
|
def safe_enumerate(iterable):
for (i, v) in enumerate(iterable):
if (v is not None):
(yield (i, v))
|
[
"def",
"safe_enumerate",
"(",
"iterable",
")",
":",
"for",
"(",
"i",
",",
"v",
")",
"in",
"enumerate",
"(",
"iterable",
")",
":",
"if",
"(",
"v",
"is",
"not",
"None",
")",
":",
"(",
"yield",
"(",
"i",
",",
"v",
")",
")"
] |
enumerate which does not yield none values .
|
train
| false
|
10,377
|
def build_initiator_target_map(connector, target_wwns, lookup_service):
init_targ_map = {}
initiator_wwns = connector['wwpns']
if lookup_service:
dev_map = lookup_service.get_device_mapping_from_network(initiator_wwns, target_wwns)
for fabric_name in dev_map:
fabric = dev_map[fabric_name]
for initiator in fabric['initiator_port_wwn_list']:
init_targ_map[initiator] = fabric['target_port_wwn_list']
else:
for initiator in initiator_wwns:
init_targ_map[initiator] = target_wwns
return init_targ_map
|
[
"def",
"build_initiator_target_map",
"(",
"connector",
",",
"target_wwns",
",",
"lookup_service",
")",
":",
"init_targ_map",
"=",
"{",
"}",
"initiator_wwns",
"=",
"connector",
"[",
"'wwpns'",
"]",
"if",
"lookup_service",
":",
"dev_map",
"=",
"lookup_service",
".",
"get_device_mapping_from_network",
"(",
"initiator_wwns",
",",
"target_wwns",
")",
"for",
"fabric_name",
"in",
"dev_map",
":",
"fabric",
"=",
"dev_map",
"[",
"fabric_name",
"]",
"for",
"initiator",
"in",
"fabric",
"[",
"'initiator_port_wwn_list'",
"]",
":",
"init_targ_map",
"[",
"initiator",
"]",
"=",
"fabric",
"[",
"'target_port_wwn_list'",
"]",
"else",
":",
"for",
"initiator",
"in",
"initiator_wwns",
":",
"init_targ_map",
"[",
"initiator",
"]",
"=",
"target_wwns",
"return",
"init_targ_map"
] |
return a dictionary mapping server-wwns and lists of storage-wwns .
|
train
| false
|
10,380
|
@register.inclusion_tag('addons/includes/collection_add_widget.html')
@register.function
@jinja2.contextfunction
def collection_add_widget(context, addon, condensed=False):
c = dict(context.items())
c.update(locals())
return c
|
[
"@",
"register",
".",
"inclusion_tag",
"(",
"'addons/includes/collection_add_widget.html'",
")",
"@",
"register",
".",
"function",
"@",
"jinja2",
".",
"contextfunction",
"def",
"collection_add_widget",
"(",
"context",
",",
"addon",
",",
"condensed",
"=",
"False",
")",
":",
"c",
"=",
"dict",
"(",
"context",
".",
"items",
"(",
")",
")",
"c",
".",
"update",
"(",
"locals",
"(",
")",
")",
"return",
"c"
] |
displays add to collection widget .
|
train
| false
|
10,381
|
def element_to_extension_element(element):
exel = ExtensionElement(element.c_tag, element.c_namespace, text=element.text)
exel.attributes.update(element.extension_attributes)
exel.children.extend(element.extension_elements)
for (xml_attribute, (member_name, typ, req)) in element.c_attributes.iteritems():
member_value = getattr(element, member_name)
if (member_value is not None):
exel.attributes[xml_attribute] = member_value
exel.children.extend([element_to_extension_element(c) for c in element.children_with_values()])
return exel
|
[
"def",
"element_to_extension_element",
"(",
"element",
")",
":",
"exel",
"=",
"ExtensionElement",
"(",
"element",
".",
"c_tag",
",",
"element",
".",
"c_namespace",
",",
"text",
"=",
"element",
".",
"text",
")",
"exel",
".",
"attributes",
".",
"update",
"(",
"element",
".",
"extension_attributes",
")",
"exel",
".",
"children",
".",
"extend",
"(",
"element",
".",
"extension_elements",
")",
"for",
"(",
"xml_attribute",
",",
"(",
"member_name",
",",
"typ",
",",
"req",
")",
")",
"in",
"element",
".",
"c_attributes",
".",
"iteritems",
"(",
")",
":",
"member_value",
"=",
"getattr",
"(",
"element",
",",
"member_name",
")",
"if",
"(",
"member_value",
"is",
"not",
"None",
")",
":",
"exel",
".",
"attributes",
"[",
"xml_attribute",
"]",
"=",
"member_value",
"exel",
".",
"children",
".",
"extend",
"(",
"[",
"element_to_extension_element",
"(",
"c",
")",
"for",
"c",
"in",
"element",
".",
"children_with_values",
"(",
")",
"]",
")",
"return",
"exel"
] |
convert an element into a extension element .
|
train
| true
|
10,382
|
def _force_update_info(info_base, info_target):
exclude_keys = ['chs', 'ch_names', 'nchan']
info_target = np.atleast_1d(info_target).ravel()
all_infos = np.hstack([info_base, info_target])
for ii in all_infos:
if (not isinstance(ii, Info)):
raise ValueError(('Inputs must be of type Info. Found type %s' % type(ii)))
for (key, val) in info_base.items():
if (key in exclude_keys):
continue
for i_targ in info_target:
i_targ[key] = val
|
[
"def",
"_force_update_info",
"(",
"info_base",
",",
"info_target",
")",
":",
"exclude_keys",
"=",
"[",
"'chs'",
",",
"'ch_names'",
",",
"'nchan'",
"]",
"info_target",
"=",
"np",
".",
"atleast_1d",
"(",
"info_target",
")",
".",
"ravel",
"(",
")",
"all_infos",
"=",
"np",
".",
"hstack",
"(",
"[",
"info_base",
",",
"info_target",
"]",
")",
"for",
"ii",
"in",
"all_infos",
":",
"if",
"(",
"not",
"isinstance",
"(",
"ii",
",",
"Info",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Inputs must be of type Info. Found type %s'",
"%",
"type",
"(",
"ii",
")",
")",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"info_base",
".",
"items",
"(",
")",
":",
"if",
"(",
"key",
"in",
"exclude_keys",
")",
":",
"continue",
"for",
"i_targ",
"in",
"info_target",
":",
"i_targ",
"[",
"key",
"]",
"=",
"val"
] |
update target info objects with values from info base .
|
train
| false
|
10,384
|
def timestamp_local(value):
try:
return dt_util.as_local(dt_util.utc_from_timestamp(value)).strftime(DATE_STR_FORMAT)
except (ValueError, TypeError):
return value
|
[
"def",
"timestamp_local",
"(",
"value",
")",
":",
"try",
":",
"return",
"dt_util",
".",
"as_local",
"(",
"dt_util",
".",
"utc_from_timestamp",
"(",
"value",
")",
")",
".",
"strftime",
"(",
"DATE_STR_FORMAT",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"value"
] |
filter to convert given timestamp to local date/time .
|
train
| false
|
10,385
|
def build_reverse_dictionary(word_to_id):
reverse_dictionary = dict(zip(word_to_id.values(), word_to_id.keys()))
return reverse_dictionary
|
[
"def",
"build_reverse_dictionary",
"(",
"word_to_id",
")",
":",
"reverse_dictionary",
"=",
"dict",
"(",
"zip",
"(",
"word_to_id",
".",
"values",
"(",
")",
",",
"word_to_id",
".",
"keys",
"(",
")",
")",
")",
"return",
"reverse_dictionary"
] |
given a dictionary for converting word to integer id .
|
train
| true
|
10,387
|
def zy_basis_transform(self, format='sympy'):
return matrix_cache.get_matrix('ZY', format)
|
[
"def",
"zy_basis_transform",
"(",
"self",
",",
"format",
"=",
"'sympy'",
")",
":",
"return",
"matrix_cache",
".",
"get_matrix",
"(",
"'ZY'",
",",
"format",
")"
] |
transformation matrix from z to y basis .
|
train
| false
|
10,388
|
@register.simple_tag
def bootstrap_button(*args, **kwargs):
return render_button(*args, **kwargs)
|
[
"@",
"register",
".",
"simple_tag",
"def",
"bootstrap_button",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"render_button",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] |
render a button **tag name**:: bootstrap_button **parameters**: content the text to be displayed in the button button_type optional field defining what type of button this is .
|
train
| false
|
10,389
|
def require_version(version):
def check_require_version(f):
version_elements = version.split('.')
try:
compare = tuple([int(v) for v in version_elements])
except ValueError:
raise ValueError(('%s is not a correct version : should be X.Y[.Z].' % version))
current = sys.version_info[:3]
if (current < compare):
def new_f(self, *args, **kwargs):
self.skipTest(('Need at least %s version of python. Current version is %s.' % (version, '.'.join([str(element) for element in current]))))
new_f.__name__ = f.__name__
return new_f
else:
return f
return check_require_version
|
[
"def",
"require_version",
"(",
"version",
")",
":",
"def",
"check_require_version",
"(",
"f",
")",
":",
"version_elements",
"=",
"version",
".",
"split",
"(",
"'.'",
")",
"try",
":",
"compare",
"=",
"tuple",
"(",
"[",
"int",
"(",
"v",
")",
"for",
"v",
"in",
"version_elements",
"]",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"(",
"'%s is not a correct version : should be X.Y[.Z].'",
"%",
"version",
")",
")",
"current",
"=",
"sys",
".",
"version_info",
"[",
":",
"3",
"]",
"if",
"(",
"current",
"<",
"compare",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"skipTest",
"(",
"(",
"'Need at least %s version of python. Current version is %s.'",
"%",
"(",
"version",
",",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"element",
")",
"for",
"element",
"in",
"current",
"]",
")",
")",
")",
")",
"new_f",
".",
"__name__",
"=",
"f",
".",
"__name__",
"return",
"new_f",
"else",
":",
"return",
"f",
"return",
"check_require_version"
] |
compare version of python interpreter to the given one .
|
train
| false
|
10,390
|
def _set_up_ready_watcher():
ready_watcher = UserFactory(email='ready@example.com')
ReadyRevisionEvent.notify(ready_watcher)
return ready_watcher
|
[
"def",
"_set_up_ready_watcher",
"(",
")",
":",
"ready_watcher",
"=",
"UserFactory",
"(",
"email",
"=",
"'ready@example.com'",
")",
"ReadyRevisionEvent",
".",
"notify",
"(",
"ready_watcher",
")",
"return",
"ready_watcher"
] |
make a user who watches for revision readiness .
|
train
| false
|
10,392
|
def distance_to_current_waypoint():
nextwaypoint = vehicle.commands.next
if (nextwaypoint == 0):
return None
missionitem = vehicle.commands[(nextwaypoint - 1)]
lat = missionitem.x
lon = missionitem.y
alt = missionitem.z
targetWaypointLocation = LocationGlobalRelative(lat, lon, alt)
distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation)
return distancetopoint
|
[
"def",
"distance_to_current_waypoint",
"(",
")",
":",
"nextwaypoint",
"=",
"vehicle",
".",
"commands",
".",
"next",
"if",
"(",
"nextwaypoint",
"==",
"0",
")",
":",
"return",
"None",
"missionitem",
"=",
"vehicle",
".",
"commands",
"[",
"(",
"nextwaypoint",
"-",
"1",
")",
"]",
"lat",
"=",
"missionitem",
".",
"x",
"lon",
"=",
"missionitem",
".",
"y",
"alt",
"=",
"missionitem",
".",
"z",
"targetWaypointLocation",
"=",
"LocationGlobalRelative",
"(",
"lat",
",",
"lon",
",",
"alt",
")",
"distancetopoint",
"=",
"get_distance_metres",
"(",
"vehicle",
".",
"location",
".",
"global_frame",
",",
"targetWaypointLocation",
")",
"return",
"distancetopoint"
] |
gets distance in metres to the current waypoint .
|
train
| true
|
10,393
|
def processChildNodesByIndexValue(elementNode, function, index, indexValue, value):
if (indexValue.indexName != ''):
function.localDictionary[indexValue.indexName] = index
if (indexValue.valueName != ''):
function.localDictionary[indexValue.valueName] = value
function.processChildNodes(elementNode)
|
[
"def",
"processChildNodesByIndexValue",
"(",
"elementNode",
",",
"function",
",",
"index",
",",
"indexValue",
",",
"value",
")",
":",
"if",
"(",
"indexValue",
".",
"indexName",
"!=",
"''",
")",
":",
"function",
".",
"localDictionary",
"[",
"indexValue",
".",
"indexName",
"]",
"=",
"index",
"if",
"(",
"indexValue",
".",
"valueName",
"!=",
"''",
")",
":",
"function",
".",
"localDictionary",
"[",
"indexValue",
".",
"valueName",
"]",
"=",
"value",
"function",
".",
"processChildNodes",
"(",
"elementNode",
")"
] |
process childnodes by index value .
|
train
| false
|
10,394
|
def jwt_get_user_id_from_payload_handler(payload):
warnings.warn('The following will be removed in the future. Use `JWT_PAYLOAD_GET_USERNAME_HANDLER` instead.', DeprecationWarning)
return payload.get('user_id')
|
[
"def",
"jwt_get_user_id_from_payload_handler",
"(",
"payload",
")",
":",
"warnings",
".",
"warn",
"(",
"'The following will be removed in the future. Use `JWT_PAYLOAD_GET_USERNAME_HANDLER` instead.'",
",",
"DeprecationWarning",
")",
"return",
"payload",
".",
"get",
"(",
"'user_id'",
")"
] |
override this function if user_id is formatted differently in payload .
|
train
| false
|
10,395
|
def parse_newick(lines, constructor=PhyloNode):
return DndParser(lines, constructor=constructor, unescape_name=True)
|
[
"def",
"parse_newick",
"(",
"lines",
",",
"constructor",
"=",
"PhyloNode",
")",
":",
"return",
"DndParser",
"(",
"lines",
",",
"constructor",
"=",
"constructor",
",",
"unescape_name",
"=",
"True",
")"
] |
return phylonode from newick file handle stripping quotes from tip names this function wraps cogent .
|
train
| false
|
10,396
|
def _cmp_by_highest_wg(path1, path2):
return None
|
[
"def",
"_cmp_by_highest_wg",
"(",
"path1",
",",
"path2",
")",
":",
"return",
"None"
] |
selects a path with highest weight .
|
train
| false
|
10,397
|
@mock_ec2
def test_igw_delete_attached():
conn = boto.connect_vpc(u'the_key', u'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.delete_internet_gateway(igw.id)
cm.exception.code.should.equal(u'DependencyViolation')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
|
[
"@",
"mock_ec2",
"def",
"test_igw_delete_attached",
"(",
")",
":",
"conn",
"=",
"boto",
".",
"connect_vpc",
"(",
"u'the_key'",
",",
"u'the_secret'",
")",
"igw",
"=",
"conn",
".",
"create_internet_gateway",
"(",
")",
"vpc",
"=",
"conn",
".",
"create_vpc",
"(",
"VPC_CIDR",
")",
"conn",
".",
"attach_internet_gateway",
"(",
"igw",
".",
"id",
",",
"vpc",
".",
"id",
")",
"with",
"assert_raises",
"(",
"EC2ResponseError",
")",
"as",
"cm",
":",
"conn",
".",
"delete_internet_gateway",
"(",
"igw",
".",
"id",
")",
"cm",
".",
"exception",
".",
"code",
".",
"should",
".",
"equal",
"(",
"u'DependencyViolation'",
")",
"cm",
".",
"exception",
".",
"status",
".",
"should",
".",
"equal",
"(",
"400",
")",
"cm",
".",
"exception",
".",
"request_id",
".",
"should_not",
".",
"be",
".",
"none"
] |
internet gateway fail to delete attached .
|
train
| false
|
10,398
|
def _get_skiprows(skiprows):
if isinstance(skiprows, slice):
return lrange((skiprows.start or 0), skiprows.stop, (skiprows.step or 1))
elif (isinstance(skiprows, numbers.Integral) or is_list_like(skiprows)):
return skiprows
elif (skiprows is None):
return 0
raise TypeError(('%r is not a valid type for skipping rows' % type(skiprows).__name__))
|
[
"def",
"_get_skiprows",
"(",
"skiprows",
")",
":",
"if",
"isinstance",
"(",
"skiprows",
",",
"slice",
")",
":",
"return",
"lrange",
"(",
"(",
"skiprows",
".",
"start",
"or",
"0",
")",
",",
"skiprows",
".",
"stop",
",",
"(",
"skiprows",
".",
"step",
"or",
"1",
")",
")",
"elif",
"(",
"isinstance",
"(",
"skiprows",
",",
"numbers",
".",
"Integral",
")",
"or",
"is_list_like",
"(",
"skiprows",
")",
")",
":",
"return",
"skiprows",
"elif",
"(",
"skiprows",
"is",
"None",
")",
":",
"return",
"0",
"raise",
"TypeError",
"(",
"(",
"'%r is not a valid type for skipping rows'",
"%",
"type",
"(",
"skiprows",
")",
".",
"__name__",
")",
")"
] |
get an iterator given an integer .
|
train
| true
|
10,399
|
def parsemsg(s):
prefix = ''
trailing = []
if (not s):
raise IRCBadMessage('Empty line.')
if (s[0] == ':'):
(prefix, s) = s[1:].split(' ', 1)
if (s.find(' :') != (-1)):
(s, trailing) = s.split(' :', 1)
args = s.split()
args.append(trailing)
else:
args = s.split()
command = args.pop(0)
return (prefix, command, args)
|
[
"def",
"parsemsg",
"(",
"s",
")",
":",
"prefix",
"=",
"''",
"trailing",
"=",
"[",
"]",
"if",
"(",
"not",
"s",
")",
":",
"raise",
"IRCBadMessage",
"(",
"'Empty line.'",
")",
"if",
"(",
"s",
"[",
"0",
"]",
"==",
"':'",
")",
":",
"(",
"prefix",
",",
"s",
")",
"=",
"s",
"[",
"1",
":",
"]",
".",
"split",
"(",
"' '",
",",
"1",
")",
"if",
"(",
"s",
".",
"find",
"(",
"' :'",
")",
"!=",
"(",
"-",
"1",
")",
")",
":",
"(",
"s",
",",
"trailing",
")",
"=",
"s",
".",
"split",
"(",
"' :'",
",",
"1",
")",
"args",
"=",
"s",
".",
"split",
"(",
")",
"args",
".",
"append",
"(",
"trailing",
")",
"else",
":",
"args",
"=",
"s",
".",
"split",
"(",
")",
"command",
"=",
"args",
".",
"pop",
"(",
"0",
")",
"return",
"(",
"prefix",
",",
"command",
",",
"args",
")"
] |
breaks a message from an irc server into its prefix .
|
train
| true
|
10,400
|
def find_first_level_groups(string, enclosing, blank_sep=None):
groups = find_first_level_groups_span(string, enclosing)
if blank_sep:
for (start, end) in groups:
string = str_replace(string, start, blank_sep)
string = str_replace(string, (end - 1), blank_sep)
return split_on_groups(string, groups)
|
[
"def",
"find_first_level_groups",
"(",
"string",
",",
"enclosing",
",",
"blank_sep",
"=",
"None",
")",
":",
"groups",
"=",
"find_first_level_groups_span",
"(",
"string",
",",
"enclosing",
")",
"if",
"blank_sep",
":",
"for",
"(",
"start",
",",
"end",
")",
"in",
"groups",
":",
"string",
"=",
"str_replace",
"(",
"string",
",",
"start",
",",
"blank_sep",
")",
"string",
"=",
"str_replace",
"(",
"string",
",",
"(",
"end",
"-",
"1",
")",
",",
"blank_sep",
")",
"return",
"split_on_groups",
"(",
"string",
",",
"groups",
")"
] |
return a list of groups that could be split because of explicit grouping .
|
train
| false
|
10,401
|
def format_html_pre_18(format_string, *args, **kwargs):
args_safe = map(conditional_escape, args)
kwargs_safe = {}
for k in kwargs:
kwargs_safe[k] = conditional_escape(kwargs[k])
return mark_safe(format_string.format(*args_safe, **kwargs_safe))
|
[
"def",
"format_html_pre_18",
"(",
"format_string",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"args_safe",
"=",
"map",
"(",
"conditional_escape",
",",
"args",
")",
"kwargs_safe",
"=",
"{",
"}",
"for",
"k",
"in",
"kwargs",
":",
"kwargs_safe",
"[",
"k",
"]",
"=",
"conditional_escape",
"(",
"kwargs",
"[",
"k",
"]",
")",
"return",
"mark_safe",
"(",
"format_string",
".",
"format",
"(",
"*",
"args_safe",
",",
"**",
"kwargs_safe",
")",
")"
] |
fake function to support format_html in django < 1 .
|
train
| false
|
10,402
|
def listToStrValue(value):
if isinstance(value, (set, tuple)):
value = list(value)
if isinstance(value, list):
retVal = value.__str__().lstrip('[').rstrip(']')
else:
retVal = value
return retVal
|
[
"def",
"listToStrValue",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"set",
",",
"tuple",
")",
")",
":",
"value",
"=",
"list",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"retVal",
"=",
"value",
".",
"__str__",
"(",
")",
".",
"lstrip",
"(",
"'['",
")",
".",
"rstrip",
"(",
"']'",
")",
"else",
":",
"retVal",
"=",
"value",
"return",
"retVal"
] |
flattens list to a string value .
|
train
| false
|
10,403
|
def extract_angular(fileobj, keywords, comment_tags, options):
parser = AngularGettextHTMLParser()
for line in fileobj:
parser.feed(line)
for string in parser.strings:
(yield string)
|
[
"def",
"extract_angular",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"parser",
"=",
"AngularGettextHTMLParser",
"(",
")",
"for",
"line",
"in",
"fileobj",
":",
"parser",
".",
"feed",
"(",
"line",
")",
"for",
"string",
"in",
"parser",
".",
"strings",
":",
"(",
"yield",
"string",
")"
] |
extract messages from angular template files that use the angular-gettext translate directive as per URL .
|
train
| true
|
10,405
|
def _create_course(test, course_key, course_data):
course_url = get_url('course_handler', course_key, 'course_key_string')
response = test.client.ajax_post(course_url, course_data)
test.assertEqual(response.status_code, 200)
data = parse_json(response)
test.assertNotIn('ErrMsg', data)
test.assertEqual(data['url'], course_url)
|
[
"def",
"_create_course",
"(",
"test",
",",
"course_key",
",",
"course_data",
")",
":",
"course_url",
"=",
"get_url",
"(",
"'course_handler'",
",",
"course_key",
",",
"'course_key_string'",
")",
"response",
"=",
"test",
".",
"client",
".",
"ajax_post",
"(",
"course_url",
",",
"course_data",
")",
"test",
".",
"assertEqual",
"(",
"response",
".",
"status_code",
",",
"200",
")",
"data",
"=",
"parse_json",
"(",
"response",
")",
"test",
".",
"assertNotIn",
"(",
"'ErrMsg'",
",",
"data",
")",
"test",
".",
"assertEqual",
"(",
"data",
"[",
"'url'",
"]",
",",
"course_url",
")"
] |
creates a course via an ajax request and verifies the url returned in the response .
|
train
| false
|
10,407
|
@handle_response_format
@treeio_login_required
def widget_my_watchlist(request, response_format='html'):
profile = request.user.profile
query = ((_get_filter_query(profile, do_recipients=False) & Q(about__in=profile.subscriptions.all())) & (~ Q(author=profile)))
updates = UpdateRecord.objects.filter(query).distinct()
context = _get_default_context(request)
context.update({'updates': updates, 'profile': profile})
return render_to_response('news/widgets/my_watchlist', context, context_instance=RequestContext(request), response_format=response_format)
|
[
"@",
"handle_response_format",
"@",
"treeio_login_required",
"def",
"widget_my_watchlist",
"(",
"request",
",",
"response_format",
"=",
"'html'",
")",
":",
"profile",
"=",
"request",
".",
"user",
".",
"profile",
"query",
"=",
"(",
"(",
"_get_filter_query",
"(",
"profile",
",",
"do_recipients",
"=",
"False",
")",
"&",
"Q",
"(",
"about__in",
"=",
"profile",
".",
"subscriptions",
".",
"all",
"(",
")",
")",
")",
"&",
"(",
"~",
"Q",
"(",
"author",
"=",
"profile",
")",
")",
")",
"updates",
"=",
"UpdateRecord",
".",
"objects",
".",
"filter",
"(",
"query",
")",
".",
"distinct",
"(",
")",
"context",
"=",
"_get_default_context",
"(",
"request",
")",
"context",
".",
"update",
"(",
"{",
"'updates'",
":",
"updates",
",",
"'profile'",
":",
"profile",
"}",
")",
"return",
"render_to_response",
"(",
"'news/widgets/my_watchlist'",
",",
"context",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] |
displays news about all objects a user is subscribed to .
|
train
| false
|
10,408
|
def document_generator(dir_path_pattern, count=None):
for (running_count, item) in enumerate(glob.iglob(dir_path_pattern)):
if (count and (running_count >= count)):
raise StopIteration()
doc_id = os.path.basename(item)
with codecs.open(item, encoding='utf-8') as f:
try:
text = f.read()
except UnicodeDecodeError:
continue
(yield Document(text, doc_id, item))
|
[
"def",
"document_generator",
"(",
"dir_path_pattern",
",",
"count",
"=",
"None",
")",
":",
"for",
"(",
"running_count",
",",
"item",
")",
"in",
"enumerate",
"(",
"glob",
".",
"iglob",
"(",
"dir_path_pattern",
")",
")",
":",
"if",
"(",
"count",
"and",
"(",
"running_count",
">=",
"count",
")",
")",
":",
"raise",
"StopIteration",
"(",
")",
"doc_id",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"item",
")",
"with",
"codecs",
".",
"open",
"(",
"item",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"try",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",
"except",
"UnicodeDecodeError",
":",
"continue",
"(",
"yield",
"Document",
"(",
"text",
",",
"doc_id",
",",
"item",
")",
")"
] |
generator for the input movie documents .
|
train
| false
|
10,410
|
def invalidate_pricing_cache():
PRICING_DATA['compute'] = {}
PRICING_DATA['storage'] = {}
|
[
"def",
"invalidate_pricing_cache",
"(",
")",
":",
"PRICING_DATA",
"[",
"'compute'",
"]",
"=",
"{",
"}",
"PRICING_DATA",
"[",
"'storage'",
"]",
"=",
"{",
"}"
] |
invalidate pricing cache for all the drivers .
|
train
| false
|
10,411
|
def proj_transform(xs, ys, zs, M):
vec = vec_pad_ones(xs, ys, zs)
return proj_transform_vec(vec, M)
|
[
"def",
"proj_transform",
"(",
"xs",
",",
"ys",
",",
"zs",
",",
"M",
")",
":",
"vec",
"=",
"vec_pad_ones",
"(",
"xs",
",",
"ys",
",",
"zs",
")",
"return",
"proj_transform_vec",
"(",
"vec",
",",
"M",
")"
] |
transform the points by the projection matrix .
|
train
| false
|
10,412
|
def privacy_info_handle(info, anonymous, name=False):
if anonymous:
return ('A user' if name else '')
return info
|
[
"def",
"privacy_info_handle",
"(",
"info",
",",
"anonymous",
",",
"name",
"=",
"False",
")",
":",
"if",
"anonymous",
":",
"return",
"(",
"'A user'",
"if",
"name",
"else",
"''",
")",
"return",
"info"
] |
hide user info from api if anonymous .
|
train
| false
|
10,413
|
def title_from_content(content):
for end in (u'. ', u'?', u'!', u'<br />', u'\n', u'</p>'):
if (end in content):
content = (content.split(end)[0] + end)
break
return strip_tags(content)
|
[
"def",
"title_from_content",
"(",
"content",
")",
":",
"for",
"end",
"in",
"(",
"u'. '",
",",
"u'?'",
",",
"u'!'",
",",
"u'<br />'",
",",
"u'\\n'",
",",
"u'</p>'",
")",
":",
"if",
"(",
"end",
"in",
"content",
")",
":",
"content",
"=",
"(",
"content",
".",
"split",
"(",
"end",
")",
"[",
"0",
"]",
"+",
"end",
")",
"break",
"return",
"strip_tags",
"(",
"content",
")"
] |
try and extract the first sentence from a block of test to use as a title .
|
train
| false
|
10,414
|
def geom_output(func, argtypes, offset=None):
func.argtypes = argtypes
if (not offset):
func.restype = c_void_p
func.errcheck = check_geom
else:
func.restype = c_int
def geomerrcheck(result, func, cargs):
return check_geom_offset(result, func, cargs, offset)
func.errcheck = geomerrcheck
return func
|
[
"def",
"geom_output",
"(",
"func",
",",
"argtypes",
",",
"offset",
"=",
"None",
")",
":",
"func",
".",
"argtypes",
"=",
"argtypes",
"if",
"(",
"not",
"offset",
")",
":",
"func",
".",
"restype",
"=",
"c_void_p",
"func",
".",
"errcheck",
"=",
"check_geom",
"else",
":",
"func",
".",
"restype",
"=",
"c_int",
"def",
"geomerrcheck",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"return",
"check_geom_offset",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
")",
"func",
".",
"errcheck",
"=",
"geomerrcheck",
"return",
"func"
] |
for geos routines that return a geometry .
|
train
| false
|
10,416
|
def findtemplate(template=None):
if (MacOS.runtimemodel == 'macho'):
return None
if (not template):
template = TEMPLATE
for p in sys.path:
file = os.path.join(p, template)
try:
(file, d1, d2) = Carbon.File.FSResolveAliasFile(file, 1)
break
except (Carbon.File.Error, ValueError):
continue
else:
raise BuildError, ('Template %r not found on sys.path' % (template,))
file = file.as_pathname()
return file
|
[
"def",
"findtemplate",
"(",
"template",
"=",
"None",
")",
":",
"if",
"(",
"MacOS",
".",
"runtimemodel",
"==",
"'macho'",
")",
":",
"return",
"None",
"if",
"(",
"not",
"template",
")",
":",
"template",
"=",
"TEMPLATE",
"for",
"p",
"in",
"sys",
".",
"path",
":",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"template",
")",
"try",
":",
"(",
"file",
",",
"d1",
",",
"d2",
")",
"=",
"Carbon",
".",
"File",
".",
"FSResolveAliasFile",
"(",
"file",
",",
"1",
")",
"break",
"except",
"(",
"Carbon",
".",
"File",
".",
"Error",
",",
"ValueError",
")",
":",
"continue",
"else",
":",
"raise",
"BuildError",
",",
"(",
"'Template %r not found on sys.path'",
"%",
"(",
"template",
",",
")",
")",
"file",
"=",
"file",
".",
"as_pathname",
"(",
")",
"return",
"file"
] |
locate the applet template along sys .
|
train
| false
|
10,417
|
@aggregate(_(u'Sum of'))
def aggregate_sum(items, col):
return sum((getattr(item, col) for item in items))
|
[
"@",
"aggregate",
"(",
"_",
"(",
"u'Sum of'",
")",
")",
"def",
"aggregate_sum",
"(",
"items",
",",
"col",
")",
":",
"return",
"sum",
"(",
"(",
"getattr",
"(",
"item",
",",
"col",
")",
"for",
"item",
"in",
"items",
")",
")"
] |
function to use on group by charts .
|
train
| false
|
10,418
|
def test_ast_good_global():
can_compile(u'(global a)')
can_compile(u'(global foo bar)')
|
[
"def",
"test_ast_good_global",
"(",
")",
":",
"can_compile",
"(",
"u'(global a)'",
")",
"can_compile",
"(",
"u'(global foo bar)'",
")"
] |
make sure ast can compile valid global .
|
train
| false
|
10,419
|
def _get_blkno_placements(blknos, blk_count, group=True):
blknos = _ensure_int64(blknos)
for (blkno, indexer) in lib.get_blkno_indexers(blknos, group):
(yield (blkno, BlockPlacement(indexer)))
|
[
"def",
"_get_blkno_placements",
"(",
"blknos",
",",
"blk_count",
",",
"group",
"=",
"True",
")",
":",
"blknos",
"=",
"_ensure_int64",
"(",
"blknos",
")",
"for",
"(",
"blkno",
",",
"indexer",
")",
"in",
"lib",
".",
"get_blkno_indexers",
"(",
"blknos",
",",
"group",
")",
":",
"(",
"yield",
"(",
"blkno",
",",
"BlockPlacement",
"(",
"indexer",
")",
")",
")"
] |
parameters blknos : array of int64 blk_count : int group : bool returns iterator yield .
|
train
| false
|
10,420
|
@transaction.non_atomic_requests
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
@require_POST
def generate_certificate_exceptions(request, course_id, generate_for=None):
course_key = CourseKey.from_string(course_id)
if (generate_for == 'all'):
students = 'all_whitelisted'
elif (generate_for == 'new'):
students = 'whitelisted_not_generated'
else:
return JsonResponse({'success': False, 'message': _('Invalid data, generate_for must be "new" or "all".')}, status=400)
lms.djangoapps.instructor_task.api.generate_certificates_for_students(request, course_key, student_set=students)
response_payload = {'success': True, 'message': _('Certificate generation started for white listed students.')}
return JsonResponse(response_payload)
|
[
"@",
"transaction",
".",
"non_atomic_requests",
"@",
"ensure_csrf_cookie",
"@",
"cache_control",
"(",
"no_cache",
"=",
"True",
",",
"no_store",
"=",
"True",
",",
"must_revalidate",
"=",
"True",
")",
"@",
"require_global_staff",
"@",
"require_POST",
"def",
"generate_certificate_exceptions",
"(",
"request",
",",
"course_id",
",",
"generate_for",
"=",
"None",
")",
":",
"course_key",
"=",
"CourseKey",
".",
"from_string",
"(",
"course_id",
")",
"if",
"(",
"generate_for",
"==",
"'all'",
")",
":",
"students",
"=",
"'all_whitelisted'",
"elif",
"(",
"generate_for",
"==",
"'new'",
")",
":",
"students",
"=",
"'whitelisted_not_generated'",
"else",
":",
"return",
"JsonResponse",
"(",
"{",
"'success'",
":",
"False",
",",
"'message'",
":",
"_",
"(",
"'Invalid data, generate_for must be \"new\" or \"all\".'",
")",
"}",
",",
"status",
"=",
"400",
")",
"lms",
".",
"djangoapps",
".",
"instructor_task",
".",
"api",
".",
"generate_certificates_for_students",
"(",
"request",
",",
"course_key",
",",
"student_set",
"=",
"students",
")",
"response_payload",
"=",
"{",
"'success'",
":",
"True",
",",
"'message'",
":",
"_",
"(",
"'Certificate generation started for white listed students.'",
")",
"}",
"return",
"JsonResponse",
"(",
"response_payload",
")"
] |
generate certificate for students in the certificate white list .
|
train
| false
|
10,421
|
def platforms_to_releases(info, debug):
output = []
temp_releases = {}
platforms = info.get('platforms')
for platform in platforms:
for release in platforms[platform]:
key = ('%s-%s' % (release['version'], release['url']))
if (key not in temp_releases):
temp_releases[key] = {'sublime_text': '<3000', 'version': release['version'], 'date': info.get('last_modified', '2011-08-01 00:00:00'), 'url': update_url(release['url'], debug), 'platforms': []}
if (platform == '*'):
temp_releases[key]['platforms'] = ['*']
elif (temp_releases[key]['platforms'] != ['*']):
temp_releases[key]['platforms'].append(platform)
for key in temp_releases:
release = temp_releases[key]
if (release['platforms'] == ['windows', 'linux', 'osx']):
release['platforms'] = ['*']
output.append(release)
return output
|
[
"def",
"platforms_to_releases",
"(",
"info",
",",
"debug",
")",
":",
"output",
"=",
"[",
"]",
"temp_releases",
"=",
"{",
"}",
"platforms",
"=",
"info",
".",
"get",
"(",
"'platforms'",
")",
"for",
"platform",
"in",
"platforms",
":",
"for",
"release",
"in",
"platforms",
"[",
"platform",
"]",
":",
"key",
"=",
"(",
"'%s-%s'",
"%",
"(",
"release",
"[",
"'version'",
"]",
",",
"release",
"[",
"'url'",
"]",
")",
")",
"if",
"(",
"key",
"not",
"in",
"temp_releases",
")",
":",
"temp_releases",
"[",
"key",
"]",
"=",
"{",
"'sublime_text'",
":",
"'<3000'",
",",
"'version'",
":",
"release",
"[",
"'version'",
"]",
",",
"'date'",
":",
"info",
".",
"get",
"(",
"'last_modified'",
",",
"'2011-08-01 00:00:00'",
")",
",",
"'url'",
":",
"update_url",
"(",
"release",
"[",
"'url'",
"]",
",",
"debug",
")",
",",
"'platforms'",
":",
"[",
"]",
"}",
"if",
"(",
"platform",
"==",
"'*'",
")",
":",
"temp_releases",
"[",
"key",
"]",
"[",
"'platforms'",
"]",
"=",
"[",
"'*'",
"]",
"elif",
"(",
"temp_releases",
"[",
"key",
"]",
"[",
"'platforms'",
"]",
"!=",
"[",
"'*'",
"]",
")",
":",
"temp_releases",
"[",
"key",
"]",
"[",
"'platforms'",
"]",
".",
"append",
"(",
"platform",
")",
"for",
"key",
"in",
"temp_releases",
":",
"release",
"=",
"temp_releases",
"[",
"key",
"]",
"if",
"(",
"release",
"[",
"'platforms'",
"]",
"==",
"[",
"'windows'",
",",
"'linux'",
",",
"'osx'",
"]",
")",
":",
"release",
"[",
"'platforms'",
"]",
"=",
"[",
"'*'",
"]",
"output",
".",
"append",
"(",
"release",
")",
"return",
"output"
] |
accepts a dict from a schema version 1 .
|
train
| false
|
10,423
|
def do_get_relationship(parser, token):
bits = token.contents.split()
if (len(bits) == 3):
return GetRelationship(bits[1], bits[2])
if (len(bits) == 5):
return GetRelationship(bits[1], bits[2], bits[4])
if (len(bits) == 4):
raise template.TemplateSyntaxError, ("The tag '%s' needs an 'as' as its third argument." % bits[0])
if (len(bits) < 3):
raise template.TemplateSyntaxError, ("The tag '%s' takes two arguments" % bits[0])
|
[
"def",
"do_get_relationship",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"(",
"len",
"(",
"bits",
")",
"==",
"3",
")",
":",
"return",
"GetRelationship",
"(",
"bits",
"[",
"1",
"]",
",",
"bits",
"[",
"2",
"]",
")",
"if",
"(",
"len",
"(",
"bits",
")",
"==",
"5",
")",
":",
"return",
"GetRelationship",
"(",
"bits",
"[",
"1",
"]",
",",
"bits",
"[",
"2",
"]",
",",
"bits",
"[",
"4",
"]",
")",
"if",
"(",
"len",
"(",
"bits",
")",
"==",
"4",
")",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
",",
"(",
"\"The tag '%s' needs an 'as' as its third argument.\"",
"%",
"bits",
"[",
"0",
"]",
")",
"if",
"(",
"len",
"(",
"bits",
")",
"<",
"3",
")",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
",",
"(",
"\"The tag '%s' takes two arguments\"",
"%",
"bits",
"[",
"0",
"]",
")"
] |
get relationship between two users .
|
train
| false
|
10,426
|
def keep_awake():
if (KERNEL32 or sleepless):
if sabnzbd.cfg.keep_awake():
awake = False
if (not sabnzbd.downloader.Downloader.do.paused):
if ((not PostProcessor.do.empty()) or (not NzbQueue.do.is_empty())):
awake = True
if KERNEL32:
KERNEL32.SetThreadExecutionState(ctypes.c_int(1))
else:
sleepless.keep_awake(u'SABnzbd is busy downloading and/or post-processing')
if ((not awake) and sleepless):
sleepless.allow_sleep()
|
[
"def",
"keep_awake",
"(",
")",
":",
"if",
"(",
"KERNEL32",
"or",
"sleepless",
")",
":",
"if",
"sabnzbd",
".",
"cfg",
".",
"keep_awake",
"(",
")",
":",
"awake",
"=",
"False",
"if",
"(",
"not",
"sabnzbd",
".",
"downloader",
".",
"Downloader",
".",
"do",
".",
"paused",
")",
":",
"if",
"(",
"(",
"not",
"PostProcessor",
".",
"do",
".",
"empty",
"(",
")",
")",
"or",
"(",
"not",
"NzbQueue",
".",
"do",
".",
"is_empty",
"(",
")",
")",
")",
":",
"awake",
"=",
"True",
"if",
"KERNEL32",
":",
"KERNEL32",
".",
"SetThreadExecutionState",
"(",
"ctypes",
".",
"c_int",
"(",
"1",
")",
")",
"else",
":",
"sleepless",
".",
"keep_awake",
"(",
"u'SABnzbd is busy downloading and/or post-processing'",
")",
"if",
"(",
"(",
"not",
"awake",
")",
"and",
"sleepless",
")",
":",
"sleepless",
".",
"allow_sleep",
"(",
")"
] |
if we still have work to do .
|
train
| false
|
10,427
|
def mc_sample_path(P, init=0, sample_size=1000, random_state=None):
random_state = check_random_state(random_state)
if isinstance(init, numbers.Integral):
X_0 = init
else:
cdf0 = np.cumsum(init)
u_0 = random_state.random_sample()
X_0 = searchsorted(cdf0, u_0)
mc = MarkovChain(P)
return mc.simulate(ts_length=sample_size, init=X_0, random_state=random_state)
|
[
"def",
"mc_sample_path",
"(",
"P",
",",
"init",
"=",
"0",
",",
"sample_size",
"=",
"1000",
",",
"random_state",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"if",
"isinstance",
"(",
"init",
",",
"numbers",
".",
"Integral",
")",
":",
"X_0",
"=",
"init",
"else",
":",
"cdf0",
"=",
"np",
".",
"cumsum",
"(",
"init",
")",
"u_0",
"=",
"random_state",
".",
"random_sample",
"(",
")",
"X_0",
"=",
"searchsorted",
"(",
"cdf0",
",",
"u_0",
")",
"mc",
"=",
"MarkovChain",
"(",
"P",
")",
"return",
"mc",
".",
"simulate",
"(",
"ts_length",
"=",
"sample_size",
",",
"init",
"=",
"X_0",
",",
"random_state",
"=",
"random_state",
")"
] |
generates one sample path from the markov chain represented by transition matrix p on state space s = {{0 .
|
train
| true
|
10,428
|
def _ensure_no_filesystem(device, block_device_manager):
if block_device_manager.has_filesystem(device):
raise FilesystemExists(device)
|
[
"def",
"_ensure_no_filesystem",
"(",
"device",
",",
"block_device_manager",
")",
":",
"if",
"block_device_manager",
".",
"has_filesystem",
"(",
"device",
")",
":",
"raise",
"FilesystemExists",
"(",
"device",
")"
] |
raises an error if theres already a filesystem on device .
|
train
| false
|
10,429
|
def for_unsigned_dtypes(name='dtype'):
return for_dtypes(_unsigned_dtypes, name=name)
|
[
"def",
"for_unsigned_dtypes",
"(",
"name",
"=",
"'dtype'",
")",
":",
"return",
"for_dtypes",
"(",
"_unsigned_dtypes",
",",
"name",
"=",
"name",
")"
] |
decorator that checks the fixture with all dtypes .
|
train
| false
|
10,431
|
def path_from_name(name, ext=None, sep=u'|'):
if ext:
return fsencode((name.replace(os.sep, sep) + ext))
else:
return fsencode(name.replace(os.sep, sep))
|
[
"def",
"path_from_name",
"(",
"name",
",",
"ext",
"=",
"None",
",",
"sep",
"=",
"u'|'",
")",
":",
"if",
"ext",
":",
"return",
"fsencode",
"(",
"(",
"name",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"sep",
")",
"+",
"ext",
")",
")",
"else",
":",
"return",
"fsencode",
"(",
"name",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"sep",
")",
")"
] |
convert name with optional extension to file path .
|
train
| false
|
10,432
|
def xblock_studio_url(xblock, parent_xblock=None):
if (not xblock_has_own_studio_page(xblock, parent_xblock)):
return None
category = xblock.category
if (category == 'course'):
return reverse_course_url('course_handler', xblock.location.course_key)
elif (category in ('chapter', 'sequential')):
return u'{url}?show={usage_key}'.format(url=reverse_course_url('course_handler', xblock.location.course_key), usage_key=urllib.quote(unicode(xblock.location)))
elif (category == 'library'):
library_key = xblock.location.course_key
return reverse_library_url('library_handler', library_key)
else:
return reverse_usage_url('container_handler', xblock.location)
|
[
"def",
"xblock_studio_url",
"(",
"xblock",
",",
"parent_xblock",
"=",
"None",
")",
":",
"if",
"(",
"not",
"xblock_has_own_studio_page",
"(",
"xblock",
",",
"parent_xblock",
")",
")",
":",
"return",
"None",
"category",
"=",
"xblock",
".",
"category",
"if",
"(",
"category",
"==",
"'course'",
")",
":",
"return",
"reverse_course_url",
"(",
"'course_handler'",
",",
"xblock",
".",
"location",
".",
"course_key",
")",
"elif",
"(",
"category",
"in",
"(",
"'chapter'",
",",
"'sequential'",
")",
")",
":",
"return",
"u'{url}?show={usage_key}'",
".",
"format",
"(",
"url",
"=",
"reverse_course_url",
"(",
"'course_handler'",
",",
"xblock",
".",
"location",
".",
"course_key",
")",
",",
"usage_key",
"=",
"urllib",
".",
"quote",
"(",
"unicode",
"(",
"xblock",
".",
"location",
")",
")",
")",
"elif",
"(",
"category",
"==",
"'library'",
")",
":",
"library_key",
"=",
"xblock",
".",
"location",
".",
"course_key",
"return",
"reverse_library_url",
"(",
"'library_handler'",
",",
"library_key",
")",
"else",
":",
"return",
"reverse_usage_url",
"(",
"'container_handler'",
",",
"xblock",
".",
"location",
")"
] |
returns the studio editing url for the specified xblock .
|
train
| false
|
10,433
|
def ensure_soup(value, parser=None):
if isinstance(value, BeautifulSoup):
return value.find()
if isinstance(value, Tag):
return value
if isinstance(value, list):
return [ensure_soup(item, parser=parser) for item in value]
parsed = BeautifulSoup(value, features=parser)
return parsed.find()
|
[
"def",
"ensure_soup",
"(",
"value",
",",
"parser",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"BeautifulSoup",
")",
":",
"return",
"value",
".",
"find",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"Tag",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"ensure_soup",
"(",
"item",
",",
"parser",
"=",
"parser",
")",
"for",
"item",
"in",
"value",
"]",
"parsed",
"=",
"BeautifulSoup",
"(",
"value",
",",
"features",
"=",
"parser",
")",
"return",
"parsed",
".",
"find",
"(",
")"
] |
coerce a value to tag .
|
train
| true
|
10,436
|
def prism():
rc('image', cmap='prism')
im = gci()
if (im is not None):
im.set_cmap(cm.prism)
draw_if_interactive()
|
[
"def",
"prism",
"(",
")",
":",
"rc",
"(",
"'image'",
",",
"cmap",
"=",
"'prism'",
")",
"im",
"=",
"gci",
"(",
")",
"if",
"(",
"im",
"is",
"not",
"None",
")",
":",
"im",
".",
"set_cmap",
"(",
"cm",
".",
"prism",
")",
"draw_if_interactive",
"(",
")"
] |
set the default colormap to prism and apply to current image if any .
|
train
| false
|
10,437
|
def test_wrong_nn():
kind = 'borderline1'
nn_m = 'rnd'
nn_k = NearestNeighbors(n_neighbors=6)
smote = SMOTE(random_state=RND_SEED, kind=kind, k_neighbors=nn_k, m_neighbors=nn_m)
assert_raises(ValueError, smote.fit_sample, X, Y)
nn_k = 'rnd'
nn_m = NearestNeighbors(n_neighbors=10)
smote = SMOTE(random_state=RND_SEED, kind=kind, k_neighbors=nn_k, m_neighbors=nn_m)
assert_raises(ValueError, smote.fit_sample, X, Y)
kind = 'regular'
nn_k = 'rnd'
smote = SMOTE(random_state=RND_SEED, kind=kind, k_neighbors=nn_k)
assert_raises(ValueError, smote.fit_sample, X, Y)
|
[
"def",
"test_wrong_nn",
"(",
")",
":",
"kind",
"=",
"'borderline1'",
"nn_m",
"=",
"'rnd'",
"nn_k",
"=",
"NearestNeighbors",
"(",
"n_neighbors",
"=",
"6",
")",
"smote",
"=",
"SMOTE",
"(",
"random_state",
"=",
"RND_SEED",
",",
"kind",
"=",
"kind",
",",
"k_neighbors",
"=",
"nn_k",
",",
"m_neighbors",
"=",
"nn_m",
")",
"assert_raises",
"(",
"ValueError",
",",
"smote",
".",
"fit_sample",
",",
"X",
",",
"Y",
")",
"nn_k",
"=",
"'rnd'",
"nn_m",
"=",
"NearestNeighbors",
"(",
"n_neighbors",
"=",
"10",
")",
"smote",
"=",
"SMOTE",
"(",
"random_state",
"=",
"RND_SEED",
",",
"kind",
"=",
"kind",
",",
"k_neighbors",
"=",
"nn_k",
",",
"m_neighbors",
"=",
"nn_m",
")",
"assert_raises",
"(",
"ValueError",
",",
"smote",
".",
"fit_sample",
",",
"X",
",",
"Y",
")",
"kind",
"=",
"'regular'",
"nn_k",
"=",
"'rnd'",
"smote",
"=",
"SMOTE",
"(",
"random_state",
"=",
"RND_SEED",
",",
"kind",
"=",
"kind",
",",
"k_neighbors",
"=",
"nn_k",
")",
"assert_raises",
"(",
"ValueError",
",",
"smote",
".",
"fit_sample",
",",
"X",
",",
"Y",
")"
] |
test either if an error is raised while passing a wrong nn object .
|
train
| false
|
10,440
|
def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
|
[
"def",
"cxBlend",
"(",
"ind1",
",",
"ind2",
",",
"alpha",
")",
":",
"for",
"(",
"i",
",",
"(",
"x1",
",",
"x2",
")",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"ind1",
",",
"ind2",
")",
")",
":",
"gamma",
"=",
"(",
"(",
"(",
"1.0",
"+",
"(",
"2.0",
"*",
"alpha",
")",
")",
"*",
"random",
".",
"random",
"(",
")",
")",
"-",
"alpha",
")",
"ind1",
"[",
"i",
"]",
"=",
"(",
"(",
"(",
"1.0",
"-",
"gamma",
")",
"*",
"x1",
")",
"+",
"(",
"gamma",
"*",
"x2",
")",
")",
"ind2",
"[",
"i",
"]",
"=",
"(",
"(",
"gamma",
"*",
"x1",
")",
"+",
"(",
"(",
"1.0",
"-",
"gamma",
")",
"*",
"x2",
")",
")",
"return",
"(",
"ind1",
",",
"ind2",
")"
] |
executes a blend crossover that modify in-place the input individuals .
|
train
| false
|
10,443
|
def nlinks_file(path):
if iswindows:
return windows_nlinks(path)
return os.stat(path).st_nlink
|
[
"def",
"nlinks_file",
"(",
"path",
")",
":",
"if",
"iswindows",
":",
"return",
"windows_nlinks",
"(",
"path",
")",
"return",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_nlink"
] |
return number of hardlinks to the file .
|
train
| false
|
10,444
|
def school():
output = s3_rest_controller()
return output
|
[
"def",
"school",
"(",
")",
":",
"output",
"=",
"s3_rest_controller",
"(",
")",
"return",
"output"
] |
restful crud controller .
|
train
| false
|
10,446
|
def get_units_with_due_date(course):
units = []
def visit(node):
'\n Visit a node. Checks to see if node has a due date and appends to\n `units` if it does. Otherwise recurses into children to search for\n nodes with due dates.\n '
if getattr(node, 'due', None):
units.append(node)
else:
for child in node.get_children():
visit(child)
visit(course)
return units
|
[
"def",
"get_units_with_due_date",
"(",
"course",
")",
":",
"units",
"=",
"[",
"]",
"def",
"visit",
"(",
"node",
")",
":",
"if",
"getattr",
"(",
"node",
",",
"'due'",
",",
"None",
")",
":",
"units",
".",
"append",
"(",
"node",
")",
"else",
":",
"for",
"child",
"in",
"node",
".",
"get_children",
"(",
")",
":",
"visit",
"(",
"child",
")",
"visit",
"(",
"course",
")",
"return",
"units"
] |
returns all top level units which have due dates .
|
train
| false
|
10,447
|
def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[(~ state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
|
[
"def",
"_step6",
"(",
"state",
")",
":",
"if",
"(",
"np",
".",
"any",
"(",
"state",
".",
"row_uncovered",
")",
"and",
"np",
".",
"any",
"(",
"state",
".",
"col_uncovered",
")",
")",
":",
"minval",
"=",
"np",
".",
"min",
"(",
"state",
".",
"C",
"[",
"state",
".",
"row_uncovered",
"]",
",",
"axis",
"=",
"0",
")",
"minval",
"=",
"np",
".",
"min",
"(",
"minval",
"[",
"state",
".",
"col_uncovered",
"]",
")",
"state",
".",
"C",
"[",
"(",
"~",
"state",
".",
"row_uncovered",
")",
"]",
"+=",
"minval",
"state",
".",
"C",
"[",
":",
",",
"state",
".",
"col_uncovered",
"]",
"-=",
"minval",
"return",
"_step4"
] |
add the value found in step 4 to every element of each covered row .
|
train
| false
|
10,449
|
def pdbref(accessing_obj, accessed_obj, *args, **kwargs):
return dbref(_to_player(accessing_obj), accessed_obj, *args, **kwargs)
|
[
"def",
"pdbref",
"(",
"accessing_obj",
",",
"accessed_obj",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"dbref",
"(",
"_to_player",
"(",
"accessing_obj",
")",
",",
"accessed_obj",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] |
same as dbref .
|
train
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.