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 |
|---|---|---|---|---|---|
16,837 | def update_emoji():
global RE_EMOJI
global URL_EMOJI
emoji_list = get_github_emoji()
emoji_map = {}
if (emoji_list is not None):
for emoji in emoji_list:
url = emoji_list[emoji]
m = RE_ASSET.match(url)
if m:
emoji_map[emoji] = m.group(u'image')
if emoji_map:
RE_EMOJI = (u':(%s):' % u'|'.join([re.escape(key) for key in sorted(emoji_map.keys())]))
URL_EMOJI = copy.copy(emoji_map)
| [
"def",
"update_emoji",
"(",
")",
":",
"global",
"RE_EMOJI",
"global",
"URL_EMOJI",
"emoji_list",
"=",
"get_github_emoji",
"(",
")",
"emoji_map",
"=",
"{",
"}",
"if",
"(",
"emoji_list",
"is",
"not",
"None",
")",
":",
"for",
"emoji",
"in",
"emoji_list",
":",
"url",
"=",
"emoji_list",
"[",
"emoji",
"]",
"m",
"=",
"RE_ASSET",
".",
"match",
"(",
"url",
")",
"if",
"m",
":",
"emoji_map",
"[",
"emoji",
"]",
"=",
"m",
".",
"group",
"(",
"u'image'",
")",
"if",
"emoji_map",
":",
"RE_EMOJI",
"=",
"(",
"u':(%s):'",
"%",
"u'|'",
".",
"join",
"(",
"[",
"re",
".",
"escape",
"(",
"key",
")",
"for",
"key",
"in",
"sorted",
"(",
"emoji_map",
".",
"keys",
"(",
")",
")",
"]",
")",
")",
"URL_EMOJI",
"=",
"copy",
".",
"copy",
"(",
"emoji_map",
")"
] | update the emoji pattern in memory . | train | false |
16,841 | def _format_float(value):
value_str = '{:.16G}'.format(value)
if (('.' not in value_str) and ('E' not in value_str)):
value_str += '.0'
elif ('E' in value_str):
(significand, exponent) = value_str.split('E')
if (exponent[0] in ('+', '-')):
sign = exponent[0]
exponent = exponent[1:]
else:
sign = ''
value_str = '{}E{}{:02d}'.format(significand, sign, int(exponent))
str_len = len(value_str)
if (str_len > 20):
idx = value_str.find('E')
if (idx < 0):
value_str = value_str[:20]
else:
value_str = (value_str[:(20 - (str_len - idx))] + value_str[idx:])
return value_str
| [
"def",
"_format_float",
"(",
"value",
")",
":",
"value_str",
"=",
"'{:.16G}'",
".",
"format",
"(",
"value",
")",
"if",
"(",
"(",
"'.'",
"not",
"in",
"value_str",
")",
"and",
"(",
"'E'",
"not",
"in",
"value_str",
")",
")",
":",
"value_str",
"+=",
"'.0'",
"elif",
"(",
"'E'",
"in",
"value_str",
")",
":",
"(",
"significand",
",",
"exponent",
")",
"=",
"value_str",
".",
"split",
"(",
"'E'",
")",
"if",
"(",
"exponent",
"[",
"0",
"]",
"in",
"(",
"'+'",
",",
"'-'",
")",
")",
":",
"sign",
"=",
"exponent",
"[",
"0",
"]",
"exponent",
"=",
"exponent",
"[",
"1",
":",
"]",
"else",
":",
"sign",
"=",
"''",
"value_str",
"=",
"'{}E{}{:02d}'",
".",
"format",
"(",
"significand",
",",
"sign",
",",
"int",
"(",
"exponent",
")",
")",
"str_len",
"=",
"len",
"(",
"value_str",
")",
"if",
"(",
"str_len",
">",
"20",
")",
":",
"idx",
"=",
"value_str",
".",
"find",
"(",
"'E'",
")",
"if",
"(",
"idx",
"<",
"0",
")",
":",
"value_str",
"=",
"value_str",
"[",
":",
"20",
"]",
"else",
":",
"value_str",
"=",
"(",
"value_str",
"[",
":",
"(",
"20",
"-",
"(",
"str_len",
"-",
"idx",
")",
")",
"]",
"+",
"value_str",
"[",
"idx",
":",
"]",
")",
"return",
"value_str"
] | format a floating number to make sure it gets the decimal point . | train | false |
16,843 | def get_app_dir(app_name, roaming=True, force_posix=False):
if WIN:
key = ((roaming and 'APPDATA') or 'LOCALAPPDATA')
folder = os.environ.get(key)
if (folder is None):
folder = os.path.expanduser('~')
return os.path.join(folder, app_name)
if force_posix:
return os.path.join(os.path.expanduser(('~/.' + _posixify(app_name))))
if (sys.platform == 'darwin'):
return os.path.join(os.path.expanduser('~/Library/Application Support'), app_name)
return os.path.join(os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')), _posixify(app_name))
| [
"def",
"get_app_dir",
"(",
"app_name",
",",
"roaming",
"=",
"True",
",",
"force_posix",
"=",
"False",
")",
":",
"if",
"WIN",
":",
"key",
"=",
"(",
"(",
"roaming",
"and",
"'APPDATA'",
")",
"or",
"'LOCALAPPDATA'",
")",
"folder",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"key",
")",
"if",
"(",
"folder",
"is",
"None",
")",
":",
"folder",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"app_name",
")",
"if",
"force_posix",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"(",
"'~/.'",
"+",
"_posixify",
"(",
"app_name",
")",
")",
")",
")",
"if",
"(",
"sys",
".",
"platform",
"==",
"'darwin'",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/Library/Application Support'",
")",
",",
"app_name",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
",",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.config'",
")",
")",
",",
"_posixify",
"(",
"app_name",
")",
")"
] | returns the config folder for the application . | train | true |
16,844 | def _import_module_functions(module_path):
functions_dict = {}
module = __import__(module_path)
for part in module_path.split('.')[1:]:
module = getattr(module, part)
for (k, v) in module.__dict__.items():
try:
if (v.__module__ != module_path):
continue
functions_dict[k] = v
except AttributeError:
pass
return functions_dict
| [
"def",
"_import_module_functions",
"(",
"module_path",
")",
":",
"functions_dict",
"=",
"{",
"}",
"module",
"=",
"__import__",
"(",
"module_path",
")",
"for",
"part",
"in",
"module_path",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
":",
"module",
"=",
"getattr",
"(",
"module",
",",
"part",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"module",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"(",
"v",
".",
"__module__",
"!=",
"module_path",
")",
":",
"continue",
"functions_dict",
"[",
"k",
"]",
"=",
"v",
"except",
"AttributeError",
":",
"pass",
"return",
"functions_dict"
] | import a module and get the functions and return them in a dict . | train | false |
16,845 | @addon_view
@non_atomic_requests
def contributions_series(request, addon, group, start, end, format):
date_range = check_series_params_or_404(group, start, end, format)
check_stats_permission(request, addon, for_contributions=True)
qs = Contribution.objects.extra(select={'date_created': 'date(created)'}).filter(addon=addon, amount__gt=0, transaction_id__isnull=False, created__range=date_range).values('date_created').annotate(count=Count('amount'), average=Avg('amount'), total=Sum('amount'))
series = sorted(qs, key=(lambda x: x['date_created']), reverse=True)
for row in series:
row['end'] = row['date'] = row.pop('date_created')
if (format == 'csv'):
return render_csv(request, addon, series, ['date', 'count', 'total', 'average'])
elif (format == 'json'):
return render_json(request, addon, series)
| [
"@",
"addon_view",
"@",
"non_atomic_requests",
"def",
"contributions_series",
"(",
"request",
",",
"addon",
",",
"group",
",",
"start",
",",
"end",
",",
"format",
")",
":",
"date_range",
"=",
"check_series_params_or_404",
"(",
"group",
",",
"start",
",",
"end",
",",
"format",
")",
"check_stats_permission",
"(",
"request",
",",
"addon",
",",
"for_contributions",
"=",
"True",
")",
"qs",
"=",
"Contribution",
".",
"objects",
".",
"extra",
"(",
"select",
"=",
"{",
"'date_created'",
":",
"'date(created)'",
"}",
")",
".",
"filter",
"(",
"addon",
"=",
"addon",
",",
"amount__gt",
"=",
"0",
",",
"transaction_id__isnull",
"=",
"False",
",",
"created__range",
"=",
"date_range",
")",
".",
"values",
"(",
"'date_created'",
")",
".",
"annotate",
"(",
"count",
"=",
"Count",
"(",
"'amount'",
")",
",",
"average",
"=",
"Avg",
"(",
"'amount'",
")",
",",
"total",
"=",
"Sum",
"(",
"'amount'",
")",
")",
"series",
"=",
"sorted",
"(",
"qs",
",",
"key",
"=",
"(",
"lambda",
"x",
":",
"x",
"[",
"'date_created'",
"]",
")",
",",
"reverse",
"=",
"True",
")",
"for",
"row",
"in",
"series",
":",
"row",
"[",
"'end'",
"]",
"=",
"row",
"[",
"'date'",
"]",
"=",
"row",
".",
"pop",
"(",
"'date_created'",
")",
"if",
"(",
"format",
"==",
"'csv'",
")",
":",
"return",
"render_csv",
"(",
"request",
",",
"addon",
",",
"series",
",",
"[",
"'date'",
",",
"'count'",
",",
"'total'",
",",
"'average'",
"]",
")",
"elif",
"(",
"format",
"==",
"'json'",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"addon",
",",
"series",
")"
] | generate summarized contributions grouped by group in format . | train | false |
16,847 | def arg_to_array(func):
def fn(self, arg, *args, **kwargs):
'Function\n\n Parameters\n ----------\n arg : array-like\n Argument to convert.\n *args : tuple\n Arguments.\n **kwargs : dict\n Keyword arguments.\n\n Returns\n -------\n value : object\n The return value of the function.\n '
return func(self, np.array(arg), *args, **kwargs)
return fn
| [
"def",
"arg_to_array",
"(",
"func",
")",
":",
"def",
"fn",
"(",
"self",
",",
"arg",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"func",
"(",
"self",
",",
"np",
".",
"array",
"(",
"arg",
")",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"fn"
] | decorator to convert argument to array . | train | true |
16,849 | def get_user_config_path():
return os.path.join(xdg.get_config_dir(), 'config.py')
| [
"def",
"get_user_config_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"xdg",
".",
"get_config_dir",
"(",
")",
",",
"'config.py'",
")"
] | get the path to the user config file . | train | false |
16,850 | def IsTypePackable(field_type):
return (field_type not in NON_PACKABLE_TYPES)
| [
"def",
"IsTypePackable",
"(",
"field_type",
")",
":",
"return",
"(",
"field_type",
"not",
"in",
"NON_PACKABLE_TYPES",
")"
] | return true iff packable = true is valid for fields of this type . | train | false |
16,851 | def sort_collator():
global _sort_collator
if (_sort_collator is None):
_sort_collator = collator().clone()
_sort_collator.strength = _icu.UCOL_SECONDARY
_sort_collator.numeric = tweaks[u'numeric_collation']
return _sort_collator
| [
"def",
"sort_collator",
"(",
")",
":",
"global",
"_sort_collator",
"if",
"(",
"_sort_collator",
"is",
"None",
")",
":",
"_sort_collator",
"=",
"collator",
"(",
")",
".",
"clone",
"(",
")",
"_sort_collator",
".",
"strength",
"=",
"_icu",
".",
"UCOL_SECONDARY",
"_sort_collator",
".",
"numeric",
"=",
"tweaks",
"[",
"u'numeric_collation'",
"]",
"return",
"_sort_collator"
] | ignores case differences and recognizes numbers in strings . | train | false |
16,852 | def remove_known_host(reactor, hostname):
return run(reactor, ['ssh-keygen', '-R', hostname])
| [
"def",
"remove_known_host",
"(",
"reactor",
",",
"hostname",
")",
":",
"return",
"run",
"(",
"reactor",
",",
"[",
"'ssh-keygen'",
",",
"'-R'",
",",
"hostname",
"]",
")"
] | remove all keys belonging to hostname from a known_hosts file . | train | false |
16,853 | def Async(proxy):
key = id(proxy)
if (key in _async_proxy_cache):
return _async_proxy_cache[key]
else:
new_proxy = AsyncNetProxy(proxy)
_async_proxy_cache[key] = new_proxy
return new_proxy
| [
"def",
"Async",
"(",
"proxy",
")",
":",
"key",
"=",
"id",
"(",
"proxy",
")",
"if",
"(",
"key",
"in",
"_async_proxy_cache",
")",
":",
"return",
"_async_proxy_cache",
"[",
"key",
"]",
"else",
":",
"new_proxy",
"=",
"AsyncNetProxy",
"(",
"proxy",
")",
"_async_proxy_cache",
"[",
"key",
"]",
"=",
"new_proxy",
"return",
"new_proxy"
] | a factory for creating asynchronous proxies for existing synchronous ones . | train | false |
16,855 | def lowess(endog, exog, frac=(2.0 / 3), it=3):
x = exog
if (exog.ndim != 1):
raise ValueError('exog must be a vector')
if (endog.ndim != 1):
raise ValueError('endog must be a vector')
if (endog.shape[0] != x.shape[0]):
raise ValueError('exog and endog must have same length')
n = exog.shape[0]
fitted = np.zeros(n)
k = int((frac * n))
index_array = np.argsort(exog)
x_copy = np.array(exog[index_array])
y_copy = endog[index_array]
(fitted, weights) = _lowess_initial_fit(x_copy, y_copy, k, n)
for i in range(it):
_lowess_robustify_fit(x_copy, y_copy, fitted, weights, k, n)
out = np.array([x_copy, fitted]).T
out.shape = (n, 2)
return out
| [
"def",
"lowess",
"(",
"endog",
",",
"exog",
",",
"frac",
"=",
"(",
"2.0",
"/",
"3",
")",
",",
"it",
"=",
"3",
")",
":",
"x",
"=",
"exog",
"if",
"(",
"exog",
".",
"ndim",
"!=",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'exog must be a vector'",
")",
"if",
"(",
"endog",
".",
"ndim",
"!=",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'endog must be a vector'",
")",
"if",
"(",
"endog",
".",
"shape",
"[",
"0",
"]",
"!=",
"x",
".",
"shape",
"[",
"0",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'exog and endog must have same length'",
")",
"n",
"=",
"exog",
".",
"shape",
"[",
"0",
"]",
"fitted",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"k",
"=",
"int",
"(",
"(",
"frac",
"*",
"n",
")",
")",
"index_array",
"=",
"np",
".",
"argsort",
"(",
"exog",
")",
"x_copy",
"=",
"np",
".",
"array",
"(",
"exog",
"[",
"index_array",
"]",
")",
"y_copy",
"=",
"endog",
"[",
"index_array",
"]",
"(",
"fitted",
",",
"weights",
")",
"=",
"_lowess_initial_fit",
"(",
"x_copy",
",",
"y_copy",
",",
"k",
",",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"it",
")",
":",
"_lowess_robustify_fit",
"(",
"x_copy",
",",
"y_copy",
",",
"fitted",
",",
"weights",
",",
"k",
",",
"n",
")",
"out",
"=",
"np",
".",
"array",
"(",
"[",
"x_copy",
",",
"fitted",
"]",
")",
".",
"T",
"out",
".",
"shape",
"=",
"(",
"n",
",",
"2",
")",
"return",
"out"
] | returns y-values estimated using the lowess function in statsmodels . | train | false |
16,856 | def _methodFunction(classObject, methodName):
methodObject = getattr(classObject, methodName)
if _PY3:
return methodObject
return methodObject.im_func
| [
"def",
"_methodFunction",
"(",
"classObject",
",",
"methodName",
")",
":",
"methodObject",
"=",
"getattr",
"(",
"classObject",
",",
"methodName",
")",
"if",
"_PY3",
":",
"return",
"methodObject",
"return",
"methodObject",
".",
"im_func"
] | retrieve the function object implementing a method name given the class its on and a method name . | train | false |
16,857 | def simple_preprocess(doc, deacc=False, min_len=2, max_len=15):
tokens = [token for token in tokenize(doc, lower=True, deacc=deacc, errors='ignore') if ((min_len <= len(token) <= max_len) and (not token.startswith('_')))]
return tokens
| [
"def",
"simple_preprocess",
"(",
"doc",
",",
"deacc",
"=",
"False",
",",
"min_len",
"=",
"2",
",",
"max_len",
"=",
"15",
")",
":",
"tokens",
"=",
"[",
"token",
"for",
"token",
"in",
"tokenize",
"(",
"doc",
",",
"lower",
"=",
"True",
",",
"deacc",
"=",
"deacc",
",",
"errors",
"=",
"'ignore'",
")",
"if",
"(",
"(",
"min_len",
"<=",
"len",
"(",
"token",
")",
"<=",
"max_len",
")",
"and",
"(",
"not",
"token",
".",
"startswith",
"(",
"'_'",
")",
")",
")",
"]",
"return",
"tokens"
] | convert a document into a list of tokens . | train | true |
16,860 | def fix_missing_locations(node):
def _fix(node, lineno, col_offset):
if ('lineno' in node._attributes):
if (not hasattr(node, 'lineno')):
node.lineno = lineno
else:
lineno = node.lineno
if ('col_offset' in node._attributes):
if (not hasattr(node, 'col_offset')):
node.col_offset = col_offset
else:
col_offset = node.col_offset
for child in iter_child_nodes(node):
_fix(child, lineno, col_offset)
_fix(node, 1, 0)
return node
| [
"def",
"fix_missing_locations",
"(",
"node",
")",
":",
"def",
"_fix",
"(",
"node",
",",
"lineno",
",",
"col_offset",
")",
":",
"if",
"(",
"'lineno'",
"in",
"node",
".",
"_attributes",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"node",
",",
"'lineno'",
")",
")",
":",
"node",
".",
"lineno",
"=",
"lineno",
"else",
":",
"lineno",
"=",
"node",
".",
"lineno",
"if",
"(",
"'col_offset'",
"in",
"node",
".",
"_attributes",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"node",
",",
"'col_offset'",
")",
")",
":",
"node",
".",
"col_offset",
"=",
"col_offset",
"else",
":",
"col_offset",
"=",
"node",
".",
"col_offset",
"for",
"child",
"in",
"iter_child_nodes",
"(",
"node",
")",
":",
"_fix",
"(",
"child",
",",
"lineno",
",",
"col_offset",
")",
"_fix",
"(",
"node",
",",
"1",
",",
"0",
")",
"return",
"node"
] | some nodes require a line number and the column offset . | train | true |
16,861 | def mygettext(string):
return _(string)
| [
"def",
"mygettext",
"(",
"string",
")",
":",
"return",
"_",
"(",
"string",
")"
] | used instead of _ when creating translationproxies . | train | false |
16,862 | def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
if (scheme is None):
scheme = _get_current_scheme()
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}'.format(power, scheme, sub_group, setting_guid, value)
return __salt__['cmd.run'](cmd, python_shell=False)
| [
"def",
"_set_powercfg_value",
"(",
"scheme",
",",
"sub_group",
",",
"setting_guid",
",",
"power",
",",
"value",
")",
":",
"if",
"(",
"scheme",
"is",
"None",
")",
":",
"scheme",
"=",
"_get_current_scheme",
"(",
")",
"cmd",
"=",
"'powercfg /set{0}valueindex {1} {2} {3} {4}'",
".",
"format",
"(",
"power",
",",
"scheme",
",",
"sub_group",
",",
"setting_guid",
",",
"value",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")"
] | sets the value of a setting with a given power to the given scheme . | train | true |
16,864 | def get_locale_from_accept_header(request):
header = request.headers.get('Accept-Language', '')
parsed = parse_accept_language_header(header)
if (parsed is None):
return None
pairs_sorted_by_q = sorted(parsed.items(), key=(lambda (lang, q): q), reverse=True)
locale = Locale.negotiate([lang for (lang, q) in pairs_sorted_by_q], request.app.config.get('locales'), sep='_')
return str(locale)
| [
"def",
"get_locale_from_accept_header",
"(",
"request",
")",
":",
"header",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Accept-Language'",
",",
"''",
")",
"parsed",
"=",
"parse_accept_language_header",
"(",
"header",
")",
"if",
"(",
"parsed",
"is",
"None",
")",
":",
"return",
"None",
"pairs_sorted_by_q",
"=",
"sorted",
"(",
"parsed",
".",
"items",
"(",
")",
",",
"key",
"=",
"(",
"lambda",
"(",
"lang",
",",
"q",
")",
":",
"q",
")",
",",
"reverse",
"=",
"True",
")",
"locale",
"=",
"Locale",
".",
"negotiate",
"(",
"[",
"lang",
"for",
"(",
"lang",
",",
"q",
")",
"in",
"pairs_sorted_by_q",
"]",
",",
"request",
".",
"app",
".",
"config",
".",
"get",
"(",
"'locales'",
")",
",",
"sep",
"=",
"'_'",
")",
"return",
"str",
"(",
"locale",
")"
] | detect locale from request . | train | false |
16,866 | def is_pep8_available():
try:
import pep8
if (not hasattr(pep8, 'BaseReport')):
raise ImportError()
return True
except ImportError:
return False
| [
"def",
"is_pep8_available",
"(",
")",
":",
"try",
":",
"import",
"pep8",
"if",
"(",
"not",
"hasattr",
"(",
"pep8",
",",
"'BaseReport'",
")",
")",
":",
"raise",
"ImportError",
"(",
")",
"return",
"True",
"except",
"ImportError",
":",
"return",
"False"
] | checks if pep8 is availalbe . | train | false |
16,867 | def ascontiguousarray(a, dtype=None):
return core.ascontiguousarray(a, dtype)
| [
"def",
"ascontiguousarray",
"(",
"a",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"core",
".",
"ascontiguousarray",
"(",
"a",
",",
"dtype",
")"
] | returns a c-contiguous array . | train | false |
16,868 | def cbs_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
html = get_content(url)
pid = match1(html, "video\\.settings\\.pid\\s*=\\s*\\'([^\\']+)\\'")
title = match1(html, 'video\\.settings\\.title\\s*=\\s*\\"([^\\"]+)\\"')
theplatform_download_by_pid(pid, title, output_dir=output_dir, merge=merge, info_only=info_only)
| [
"def",
"cbs_download",
"(",
"url",
",",
"output_dir",
"=",
"'.'",
",",
"merge",
"=",
"True",
",",
"info_only",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"html",
"=",
"get_content",
"(",
"url",
")",
"pid",
"=",
"match1",
"(",
"html",
",",
"\"video\\\\.settings\\\\.pid\\\\s*=\\\\s*\\\\'([^\\\\']+)\\\\'\"",
")",
"title",
"=",
"match1",
"(",
"html",
",",
"'video\\\\.settings\\\\.title\\\\s*=\\\\s*\\\\\"([^\\\\\"]+)\\\\\"'",
")",
"theplatform_download_by_pid",
"(",
"pid",
",",
"title",
",",
"output_dir",
"=",
"output_dir",
",",
"merge",
"=",
"merge",
",",
"info_only",
"=",
"info_only",
")"
] | downloads cbs videos by url . | train | true |
16,870 | def expect_json(view_function):
@wraps(view_function)
def parse_json_into_request(request, *args, **kwargs):
if (('application/json' in request.META.get('CONTENT_TYPE', '')) and request.body):
try:
request.json = json.loads(request.body)
except ValueError:
return JsonResponseBadRequest({'error': 'Invalid JSON'})
else:
request.json = {}
return view_function(request, *args, **kwargs)
return parse_json_into_request
| [
"def",
"expect_json",
"(",
"view_function",
")",
":",
"@",
"wraps",
"(",
"view_function",
")",
"def",
"parse_json_into_request",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"(",
"'application/json'",
"in",
"request",
".",
"META",
".",
"get",
"(",
"'CONTENT_TYPE'",
",",
"''",
")",
")",
"and",
"request",
".",
"body",
")",
":",
"try",
":",
"request",
".",
"json",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
")",
"except",
"ValueError",
":",
"return",
"JsonResponseBadRequest",
"(",
"{",
"'error'",
":",
"'Invalid JSON'",
"}",
")",
"else",
":",
"request",
".",
"json",
"=",
"{",
"}",
"return",
"view_function",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"parse_json_into_request"
] | view decorator for simplifying handing of requests that expect json . | train | false |
16,871 | def is_matching_event(expected_event, actual_event, tolerate=None):
return (len(get_event_differences(expected_event, actual_event, tolerate=tolerate)) == 0)
| [
"def",
"is_matching_event",
"(",
"expected_event",
",",
"actual_event",
",",
"tolerate",
"=",
"None",
")",
":",
"return",
"(",
"len",
"(",
"get_event_differences",
"(",
"expected_event",
",",
"actual_event",
",",
"tolerate",
"=",
"tolerate",
")",
")",
"==",
"0",
")"
] | return true iff the actual_event matches the expected_event given the tolerances . | train | false |
16,872 | def commit_on_success_unless_managed(using=None, savepoint=False):
connection = get_connection(using)
if (connection.get_autocommit() or connection.in_atomic_block):
return atomic(using, savepoint)
else:
def entering(using):
pass
def exiting(exc_type, using):
set_dirty(using=using)
return _transaction_func(entering, exiting, using)
| [
"def",
"commit_on_success_unless_managed",
"(",
"using",
"=",
"None",
",",
"savepoint",
"=",
"False",
")",
":",
"connection",
"=",
"get_connection",
"(",
"using",
")",
"if",
"(",
"connection",
".",
"get_autocommit",
"(",
")",
"or",
"connection",
".",
"in_atomic_block",
")",
":",
"return",
"atomic",
"(",
"using",
",",
"savepoint",
")",
"else",
":",
"def",
"entering",
"(",
"using",
")",
":",
"pass",
"def",
"exiting",
"(",
"exc_type",
",",
"using",
")",
":",
"set_dirty",
"(",
"using",
"=",
"using",
")",
"return",
"_transaction_func",
"(",
"entering",
",",
"exiting",
",",
"using",
")"
] | transitory api to preserve backwards-compatibility while refactoring . | train | false |
16,874 | def role_add(user, role):
ret = {}
roles = role.split(',')
known_roles = role_list().keys()
valid_roles = [r for r in roles if (r in known_roles)]
log.debug('rbac.role_add - roles={0}, known_roles={1}, valid_roles={2}'.format(roles, known_roles, valid_roles))
if (len(valid_roles) > 0):
res = __salt__['cmd.run_all']('usermod -R "{roles}" {login}'.format(login=user, roles=','.join(set((role_get(user) + valid_roles)))))
if (res['retcode'] > 0):
ret['Error'] = {'retcode': res['retcode'], 'message': (res['stderr'] if ('stderr' in res) else res['stdout'])}
return ret
active_roles = role_get(user)
for r in roles:
if (r not in valid_roles):
ret[r] = 'Unknown'
elif (r in active_roles):
ret[r] = 'Added'
else:
ret[r] = 'Failed'
return ret
| [
"def",
"role_add",
"(",
"user",
",",
"role",
")",
":",
"ret",
"=",
"{",
"}",
"roles",
"=",
"role",
".",
"split",
"(",
"','",
")",
"known_roles",
"=",
"role_list",
"(",
")",
".",
"keys",
"(",
")",
"valid_roles",
"=",
"[",
"r",
"for",
"r",
"in",
"roles",
"if",
"(",
"r",
"in",
"known_roles",
")",
"]",
"log",
".",
"debug",
"(",
"'rbac.role_add - roles={0}, known_roles={1}, valid_roles={2}'",
".",
"format",
"(",
"roles",
",",
"known_roles",
",",
"valid_roles",
")",
")",
"if",
"(",
"len",
"(",
"valid_roles",
")",
">",
"0",
")",
":",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'usermod -R \"{roles}\" {login}'",
".",
"format",
"(",
"login",
"=",
"user",
",",
"roles",
"=",
"','",
".",
"join",
"(",
"set",
"(",
"(",
"role_get",
"(",
"user",
")",
"+",
"valid_roles",
")",
")",
")",
")",
")",
"if",
"(",
"res",
"[",
"'retcode'",
"]",
">",
"0",
")",
":",
"ret",
"[",
"'Error'",
"]",
"=",
"{",
"'retcode'",
":",
"res",
"[",
"'retcode'",
"]",
",",
"'message'",
":",
"(",
"res",
"[",
"'stderr'",
"]",
"if",
"(",
"'stderr'",
"in",
"res",
")",
"else",
"res",
"[",
"'stdout'",
"]",
")",
"}",
"return",
"ret",
"active_roles",
"=",
"role_get",
"(",
"user",
")",
"for",
"r",
"in",
"roles",
":",
"if",
"(",
"r",
"not",
"in",
"valid_roles",
")",
":",
"ret",
"[",
"r",
"]",
"=",
"'Unknown'",
"elif",
"(",
"r",
"in",
"active_roles",
")",
":",
"ret",
"[",
"r",
"]",
"=",
"'Added'",
"else",
":",
"ret",
"[",
"r",
"]",
"=",
"'Failed'",
"return",
"ret"
] | add role to user user : string username role : string role name cli example: . | train | true |
16,877 | def matches(what, glob_patterns):
return any((fnmatch.fnmatch(what, glob_pattern) for glob_pattern in glob_patterns))
| [
"def",
"matches",
"(",
"what",
",",
"glob_patterns",
")",
":",
"return",
"any",
"(",
"(",
"fnmatch",
".",
"fnmatch",
"(",
"what",
",",
"glob_pattern",
")",
"for",
"glob_pattern",
"in",
"glob_patterns",
")",
")"
] | check for matches in both cdao and obo namespaces . | train | false |
16,878 | def _status_csf():
cmd = 'test -e /etc/csf/csf.disable'
out = __salt__['cmd.run_all'](cmd)
return bool(out['retcode'])
| [
"def",
"_status_csf",
"(",
")",
":",
"cmd",
"=",
"'test -e /etc/csf/csf.disable'",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"return",
"bool",
"(",
"out",
"[",
"'retcode'",
"]",
")"
] | return true if csf is running otherwise return false . | train | false |
16,879 | def getJoinedPath(path, subName=''):
if (subName == ''):
return path
return os.path.join(path, subName)
| [
"def",
"getJoinedPath",
"(",
"path",
",",
"subName",
"=",
"''",
")",
":",
"if",
"(",
"subName",
"==",
"''",
")",
":",
"return",
"path",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"subName",
")"
] | get the joined file path . | train | false |
16,883 | def get_standard_freq(freq):
msg = 'get_standard_freq is deprecated. Use to_offset(freq).rule_code instead.'
warnings.warn(msg, FutureWarning, stacklevel=2)
return to_offset(freq).rule_code
| [
"def",
"get_standard_freq",
"(",
"freq",
")",
":",
"msg",
"=",
"'get_standard_freq is deprecated. Use to_offset(freq).rule_code instead.'",
"warnings",
".",
"warn",
"(",
"msg",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"to_offset",
"(",
"freq",
")",
".",
"rule_code"
] | return the standardized frequency string . | train | false |
16,884 | def test_newlines():
superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')
superConsole.SendKeys('{ENTER}')
superConsole.SendKeys('None{ENTER}')
superConsole.SendKeys('{ENTER}{ENTER}{ENTER}')
superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
for lines in getTestOutput():
AreEqual(removePrompts(lines), [])
| [
"def",
"test_newlines",
"(",
")",
":",
"superConsole",
".",
"SendKeys",
"(",
"'outputRedirectStart{(}{)}{ENTER}'",
")",
"superConsole",
".",
"SendKeys",
"(",
"'{ENTER}'",
")",
"superConsole",
".",
"SendKeys",
"(",
"'None{ENTER}'",
")",
"superConsole",
".",
"SendKeys",
"(",
"'{ENTER}{ENTER}{ENTER}'",
")",
"superConsole",
".",
"SendKeys",
"(",
"'outputRedirectStop{(}{)}{ENTER}'",
")",
"for",
"lines",
"in",
"getTestOutput",
"(",
")",
":",
"AreEqual",
"(",
"removePrompts",
"(",
"lines",
")",
",",
"[",
"]",
")"
] | ensure empty lines do not break the console . | train | false |
16,885 | def skills_filter(req_id):
rstable = s3db.req_req_skill
rows = db((rstable.req_id == req_id)).select(rstable.skill_id)
filter_opts = []
for r in rows:
multi_skill_id = r.skill_id
for skill_id in multi_skill_id:
filter_opts.append(skill_id)
if (len(filter_opts) == 1):
field = s3db.req_commit_skill.skill_id
field.default = skill_id
field.writable = False
return
s3db.req_commit_skill.skill_id.requires = IS_ONE_OF(db, 'hrm_skill.id', s3db.hrm_multi_skill_represent, filterby='id', filter_opts=filter_opts, sort=True, multiple=True)
| [
"def",
"skills_filter",
"(",
"req_id",
")",
":",
"rstable",
"=",
"s3db",
".",
"req_req_skill",
"rows",
"=",
"db",
"(",
"(",
"rstable",
".",
"req_id",
"==",
"req_id",
")",
")",
".",
"select",
"(",
"rstable",
".",
"skill_id",
")",
"filter_opts",
"=",
"[",
"]",
"for",
"r",
"in",
"rows",
":",
"multi_skill_id",
"=",
"r",
".",
"skill_id",
"for",
"skill_id",
"in",
"multi_skill_id",
":",
"filter_opts",
".",
"append",
"(",
"skill_id",
")",
"if",
"(",
"len",
"(",
"filter_opts",
")",
"==",
"1",
")",
":",
"field",
"=",
"s3db",
".",
"req_commit_skill",
".",
"skill_id",
"field",
".",
"default",
"=",
"skill_id",
"field",
".",
"writable",
"=",
"False",
"return",
"s3db",
".",
"req_commit_skill",
".",
"skill_id",
".",
"requires",
"=",
"IS_ONE_OF",
"(",
"db",
",",
"'hrm_skill.id'",
",",
"s3db",
".",
"hrm_multi_skill_represent",
",",
"filterby",
"=",
"'id'",
",",
"filter_opts",
"=",
"filter_opts",
",",
"sort",
"=",
"True",
",",
"multiple",
"=",
"True",
")"
] | limit commit skills to skills from the request - dry helper function . | train | false |
16,887 | def load_yaml(filename):
try:
with open(filename, 'r') as f:
return yaml.load(f, Loader=Loader)
except (IOError, yaml.error.YAMLError) as exc:
raise ConfigReadError(filename, exc)
| [
"def",
"load_yaml",
"(",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"load",
"(",
"f",
",",
"Loader",
"=",
"Loader",
")",
"except",
"(",
"IOError",
",",
"yaml",
".",
"error",
".",
"YAMLError",
")",
"as",
"exc",
":",
"raise",
"ConfigReadError",
"(",
"filename",
",",
"exc",
")"
] | read a yaml document from a file . | train | true |
16,888 | def get_tau_sd(tau=None, sd=None):
if (tau is None):
if (sd is None):
sd = 1.0
tau = 1.0
else:
tau = (sd ** (-2.0))
elif (sd is not None):
raise ValueError("Can't pass both tau and sd")
else:
sd = (tau ** (-0.5))
tau = (1.0 * tau)
sd = (1.0 * sd)
return (tau, sd)
| [
"def",
"get_tau_sd",
"(",
"tau",
"=",
"None",
",",
"sd",
"=",
"None",
")",
":",
"if",
"(",
"tau",
"is",
"None",
")",
":",
"if",
"(",
"sd",
"is",
"None",
")",
":",
"sd",
"=",
"1.0",
"tau",
"=",
"1.0",
"else",
":",
"tau",
"=",
"(",
"sd",
"**",
"(",
"-",
"2.0",
")",
")",
"elif",
"(",
"sd",
"is",
"not",
"None",
")",
":",
"raise",
"ValueError",
"(",
"\"Can't pass both tau and sd\"",
")",
"else",
":",
"sd",
"=",
"(",
"tau",
"**",
"(",
"-",
"0.5",
")",
")",
"tau",
"=",
"(",
"1.0",
"*",
"tau",
")",
"sd",
"=",
"(",
"1.0",
"*",
"sd",
")",
"return",
"(",
"tau",
",",
"sd",
")"
] | find precision and standard deviation . | train | false |
16,889 | @register(None)
def _check_generic(brain, match_kind, match, target_dict, cred_dict):
match = (match % target_dict)
if (match_kind in cred_dict):
return (match == unicode(cred_dict[match_kind]))
return False
| [
"@",
"register",
"(",
"None",
")",
"def",
"_check_generic",
"(",
"brain",
",",
"match_kind",
",",
"match",
",",
"target_dict",
",",
"cred_dict",
")",
":",
"match",
"=",
"(",
"match",
"%",
"target_dict",
")",
"if",
"(",
"match_kind",
"in",
"cred_dict",
")",
":",
"return",
"(",
"match",
"==",
"unicode",
"(",
"cred_dict",
"[",
"match_kind",
"]",
")",
")",
"return",
"False"
] | check an individual match . | train | false |
16,891 | def deploy_script(scriptpath, *args):
put(local_path=scriptpath, remote_path='', mirror_local_mode=True)
scriptfile = os.path.split(scriptpath)[1]
args_str = ' '.join(args)
run(((('./' + scriptfile) + ' ') + args_str))
| [
"def",
"deploy_script",
"(",
"scriptpath",
",",
"*",
"args",
")",
":",
"put",
"(",
"local_path",
"=",
"scriptpath",
",",
"remote_path",
"=",
"''",
",",
"mirror_local_mode",
"=",
"True",
")",
"scriptfile",
"=",
"os",
".",
"path",
".",
"split",
"(",
"scriptpath",
")",
"[",
"1",
"]",
"args_str",
"=",
"' '",
".",
"join",
"(",
"args",
")",
"run",
"(",
"(",
"(",
"(",
"'./'",
"+",
"scriptfile",
")",
"+",
"' '",
")",
"+",
"args_str",
")",
")"
] | copies to remote and executes local script . | train | false |
16,893 | @requires_application()
def test_functionality_proxy():
_test_basics('gl2 debug')
| [
"@",
"requires_application",
"(",
")",
"def",
"test_functionality_proxy",
"(",
")",
":",
"_test_basics",
"(",
"'gl2 debug'",
")"
] | test gl proxy class for basic functionality . | train | false |
16,894 | def is_valid_ethernet_tag_id(etag_id):
return (isinstance(etag_id, numbers.Integral) and (0 <= etag_id <= 4294967295))
| [
"def",
"is_valid_ethernet_tag_id",
"(",
"etag_id",
")",
":",
"return",
"(",
"isinstance",
"(",
"etag_id",
",",
"numbers",
".",
"Integral",
")",
"and",
"(",
"0",
"<=",
"etag_id",
"<=",
"4294967295",
")",
")"
] | returns true if the given evpn ethernet tag id is valid . | train | false |
16,895 | def get_lus_version():
fsvers = '/proc/fs/lustre/version'
logging.debug((' opening file ' + fsvers))
try:
fobj = open(fsvers)
except IOError:
logging.debug(('ERROR opening file ' + fsvers))
exit()
vals = []
for line in fobj:
item = re.split('\\s+', line.rstrip())
vals.append(item)
for n in range(len(vals)):
if ('lustre:' in vals[n]):
vers_string = vals[n][1]
fir = vers_string.find('.')
sec = vers_string.find('.', (fir + 1))
lus_version = ((vers_string[0:fir] + '.') + vers_string[(fir + 1):sec])
logging.debug((' lus_version: ' + str(lus_version)))
return float(lus_version)
| [
"def",
"get_lus_version",
"(",
")",
":",
"fsvers",
"=",
"'/proc/fs/lustre/version'",
"logging",
".",
"debug",
"(",
"(",
"' opening file '",
"+",
"fsvers",
")",
")",
"try",
":",
"fobj",
"=",
"open",
"(",
"fsvers",
")",
"except",
"IOError",
":",
"logging",
".",
"debug",
"(",
"(",
"'ERROR opening file '",
"+",
"fsvers",
")",
")",
"exit",
"(",
")",
"vals",
"=",
"[",
"]",
"for",
"line",
"in",
"fobj",
":",
"item",
"=",
"re",
".",
"split",
"(",
"'\\\\s+'",
",",
"line",
".",
"rstrip",
"(",
")",
")",
"vals",
".",
"append",
"(",
"item",
")",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"vals",
")",
")",
":",
"if",
"(",
"'lustre:'",
"in",
"vals",
"[",
"n",
"]",
")",
":",
"vers_string",
"=",
"vals",
"[",
"n",
"]",
"[",
"1",
"]",
"fir",
"=",
"vers_string",
".",
"find",
"(",
"'.'",
")",
"sec",
"=",
"vers_string",
".",
"find",
"(",
"'.'",
",",
"(",
"fir",
"+",
"1",
")",
")",
"lus_version",
"=",
"(",
"(",
"vers_string",
"[",
"0",
":",
"fir",
"]",
"+",
"'.'",
")",
"+",
"vers_string",
"[",
"(",
"fir",
"+",
"1",
")",
":",
"sec",
"]",
")",
"logging",
".",
"debug",
"(",
"(",
"' lus_version: '",
"+",
"str",
"(",
"lus_version",
")",
")",
")",
"return",
"float",
"(",
"lus_version",
")"
] | return lustre version number . | train | false |
16,896 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
16,898 | def http_error(httpexception, errno=None, code=None, error=None, message=None, info=None, details=None):
errno = (errno or ERRORS.UNDEFINED)
if isinstance(errno, Enum):
errno = errno.value
logger.bind(errno=errno)
body = {'code': (code or httpexception.code), 'errno': errno, 'error': (error or httpexception.title)}
if (message is not None):
body['message'] = message
if (info is not None):
body['info'] = info
if (details is not None):
body['details'] = details
response = httpexception
response.body = json.dumps(body).encode('utf-8')
response.content_type = 'application/json'
return response
| [
"def",
"http_error",
"(",
"httpexception",
",",
"errno",
"=",
"None",
",",
"code",
"=",
"None",
",",
"error",
"=",
"None",
",",
"message",
"=",
"None",
",",
"info",
"=",
"None",
",",
"details",
"=",
"None",
")",
":",
"errno",
"=",
"(",
"errno",
"or",
"ERRORS",
".",
"UNDEFINED",
")",
"if",
"isinstance",
"(",
"errno",
",",
"Enum",
")",
":",
"errno",
"=",
"errno",
".",
"value",
"logger",
".",
"bind",
"(",
"errno",
"=",
"errno",
")",
"body",
"=",
"{",
"'code'",
":",
"(",
"code",
"or",
"httpexception",
".",
"code",
")",
",",
"'errno'",
":",
"errno",
",",
"'error'",
":",
"(",
"error",
"or",
"httpexception",
".",
"title",
")",
"}",
"if",
"(",
"message",
"is",
"not",
"None",
")",
":",
"body",
"[",
"'message'",
"]",
"=",
"message",
"if",
"(",
"info",
"is",
"not",
"None",
")",
":",
"body",
"[",
"'info'",
"]",
"=",
"info",
"if",
"(",
"details",
"is",
"not",
"None",
")",
":",
"body",
"[",
"'details'",
"]",
"=",
"details",
"response",
"=",
"httpexception",
"response",
".",
"body",
"=",
"json",
".",
"dumps",
"(",
"body",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"response",
".",
"content_type",
"=",
"'application/json'",
"return",
"response"
] | return a json formated response matching the error http api . | train | false |
16,900 | def working_path(filename):
return os.path.join(WORKING_DIR, filename)
| [
"def",
"working_path",
"(",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"WORKING_DIR",
",",
"filename",
")"
] | return an absolute path for . | train | false |
16,901 | def publish_doctree(source, source_path=None, source_class=io.StringInput, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=False):
pub = Publisher(reader=reader, parser=parser, writer=None, settings=settings, source_class=source_class, destination_class=io.NullOutput)
pub.set_components(reader_name, parser_name, 'null')
pub.process_programmatic_settings(settings_spec, settings_overrides, config_section)
pub.set_source(source, source_path)
pub.set_destination(None, None)
output = pub.publish(enable_exit_status=enable_exit_status)
return pub.document
| [
"def",
"publish_doctree",
"(",
"source",
",",
"source_path",
"=",
"None",
",",
"source_class",
"=",
"io",
".",
"StringInput",
",",
"reader",
"=",
"None",
",",
"reader_name",
"=",
"'standalone'",
",",
"parser",
"=",
"None",
",",
"parser_name",
"=",
"'restructuredtext'",
",",
"settings",
"=",
"None",
",",
"settings_spec",
"=",
"None",
",",
"settings_overrides",
"=",
"None",
",",
"config_section",
"=",
"None",
",",
"enable_exit_status",
"=",
"False",
")",
":",
"pub",
"=",
"Publisher",
"(",
"reader",
"=",
"reader",
",",
"parser",
"=",
"parser",
",",
"writer",
"=",
"None",
",",
"settings",
"=",
"settings",
",",
"source_class",
"=",
"source_class",
",",
"destination_class",
"=",
"io",
".",
"NullOutput",
")",
"pub",
".",
"set_components",
"(",
"reader_name",
",",
"parser_name",
",",
"'null'",
")",
"pub",
".",
"process_programmatic_settings",
"(",
"settings_spec",
",",
"settings_overrides",
",",
"config_section",
")",
"pub",
".",
"set_source",
"(",
"source",
",",
"source_path",
")",
"pub",
".",
"set_destination",
"(",
"None",
",",
"None",
")",
"output",
"=",
"pub",
".",
"publish",
"(",
"enable_exit_status",
"=",
"enable_exit_status",
")",
"return",
"pub",
".",
"document"
] | set up & run a publisher for programmatic use with string i/o . | train | false |
16,902 | def _get_sentences_with_word_count(sentences, word_count):
length = 0
selected_sentences = []
for sentence in sentences:
words_in_sentence = len(sentence.text.split())
if (abs(((word_count - length) - words_in_sentence)) > abs((word_count - length))):
return selected_sentences
selected_sentences.append(sentence)
length += words_in_sentence
return selected_sentences
| [
"def",
"_get_sentences_with_word_count",
"(",
"sentences",
",",
"word_count",
")",
":",
"length",
"=",
"0",
"selected_sentences",
"=",
"[",
"]",
"for",
"sentence",
"in",
"sentences",
":",
"words_in_sentence",
"=",
"len",
"(",
"sentence",
".",
"text",
".",
"split",
"(",
")",
")",
"if",
"(",
"abs",
"(",
"(",
"(",
"word_count",
"-",
"length",
")",
"-",
"words_in_sentence",
")",
")",
">",
"abs",
"(",
"(",
"word_count",
"-",
"length",
")",
")",
")",
":",
"return",
"selected_sentences",
"selected_sentences",
".",
"append",
"(",
"sentence",
")",
"length",
"+=",
"words_in_sentence",
"return",
"selected_sentences"
] | given a list of sentences . | train | true |
16,903 | def _reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
if (format is not None):
kwargs = (kwargs or {})
kwargs['format'] = format
return reverse(viewname, args=args, kwargs=kwargs, **extra)
| [
"def",
"_reverse",
"(",
"viewname",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"request",
"=",
"None",
",",
"format",
"=",
"None",
",",
"**",
"extra",
")",
":",
"if",
"(",
"format",
"is",
"not",
"None",
")",
":",
"kwargs",
"=",
"(",
"kwargs",
"or",
"{",
"}",
")",
"kwargs",
"[",
"'format'",
"]",
"=",
"format",
"return",
"reverse",
"(",
"viewname",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"**",
"extra",
")"
] | same as django . | train | false |
16,904 | @lru_cache(maxsize=None)
def cache_installed():
has_key = bool(getattr(settings, u'NEVERCACHE_KEY', u''))
def flatten(seqs):
return (item for seq in seqs for item in seq)
middleware_classes = map(import_string, get_middleware_setting())
middleware_ancestors = set(flatten(map(getmro, middleware_classes)))
mezzanine_cache_middleware_classes = {import_string(u'mezzanine.core.middleware.UpdateCacheMiddleware'), import_string(u'mezzanine.core.middleware.FetchFromCacheMiddleware')}
return (has_key and settings.CACHES and (not settings.TESTING) and mezzanine_cache_middleware_classes.issubset(middleware_ancestors))
| [
"@",
"lru_cache",
"(",
"maxsize",
"=",
"None",
")",
"def",
"cache_installed",
"(",
")",
":",
"has_key",
"=",
"bool",
"(",
"getattr",
"(",
"settings",
",",
"u'NEVERCACHE_KEY'",
",",
"u''",
")",
")",
"def",
"flatten",
"(",
"seqs",
")",
":",
"return",
"(",
"item",
"for",
"seq",
"in",
"seqs",
"for",
"item",
"in",
"seq",
")",
"middleware_classes",
"=",
"map",
"(",
"import_string",
",",
"get_middleware_setting",
"(",
")",
")",
"middleware_ancestors",
"=",
"set",
"(",
"flatten",
"(",
"map",
"(",
"getmro",
",",
"middleware_classes",
")",
")",
")",
"mezzanine_cache_middleware_classes",
"=",
"{",
"import_string",
"(",
"u'mezzanine.core.middleware.UpdateCacheMiddleware'",
")",
",",
"import_string",
"(",
"u'mezzanine.core.middleware.FetchFromCacheMiddleware'",
")",
"}",
"return",
"(",
"has_key",
"and",
"settings",
".",
"CACHES",
"and",
"(",
"not",
"settings",
".",
"TESTING",
")",
"and",
"mezzanine_cache_middleware_classes",
".",
"issubset",
"(",
"middleware_ancestors",
")",
")"
] | returns true if a cache backend is configured . | train | false |
16,905 | def create_multiple_choice_problem(problem_name):
xml_data = create_multiple_choice_xml()
return XBlockFixtureDesc('problem', problem_name, data=xml_data, metadata={'rerandomize': 'always'})
| [
"def",
"create_multiple_choice_problem",
"(",
"problem_name",
")",
":",
"xml_data",
"=",
"create_multiple_choice_xml",
"(",
")",
"return",
"XBlockFixtureDesc",
"(",
"'problem'",
",",
"problem_name",
",",
"data",
"=",
"xml_data",
",",
"metadata",
"=",
"{",
"'rerandomize'",
":",
"'always'",
"}",
")"
] | return the multiple choice problem descriptor . | train | false |
16,907 | def sh_string(s):
if ('\x00' in s):
log.error('sh_string(): Cannot create a null-byte')
chars = set(s)
very_good = set(((string.ascii_letters + string.digits) + '_+.,/'))
if (chars <= very_good):
return s
if (not (chars & set(ESCAPED))):
return ("'%s'" % s)
quoted_string = ''
quoted = False
for char in s:
if (char not in ESCAPED):
if (not quoted):
quoted_string += SINGLE_QUOTE
quoted = True
quoted_string += char
else:
if quoted:
quoted = False
quoted_string += SINGLE_QUOTE
quoted_string += ESCAPED[char]
if quoted:
quoted_string += SINGLE_QUOTE
return quoted_string
| [
"def",
"sh_string",
"(",
"s",
")",
":",
"if",
"(",
"'\\x00'",
"in",
"s",
")",
":",
"log",
".",
"error",
"(",
"'sh_string(): Cannot create a null-byte'",
")",
"chars",
"=",
"set",
"(",
"s",
")",
"very_good",
"=",
"set",
"(",
"(",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"+",
"'_+.,/'",
")",
")",
"if",
"(",
"chars",
"<=",
"very_good",
")",
":",
"return",
"s",
"if",
"(",
"not",
"(",
"chars",
"&",
"set",
"(",
"ESCAPED",
")",
")",
")",
":",
"return",
"(",
"\"'%s'\"",
"%",
"s",
")",
"quoted_string",
"=",
"''",
"quoted",
"=",
"False",
"for",
"char",
"in",
"s",
":",
"if",
"(",
"char",
"not",
"in",
"ESCAPED",
")",
":",
"if",
"(",
"not",
"quoted",
")",
":",
"quoted_string",
"+=",
"SINGLE_QUOTE",
"quoted",
"=",
"True",
"quoted_string",
"+=",
"char",
"else",
":",
"if",
"quoted",
":",
"quoted",
"=",
"False",
"quoted_string",
"+=",
"SINGLE_QUOTE",
"quoted_string",
"+=",
"ESCAPED",
"[",
"char",
"]",
"if",
"quoted",
":",
"quoted_string",
"+=",
"SINGLE_QUOTE",
"return",
"quoted_string"
] | outputs a string in a format that will be understood by /bin/sh . | train | false |
16,908 | def test_calibration_nan_imputer():
(X, y) = make_classification(n_samples=10, n_features=2, n_informative=2, n_redundant=0, random_state=42)
X[(0, 0)] = np.nan
clf = Pipeline([('imputer', Imputer()), ('rf', RandomForestClassifier(n_estimators=1))])
clf_c = CalibratedClassifierCV(clf, cv=2, method='isotonic')
clf_c.fit(X, y)
clf_c.predict(X)
| [
"def",
"test_calibration_nan_imputer",
"(",
")",
":",
"(",
"X",
",",
"y",
")",
"=",
"make_classification",
"(",
"n_samples",
"=",
"10",
",",
"n_features",
"=",
"2",
",",
"n_informative",
"=",
"2",
",",
"n_redundant",
"=",
"0",
",",
"random_state",
"=",
"42",
")",
"X",
"[",
"(",
"0",
",",
"0",
")",
"]",
"=",
"np",
".",
"nan",
"clf",
"=",
"Pipeline",
"(",
"[",
"(",
"'imputer'",
",",
"Imputer",
"(",
")",
")",
",",
"(",
"'rf'",
",",
"RandomForestClassifier",
"(",
"n_estimators",
"=",
"1",
")",
")",
"]",
")",
"clf_c",
"=",
"CalibratedClassifierCV",
"(",
"clf",
",",
"cv",
"=",
"2",
",",
"method",
"=",
"'isotonic'",
")",
"clf_c",
".",
"fit",
"(",
"X",
",",
"y",
")",
"clf_c",
".",
"predict",
"(",
"X",
")"
] | test that calibration can accept nan . | train | false |
16,909 | def get_Http():
global Http
return Http
| [
"def",
"get_Http",
"(",
")",
":",
"global",
"Http",
"return",
"Http"
] | return current transport class . | train | false |
16,911 | def indefinite_article(word):
return 'a'
| [
"def",
"indefinite_article",
"(",
"word",
")",
":",
"return",
"'a'"
] | returns the indefinite article for a given word . | train | false |
16,912 | def _check_for_misordered_fields(entries, expected):
actual = [field for field in entries.keys() if (field in expected)]
expected = [field for field in expected if (field in actual)]
if (actual != expected):
actual_label = ', '.join(actual)
expected_label = ', '.join(expected)
raise ValueError(("The fields in a section of the document are misordered. It should be '%s' but was '%s'" % (actual_label, expected_label)))
| [
"def",
"_check_for_misordered_fields",
"(",
"entries",
",",
"expected",
")",
":",
"actual",
"=",
"[",
"field",
"for",
"field",
"in",
"entries",
".",
"keys",
"(",
")",
"if",
"(",
"field",
"in",
"expected",
")",
"]",
"expected",
"=",
"[",
"field",
"for",
"field",
"in",
"expected",
"if",
"(",
"field",
"in",
"actual",
")",
"]",
"if",
"(",
"actual",
"!=",
"expected",
")",
":",
"actual_label",
"=",
"', '",
".",
"join",
"(",
"actual",
")",
"expected_label",
"=",
"', '",
".",
"join",
"(",
"expected",
")",
"raise",
"ValueError",
"(",
"(",
"\"The fields in a section of the document are misordered. It should be '%s' but was '%s'\"",
"%",
"(",
"actual_label",
",",
"expected_label",
")",
")",
")"
] | to be valid a network status documents fiends need to appear in a specific order . | train | false |
16,913 | @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_volume_attachments(cs, args):
volumes = cs.volumes.get_server_volumes(_find_server(cs, args.server).id)
_translate_volume_attachments_keys(volumes)
utils.print_list(volumes, ['ID', 'DEVICE', 'SERVER ID', 'VOLUME ID'])
| [
"@",
"utils",
".",
"arg",
"(",
"'server'",
",",
"metavar",
"=",
"'<server>'",
",",
"help",
"=",
"_",
"(",
"'Name or ID of server.'",
")",
")",
"def",
"do_volume_attachments",
"(",
"cs",
",",
"args",
")",
":",
"volumes",
"=",
"cs",
".",
"volumes",
".",
"get_server_volumes",
"(",
"_find_server",
"(",
"cs",
",",
"args",
".",
"server",
")",
".",
"id",
")",
"_translate_volume_attachments_keys",
"(",
"volumes",
")",
"utils",
".",
"print_list",
"(",
"volumes",
",",
"[",
"'ID'",
",",
"'DEVICE'",
",",
"'SERVER ID'",
",",
"'VOLUME ID'",
"]",
")"
] | list all the volumes attached to a server . | train | false |
16,914 | def _stc_src_sel(src, stc):
if isinstance(stc, VolSourceEstimate):
vertices = [stc.vertices]
else:
vertices = stc.vertices
if (not (len(src) == len(vertices))):
raise RuntimeError(('Mismatch between number of source spaces (%s) and STC vertices (%s)' % (len(src), len(vertices))))
src_sels = []
offset = 0
for (s, v) in zip(src, vertices):
src_sel = np.intersect1d(s['vertno'], v)
src_sel = np.searchsorted(s['vertno'], src_sel)
src_sels.append((src_sel + offset))
offset += len(s['vertno'])
src_sel = np.concatenate(src_sels)
return src_sel
| [
"def",
"_stc_src_sel",
"(",
"src",
",",
"stc",
")",
":",
"if",
"isinstance",
"(",
"stc",
",",
"VolSourceEstimate",
")",
":",
"vertices",
"=",
"[",
"stc",
".",
"vertices",
"]",
"else",
":",
"vertices",
"=",
"stc",
".",
"vertices",
"if",
"(",
"not",
"(",
"len",
"(",
"src",
")",
"==",
"len",
"(",
"vertices",
")",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"(",
"'Mismatch between number of source spaces (%s) and STC vertices (%s)'",
"%",
"(",
"len",
"(",
"src",
")",
",",
"len",
"(",
"vertices",
")",
")",
")",
")",
"src_sels",
"=",
"[",
"]",
"offset",
"=",
"0",
"for",
"(",
"s",
",",
"v",
")",
"in",
"zip",
"(",
"src",
",",
"vertices",
")",
":",
"src_sel",
"=",
"np",
".",
"intersect1d",
"(",
"s",
"[",
"'vertno'",
"]",
",",
"v",
")",
"src_sel",
"=",
"np",
".",
"searchsorted",
"(",
"s",
"[",
"'vertno'",
"]",
",",
"src_sel",
")",
"src_sels",
".",
"append",
"(",
"(",
"src_sel",
"+",
"offset",
")",
")",
"offset",
"+=",
"len",
"(",
"s",
"[",
"'vertno'",
"]",
")",
"src_sel",
"=",
"np",
".",
"concatenate",
"(",
"src_sels",
")",
"return",
"src_sel"
] | select the vertex indices of a source space using a source estimate . | train | false |
16,915 | def in_exception_handler():
return (sys.exc_info() != (None, None, None))
| [
"def",
"in_exception_handler",
"(",
")",
":",
"return",
"(",
"sys",
".",
"exc_info",
"(",
")",
"!=",
"(",
"None",
",",
"None",
",",
"None",
")",
")"
] | is there an active exception? . | train | false |
16,916 | def fake_get_platform():
if (sys.platform == 'darwin'):
return 'macosx-'
else:
return 'linux-'
| [
"def",
"fake_get_platform",
"(",
")",
":",
"if",
"(",
"sys",
".",
"platform",
"==",
"'darwin'",
")",
":",
"return",
"'macosx-'",
"else",
":",
"return",
"'linux-'"
] | fake distutils . | train | false |
16,917 | @mock_streams('stdout')
def test_puts_with_prefix():
s = 'my output'
h = 'localhost'
with settings(host_string=h):
puts(s)
eq_(sys.stdout.getvalue(), ('[%s] %s' % (h, (s + '\n'))))
| [
"@",
"mock_streams",
"(",
"'stdout'",
")",
"def",
"test_puts_with_prefix",
"(",
")",
":",
"s",
"=",
"'my output'",
"h",
"=",
"'localhost'",
"with",
"settings",
"(",
"host_string",
"=",
"h",
")",
":",
"puts",
"(",
"s",
")",
"eq_",
"(",
"sys",
".",
"stdout",
".",
"getvalue",
"(",
")",
",",
"(",
"'[%s] %s'",
"%",
"(",
"h",
",",
"(",
"s",
"+",
"'\\n'",
")",
")",
")",
")"
] | puts() should prefix output with env . | train | false |
16,918 | @receiver(post_delete, sender=Project)
@receiver(post_delete, sender=SubProject)
def delete_object_dir(sender, instance, **kwargs):
if (hasattr(instance, 'is_repo_link') and instance.is_repo_link):
return
project_path = instance.get_path()
if os.path.exists(project_path):
shutil.rmtree(project_path)
| [
"@",
"receiver",
"(",
"post_delete",
",",
"sender",
"=",
"Project",
")",
"@",
"receiver",
"(",
"post_delete",
",",
"sender",
"=",
"SubProject",
")",
"def",
"delete_object_dir",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"hasattr",
"(",
"instance",
",",
"'is_repo_link'",
")",
"and",
"instance",
".",
"is_repo_link",
")",
":",
"return",
"project_path",
"=",
"instance",
".",
"get_path",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"project_path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"project_path",
")"
] | handler to delete project directory on project deletion . | train | false |
16,919 | def complete_signin(request, redirect_field_name=REDIRECT_FIELD_NAME, openid_form=OpenidSigninForm, auth_form=AuthenticationForm, on_success=signin_success, on_failure=signin_failure, extra_context=None):
return complete(request, on_success, on_failure, (get_url_host(request) + reverse('user_complete_signin')), redirect_field_name=redirect_field_name, openid_form=openid_form, auth_form=auth_form, extra_context=extra_context)
| [
"def",
"complete_signin",
"(",
"request",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
",",
"openid_form",
"=",
"OpenidSigninForm",
",",
"auth_form",
"=",
"AuthenticationForm",
",",
"on_success",
"=",
"signin_success",
",",
"on_failure",
"=",
"signin_failure",
",",
"extra_context",
"=",
"None",
")",
":",
"return",
"complete",
"(",
"request",
",",
"on_success",
",",
"on_failure",
",",
"(",
"get_url_host",
"(",
"request",
")",
"+",
"reverse",
"(",
"'user_complete_signin'",
")",
")",
",",
"redirect_field_name",
"=",
"redirect_field_name",
",",
"openid_form",
"=",
"openid_form",
",",
"auth_form",
"=",
"auth_form",
",",
"extra_context",
"=",
"extra_context",
")"
] | in case of complete signin with openid :attr request: request object :attr openid_form: form use for openid signin . | train | false |
16,921 | def set_other_config_pci(session, vm_ref, params):
other_config = session.call_xenapi('VM.get_other_config', vm_ref)
other_config['pci'] = params
session.call_xenapi('VM.set_other_config', vm_ref, other_config)
| [
"def",
"set_other_config_pci",
"(",
"session",
",",
"vm_ref",
",",
"params",
")",
":",
"other_config",
"=",
"session",
".",
"call_xenapi",
"(",
"'VM.get_other_config'",
",",
"vm_ref",
")",
"other_config",
"[",
"'pci'",
"]",
"=",
"params",
"session",
".",
"call_xenapi",
"(",
"'VM.set_other_config'",
",",
"vm_ref",
",",
"other_config",
")"
] | set the pci key of other-config parameter to params . | train | false |
16,922 | def _prefix_only_url_replace_regex(pattern):
return re.compile(u'\n (?x) # flags=re.VERBOSE\n (?P<quote>\\\\?[\'"]) # the opening quotes\n {}\n (?P=quote) # the first matching closing quote\n '.format(pattern))
| [
"def",
"_prefix_only_url_replace_regex",
"(",
"pattern",
")",
":",
"return",
"re",
".",
"compile",
"(",
"u'\\n (?x) # flags=re.VERBOSE\\n (?P<quote>\\\\\\\\?[\\'\"]) # the opening quotes\\n {}\\n (?P=quote) # the first matching closing quote\\n '",
".",
"format",
"(",
"pattern",
")",
")"
] | match urls in quotes pulling out the fields from pattern . | train | false |
16,923 | def is_inverse_pair(node_op, prev_op, inv_pair):
node_is_op0 = isinstance(node_op, inv_pair[0])
node_is_op1 = isinstance(node_op, inv_pair[1])
prev_is_op0 = isinstance(prev_op, inv_pair[0])
prev_is_op1 = isinstance(prev_op, inv_pair[1])
return ((node_is_op0 and prev_is_op1) or (node_is_op1 and prev_is_op0))
| [
"def",
"is_inverse_pair",
"(",
"node_op",
",",
"prev_op",
",",
"inv_pair",
")",
":",
"node_is_op0",
"=",
"isinstance",
"(",
"node_op",
",",
"inv_pair",
"[",
"0",
"]",
")",
"node_is_op1",
"=",
"isinstance",
"(",
"node_op",
",",
"inv_pair",
"[",
"1",
"]",
")",
"prev_is_op0",
"=",
"isinstance",
"(",
"prev_op",
",",
"inv_pair",
"[",
"0",
"]",
")",
"prev_is_op1",
"=",
"isinstance",
"(",
"prev_op",
",",
"inv_pair",
"[",
"1",
"]",
")",
"return",
"(",
"(",
"node_is_op0",
"and",
"prev_is_op1",
")",
"or",
"(",
"node_is_op1",
"and",
"prev_is_op0",
")",
")"
] | given two consecutive operations . | train | false |
16,924 | def requires_network(test):
def _is_unreachable_err(err):
return (getattr(err, 'errno', None) in (errno.ENETUNREACH, errno.EHOSTUNREACH))
def _has_route():
try:
sock = socket.create_connection((TARPIT_HOST, 80), 0.0001)
sock.close()
return True
except socket.timeout:
return True
except socket.error as e:
if _is_unreachable_err(e):
return False
else:
raise
@functools.wraps(test)
def wrapper(*args, **kwargs):
global _requires_network_has_route
if (_requires_network_has_route is None):
_requires_network_has_route = _has_route()
if _requires_network_has_route:
return test(*args, **kwargs)
else:
msg = "Can't run {name} because the network is unreachable".format(name=test.__name__)
raise SkipTest(msg)
return wrapper
| [
"def",
"requires_network",
"(",
"test",
")",
":",
"def",
"_is_unreachable_err",
"(",
"err",
")",
":",
"return",
"(",
"getattr",
"(",
"err",
",",
"'errno'",
",",
"None",
")",
"in",
"(",
"errno",
".",
"ENETUNREACH",
",",
"errno",
".",
"EHOSTUNREACH",
")",
")",
"def",
"_has_route",
"(",
")",
":",
"try",
":",
"sock",
"=",
"socket",
".",
"create_connection",
"(",
"(",
"TARPIT_HOST",
",",
"80",
")",
",",
"0.0001",
")",
"sock",
".",
"close",
"(",
")",
"return",
"True",
"except",
"socket",
".",
"timeout",
":",
"return",
"True",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"if",
"_is_unreachable_err",
"(",
"e",
")",
":",
"return",
"False",
"else",
":",
"raise",
"@",
"functools",
".",
"wraps",
"(",
"test",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"global",
"_requires_network_has_route",
"if",
"(",
"_requires_network_has_route",
"is",
"None",
")",
":",
"_requires_network_has_route",
"=",
"_has_route",
"(",
")",
"if",
"_requires_network_has_route",
":",
"return",
"test",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"else",
":",
"msg",
"=",
"\"Can't run {name} because the network is unreachable\"",
".",
"format",
"(",
"name",
"=",
"test",
".",
"__name__",
")",
"raise",
"SkipTest",
"(",
"msg",
")",
"return",
"wrapper"
] | helps you skip tests that require the network . | train | false |
16,925 | def HandleRequest(unused_environ, handler_name, unused_url, post_data, unused_error, application_root, python_lib, import_hook=None):
body = cStringIO.StringIO()
module_name = _FileToModuleName(handler_name)
(parent_module, _, submodule_name) = module_name.rpartition('.')
parent_module = _GetModuleOrNone(parent_module)
main = None
if (module_name in sys.modules):
module = sys.modules[module_name]
main = _GetValidMain(module)
if (not main):
module = imp.new_module('__main__')
if (import_hook is not None):
module.__loader__ = import_hook
saved_streams = (sys.stdin, sys.stdout)
try:
sys.modules['__main__'] = module
module.__dict__['__name__'] = '__main__'
sys.stdin = post_data
sys.stdout = body
if main:
os.environ['PATH_TRANSLATED'] = module.__file__
main()
else:
filename = _AbsolutePath(handler_name, application_root, python_lib)
if filename.endswith((os.sep + '__init__.py')):
module.__path__ = [os.path.dirname(filename)]
if (import_hook is None):
(code, filename) = _LoadModuleCode(filename)
else:
code = import_hook.get_code(module_name)
if (not code):
return {'error': 2}
os.environ['PATH_TRANSLATED'] = filename
module.__file__ = filename
try:
sys.modules[module_name] = module
eval(code, module.__dict__)
except:
del sys.modules[module_name]
if (parent_module and (submodule_name in parent_module.__dict__)):
del parent_module.__dict__[submodule_name]
raise
else:
if parent_module:
parent_module.__dict__[submodule_name] = module
return _ParseResponse(body)
except:
exception = sys.exc_info()
message = ''.join(traceback.format_exception(exception[0], exception[1], exception[2].tb_next))
logging.error(message)
return {'error': 1}
finally:
(sys.stdin, sys.stdout) = saved_streams
module.__name__ = module_name
if ('__main__' in sys.modules):
del sys.modules['__main__']
| [
"def",
"HandleRequest",
"(",
"unused_environ",
",",
"handler_name",
",",
"unused_url",
",",
"post_data",
",",
"unused_error",
",",
"application_root",
",",
"python_lib",
",",
"import_hook",
"=",
"None",
")",
":",
"body",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"module_name",
"=",
"_FileToModuleName",
"(",
"handler_name",
")",
"(",
"parent_module",
",",
"_",
",",
"submodule_name",
")",
"=",
"module_name",
".",
"rpartition",
"(",
"'.'",
")",
"parent_module",
"=",
"_GetModuleOrNone",
"(",
"parent_module",
")",
"main",
"=",
"None",
"if",
"(",
"module_name",
"in",
"sys",
".",
"modules",
")",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"main",
"=",
"_GetValidMain",
"(",
"module",
")",
"if",
"(",
"not",
"main",
")",
":",
"module",
"=",
"imp",
".",
"new_module",
"(",
"'__main__'",
")",
"if",
"(",
"import_hook",
"is",
"not",
"None",
")",
":",
"module",
".",
"__loader__",
"=",
"import_hook",
"saved_streams",
"=",
"(",
"sys",
".",
"stdin",
",",
"sys",
".",
"stdout",
")",
"try",
":",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"=",
"module",
"module",
".",
"__dict__",
"[",
"'__name__'",
"]",
"=",
"'__main__'",
"sys",
".",
"stdin",
"=",
"post_data",
"sys",
".",
"stdout",
"=",
"body",
"if",
"main",
":",
"os",
".",
"environ",
"[",
"'PATH_TRANSLATED'",
"]",
"=",
"module",
".",
"__file__",
"main",
"(",
")",
"else",
":",
"filename",
"=",
"_AbsolutePath",
"(",
"handler_name",
",",
"application_root",
",",
"python_lib",
")",
"if",
"filename",
".",
"endswith",
"(",
"(",
"os",
".",
"sep",
"+",
"'__init__.py'",
")",
")",
":",
"module",
".",
"__path__",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"]",
"if",
"(",
"import_hook",
"is",
"None",
")",
":",
"(",
"code",
",",
"filename",
")",
"=",
"_LoadModuleCode",
"(",
"filename",
")",
"else",
":",
"code",
"=",
"import_hook",
".",
"get_code",
"(",
"module_name",
")",
"if",
"(",
"not",
"code",
")",
":",
"return",
"{",
"'error'",
":",
"2",
"}",
"os",
".",
"environ",
"[",
"'PATH_TRANSLATED'",
"]",
"=",
"filename",
"module",
".",
"__file__",
"=",
"filename",
"try",
":",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"=",
"module",
"eval",
"(",
"code",
",",
"module",
".",
"__dict__",
")",
"except",
":",
"del",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"if",
"(",
"parent_module",
"and",
"(",
"submodule_name",
"in",
"parent_module",
".",
"__dict__",
")",
")",
":",
"del",
"parent_module",
".",
"__dict__",
"[",
"submodule_name",
"]",
"raise",
"else",
":",
"if",
"parent_module",
":",
"parent_module",
".",
"__dict__",
"[",
"submodule_name",
"]",
"=",
"module",
"return",
"_ParseResponse",
"(",
"body",
")",
"except",
":",
"exception",
"=",
"sys",
".",
"exc_info",
"(",
")",
"message",
"=",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"exception",
"[",
"0",
"]",
",",
"exception",
"[",
"1",
"]",
",",
"exception",
"[",
"2",
"]",
".",
"tb_next",
")",
")",
"logging",
".",
"error",
"(",
"message",
")",
"return",
"{",
"'error'",
":",
"1",
"}",
"finally",
":",
"(",
"sys",
".",
"stdin",
",",
"sys",
".",
"stdout",
")",
"=",
"saved_streams",
"module",
".",
"__name__",
"=",
"module_name",
"if",
"(",
"'__main__'",
"in",
"sys",
".",
"modules",
")",
":",
"del",
"sys",
".",
"modules",
"[",
"'__main__'",
"]"
] | handle a single wsgi request . | train | false |
16,926 | def nsmallest(arr, n, keep='first'):
if (keep == 'last'):
arr = arr[::(-1)]
narr = len(arr)
n = min(n, narr)
sdtype = str(arr.dtype)
arr = arr.view(_dtype_map.get(sdtype, sdtype))
kth_val = algos.kth_smallest(arr.copy(), (n - 1))
return _finalize_nsmallest(arr, kth_val, n, keep, narr)
| [
"def",
"nsmallest",
"(",
"arr",
",",
"n",
",",
"keep",
"=",
"'first'",
")",
":",
"if",
"(",
"keep",
"==",
"'last'",
")",
":",
"arr",
"=",
"arr",
"[",
":",
":",
"(",
"-",
"1",
")",
"]",
"narr",
"=",
"len",
"(",
"arr",
")",
"n",
"=",
"min",
"(",
"n",
",",
"narr",
")",
"sdtype",
"=",
"str",
"(",
"arr",
".",
"dtype",
")",
"arr",
"=",
"arr",
".",
"view",
"(",
"_dtype_map",
".",
"get",
"(",
"sdtype",
",",
"sdtype",
")",
")",
"kth_val",
"=",
"algos",
".",
"kth_smallest",
"(",
"arr",
".",
"copy",
"(",
")",
",",
"(",
"n",
"-",
"1",
")",
")",
"return",
"_finalize_nsmallest",
"(",
"arr",
",",
"kth_val",
",",
"n",
",",
"keep",
",",
"narr",
")"
] | find the n smallest elements in a dataset . | train | false |
16,927 | def instance_group_create(context, values, policies=None, members=None):
return IMPL.instance_group_create(context, values, policies, members)
| [
"def",
"instance_group_create",
"(",
"context",
",",
"values",
",",
"policies",
"=",
"None",
",",
"members",
"=",
"None",
")",
":",
"return",
"IMPL",
".",
"instance_group_create",
"(",
"context",
",",
"values",
",",
"policies",
",",
"members",
")"
] | create a new group . | train | false |
16,928 | def _onPygletMousePress(x, y, button, modifiers, emulated=False):
global mouseButtons, mouseClick, mouseTimes
now = psychopy.clock.getTime()
if emulated:
label = 'Emulated'
else:
label = ''
if (button & LEFT):
mouseButtons[0] = 1
mouseTimes[0] = (now - mouseClick[0].getLastResetTime())
label += ' Left'
if (button & MIDDLE):
mouseButtons[1] = 1
mouseTimes[1] = (now - mouseClick[1].getLastResetTime())
label += ' Middle'
if (button & RIGHT):
mouseButtons[2] = 1
mouseTimes[2] = (now - mouseClick[2].getLastResetTime())
label += ' Right'
logging.data(('Mouse: %s button down, pos=(%i,%i)' % (label.strip(), x, y)))
| [
"def",
"_onPygletMousePress",
"(",
"x",
",",
"y",
",",
"button",
",",
"modifiers",
",",
"emulated",
"=",
"False",
")",
":",
"global",
"mouseButtons",
",",
"mouseClick",
",",
"mouseTimes",
"now",
"=",
"psychopy",
".",
"clock",
".",
"getTime",
"(",
")",
"if",
"emulated",
":",
"label",
"=",
"'Emulated'",
"else",
":",
"label",
"=",
"''",
"if",
"(",
"button",
"&",
"LEFT",
")",
":",
"mouseButtons",
"[",
"0",
"]",
"=",
"1",
"mouseTimes",
"[",
"0",
"]",
"=",
"(",
"now",
"-",
"mouseClick",
"[",
"0",
"]",
".",
"getLastResetTime",
"(",
")",
")",
"label",
"+=",
"' Left'",
"if",
"(",
"button",
"&",
"MIDDLE",
")",
":",
"mouseButtons",
"[",
"1",
"]",
"=",
"1",
"mouseTimes",
"[",
"1",
"]",
"=",
"(",
"now",
"-",
"mouseClick",
"[",
"1",
"]",
".",
"getLastResetTime",
"(",
")",
")",
"label",
"+=",
"' Middle'",
"if",
"(",
"button",
"&",
"RIGHT",
")",
":",
"mouseButtons",
"[",
"2",
"]",
"=",
"1",
"mouseTimes",
"[",
"2",
"]",
"=",
"(",
"now",
"-",
"mouseClick",
"[",
"2",
"]",
".",
"getLastResetTime",
"(",
")",
")",
"label",
"+=",
"' Right'",
"logging",
".",
"data",
"(",
"(",
"'Mouse: %s button down, pos=(%i,%i)'",
"%",
"(",
"label",
".",
"strip",
"(",
")",
",",
"x",
",",
"y",
")",
")",
")"
] | button left=1 . | train | false |
16,929 | def Comma():
return Leaf(token.COMMA, u',')
| [
"def",
"Comma",
"(",
")",
":",
"return",
"Leaf",
"(",
"token",
".",
"COMMA",
",",
"u','",
")"
] | a comma leaf . | train | false |
16,932 | @requires_segment_info
def tab_modified_indicator(pl, segment_info, text=u'+'):
for buf_segment_info in list_tabpage_buffers_segment_info(segment_info):
if int(vim_getbufoption(buf_segment_info, u'modified')):
return [{u'contents': text, u'highlight_groups': [u'tab_modified_indicator', u'modified_indicator']}]
return None
| [
"@",
"requires_segment_info",
"def",
"tab_modified_indicator",
"(",
"pl",
",",
"segment_info",
",",
"text",
"=",
"u'+'",
")",
":",
"for",
"buf_segment_info",
"in",
"list_tabpage_buffers_segment_info",
"(",
"segment_info",
")",
":",
"if",
"int",
"(",
"vim_getbufoption",
"(",
"buf_segment_info",
",",
"u'modified'",
")",
")",
":",
"return",
"[",
"{",
"u'contents'",
":",
"text",
",",
"u'highlight_groups'",
":",
"[",
"u'tab_modified_indicator'",
",",
"u'modified_indicator'",
"]",
"}",
"]",
"return",
"None"
] | return a file modified indicator for tabpages . | train | false |
16,933 | def CDLHIGHWAVE(barDs, count):
return call_talib_with_ohlc(barDs, count, talib.CDLHIGHWAVE)
| [
"def",
"CDLHIGHWAVE",
"(",
"barDs",
",",
"count",
")",
":",
"return",
"call_talib_with_ohlc",
"(",
"barDs",
",",
"count",
",",
"talib",
".",
"CDLHIGHWAVE",
")"
] | high-wave candle . | train | false |
16,936 | def test_shared_cudandarray():
a = cuda.shared_constructor(cuda.CudaNdarray.zeros((2, 3)))
assert isinstance(a.type, tcn.CudaNdarrayType)
| [
"def",
"test_shared_cudandarray",
"(",
")",
":",
"a",
"=",
"cuda",
".",
"shared_constructor",
"(",
"cuda",
".",
"CudaNdarray",
".",
"zeros",
"(",
"(",
"2",
",",
"3",
")",
")",
")",
"assert",
"isinstance",
"(",
"a",
".",
"type",
",",
"tcn",
".",
"CudaNdarrayType",
")"
] | test that we can create a cudandarraysharedvariable from a cudandarray . | train | false |
16,937 | def lock_held():
return False
| [
"def",
"lock_held",
"(",
")",
":",
"return",
"False"
] | return false since threading is not supported . | train | false |
16,939 | def OutDedent(format='', *args):
if format:
VaOutput(format, args)
DedentLevel()
| [
"def",
"OutDedent",
"(",
"format",
"=",
"''",
",",
"*",
"args",
")",
":",
"if",
"format",
":",
"VaOutput",
"(",
"format",
",",
"args",
")",
"DedentLevel",
"(",
")"
] | combine output() followed by dedentlevel() . | train | false |
16,941 | def parse_multipart_headers(iterable):
result = []
for line in iterable:
line = to_native(line)
(line, line_terminated) = _line_parse(line)
if (not line_terminated):
raise ValueError('unexpected end of line in multipart header')
if (not line):
break
elif ((line[0] in ' DCTB ') and result):
(key, value) = result[(-1)]
result[(-1)] = (key, ((value + '\n ') + line[1:]))
else:
parts = line.split(':', 1)
if (len(parts) == 2):
result.append((parts[0].strip(), parts[1].strip()))
return Headers(result)
| [
"def",
"parse_multipart_headers",
"(",
"iterable",
")",
":",
"result",
"=",
"[",
"]",
"for",
"line",
"in",
"iterable",
":",
"line",
"=",
"to_native",
"(",
"line",
")",
"(",
"line",
",",
"line_terminated",
")",
"=",
"_line_parse",
"(",
"line",
")",
"if",
"(",
"not",
"line_terminated",
")",
":",
"raise",
"ValueError",
"(",
"'unexpected end of line in multipart header'",
")",
"if",
"(",
"not",
"line",
")",
":",
"break",
"elif",
"(",
"(",
"line",
"[",
"0",
"]",
"in",
"' DCTB '",
")",
"and",
"result",
")",
":",
"(",
"key",
",",
"value",
")",
"=",
"result",
"[",
"(",
"-",
"1",
")",
"]",
"result",
"[",
"(",
"-",
"1",
")",
"]",
"=",
"(",
"key",
",",
"(",
"(",
"value",
"+",
"'\\n '",
")",
"+",
"line",
"[",
"1",
":",
"]",
")",
")",
"else",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"(",
"len",
"(",
"parts",
")",
"==",
"2",
")",
":",
"result",
".",
"append",
"(",
"(",
"parts",
"[",
"0",
"]",
".",
"strip",
"(",
")",
",",
"parts",
"[",
"1",
"]",
".",
"strip",
"(",
")",
")",
")",
"return",
"Headers",
"(",
"result",
")"
] | parses multipart headers from an iterable that yields lines . | train | true |
16,942 | def mkFilter(parts):
if (parts is None):
parts = [BasicServiceEndpoint]
try:
parts = list(parts)
except TypeError:
return mkCompoundFilter([parts])
else:
return mkCompoundFilter(parts)
| [
"def",
"mkFilter",
"(",
"parts",
")",
":",
"if",
"(",
"parts",
"is",
"None",
")",
":",
"parts",
"=",
"[",
"BasicServiceEndpoint",
"]",
"try",
":",
"parts",
"=",
"list",
"(",
"parts",
")",
"except",
"TypeError",
":",
"return",
"mkCompoundFilter",
"(",
"[",
"parts",
"]",
")",
"else",
":",
"return",
"mkCompoundFilter",
"(",
"parts",
")"
] | convert a filter-convertable thing into a filter . | train | true |
16,943 | def _compute_n_patches(i_h, i_w, p_h, p_w, max_patches=None):
n_h = ((i_h - p_h) + 1)
n_w = ((i_w - p_w) + 1)
all_patches = (n_h * n_w)
if max_patches:
if (isinstance(max_patches, numbers.Integral) and (max_patches < all_patches)):
return max_patches
elif (isinstance(max_patches, numbers.Real) and (0 < max_patches < 1)):
return int((max_patches * all_patches))
else:
raise ValueError(('Invalid value for max_patches: %r' % max_patches))
else:
return all_patches
| [
"def",
"_compute_n_patches",
"(",
"i_h",
",",
"i_w",
",",
"p_h",
",",
"p_w",
",",
"max_patches",
"=",
"None",
")",
":",
"n_h",
"=",
"(",
"(",
"i_h",
"-",
"p_h",
")",
"+",
"1",
")",
"n_w",
"=",
"(",
"(",
"i_w",
"-",
"p_w",
")",
"+",
"1",
")",
"all_patches",
"=",
"(",
"n_h",
"*",
"n_w",
")",
"if",
"max_patches",
":",
"if",
"(",
"isinstance",
"(",
"max_patches",
",",
"numbers",
".",
"Integral",
")",
"and",
"(",
"max_patches",
"<",
"all_patches",
")",
")",
":",
"return",
"max_patches",
"elif",
"(",
"isinstance",
"(",
"max_patches",
",",
"numbers",
".",
"Real",
")",
"and",
"(",
"0",
"<",
"max_patches",
"<",
"1",
")",
")",
":",
"return",
"int",
"(",
"(",
"max_patches",
"*",
"all_patches",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"'Invalid value for max_patches: %r'",
"%",
"max_patches",
")",
")",
"else",
":",
"return",
"all_patches"
] | compute the number of patches that will be extracted in an image . | train | false |
16,945 | def get_stay_open():
return stay_open
| [
"def",
"get_stay_open",
"(",
")",
":",
"return",
"stay_open"
] | get stay_open variable . | train | false |
16,946 | def usage_key_with_run(usage_key_string):
usage_key = UsageKey.from_string(usage_key_string)
usage_key = usage_key.replace(course_key=modulestore().fill_in_run(usage_key.course_key))
return usage_key
| [
"def",
"usage_key_with_run",
"(",
"usage_key_string",
")",
":",
"usage_key",
"=",
"UsageKey",
".",
"from_string",
"(",
"usage_key_string",
")",
"usage_key",
"=",
"usage_key",
".",
"replace",
"(",
"course_key",
"=",
"modulestore",
"(",
")",
".",
"fill_in_run",
"(",
"usage_key",
".",
"course_key",
")",
")",
"return",
"usage_key"
] | converts usage_key_string to a usagekey . | train | false |
16,947 | @builtin(u'Capitalize text', capitalize, apply_func_to_match_groups)
def replace_capitalize(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
return apply_func_to_match_groups(match, capitalize)
| [
"@",
"builtin",
"(",
"u'Capitalize text'",
",",
"capitalize",
",",
"apply_func_to_match_groups",
")",
"def",
"replace_capitalize",
"(",
"match",
",",
"number",
",",
"file_name",
",",
"metadata",
",",
"dictionaries",
",",
"data",
",",
"functions",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"apply_func_to_match_groups",
"(",
"match",
",",
"capitalize",
")"
] | capitalize matched text . | train | false |
16,948 | def unsqueeze(data, axis, oldshape):
newshape = list(oldshape)
newshape[axis] = 1
return data.reshape(newshape)
| [
"def",
"unsqueeze",
"(",
"data",
",",
"axis",
",",
"oldshape",
")",
":",
"newshape",
"=",
"list",
"(",
"oldshape",
")",
"newshape",
"[",
"axis",
"]",
"=",
"1",
"return",
"data",
".",
"reshape",
"(",
"newshape",
")"
] | unsqueeze a collapsed array . | train | false |
16,949 | def extend_environ(**kwargs):
env = os.environ.copy()
env.update(kwargs)
return env
| [
"def",
"extend_environ",
"(",
"**",
"kwargs",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"kwargs",
")",
"return",
"env"
] | return a copy of os . | train | false |
16,951 | def raw_highlight(classified_text):
result = []
for (kind, text) in classified_text:
result.append(('%15s: %r\n' % ((kind or 'plain'), text)))
return ''.join(result)
| [
"def",
"raw_highlight",
"(",
"classified_text",
")",
":",
"result",
"=",
"[",
"]",
"for",
"(",
"kind",
",",
"text",
")",
"in",
"classified_text",
":",
"result",
".",
"append",
"(",
"(",
"'%15s: %r\\n'",
"%",
"(",
"(",
"kind",
"or",
"'plain'",
")",
",",
"text",
")",
")",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | straight text display of text classifications . | train | false |
16,952 | def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if (not conn):
return None
results = odict.OrderedDict()
users = get_all_users(path_prefix, region, key, keyid, profile)
for user in users:
name = user.user_name
_policies = conn.get_all_user_policies(name, max_items=100)
_policies = _policies.list_user_policies_response.list_user_policies_result.policy_names
policies = {}
for policy_name in _policies:
_policy = conn.get_user_policy(name, policy_name)
_policy = json.loads(_unquote(_policy.get_user_policy_response.get_user_policy_result.policy_document))
policies[policy_name] = _policy
user_sls = []
user_sls.append({'name': name})
user_sls.append({'policies': policies})
user_sls.append({'path': user.path})
results[('manage user ' + name)] = {'boto_iam.user_present': user_sls}
return _safe_dump(results)
| [
"def",
"export_users",
"(",
"path_prefix",
"=",
"'/'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"if",
"(",
"not",
"conn",
")",
":",
"return",
"None",
"results",
"=",
"odict",
".",
"OrderedDict",
"(",
")",
"users",
"=",
"get_all_users",
"(",
"path_prefix",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
"for",
"user",
"in",
"users",
":",
"name",
"=",
"user",
".",
"user_name",
"_policies",
"=",
"conn",
".",
"get_all_user_policies",
"(",
"name",
",",
"max_items",
"=",
"100",
")",
"_policies",
"=",
"_policies",
".",
"list_user_policies_response",
".",
"list_user_policies_result",
".",
"policy_names",
"policies",
"=",
"{",
"}",
"for",
"policy_name",
"in",
"_policies",
":",
"_policy",
"=",
"conn",
".",
"get_user_policy",
"(",
"name",
",",
"policy_name",
")",
"_policy",
"=",
"json",
".",
"loads",
"(",
"_unquote",
"(",
"_policy",
".",
"get_user_policy_response",
".",
"get_user_policy_result",
".",
"policy_document",
")",
")",
"policies",
"[",
"policy_name",
"]",
"=",
"_policy",
"user_sls",
"=",
"[",
"]",
"user_sls",
".",
"append",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"user_sls",
".",
"append",
"(",
"{",
"'policies'",
":",
"policies",
"}",
")",
"user_sls",
".",
"append",
"(",
"{",
"'path'",
":",
"user",
".",
"path",
"}",
")",
"results",
"[",
"(",
"'manage user '",
"+",
"name",
")",
"]",
"=",
"{",
"'boto_iam.user_present'",
":",
"user_sls",
"}",
"return",
"_safe_dump",
"(",
"results",
")"
] | get all iam user details . | train | true |
16,953 | def allFrameObjs():
f = sys._getframe()
objs = []
while (f is not None):
objs.append(f)
objs.append(f.f_code)
f = f.f_back
return objs
| [
"def",
"allFrameObjs",
"(",
")",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
")",
"objs",
"=",
"[",
"]",
"while",
"(",
"f",
"is",
"not",
"None",
")",
":",
"objs",
".",
"append",
"(",
"f",
")",
"objs",
".",
"append",
"(",
"f",
".",
"f_code",
")",
"f",
"=",
"f",
".",
"f_back",
"return",
"objs"
] | return list of frame objects in current stack . | train | false |
16,954 | @testing.requires_testing_data
def test_read_labels_from_annot_annot2labels():
label_fnames = glob.glob((label_dir + '/*.label'))
label_fnames.sort()
labels_mne = [read_label(fname) for fname in label_fnames]
labels = read_labels_from_annot('sample', subjects_dir=subjects_dir)
_assert_labels_equal(labels, labels_mne, ignore_pos=True)
| [
"@",
"testing",
".",
"requires_testing_data",
"def",
"test_read_labels_from_annot_annot2labels",
"(",
")",
":",
"label_fnames",
"=",
"glob",
".",
"glob",
"(",
"(",
"label_dir",
"+",
"'/*.label'",
")",
")",
"label_fnames",
".",
"sort",
"(",
")",
"labels_mne",
"=",
"[",
"read_label",
"(",
"fname",
")",
"for",
"fname",
"in",
"label_fnames",
"]",
"labels",
"=",
"read_labels_from_annot",
"(",
"'sample'",
",",
"subjects_dir",
"=",
"subjects_dir",
")",
"_assert_labels_equal",
"(",
"labels",
",",
"labels_mne",
",",
"ignore_pos",
"=",
"True",
")"
] | test reading labels from parc . | train | false |
16,955 | def _solve_explike_DE(f, x, DE, g, k):
from sympy.solvers import rsolve
for t in Add.make_args(DE):
(coeff, d) = t.as_independent(g)
if coeff.free_symbols:
return
RE = exp_re(DE, g, k)
init = {}
for i in range(len(Add.make_args(RE))):
if i:
f = f.diff(x)
init[g(k).subs(k, i)] = f.limit(x, 0)
sol = rsolve(RE, g(k), init)
if sol:
return ((sol / factorial(k)), S.Zero, S.Zero)
| [
"def",
"_solve_explike_DE",
"(",
"f",
",",
"x",
",",
"DE",
",",
"g",
",",
"k",
")",
":",
"from",
"sympy",
".",
"solvers",
"import",
"rsolve",
"for",
"t",
"in",
"Add",
".",
"make_args",
"(",
"DE",
")",
":",
"(",
"coeff",
",",
"d",
")",
"=",
"t",
".",
"as_independent",
"(",
"g",
")",
"if",
"coeff",
".",
"free_symbols",
":",
"return",
"RE",
"=",
"exp_re",
"(",
"DE",
",",
"g",
",",
"k",
")",
"init",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"Add",
".",
"make_args",
"(",
"RE",
")",
")",
")",
":",
"if",
"i",
":",
"f",
"=",
"f",
".",
"diff",
"(",
"x",
")",
"init",
"[",
"g",
"(",
"k",
")",
".",
"subs",
"(",
"k",
",",
"i",
")",
"]",
"=",
"f",
".",
"limit",
"(",
"x",
",",
"0",
")",
"sol",
"=",
"rsolve",
"(",
"RE",
",",
"g",
"(",
"k",
")",
",",
"init",
")",
"if",
"sol",
":",
"return",
"(",
"(",
"sol",
"/",
"factorial",
"(",
"k",
")",
")",
",",
"S",
".",
"Zero",
",",
"S",
".",
"Zero",
")"
] | solves de with constant coefficients . | train | false |
16,958 | def _recursive_compare(v1, v2):
if isinstance(v1, list):
if (len(v1) != len(v2)):
return False
v1.sort()
v2.sort()
for (x, y) in zip(v1, v2):
if (not _recursive_compare(x, y)):
return False
return True
elif isinstance(v1, dict):
v1 = dict(v1)
v2 = dict(v2)
if (sorted(v1) != sorted(v2)):
return False
for k in v1:
if (not _recursive_compare(v1[k], v2[k])):
return False
return True
else:
return (v1 == v2)
| [
"def",
"_recursive_compare",
"(",
"v1",
",",
"v2",
")",
":",
"if",
"isinstance",
"(",
"v1",
",",
"list",
")",
":",
"if",
"(",
"len",
"(",
"v1",
")",
"!=",
"len",
"(",
"v2",
")",
")",
":",
"return",
"False",
"v1",
".",
"sort",
"(",
")",
"v2",
".",
"sort",
"(",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"zip",
"(",
"v1",
",",
"v2",
")",
":",
"if",
"(",
"not",
"_recursive_compare",
"(",
"x",
",",
"y",
")",
")",
":",
"return",
"False",
"return",
"True",
"elif",
"isinstance",
"(",
"v1",
",",
"dict",
")",
":",
"v1",
"=",
"dict",
"(",
"v1",
")",
"v2",
"=",
"dict",
"(",
"v2",
")",
"if",
"(",
"sorted",
"(",
"v1",
")",
"!=",
"sorted",
"(",
"v2",
")",
")",
":",
"return",
"False",
"for",
"k",
"in",
"v1",
":",
"if",
"(",
"not",
"_recursive_compare",
"(",
"v1",
"[",
"k",
"]",
",",
"v2",
"[",
"k",
"]",
")",
")",
":",
"return",
"False",
"return",
"True",
"else",
":",
"return",
"(",
"v1",
"==",
"v2",
")"
] | return v1 == v2 . | train | true |
16,959 | def _donothing_func(*args, **kwargs):
pass
| [
"def",
"_donothing_func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"pass"
] | perform no good and no bad . | train | false |
16,960 | def test_stochasatic_pool_samples():
batch = 1
channel = 1
pool_shape = (2, 2)
pool_stride = (2, 2)
image_shape = (2, 2)
rng = numpy.random.RandomState(12345)
data = rng.uniform(0, 10, size=(batch, channel, image_shape[0], image_shape[1])).astype('float32')
x = theano.tensor.tensor4()
s_max = stochastic_max_pool_bc01(x, pool_shape, pool_stride, image_shape)
f = theano.function([x], s_max)
samples = []
for i in xrange(300):
samples.append(numpy.asarray(f(data))[(0, 0, 0, 0)])
counts = Counter(samples)
data = data.reshape(numpy.prod(image_shape))
data.sort()
data = data[::(-1)]
for i in range((len(data) - 1)):
assert (counts[data[i]] >= counts[data[(i + 1)]])
| [
"def",
"test_stochasatic_pool_samples",
"(",
")",
":",
"batch",
"=",
"1",
"channel",
"=",
"1",
"pool_shape",
"=",
"(",
"2",
",",
"2",
")",
"pool_stride",
"=",
"(",
"2",
",",
"2",
")",
"image_shape",
"=",
"(",
"2",
",",
"2",
")",
"rng",
"=",
"numpy",
".",
"random",
".",
"RandomState",
"(",
"12345",
")",
"data",
"=",
"rng",
".",
"uniform",
"(",
"0",
",",
"10",
",",
"size",
"=",
"(",
"batch",
",",
"channel",
",",
"image_shape",
"[",
"0",
"]",
",",
"image_shape",
"[",
"1",
"]",
")",
")",
".",
"astype",
"(",
"'float32'",
")",
"x",
"=",
"theano",
".",
"tensor",
".",
"tensor4",
"(",
")",
"s_max",
"=",
"stochastic_max_pool_bc01",
"(",
"x",
",",
"pool_shape",
",",
"pool_stride",
",",
"image_shape",
")",
"f",
"=",
"theano",
".",
"function",
"(",
"[",
"x",
"]",
",",
"s_max",
")",
"samples",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"300",
")",
":",
"samples",
".",
"append",
"(",
"numpy",
".",
"asarray",
"(",
"f",
"(",
"data",
")",
")",
"[",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"]",
")",
"counts",
"=",
"Counter",
"(",
"samples",
")",
"data",
"=",
"data",
".",
"reshape",
"(",
"numpy",
".",
"prod",
"(",
"image_shape",
")",
")",
"data",
".",
"sort",
"(",
")",
"data",
"=",
"data",
"[",
":",
":",
"(",
"-",
"1",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"(",
"len",
"(",
"data",
")",
"-",
"1",
")",
")",
":",
"assert",
"(",
"counts",
"[",
"data",
"[",
"i",
"]",
"]",
">=",
"counts",
"[",
"data",
"[",
"(",
"i",
"+",
"1",
")",
"]",
"]",
")"
] | check if the order of frequency of samples from stochastic max pool are same as the order of input values . | train | false |
16,961 | def test_iht_fit_sample_linear_svm():
est = 'linear-svm'
iht = InstanceHardnessThreshold(est, random_state=RND_SEED)
(X_resampled, y_resampled) = iht.fit_sample(X, Y)
X_gt = np.array([[(-0.3879569), 0.6894251], [(-0.09322739), 1.28177189], [(-0.77740357), 0.74097941], [0.91542919, (-0.65453327)], [(-0.03852113), 0.40910479], [(-0.43877303), 1.07366684], [(-0.18430329), 0.52328473], [(-0.65571327), 0.42412021], [(-0.28305528), 0.30284991], [1.06446472, (-1.09279772)], [0.30543283, (-0.02589502)], [(-0.00717161), 0.00318087]])
y_gt = np.array([0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0])
assert_array_equal(X_resampled, X_gt)
assert_array_equal(y_resampled, y_gt)
| [
"def",
"test_iht_fit_sample_linear_svm",
"(",
")",
":",
"est",
"=",
"'linear-svm'",
"iht",
"=",
"InstanceHardnessThreshold",
"(",
"est",
",",
"random_state",
"=",
"RND_SEED",
")",
"(",
"X_resampled",
",",
"y_resampled",
")",
"=",
"iht",
".",
"fit_sample",
"(",
"X",
",",
"Y",
")",
"X_gt",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"(",
"-",
"0.3879569",
")",
",",
"0.6894251",
"]",
",",
"[",
"(",
"-",
"0.09322739",
")",
",",
"1.28177189",
"]",
",",
"[",
"(",
"-",
"0.77740357",
")",
",",
"0.74097941",
"]",
",",
"[",
"0.91542919",
",",
"(",
"-",
"0.65453327",
")",
"]",
",",
"[",
"(",
"-",
"0.03852113",
")",
",",
"0.40910479",
"]",
",",
"[",
"(",
"-",
"0.43877303",
")",
",",
"1.07366684",
"]",
",",
"[",
"(",
"-",
"0.18430329",
")",
",",
"0.52328473",
"]",
",",
"[",
"(",
"-",
"0.65571327",
")",
",",
"0.42412021",
"]",
",",
"[",
"(",
"-",
"0.28305528",
")",
",",
"0.30284991",
"]",
",",
"[",
"1.06446472",
",",
"(",
"-",
"1.09279772",
")",
"]",
",",
"[",
"0.30543283",
",",
"(",
"-",
"0.02589502",
")",
"]",
",",
"[",
"(",
"-",
"0.00717161",
")",
",",
"0.00318087",
"]",
"]",
")",
"y_gt",
"=",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
",",
"1",
",",
"0",
",",
"1",
",",
"1",
",",
"1",
",",
"0",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
")",
"assert_array_equal",
"(",
"X_resampled",
",",
"X_gt",
")",
"assert_array_equal",
"(",
"y_resampled",
",",
"y_gt",
")"
] | test the fit sample routine with linear svm . | train | false |
16,962 | def list_all_sysfonts():
filepath = []
searchpath = list(set((TTFSearchPath + rl_config.TTFSearchPath)))
for dirname in searchpath:
for filename in glob.glob(os.path.join(os.path.expanduser(dirname), '*.[Tt][Tt][FfCc]')):
filepath.append(filename)
return filepath
| [
"def",
"list_all_sysfonts",
"(",
")",
":",
"filepath",
"=",
"[",
"]",
"searchpath",
"=",
"list",
"(",
"set",
"(",
"(",
"TTFSearchPath",
"+",
"rl_config",
".",
"TTFSearchPath",
")",
")",
")",
"for",
"dirname",
"in",
"searchpath",
":",
"for",
"filename",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"dirname",
")",
",",
"'*.[Tt][Tt][FfCc]'",
")",
")",
":",
"filepath",
".",
"append",
"(",
"filename",
")",
"return",
"filepath"
] | this function returns list of font directories of system . | train | false |
16,963 | def group_patch(context, data_dict):
_check_access('group_patch', context, data_dict)
show_context = {'model': context['model'], 'session': context['session'], 'user': context['user'], 'auth_user_obj': context['auth_user_obj']}
group_dict = _get_action('group_show')(show_context, {'id': _get_or_bust(data_dict, 'id')})
patched = dict(group_dict)
patched.pop('display_name', None)
patched.update(data_dict)
return _update.group_update(context, patched)
| [
"def",
"group_patch",
"(",
"context",
",",
"data_dict",
")",
":",
"_check_access",
"(",
"'group_patch'",
",",
"context",
",",
"data_dict",
")",
"show_context",
"=",
"{",
"'model'",
":",
"context",
"[",
"'model'",
"]",
",",
"'session'",
":",
"context",
"[",
"'session'",
"]",
",",
"'user'",
":",
"context",
"[",
"'user'",
"]",
",",
"'auth_user_obj'",
":",
"context",
"[",
"'auth_user_obj'",
"]",
"}",
"group_dict",
"=",
"_get_action",
"(",
"'group_show'",
")",
"(",
"show_context",
",",
"{",
"'id'",
":",
"_get_or_bust",
"(",
"data_dict",
",",
"'id'",
")",
"}",
")",
"patched",
"=",
"dict",
"(",
"group_dict",
")",
"patched",
".",
"pop",
"(",
"'display_name'",
",",
"None",
")",
"patched",
".",
"update",
"(",
"data_dict",
")",
"return",
"_update",
".",
"group_update",
"(",
"context",
",",
"patched",
")"
] | patch a group . | train | false |
16,964 | def numerical_sort(string_int_list):
as_int_list = []
as_str_list = []
for vlan in string_int_list:
as_int_list.append(int(vlan))
as_int_list.sort()
for vlan in as_int_list:
as_str_list.append(str(vlan))
return as_str_list
| [
"def",
"numerical_sort",
"(",
"string_int_list",
")",
":",
"as_int_list",
"=",
"[",
"]",
"as_str_list",
"=",
"[",
"]",
"for",
"vlan",
"in",
"string_int_list",
":",
"as_int_list",
".",
"append",
"(",
"int",
"(",
"vlan",
")",
")",
"as_int_list",
".",
"sort",
"(",
")",
"for",
"vlan",
"in",
"as_int_list",
":",
"as_str_list",
".",
"append",
"(",
"str",
"(",
"vlan",
")",
")",
"return",
"as_str_list"
] | sorts list of strings/integers that are digits in numerical order . | train | false |
16,966 | def get_oauth_settings():
out = frappe._dict({u'skip_authorization': frappe.db.get_value(u'OAuth Provider Settings', None, u'skip_authorization')})
return out
| [
"def",
"get_oauth_settings",
"(",
")",
":",
"out",
"=",
"frappe",
".",
"_dict",
"(",
"{",
"u'skip_authorization'",
":",
"frappe",
".",
"db",
".",
"get_value",
"(",
"u'OAuth Provider Settings'",
",",
"None",
",",
"u'skip_authorization'",
")",
"}",
")",
"return",
"out"
] | returns oauth settings . | train | false |
16,967 | def get_support_mail():
from sentry.options import get
return (get('system.support-email') or get('system.admin-email') or None)
| [
"def",
"get_support_mail",
"(",
")",
":",
"from",
"sentry",
".",
"options",
"import",
"get",
"return",
"(",
"get",
"(",
"'system.support-email'",
")",
"or",
"get",
"(",
"'system.admin-email'",
")",
"or",
"None",
")"
] | returns the most appropriate support email address . | train | false |
16,969 | def _join_relationships(workflow, parent, child_el):
if ('to' not in child_el.attrib):
raise RuntimeError((_("Node %s has a link that is missing 'to' attribute.") % parent.name))
to = child_el.attrib['to']
try:
child = Node.objects.get(workflow=workflow, name=to)
except Node.DoesNotExist as e:
raise RuntimeError((_('Node %s has not been defined.') % to))
obj = Link.objects.create(name='to', parent=parent, child=child)
obj.save()
| [
"def",
"_join_relationships",
"(",
"workflow",
",",
"parent",
",",
"child_el",
")",
":",
"if",
"(",
"'to'",
"not",
"in",
"child_el",
".",
"attrib",
")",
":",
"raise",
"RuntimeError",
"(",
"(",
"_",
"(",
"\"Node %s has a link that is missing 'to' attribute.\"",
")",
"%",
"parent",
".",
"name",
")",
")",
"to",
"=",
"child_el",
".",
"attrib",
"[",
"'to'",
"]",
"try",
":",
"child",
"=",
"Node",
".",
"objects",
".",
"get",
"(",
"workflow",
"=",
"workflow",
",",
"name",
"=",
"to",
")",
"except",
"Node",
".",
"DoesNotExist",
"as",
"e",
":",
"raise",
"RuntimeError",
"(",
"(",
"_",
"(",
"'Node %s has not been defined.'",
")",
"%",
"to",
")",
")",
"obj",
"=",
"Link",
".",
"objects",
".",
"create",
"(",
"name",
"=",
"'to'",
",",
"parent",
"=",
"parent",
",",
"child",
"=",
"child",
")",
"obj",
".",
"save",
"(",
")"
] | resolves join node links . | train | false |
16,970 | def split_on_arrow(eq):
for arrow in ARROWS:
(left, a, right) = eq.partition(arrow)
if (a != ''):
return (left, a, right)
return (eq, '', '')
| [
"def",
"split_on_arrow",
"(",
"eq",
")",
":",
"for",
"arrow",
"in",
"ARROWS",
":",
"(",
"left",
",",
"a",
",",
"right",
")",
"=",
"eq",
".",
"partition",
"(",
"arrow",
")",
"if",
"(",
"a",
"!=",
"''",
")",
":",
"return",
"(",
"left",
",",
"a",
",",
"right",
")",
"return",
"(",
"eq",
",",
"''",
",",
"''",
")"
] | split a string on an arrow . | train | false |
16,971 | def ricker(points, a):
A = (2 / (np.sqrt((3 * a)) * (np.pi ** 0.25)))
wsq = (a ** 2)
vec = (np.arange(0, points) - ((points - 1.0) / 2))
xsq = (vec ** 2)
mod = (1 - (xsq / wsq))
gauss = np.exp(((- xsq) / (2 * wsq)))
total = ((A * mod) * gauss)
return total
| [
"def",
"ricker",
"(",
"points",
",",
"a",
")",
":",
"A",
"=",
"(",
"2",
"/",
"(",
"np",
".",
"sqrt",
"(",
"(",
"3",
"*",
"a",
")",
")",
"*",
"(",
"np",
".",
"pi",
"**",
"0.25",
")",
")",
")",
"wsq",
"=",
"(",
"a",
"**",
"2",
")",
"vec",
"=",
"(",
"np",
".",
"arange",
"(",
"0",
",",
"points",
")",
"-",
"(",
"(",
"points",
"-",
"1.0",
")",
"/",
"2",
")",
")",
"xsq",
"=",
"(",
"vec",
"**",
"2",
")",
"mod",
"=",
"(",
"1",
"-",
"(",
"xsq",
"/",
"wsq",
")",
")",
"gauss",
"=",
"np",
".",
"exp",
"(",
"(",
"(",
"-",
"xsq",
")",
"/",
"(",
"2",
"*",
"wsq",
")",
")",
")",
"total",
"=",
"(",
"(",
"A",
"*",
"mod",
")",
"*",
"gauss",
")",
"return",
"total"
] | return a ricker wavelet . | train | false |
16,972 | def SAR(barDs, count, acceleration=(-4e+37), maximum=(-4e+37)):
return call_talib_with_hl(barDs, count, talib.SAR, acceleration, maximum)
| [
"def",
"SAR",
"(",
"barDs",
",",
"count",
",",
"acceleration",
"=",
"(",
"-",
"4e+37",
")",
",",
"maximum",
"=",
"(",
"-",
"4e+37",
")",
")",
":",
"return",
"call_talib_with_hl",
"(",
"barDs",
",",
"count",
",",
"talib",
".",
"SAR",
",",
"acceleration",
",",
"maximum",
")"
] | parabolic sar . | train | false |
16,973 | @pytest.fixture(scope='session')
def cli_runner():
runner = CliRunner()
def cli_main(*cli_args):
'Run cookiecutter cli main with the given args.'
return runner.invoke(main, cli_args)
return cli_main
| [
"@",
"pytest",
".",
"fixture",
"(",
"scope",
"=",
"'session'",
")",
"def",
"cli_runner",
"(",
")",
":",
"runner",
"=",
"CliRunner",
"(",
")",
"def",
"cli_main",
"(",
"*",
"cli_args",
")",
":",
"return",
"runner",
".",
"invoke",
"(",
"main",
",",
"cli_args",
")",
"return",
"cli_main"
] | fixture that returns a helper function to run the cookiecutter cli . | train | false |
16,974 | def xticks(*args, **kwargs):
ax = gca()
if (len(args) == 0):
locs = ax.get_xticks()
labels = ax.get_xticklabels()
elif (len(args) == 1):
locs = ax.set_xticks(args[0])
labels = ax.get_xticklabels()
elif (len(args) == 2):
locs = ax.set_xticks(args[0])
labels = ax.set_xticklabels(args[1], **kwargs)
else:
raise TypeError('Illegal number of arguments to xticks')
if len(kwargs):
for l in labels:
l.update(kwargs)
draw_if_interactive()
return (locs, silent_list('Text xticklabel', labels))
| [
"def",
"xticks",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"ax",
"=",
"gca",
"(",
")",
"if",
"(",
"len",
"(",
"args",
")",
"==",
"0",
")",
":",
"locs",
"=",
"ax",
".",
"get_xticks",
"(",
")",
"labels",
"=",
"ax",
".",
"get_xticklabels",
"(",
")",
"elif",
"(",
"len",
"(",
"args",
")",
"==",
"1",
")",
":",
"locs",
"=",
"ax",
".",
"set_xticks",
"(",
"args",
"[",
"0",
"]",
")",
"labels",
"=",
"ax",
".",
"get_xticklabels",
"(",
")",
"elif",
"(",
"len",
"(",
"args",
")",
"==",
"2",
")",
":",
"locs",
"=",
"ax",
".",
"set_xticks",
"(",
"args",
"[",
"0",
"]",
")",
"labels",
"=",
"ax",
".",
"set_xticklabels",
"(",
"args",
"[",
"1",
"]",
",",
"**",
"kwargs",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Illegal number of arguments to xticks'",
")",
"if",
"len",
"(",
"kwargs",
")",
":",
"for",
"l",
"in",
"labels",
":",
"l",
".",
"update",
"(",
"kwargs",
")",
"draw_if_interactive",
"(",
")",
"return",
"(",
"locs",
",",
"silent_list",
"(",
"'Text xticklabel'",
",",
"labels",
")",
")"
] | get or set the *x*-limits of the current tick locations and labels . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.