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
47,061
def get_proxy_win(): if (__grains__['os'] == 'Windows'): return _get_proxy_windows()
[ "def", "get_proxy_win", "(", ")", ":", "if", "(", "__grains__", "[", "'os'", "]", "==", "'Windows'", ")", ":", "return", "_get_proxy_windows", "(", ")" ]
gets all of the proxy settings in one call .
train
false
47,062
def yieldify(rl): def brl(expr): (yield rl(expr)) return brl
[ "def", "yieldify", "(", "rl", ")", ":", "def", "brl", "(", "expr", ")", ":", "(", "yield", "rl", "(", "expr", ")", ")", "return", "brl" ]
turn a rule into a branching rule .
train
false
47,063
@conf.commands.register def srpflood(x, filter=None, iface=None, iface_hint=None, nofilter=None, *args, **kargs): if ((iface is None) and (iface_hint is not None)): iface = conf.route.route(iface_hint)[0] s = conf.L2socket(filter=filter, iface=iface, nofilter=nofilter) r = sndrcvflood(s, x, *args, **kargs) s.close() return r
[ "@", "conf", ".", "commands", ".", "register", "def", "srpflood", "(", "x", ",", "filter", "=", "None", ",", "iface", "=", "None", ",", "iface_hint", "=", "None", ",", "nofilter", "=", "None", ",", "*", "args", ",", "**", "kargs", ")", ":", "if", "(", "(", "iface", "is", "None", ")", "and", "(", "iface_hint", "is", "not", "None", ")", ")", ":", "iface", "=", "conf", ".", "route", ".", "route", "(", "iface_hint", ")", "[", "0", "]", "s", "=", "conf", ".", "L2socket", "(", "filter", "=", "filter", ",", "iface", "=", "iface", ",", "nofilter", "=", "nofilter", ")", "r", "=", "sndrcvflood", "(", "s", ",", "x", ",", "*", "args", ",", "**", "kargs", ")", "s", ".", "close", "(", ")", "return", "r" ]
flood and receive packets at layer 2 prn: function applied to packets received .
train
true
47,065
@require_GET def locale_metrics(request, locale_code): if (locale_code not in settings.SUMO_LANGUAGES): raise Http404 product = _get_product(request) return render(request, 'dashboards/locale_metrics.html', {'current_locale': locale_code, 'product': product, 'products': Product.objects.filter(visible=True)})
[ "@", "require_GET", "def", "locale_metrics", "(", "request", ",", "locale_code", ")", ":", "if", "(", "locale_code", "not", "in", "settings", ".", "SUMO_LANGUAGES", ")", ":", "raise", "Http404", "product", "=", "_get_product", "(", "request", ")", "return", "render", "(", "request", ",", "'dashboards/locale_metrics.html'", ",", "{", "'current_locale'", ":", "locale_code", ",", "'product'", ":", "product", ",", "'products'", ":", "Product", ".", "objects", ".", "filter", "(", "visible", "=", "True", ")", "}", ")" ]
the kb metrics dashboard for a specific locale .
train
false
47,066
@register.simple_tag(takes_context=True) def comment_detail_display_hook(context, comment, render_mode): assert (render_mode in (u'review', u'text-email', u'html-email')) s = u'' for hook in CommentDetailDisplayHook.hooks: try: if (render_mode == u'review'): s += hook.render_review_comment_detail(comment) elif (render_mode in (u'text-email', u'html-email')): s += hook.render_email_comment_detail(comment, (render_mode == u'html-email')) except Exception as e: extension = hook.extension logging.error(u'Error when running CommentDetailDisplayHook with render mode "%s" in extension: %s: %s', render_mode, extension.id, e, exc_info=1) return s
[ "@", "register", ".", "simple_tag", "(", "takes_context", "=", "True", ")", "def", "comment_detail_display_hook", "(", "context", ",", "comment", ",", "render_mode", ")", ":", "assert", "(", "render_mode", "in", "(", "u'review'", ",", "u'text-email'", ",", "u'html-email'", ")", ")", "s", "=", "u''", "for", "hook", "in", "CommentDetailDisplayHook", ".", "hooks", ":", "try", ":", "if", "(", "render_mode", "==", "u'review'", ")", ":", "s", "+=", "hook", ".", "render_review_comment_detail", "(", "comment", ")", "elif", "(", "render_mode", "in", "(", "u'text-email'", ",", "u'html-email'", ")", ")", ":", "s", "+=", "hook", ".", "render_email_comment_detail", "(", "comment", ",", "(", "render_mode", "==", "u'html-email'", ")", ")", "except", "Exception", "as", "e", ":", "extension", "=", "hook", ".", "extension", "logging", ".", "error", "(", "u'Error when running CommentDetailDisplayHook with render mode \"%s\" in extension: %s: %s'", ",", "render_mode", ",", "extension", ".", "id", ",", "e", ",", "exc_info", "=", "1", ")", "return", "s" ]
displays all additional detail from commentdetaildisplayhooks .
train
false
47,068
def topngbytes(name, rows, x, y, **k): import os print name f = StringIO() w = Writer(x, y, **k) w.write(f, rows) if os.environ.get('PYPNG_TEST_TMP'): w = open(name, 'wb') w.write(f.getvalue()) w.close() return f.getvalue()
[ "def", "topngbytes", "(", "name", ",", "rows", ",", "x", ",", "y", ",", "**", "k", ")", ":", "import", "os", "print", "name", "f", "=", "StringIO", "(", ")", "w", "=", "Writer", "(", "x", ",", "y", ",", "**", "k", ")", "w", ".", "write", "(", "f", ",", "rows", ")", "if", "os", ".", "environ", ".", "get", "(", "'PYPNG_TEST_TMP'", ")", ":", "w", "=", "open", "(", "name", ",", "'wb'", ")", "w", ".", "write", "(", "f", ".", "getvalue", "(", ")", ")", "w", ".", "close", "(", ")", "return", "f", ".", "getvalue", "(", ")" ]
convenience function for creating a png file "in memory" as a string .
train
false
47,069
def filter_contents_translations(generator): inspector = GeneratorInspector(generator) current_lang = generator.settings['DEFAULT_LANG'] langs_with_sites = _SITE_DB.keys() removed_contents = _GENERATOR_DB[generator] for translations in inspector.translations_lists(): for translation in translations[:]: if (translation.lang in langs_with_sites): translations.remove(translation) removed_contents.append(translation) hiding_func = inspector.hiding_function() untrans_policy = inspector.untranslated_policy(default='hide') for (contents, other_contents) in inspector.contents_list_pairs(): for content in other_contents: if (content.lang == current_lang): _NATIVE_CONTENT_URL_DB[content.source_path] = content.url for content in contents[:]: if (content.lang == current_lang): _NATIVE_CONTENT_URL_DB[content.source_path] = content.url elif ((content.lang in langs_with_sites) and (untrans_policy != 'keep')): contents.remove(content) if (untrans_policy == 'hide'): other_contents.append(hiding_func(content)) elif (untrans_policy == 'remove'): removed_contents.append(content)
[ "def", "filter_contents_translations", "(", "generator", ")", ":", "inspector", "=", "GeneratorInspector", "(", "generator", ")", "current_lang", "=", "generator", ".", "settings", "[", "'DEFAULT_LANG'", "]", "langs_with_sites", "=", "_SITE_DB", ".", "keys", "(", ")", "removed_contents", "=", "_GENERATOR_DB", "[", "generator", "]", "for", "translations", "in", "inspector", ".", "translations_lists", "(", ")", ":", "for", "translation", "in", "translations", "[", ":", "]", ":", "if", "(", "translation", ".", "lang", "in", "langs_with_sites", ")", ":", "translations", ".", "remove", "(", "translation", ")", "removed_contents", ".", "append", "(", "translation", ")", "hiding_func", "=", "inspector", ".", "hiding_function", "(", ")", "untrans_policy", "=", "inspector", ".", "untranslated_policy", "(", "default", "=", "'hide'", ")", "for", "(", "contents", ",", "other_contents", ")", "in", "inspector", ".", "contents_list_pairs", "(", ")", ":", "for", "content", "in", "other_contents", ":", "if", "(", "content", ".", "lang", "==", "current_lang", ")", ":", "_NATIVE_CONTENT_URL_DB", "[", "content", ".", "source_path", "]", "=", "content", ".", "url", "for", "content", "in", "contents", "[", ":", "]", ":", "if", "(", "content", ".", "lang", "==", "current_lang", ")", ":", "_NATIVE_CONTENT_URL_DB", "[", "content", ".", "source_path", "]", "=", "content", ".", "url", "elif", "(", "(", "content", ".", "lang", "in", "langs_with_sites", ")", "and", "(", "untrans_policy", "!=", "'keep'", ")", ")", ":", "contents", ".", "remove", "(", "content", ")", "if", "(", "untrans_policy", "==", "'hide'", ")", ":", "other_contents", ".", "append", "(", "hiding_func", "(", "content", ")", ")", "elif", "(", "untrans_policy", "==", "'remove'", ")", ":", "removed_contents", ".", "append", "(", "content", ")" ]
filter the content and translations lists of a generator filters out 1) translations which will be generated in a different site 2) content that is not in the language of the currently generated site but in that of a different site .
train
true
47,070
def to_feather(df, path): if (not isinstance(df, DataFrame)): raise ValueError('feather only support IO with DataFrames') feather = _try_import() valid_types = {'string', 'unicode'} if (not isinstance(df.index, Int64Index)): raise ValueError('feather does not serializing {} for the index; you can .reset_index()to make the index into column(s)'.format(type(df.index))) if (not df.index.equals(RangeIndex.from_range(range(len(df))))): raise ValueError('feather does not serializing a non-default index for the index; you can .reset_index()to make the index into column(s)') if (df.index.name is not None): raise ValueError('feather does not serialize index meta-data on a default index') if (df.columns.inferred_type not in valid_types): raise ValueError('feather must have string column names') feather.write_dataframe(df, path)
[ "def", "to_feather", "(", "df", ",", "path", ")", ":", "if", "(", "not", "isinstance", "(", "df", ",", "DataFrame", ")", ")", ":", "raise", "ValueError", "(", "'feather only support IO with DataFrames'", ")", "feather", "=", "_try_import", "(", ")", "valid_types", "=", "{", "'string'", ",", "'unicode'", "}", "if", "(", "not", "isinstance", "(", "df", ".", "index", ",", "Int64Index", ")", ")", ":", "raise", "ValueError", "(", "'feather does not serializing {} for the index; you can .reset_index()to make the index into column(s)'", ".", "format", "(", "type", "(", "df", ".", "index", ")", ")", ")", "if", "(", "not", "df", ".", "index", ".", "equals", "(", "RangeIndex", ".", "from_range", "(", "range", "(", "len", "(", "df", ")", ")", ")", ")", ")", ":", "raise", "ValueError", "(", "'feather does not serializing a non-default index for the index; you can .reset_index()to make the index into column(s)'", ")", "if", "(", "df", ".", "index", ".", "name", "is", "not", "None", ")", ":", "raise", "ValueError", "(", "'feather does not serialize index meta-data on a default index'", ")", "if", "(", "df", ".", "columns", ".", "inferred_type", "not", "in", "valid_types", ")", ":", "raise", "ValueError", "(", "'feather must have string column names'", ")", "feather", ".", "write_dataframe", "(", "df", ",", "path", ")" ]
write a dataframe to the feather-format parameters df : dataframe path : string file path .
train
true
47,071
def areAdminRightsElevated(): pid = GetCurrentProcess() processToken = HANDLE() if (not OpenProcessToken(pid, TOKEN_READ, ctypes.byref(processToken))): raise ctypes.WinError() try: (elevated, elevatedSize) = (DWORD(), DWORD()) if (not GetTokenInformation(processToken, TokenElevation, ctypes.byref(elevated), ctypes.sizeof(elevated), ctypes.byref(elevatedSize))): raise ctypes.WinError() return bool(elevated) finally: CloseHandle(processToken)
[ "def", "areAdminRightsElevated", "(", ")", ":", "pid", "=", "GetCurrentProcess", "(", ")", "processToken", "=", "HANDLE", "(", ")", "if", "(", "not", "OpenProcessToken", "(", "pid", ",", "TOKEN_READ", ",", "ctypes", ".", "byref", "(", "processToken", ")", ")", ")", ":", "raise", "ctypes", ".", "WinError", "(", ")", "try", ":", "(", "elevated", ",", "elevatedSize", ")", "=", "(", "DWORD", "(", ")", ",", "DWORD", "(", ")", ")", "if", "(", "not", "GetTokenInformation", "(", "processToken", ",", "TokenElevation", ",", "ctypes", ".", "byref", "(", "elevated", ")", ",", "ctypes", ".", "sizeof", "(", "elevated", ")", ",", "ctypes", ".", "byref", "(", "elevatedSize", ")", ")", ")", ":", "raise", "ctypes", ".", "WinError", "(", ")", "return", "bool", "(", "elevated", ")", "finally", ":", "CloseHandle", "(", "processToken", ")" ]
tells you whether current script already has administrative rights .
train
false
47,072
def render_form_group(content, css_class=FORM_GROUP_CLASS): return u'<div class="{klass}">{content}</div>'.format(klass=css_class, content=content)
[ "def", "render_form_group", "(", "content", ",", "css_class", "=", "FORM_GROUP_CLASS", ")", ":", "return", "u'<div class=\"{klass}\">{content}</div>'", ".", "format", "(", "klass", "=", "css_class", ",", "content", "=", "content", ")" ]
render a bootstrap form group .
train
false
47,073
def test_gh_issue_3025(): d = np.zeros((60, 320)) d[:, :257] = 1 d[:, 260:] = 1 d[(36, 257)] = 1 d[(35, 258)] = 1 d[(35, 259)] = 1 assert (ndimage.label(d, np.ones((3, 3)))[1] == 1)
[ "def", "test_gh_issue_3025", "(", ")", ":", "d", "=", "np", ".", "zeros", "(", "(", "60", ",", "320", ")", ")", "d", "[", ":", ",", ":", "257", "]", "=", "1", "d", "[", ":", ",", "260", ":", "]", "=", "1", "d", "[", "(", "36", ",", "257", ")", "]", "=", "1", "d", "[", "(", "35", ",", "258", ")", "]", "=", "1", "d", "[", "(", "35", ",", "259", ")", "]", "=", "1", "assert", "(", "ndimage", ".", "label", "(", "d", ",", "np", ".", "ones", "(", "(", "3", ",", "3", ")", ")", ")", "[", "1", "]", "==", "1", ")" ]
github issue #3025 - improper merging of labels .
train
false
47,075
def get_google_drive_folder_location(): gdrive_db_path = 'Library/Application Support/Google/Drive/sync_config.db' yosemite_gdrive_db_path = 'Library/Application Support/Google/Drive/user_default/sync_config.db' yosemite_gdrive_db = os.path.join(os.environ['HOME'], yosemite_gdrive_db_path) if os.path.isfile(yosemite_gdrive_db): gdrive_db_path = yosemite_gdrive_db googledrive_home = None gdrive_db = os.path.join(os.environ['HOME'], gdrive_db_path) if os.path.isfile(gdrive_db): con = sqlite3.connect(gdrive_db) if con: cur = con.cursor() query = "SELECT data_value FROM data WHERE entry_key = 'local_sync_root_path';" cur.execute(query) data = cur.fetchone() googledrive_home = unicode(data[0]) con.close() if (not googledrive_home): error('Unable to find your Google Drive install =(') return googledrive_home
[ "def", "get_google_drive_folder_location", "(", ")", ":", "gdrive_db_path", "=", "'Library/Application Support/Google/Drive/sync_config.db'", "yosemite_gdrive_db_path", "=", "'Library/Application Support/Google/Drive/user_default/sync_config.db'", "yosemite_gdrive_db", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'HOME'", "]", ",", "yosemite_gdrive_db_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "yosemite_gdrive_db", ")", ":", "gdrive_db_path", "=", "yosemite_gdrive_db", "googledrive_home", "=", "None", "gdrive_db", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'HOME'", "]", ",", "gdrive_db_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "gdrive_db", ")", ":", "con", "=", "sqlite3", ".", "connect", "(", "gdrive_db", ")", "if", "con", ":", "cur", "=", "con", ".", "cursor", "(", ")", "query", "=", "\"SELECT data_value FROM data WHERE entry_key = 'local_sync_root_path';\"", "cur", ".", "execute", "(", "query", ")", "data", "=", "cur", ".", "fetchone", "(", ")", "googledrive_home", "=", "unicode", "(", "data", "[", "0", "]", ")", "con", ".", "close", "(", ")", "if", "(", "not", "googledrive_home", ")", ":", "error", "(", "'Unable to find your Google Drive install =('", ")", "return", "googledrive_home" ]
try to locate the google drive folder .
train
true
47,076
def diag(v, k=0): if isinstance(v, cupy.ndarray): if (v.ndim == 1): size = (v.size + abs(k)) ret = cupy.zeros((size, size), dtype=v.dtype) ret.diagonal(k)[:] = v return ret else: return v.diagonal(k) else: return cupy.array(numpy.diag(v, k))
[ "def", "diag", "(", "v", ",", "k", "=", "0", ")", ":", "if", "isinstance", "(", "v", ",", "cupy", ".", "ndarray", ")", ":", "if", "(", "v", ".", "ndim", "==", "1", ")", ":", "size", "=", "(", "v", ".", "size", "+", "abs", "(", "k", ")", ")", "ret", "=", "cupy", ".", "zeros", "(", "(", "size", ",", "size", ")", ",", "dtype", "=", "v", ".", "dtype", ")", "ret", ".", "diagonal", "(", "k", ")", "[", ":", "]", "=", "v", "return", "ret", "else", ":", "return", "v", ".", "diagonal", "(", "k", ")", "else", ":", "return", "cupy", ".", "array", "(", "numpy", ".", "diag", "(", "v", ",", "k", ")", ")" ]
extracts the diagonal from a matrix or makes a vector a diagonal matrix .
train
false
47,077
def unquote_header_value(value, is_filename=False): if (value and (value[0] == value[(-1)] == '"')): value = value[1:(-1)] if ((not is_filename) or (value[:2] != '\\\\')): return value.replace('\\\\', '\\').replace('\\"', '"') return value
[ "def", "unquote_header_value", "(", "value", ",", "is_filename", "=", "False", ")", ":", "if", "(", "value", "and", "(", "value", "[", "0", "]", "==", "value", "[", "(", "-", "1", ")", "]", "==", "'\"'", ")", ")", ":", "value", "=", "value", "[", "1", ":", "(", "-", "1", ")", "]", "if", "(", "(", "not", "is_filename", ")", "or", "(", "value", "[", ":", "2", "]", "!=", "'\\\\\\\\'", ")", ")", ":", "return", "value", ".", "replace", "(", "'\\\\\\\\'", ",", "'\\\\'", ")", ".", "replace", "(", "'\\\\\"'", ",", "'\"'", ")", "return", "value" ]
unquotes a header value .
train
true
47,078
@cronjobs.register def reindex_kb(): index_task.delay(DocumentMappingType, DocumentMappingType.get_indexable())
[ "@", "cronjobs", ".", "register", "def", "reindex_kb", "(", ")", ":", "index_task", ".", "delay", "(", "DocumentMappingType", ",", "DocumentMappingType", ".", "get_indexable", "(", ")", ")" ]
reindex wiki_document .
train
false
47,079
def test_chain(): chain_type = hug.types.Chain(hug.types.text, hug.types.LongerThan(10)) assert (chain_type(12345678901) == '12345678901') with pytest.raises(ValueError): chain_type(1)
[ "def", "test_chain", "(", ")", ":", "chain_type", "=", "hug", ".", "types", ".", "Chain", "(", "hug", ".", "types", ".", "text", ",", "hug", ".", "types", ".", "LongerThan", "(", "10", ")", ")", "assert", "(", "chain_type", "(", "12345678901", ")", "==", "'12345678901'", ")", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "chain_type", "(", "1", ")" ]
test to ensure that chaining together multiple types works as expected .
train
false
47,080
def compare_dataset_state(discovered_dataset, desired_dataset): if (discovered_dataset is None): return ((desired_dataset is None) or (desired_dataset.state == DatasetStates.DELETED)) if (desired_dataset is None): return (discovered_dataset.state == DatasetStates.NON_MANIFEST) if ((desired_dataset.state == DatasetStates.DELETED) and (discovered_dataset.state == DatasetStates.REGISTERED)): return True if (discovered_dataset.state != desired_dataset.state): return False if (discovered_dataset.state == DatasetStates.MOUNTED): return (discovered_dataset.mount_point == desired_dataset.mount_point) elif (discovered_dataset.state == DatasetStates.NON_MANIFEST): return True elif (discovered_dataset.state == DatasetStates.DELETED): return True else: raise ValueError('Impossible dataset states: {} {}'.format(discovered_dataset, desired_dataset))
[ "def", "compare_dataset_state", "(", "discovered_dataset", ",", "desired_dataset", ")", ":", "if", "(", "discovered_dataset", "is", "None", ")", ":", "return", "(", "(", "desired_dataset", "is", "None", ")", "or", "(", "desired_dataset", ".", "state", "==", "DatasetStates", ".", "DELETED", ")", ")", "if", "(", "desired_dataset", "is", "None", ")", ":", "return", "(", "discovered_dataset", ".", "state", "==", "DatasetStates", ".", "NON_MANIFEST", ")", "if", "(", "(", "desired_dataset", ".", "state", "==", "DatasetStates", ".", "DELETED", ")", "and", "(", "discovered_dataset", ".", "state", "==", "DatasetStates", ".", "REGISTERED", ")", ")", ":", "return", "True", "if", "(", "discovered_dataset", ".", "state", "!=", "desired_dataset", ".", "state", ")", ":", "return", "False", "if", "(", "discovered_dataset", ".", "state", "==", "DatasetStates", ".", "MOUNTED", ")", ":", "return", "(", "discovered_dataset", ".", "mount_point", "==", "desired_dataset", ".", "mount_point", ")", "elif", "(", "discovered_dataset", ".", "state", "==", "DatasetStates", ".", "NON_MANIFEST", ")", ":", "return", "True", "elif", "(", "discovered_dataset", ".", "state", "==", "DatasetStates", ".", "DELETED", ")", ":", "return", "True", "else", ":", "raise", "ValueError", "(", "'Impossible dataset states: {} {}'", ".", "format", "(", "discovered_dataset", ",", "desired_dataset", ")", ")" ]
compare a discovered dataset to a desired dataset to determine if they have converged .
train
false
47,081
def libvlc_video_set_teletext(p_mi, i_page): f = (_Cfunctions.get('libvlc_video_set_teletext', None) or _Cfunction('libvlc_video_set_teletext', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_int)) return f(p_mi, i_page)
[ "def", "libvlc_video_set_teletext", "(", "p_mi", ",", "i_page", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_teletext'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_teletext'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_int", ")", ")", "return", "f", "(", "p_mi", ",", "i_page", ")" ]
set new teletext page to retrieve .
train
true
47,084
def _analyse(fn, url): data = None if ((not fn) or (fn.code != 200)): logging.debug('No usable response from indexer, retry after 60 sec') if fn: msg = fn.msg else: msg = '' return (None, msg, True, 60, data) if ((not fn) or (fn.msg != 'OK')): logging.debug('Received nothing from indexer, retry after 60 sec') return (None, fn.msg, True, 60, data) if (('.oznzb.com' in url) and ('login?' in fn.url)): return (None, T('Unauthorized access'), False, 0, data) return (fn, fn.msg, False, 0, data)
[ "def", "_analyse", "(", "fn", ",", "url", ")", ":", "data", "=", "None", "if", "(", "(", "not", "fn", ")", "or", "(", "fn", ".", "code", "!=", "200", ")", ")", ":", "logging", ".", "debug", "(", "'No usable response from indexer, retry after 60 sec'", ")", "if", "fn", ":", "msg", "=", "fn", ".", "msg", "else", ":", "msg", "=", "''", "return", "(", "None", ",", "msg", ",", "True", ",", "60", ",", "data", ")", "if", "(", "(", "not", "fn", ")", "or", "(", "fn", ".", "msg", "!=", "'OK'", ")", ")", ":", "logging", ".", "debug", "(", "'Received nothing from indexer, retry after 60 sec'", ")", "return", "(", "None", ",", "fn", ".", "msg", ",", "True", ",", "60", ",", "data", ")", "if", "(", "(", "'.oznzb.com'", "in", "url", ")", "and", "(", "'login?'", "in", "fn", ".", "url", ")", ")", ":", "return", "(", "None", ",", "T", "(", "'Unauthorized access'", ")", ",", "False", ",", "0", ",", "data", ")", "return", "(", "fn", ",", "fn", ".", "msg", ",", "False", ",", "0", ",", "data", ")" ]
analyze response of indexer returns fn|none .
train
false
47,085
def bytes_to_long(s): acc = 0L unpack = struct.unpack length = len(s) if (length % 4): extra = (4 - (length % 4)) s = ((b('\x00') * extra) + s) length = (length + extra) for i in range(0, length, 4): acc = ((acc << 32) + unpack('>I', s[i:(i + 4)])[0]) return acc
[ "def", "bytes_to_long", "(", "s", ")", ":", "acc", "=", "0", "L", "unpack", "=", "struct", ".", "unpack", "length", "=", "len", "(", "s", ")", "if", "(", "length", "%", "4", ")", ":", "extra", "=", "(", "4", "-", "(", "length", "%", "4", ")", ")", "s", "=", "(", "(", "b", "(", "'\\x00'", ")", "*", "extra", ")", "+", "s", ")", "length", "=", "(", "length", "+", "extra", ")", "for", "i", "in", "range", "(", "0", ",", "length", ",", "4", ")", ":", "acc", "=", "(", "(", "acc", "<<", "32", ")", "+", "unpack", "(", "'>I'", ",", "s", "[", "i", ":", "(", "i", "+", "4", ")", "]", ")", "[", "0", "]", ")", "return", "acc" ]
bytes_to_long : long convert a byte string to a long integer .
train
false
47,089
def findFirstHref(link_attrs_list, target_rel): matches = findLinksRel(link_attrs_list, target_rel) if (not matches): return None first = matches[0] return first.get('href')
[ "def", "findFirstHref", "(", "link_attrs_list", ",", "target_rel", ")", ":", "matches", "=", "findLinksRel", "(", "link_attrs_list", ",", "target_rel", ")", "if", "(", "not", "matches", ")", ":", "return", "None", "first", "=", "matches", "[", "0", "]", "return", "first", ".", "get", "(", "'href'", ")" ]
return the value of the href attribute for the first link tag in the list that has target_rel as a relationship .
train
true
47,090
def update_plugin_translations(plugin): plugin_folder = os.path.join(current_app.config['PLUGINS_FOLDER'], plugin) translations_folder = os.path.join(plugin_folder, 'translations') source_file = os.path.join(translations_folder, 'messages.pot') subprocess.call(['pybabel', 'extract', '-F', 'babel.cfg', '-k', 'lazy_gettext', '-o', source_file, plugin_folder]) subprocess.call(['pybabel', 'update', '-i', source_file, '-d', translations_folder])
[ "def", "update_plugin_translations", "(", "plugin", ")", ":", "plugin_folder", "=", "os", ".", "path", ".", "join", "(", "current_app", ".", "config", "[", "'PLUGINS_FOLDER'", "]", ",", "plugin", ")", "translations_folder", "=", "os", ".", "path", ".", "join", "(", "plugin_folder", ",", "'translations'", ")", "source_file", "=", "os", ".", "path", ".", "join", "(", "translations_folder", ",", "'messages.pot'", ")", "subprocess", ".", "call", "(", "[", "'pybabel'", ",", "'extract'", ",", "'-F'", ",", "'babel.cfg'", ",", "'-k'", ",", "'lazy_gettext'", ",", "'-o'", ",", "source_file", ",", "plugin_folder", "]", ")", "subprocess", ".", "call", "(", "[", "'pybabel'", ",", "'update'", ",", "'-i'", ",", "source_file", ",", "'-d'", ",", "translations_folder", "]", ")" ]
updates the plugin translations .
train
false
47,092
def uu_decode(input, errors='strict'): assert (errors == 'strict') from cStringIO import StringIO from binascii import a2b_uu infile = StringIO(str(input)) outfile = StringIO() readline = infile.readline write = outfile.write while 1: s = readline() if (not s): raise ValueError, 'Missing "begin" line in input data' if (s[:5] == 'begin'): break while 1: s = readline() if ((not s) or (s == 'end\n')): break try: data = a2b_uu(s) except binascii.Error as v: nbytes = (((((ord(s[0]) - 32) & 63) * 4) + 5) / 3) data = a2b_uu(s[:nbytes]) write(data) if (not s): raise ValueError, 'Truncated input data' return (outfile.getvalue(), len(input))
[ "def", "uu_decode", "(", "input", ",", "errors", "=", "'strict'", ")", ":", "assert", "(", "errors", "==", "'strict'", ")", "from", "cStringIO", "import", "StringIO", "from", "binascii", "import", "a2b_uu", "infile", "=", "StringIO", "(", "str", "(", "input", ")", ")", "outfile", "=", "StringIO", "(", ")", "readline", "=", "infile", ".", "readline", "write", "=", "outfile", ".", "write", "while", "1", ":", "s", "=", "readline", "(", ")", "if", "(", "not", "s", ")", ":", "raise", "ValueError", ",", "'Missing \"begin\" line in input data'", "if", "(", "s", "[", ":", "5", "]", "==", "'begin'", ")", ":", "break", "while", "1", ":", "s", "=", "readline", "(", ")", "if", "(", "(", "not", "s", ")", "or", "(", "s", "==", "'end\\n'", ")", ")", ":", "break", "try", ":", "data", "=", "a2b_uu", "(", "s", ")", "except", "binascii", ".", "Error", "as", "v", ":", "nbytes", "=", "(", "(", "(", "(", "(", "ord", "(", "s", "[", "0", "]", ")", "-", "32", ")", "&", "63", ")", "*", "4", ")", "+", "5", ")", "/", "3", ")", "data", "=", "a2b_uu", "(", "s", "[", ":", "nbytes", "]", ")", "write", "(", "data", ")", "if", "(", "not", "s", ")", ":", "raise", "ValueError", ",", "'Truncated input data'", "return", "(", "outfile", ".", "getvalue", "(", ")", ",", "len", "(", "input", ")", ")" ]
decodes the object input and returns a tuple .
train
false
47,093
def set_gentoo_mirrors(value): return set_var('GENTOO_MIRRORS', value)
[ "def", "set_gentoo_mirrors", "(", "value", ")", ":", "return", "set_var", "(", "'GENTOO_MIRRORS'", ",", "value", ")" ]
set the gentoo_mirrors variable return a dict containing the new value for variable:: {<variable>: {old: <old-value> .
train
false
47,094
def __get_yubico_users(username): user = {} try: if __opts__['yubico_users'].get(username, None): (user['id'], user['key']) = list(__opts__['yubico_users'][username].values()) else: return None except KeyError: return None return user
[ "def", "__get_yubico_users", "(", "username", ")", ":", "user", "=", "{", "}", "try", ":", "if", "__opts__", "[", "'yubico_users'", "]", ".", "get", "(", "username", ",", "None", ")", ":", "(", "user", "[", "'id'", "]", ",", "user", "[", "'key'", "]", ")", "=", "list", "(", "__opts__", "[", "'yubico_users'", "]", "[", "username", "]", ".", "values", "(", ")", ")", "else", ":", "return", "None", "except", "KeyError", ":", "return", "None", "return", "user" ]
grab the yubikey client id & secret key .
train
true
47,095
def requires_badges_enabled(function): def wrapped(*args, **kwargs): "\n Wrapped function which bails out early if bagdes aren't enabled.\n " if (not badges_enabled()): return return function(*args, **kwargs) return wrapped
[ "def", "requires_badges_enabled", "(", "function", ")", ":", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "not", "badges_enabled", "(", ")", ")", ":", "return", "return", "function", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapped" ]
decorator that bails a function out early if badges arent enabled .
train
false
47,097
def session_missing_tests(session): session.virtualenv = False print('The following samples do not have tests:') for sample in (set(ALL_SAMPLE_DIRECTORIES) - set(ALL_TESTED_SAMPLES)): print('* {}'.format(sample))
[ "def", "session_missing_tests", "(", "session", ")", ":", "session", ".", "virtualenv", "=", "False", "print", "(", "'The following samples do not have tests:'", ")", "for", "sample", "in", "(", "set", "(", "ALL_SAMPLE_DIRECTORIES", ")", "-", "set", "(", "ALL_TESTED_SAMPLES", ")", ")", ":", "print", "(", "'* {}'", ".", "format", "(", "sample", ")", ")" ]
lists all sample directories that do not have tests .
train
false
47,099
@register.filter(name='asset_which_groups') def asset_which_group(asset, member): member = getattr(asset, member) names = [members.name for members in member.all()] return ','.join(names)
[ "@", "register", ".", "filter", "(", "name", "=", "'asset_which_groups'", ")", "def", "asset_which_group", "(", "asset", ",", "member", ")", ":", "member", "=", "getattr", "(", "asset", ",", "member", ")", "names", "=", "[", "members", ".", "name", "for", "members", "in", "member", ".", "all", "(", ")", "]", "return", "','", ".", "join", "(", "names", ")" ]
instance is a user object .
train
false
47,101
def key_pair_destroy(context, user_id, name): return IMPL.key_pair_destroy(context, user_id, name)
[ "def", "key_pair_destroy", "(", "context", ",", "user_id", ",", "name", ")", ":", "return", "IMPL", ".", "key_pair_destroy", "(", "context", ",", "user_id", ",", "name", ")" ]
destroy the key_pair or raise if it does not exist .
train
false
47,102
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('--poll', dest='poll', action='store_true', default=False, help=_('Report the server migration progress until it completes.')) def do_migrate(cs, args): server = _find_server(cs, args.server) server.migrate() if args.poll: _poll_for_status(cs.servers.get, server.id, 'migrating', ['active', 'verify_resize'])
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "@", "utils", ".", "arg", "(", "'--poll'", ",", "dest", "=", "'poll'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "_", "(", "'Report the server migration progress until it completes.'", ")", ")", "def", "do_migrate", "(", "cs", ",", "args", ")", ":", "server", "=", "_find_server", "(", "cs", ",", "args", ".", "server", ")", "server", ".", "migrate", "(", ")", "if", "args", ".", "poll", ":", "_poll_for_status", "(", "cs", ".", "servers", ".", "get", ",", "server", ".", "id", ",", "'migrating'", ",", "[", "'active'", ",", "'verify_resize'", "]", ")" ]
migrate a server .
train
false
47,103
def displayData(X, size=None, showit=False): x_length = int(np.sqrt(X.shape[1])) y_length = int(np.sqrt(X.shape[1])) if (size == None): size = np.sqrt(X.shape[0]) size = [size, size] bigimg = np.zeros(((x_length * size[0]), (y_length * size[1]))) for i in range(x_length): for j in range(y_length): im = X[:, (((i - 1) * y_length) + j)].reshape(32, 32).transpose() bigimg[(i * 32):((i + 1) * 32), (j * 32):((j + 1) * 32)] = im if showit: fig = plt.figure() plt.imshow(bigimg, cmap='gray') else: return bigimg
[ "def", "displayData", "(", "X", ",", "size", "=", "None", ",", "showit", "=", "False", ")", ":", "x_length", "=", "int", "(", "np", ".", "sqrt", "(", "X", ".", "shape", "[", "1", "]", ")", ")", "y_length", "=", "int", "(", "np", ".", "sqrt", "(", "X", ".", "shape", "[", "1", "]", ")", ")", "if", "(", "size", "==", "None", ")", ":", "size", "=", "np", ".", "sqrt", "(", "X", ".", "shape", "[", "0", "]", ")", "size", "=", "[", "size", ",", "size", "]", "bigimg", "=", "np", ".", "zeros", "(", "(", "(", "x_length", "*", "size", "[", "0", "]", ")", ",", "(", "y_length", "*", "size", "[", "1", "]", ")", ")", ")", "for", "i", "in", "range", "(", "x_length", ")", ":", "for", "j", "in", "range", "(", "y_length", ")", ":", "im", "=", "X", "[", ":", ",", "(", "(", "(", "i", "-", "1", ")", "*", "y_length", ")", "+", "j", ")", "]", ".", "reshape", "(", "32", ",", "32", ")", ".", "transpose", "(", ")", "bigimg", "[", "(", "i", "*", "32", ")", ":", "(", "(", "i", "+", "1", ")", "*", "32", ")", ",", "(", "j", "*", "32", ")", ":", "(", "(", "j", "+", "1", ")", "*", "32", ")", "]", "=", "im", "if", "showit", ":", "fig", "=", "plt", ".", "figure", "(", ")", "plt", ".", "imshow", "(", "bigimg", ",", "cmap", "=", "'gray'", ")", "else", ":", "return", "bigimg" ]
x is a n*m matrix size show each images size .
train
false
47,104
@requires_mne def test_clean_eog_ecg(): check_usage(mne_clean_eog_ecg) tempdir = _TempDir() raw = concatenate_raws([read_raw_fif(f) for f in [raw_fname, raw_fname, raw_fname]]) raw.info['bads'] = ['MEG 2443'] use_fname = op.join(tempdir, op.basename(raw_fname)) raw.save(use_fname) with ArgvSetter(('-i', use_fname, '--quiet')): mne_clean_eog_ecg.run() fnames = glob.glob(op.join(tempdir, '*proj.fif')) assert_true((len(fnames) == 2)) fnames = glob.glob(op.join(tempdir, '*-eve.fif')) assert_true((len(fnames) == 3))
[ "@", "requires_mne", "def", "test_clean_eog_ecg", "(", ")", ":", "check_usage", "(", "mne_clean_eog_ecg", ")", "tempdir", "=", "_TempDir", "(", ")", "raw", "=", "concatenate_raws", "(", "[", "read_raw_fif", "(", "f", ")", "for", "f", "in", "[", "raw_fname", ",", "raw_fname", ",", "raw_fname", "]", "]", ")", "raw", ".", "info", "[", "'bads'", "]", "=", "[", "'MEG 2443'", "]", "use_fname", "=", "op", ".", "join", "(", "tempdir", ",", "op", ".", "basename", "(", "raw_fname", ")", ")", "raw", ".", "save", "(", "use_fname", ")", "with", "ArgvSetter", "(", "(", "'-i'", ",", "use_fname", ",", "'--quiet'", ")", ")", ":", "mne_clean_eog_ecg", ".", "run", "(", ")", "fnames", "=", "glob", ".", "glob", "(", "op", ".", "join", "(", "tempdir", ",", "'*proj.fif'", ")", ")", "assert_true", "(", "(", "len", "(", "fnames", ")", "==", "2", ")", ")", "fnames", "=", "glob", ".", "glob", "(", "op", ".", "join", "(", "tempdir", ",", "'*-eve.fif'", ")", ")", "assert_true", "(", "(", "len", "(", "fnames", ")", "==", "3", ")", ")" ]
test mne clean_eog_ecg .
train
false
47,105
def pick_disk_driver_name(hypervisor_version, is_block_dev=False): if (CONF.libvirt.virt_type == 'xen'): if is_block_dev: return 'phy' else: if (hypervisor_version >= 4002000): try: execute('xend', 'status', run_as_root=True, check_exit_code=True) except OSError as exc: if (exc.errno == errno.ENOENT): LOG.debug('xend is not found') return 'qemu' else: raise except processutils.ProcessExecutionError: LOG.debug('xend is not started') return 'qemu' try: (out, err) = execute('tap-ctl', 'check', check_exit_code=False) if (out == 'ok\n'): if (hypervisor_version > 4000000): return 'tap2' else: return 'tap' else: LOG.info(_LI('tap-ctl check: %s'), out) except OSError as exc: if (exc.errno == errno.ENOENT): LOG.debug('tap-ctl tool is not installed') else: raise return 'file' elif (CONF.libvirt.virt_type in ('kvm', 'qemu')): return 'qemu' else: return None
[ "def", "pick_disk_driver_name", "(", "hypervisor_version", ",", "is_block_dev", "=", "False", ")", ":", "if", "(", "CONF", ".", "libvirt", ".", "virt_type", "==", "'xen'", ")", ":", "if", "is_block_dev", ":", "return", "'phy'", "else", ":", "if", "(", "hypervisor_version", ">=", "4002000", ")", ":", "try", ":", "execute", "(", "'xend'", ",", "'status'", ",", "run_as_root", "=", "True", ",", "check_exit_code", "=", "True", ")", "except", "OSError", "as", "exc", ":", "if", "(", "exc", ".", "errno", "==", "errno", ".", "ENOENT", ")", ":", "LOG", ".", "debug", "(", "'xend is not found'", ")", "return", "'qemu'", "else", ":", "raise", "except", "processutils", ".", "ProcessExecutionError", ":", "LOG", ".", "debug", "(", "'xend is not started'", ")", "return", "'qemu'", "try", ":", "(", "out", ",", "err", ")", "=", "execute", "(", "'tap-ctl'", ",", "'check'", ",", "check_exit_code", "=", "False", ")", "if", "(", "out", "==", "'ok\\n'", ")", ":", "if", "(", "hypervisor_version", ">", "4000000", ")", ":", "return", "'tap2'", "else", ":", "return", "'tap'", "else", ":", "LOG", ".", "info", "(", "_LI", "(", "'tap-ctl check: %s'", ")", ",", "out", ")", "except", "OSError", "as", "exc", ":", "if", "(", "exc", ".", "errno", "==", "errno", ".", "ENOENT", ")", ":", "LOG", ".", "debug", "(", "'tap-ctl tool is not installed'", ")", "else", ":", "raise", "return", "'file'", "elif", "(", "CONF", ".", "libvirt", ".", "virt_type", "in", "(", "'kvm'", ",", "'qemu'", ")", ")", ":", "return", "'qemu'", "else", ":", "return", "None" ]
pick the libvirt primary backend driver name if the hypervisor supports multiple backend drivers .
train
false
47,107
def addXIntersectionIndexesFromSegments(index, segments, xIntersectionIndexList): for segment in segments: addXIntersectionIndexesFromSegment(index, segment, xIntersectionIndexList)
[ "def", "addXIntersectionIndexesFromSegments", "(", "index", ",", "segments", ",", "xIntersectionIndexList", ")", ":", "for", "segment", "in", "segments", ":", "addXIntersectionIndexesFromSegment", "(", "index", ",", "segment", ",", "xIntersectionIndexList", ")" ]
add the x intersection indexes from the segments .
train
false
47,108
@pytest.fixture(autouse=True) def never_use_single_delete(monkeypatch): def die(): assert False monkeypatch.setattr(storage.Blob, 'delete', die) monkeypatch.setattr(storage.Bucket, 'delete_blob', die)
[ "@", "pytest", ".", "fixture", "(", "autouse", "=", "True", ")", "def", "never_use_single_delete", "(", "monkeypatch", ")", ":", "def", "die", "(", ")", ":", "assert", "False", "monkeypatch", ".", "setattr", "(", "storage", ".", "Blob", ",", "'delete'", ",", "die", ")", "monkeypatch", ".", "setattr", "(", "storage", ".", "Bucket", ",", "'delete_blob'", ",", "die", ")" ]
detect any mistaken uses of single-blob deletion .
train
false
47,109
def get_jd12(time, scale): if (time.scale == scale): newtime = time else: try: newtime = getattr(time, scale) except iers.IERSRangeError as e: _warn_iers(e) newtime = time return (newtime.jd1, newtime.jd2)
[ "def", "get_jd12", "(", "time", ",", "scale", ")", ":", "if", "(", "time", ".", "scale", "==", "scale", ")", ":", "newtime", "=", "time", "else", ":", "try", ":", "newtime", "=", "getattr", "(", "time", ",", "scale", ")", "except", "iers", ".", "IERSRangeError", "as", "e", ":", "_warn_iers", "(", "e", ")", "newtime", "=", "time", "return", "(", "newtime", ".", "jd1", ",", "newtime", ".", "jd2", ")" ]
gets jd1 and jd2 from a time object in a particular scale .
train
false
47,111
def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None): return _item_present(name=name, item='resource', item_id='{0}={1}'.format(op_default, value), item_type=None, show=['op', 'defaults'], create=['op', 'defaults'], extra_args=extra_args, cibname=cibname)
[ "def", "resource_op_defaults_to", "(", "name", ",", "op_default", ",", "value", ",", "extra_args", "=", "None", ",", "cibname", "=", "None", ")", ":", "return", "_item_present", "(", "name", "=", "name", ",", "item", "=", "'resource'", ",", "item_id", "=", "'{0}={1}'", ".", "format", "(", "op_default", ",", "value", ")", ",", "item_type", "=", "None", ",", "show", "=", "[", "'op'", ",", "'defaults'", "]", ",", "create", "=", "[", "'op'", ",", "'defaults'", "]", ",", "extra_args", "=", "extra_args", ",", "cibname", "=", "cibname", ")" ]
ensure a resource operation default in the cluster is set to a given value should be run on one cluster node only can only be run on a node with a functional pacemaker/corosync name irrelevant .
train
true
47,114
@image_comparison(baseline_images=[u'EventCollection_plot__append_positions']) def test__EventCollection__append_positions(): (splt, coll, props) = generate_EventCollection_plot() new_positions = np.hstack([props[u'positions'], props[u'extra_positions'][2]]) coll.append_positions(props[u'extra_positions'][2]) np.testing.assert_array_equal(new_positions, coll.get_positions()) check_segments(coll, new_positions, props[u'linelength'], props[u'lineoffset'], props[u'orientation']) splt.set_title(u'EventCollection: append_positions') splt.set_xlim((-1), 90)
[ "@", "image_comparison", "(", "baseline_images", "=", "[", "u'EventCollection_plot__append_positions'", "]", ")", "def", "test__EventCollection__append_positions", "(", ")", ":", "(", "splt", ",", "coll", ",", "props", ")", "=", "generate_EventCollection_plot", "(", ")", "new_positions", "=", "np", ".", "hstack", "(", "[", "props", "[", "u'positions'", "]", ",", "props", "[", "u'extra_positions'", "]", "[", "2", "]", "]", ")", "coll", ".", "append_positions", "(", "props", "[", "u'extra_positions'", "]", "[", "2", "]", ")", "np", ".", "testing", ".", "assert_array_equal", "(", "new_positions", ",", "coll", ".", "get_positions", "(", ")", ")", "check_segments", "(", "coll", ",", "new_positions", ",", "props", "[", "u'linelength'", "]", ",", "props", "[", "u'lineoffset'", "]", ",", "props", "[", "u'orientation'", "]", ")", "splt", ".", "set_title", "(", "u'EventCollection: append_positions'", ")", "splt", ".", "set_xlim", "(", "(", "-", "1", ")", ",", "90", ")" ]
check to make sure append_positions works properly .
train
false
47,116
def _remove_statements(evaluator, stmt, name): types = set() check_instance = None if (isinstance(stmt, er.InstanceElement) and stmt.is_class_var): check_instance = stmt.instance stmt = stmt.var pep0484types = pep0484.find_type_from_comment_hint_assign(evaluator, stmt, name) if pep0484types: return pep0484types types |= evaluator.eval_statement(stmt, seek_name=name) if (check_instance is not None): types = set([(er.get_instance_el(evaluator, check_instance, a, True) if isinstance(a, (er.Function, tree.Function)) else a) for a in types]) return types
[ "def", "_remove_statements", "(", "evaluator", ",", "stmt", ",", "name", ")", ":", "types", "=", "set", "(", ")", "check_instance", "=", "None", "if", "(", "isinstance", "(", "stmt", ",", "er", ".", "InstanceElement", ")", "and", "stmt", ".", "is_class_var", ")", ":", "check_instance", "=", "stmt", ".", "instance", "stmt", "=", "stmt", ".", "var", "pep0484types", "=", "pep0484", ".", "find_type_from_comment_hint_assign", "(", "evaluator", ",", "stmt", ",", "name", ")", "if", "pep0484types", ":", "return", "pep0484types", "types", "|=", "evaluator", ".", "eval_statement", "(", "stmt", ",", "seek_name", "=", "name", ")", "if", "(", "check_instance", "is", "not", "None", ")", ":", "types", "=", "set", "(", "[", "(", "er", ".", "get_instance_el", "(", "evaluator", ",", "check_instance", ",", "a", ",", "True", ")", "if", "isinstance", "(", "a", ",", "(", "er", ".", "Function", ",", "tree", ".", "Function", ")", ")", "else", "a", ")", "for", "a", "in", "types", "]", ")", "return", "types" ]
this is the part where statements are being stripped .
train
false
47,117
def topics_for(product, parent=False): statsd.incr('wiki.facets.topics_for.db') docs = Document.objects.filter(locale=settings.WIKI_DEFAULT_LANGUAGE, is_archived=False, current_revision__isnull=False, products=product, category__in=settings.IA_DEFAULT_CATEGORIES) qs = Topic.objects.filter(product=product) qs = qs.filter(visible=True, document__in=docs).annotate(num_docs=Count('document')).distinct() if (parent or (parent is None)): qs = qs.filter(parent=parent) return qs
[ "def", "topics_for", "(", "product", ",", "parent", "=", "False", ")", ":", "statsd", ".", "incr", "(", "'wiki.facets.topics_for.db'", ")", "docs", "=", "Document", ".", "objects", ".", "filter", "(", "locale", "=", "settings", ".", "WIKI_DEFAULT_LANGUAGE", ",", "is_archived", "=", "False", ",", "current_revision__isnull", "=", "False", ",", "products", "=", "product", ",", "category__in", "=", "settings", ".", "IA_DEFAULT_CATEGORIES", ")", "qs", "=", "Topic", ".", "objects", ".", "filter", "(", "product", "=", "product", ")", "qs", "=", "qs", ".", "filter", "(", "visible", "=", "True", ",", "document__in", "=", "docs", ")", ".", "annotate", "(", "num_docs", "=", "Count", "(", "'document'", ")", ")", ".", "distinct", "(", ")", "if", "(", "parent", "or", "(", "parent", "is", "None", ")", ")", ":", "qs", "=", "qs", ".", "filter", "(", "parent", "=", "parent", ")", "return", "qs" ]
returns a list of topics that apply to passed in product .
train
false
47,119
def test_neg_type___clrtype__(): AssertErrorWithMessage(TypeError, '__clrtype__() takes exactly 1 argument (0 given)', type.__clrtype__) AssertErrorWithMessage(TypeError, '__clrtype__() takes exactly 1 argument (2 given)', type.__clrtype__, None, None) AssertErrorWithMessage(TypeError, '__clrtype__() takes exactly 1 argument (3 given)', type.__clrtype__, None, None, None) AssertErrorWithPartialMessage(TypeError, ', got NoneType', type.__clrtype__, None) AssertErrorWithPartialMessage(TypeError, ', got float', type.__clrtype__, 3.14) for x in [None, [], (None,), Exception('message'), 3.14, 3L, 0, 5j, 'string', u'string', True, System, _os, os, exit, (lambda : 3.14)]: AssertError(TypeError, type.__clrtype__, x) AssertErrorWithMessage(AttributeError, "attribute '__clrtype__' of 'type' object is read-only", setattr, type, '__clrtype__', None)
[ "def", "test_neg_type___clrtype__", "(", ")", ":", "AssertErrorWithMessage", "(", "TypeError", ",", "'__clrtype__() takes exactly 1 argument (0 given)'", ",", "type", ".", "__clrtype__", ")", "AssertErrorWithMessage", "(", "TypeError", ",", "'__clrtype__() takes exactly 1 argument (2 given)'", ",", "type", ".", "__clrtype__", ",", "None", ",", "None", ")", "AssertErrorWithMessage", "(", "TypeError", ",", "'__clrtype__() takes exactly 1 argument (3 given)'", ",", "type", ".", "__clrtype__", ",", "None", ",", "None", ",", "None", ")", "AssertErrorWithPartialMessage", "(", "TypeError", ",", "', got NoneType'", ",", "type", ".", "__clrtype__", ",", "None", ")", "AssertErrorWithPartialMessage", "(", "TypeError", ",", "', got float'", ",", "type", ".", "__clrtype__", ",", "3.14", ")", "for", "x", "in", "[", "None", ",", "[", "]", ",", "(", "None", ",", ")", ",", "Exception", "(", "'message'", ")", ",", "3.14", ",", "3", "L", ",", "0", ",", "5j", ",", "'string'", ",", "u'string'", ",", "True", ",", "System", ",", "_os", ",", "os", ",", "exit", ",", "(", "lambda", ":", "3.14", ")", "]", ":", "AssertError", "(", "TypeError", ",", "type", ".", "__clrtype__", ",", "x", ")", "AssertErrorWithMessage", "(", "AttributeError", ",", "\"attribute '__clrtype__' of 'type' object is read-only\"", ",", "setattr", ",", "type", ",", "'__clrtype__'", ",", "None", ")" ]
tests out negative type .
train
false
47,120
def create_or_update(model, using=None, **kwargs): values = kwargs.pop('values', {}) defaults = kwargs.pop('defaults', {}) if (not using): using = router.db_for_write(model) objects = model.objects.using(using) affected = objects.filter(**kwargs).update(**values) if affected: return (affected, False) create_kwargs = kwargs.copy() inst = objects.model() for (k, v) in itertools.chain(six.iteritems(values), six.iteritems(defaults)): if (not isinstance(v, Model)): k = model._meta.get_field(k).attname if isinstance(v, ExpressionNode): create_kwargs[k] = resolve_expression_node(inst, v) else: create_kwargs[k] = v try: with transaction.atomic(using=using): return (objects.create(**create_kwargs), True) except IntegrityError: affected = objects.filter(**kwargs).update(**values) return (affected, False)
[ "def", "create_or_update", "(", "model", ",", "using", "=", "None", ",", "**", "kwargs", ")", ":", "values", "=", "kwargs", ".", "pop", "(", "'values'", ",", "{", "}", ")", "defaults", "=", "kwargs", ".", "pop", "(", "'defaults'", ",", "{", "}", ")", "if", "(", "not", "using", ")", ":", "using", "=", "router", ".", "db_for_write", "(", "model", ")", "objects", "=", "model", ".", "objects", ".", "using", "(", "using", ")", "affected", "=", "objects", ".", "filter", "(", "**", "kwargs", ")", ".", "update", "(", "**", "values", ")", "if", "affected", ":", "return", "(", "affected", ",", "False", ")", "create_kwargs", "=", "kwargs", ".", "copy", "(", ")", "inst", "=", "objects", ".", "model", "(", ")", "for", "(", "k", ",", "v", ")", "in", "itertools", ".", "chain", "(", "six", ".", "iteritems", "(", "values", ")", ",", "six", ".", "iteritems", "(", "defaults", ")", ")", ":", "if", "(", "not", "isinstance", "(", "v", ",", "Model", ")", ")", ":", "k", "=", "model", ".", "_meta", ".", "get_field", "(", "k", ")", ".", "attname", "if", "isinstance", "(", "v", ",", "ExpressionNode", ")", ":", "create_kwargs", "[", "k", "]", "=", "resolve_expression_node", "(", "inst", ",", "v", ")", "else", ":", "create_kwargs", "[", "k", "]", "=", "v", "try", ":", "with", "transaction", ".", "atomic", "(", "using", "=", "using", ")", ":", "return", "(", "objects", ".", "create", "(", "**", "create_kwargs", ")", ",", "True", ")", "except", "IntegrityError", ":", "affected", "=", "objects", ".", "filter", "(", "**", "kwargs", ")", ".", "update", "(", "**", "values", ")", "return", "(", "affected", ",", "False", ")" ]
similar to get_or_create .
train
false
47,121
def execute_with_nm_v2(*cmd, **kwargs): funcs = {test_data.sensor_status_cmd: get_sensor_status_init, test_data.init_sensor_cmd: init_sensor_agent, test_data.sdr_dump_cmd: sdr_dump, test_data.nm_version_cmd: get_nm_version_v2} return _execute(funcs, *cmd, **kwargs)
[ "def", "execute_with_nm_v2", "(", "*", "cmd", ",", "**", "kwargs", ")", ":", "funcs", "=", "{", "test_data", ".", "sensor_status_cmd", ":", "get_sensor_status_init", ",", "test_data", ".", "init_sensor_cmd", ":", "init_sensor_agent", ",", "test_data", ".", "sdr_dump_cmd", ":", "sdr_dump", ",", "test_data", ".", "nm_version_cmd", ":", "get_nm_version_v2", "}", "return", "_execute", "(", "funcs", ",", "*", "cmd", ",", "**", "kwargs", ")" ]
test version of execute on node manager v2 .
train
false
47,122
def read_batchfile(pythonpath, file_ending='.py'): abspaths = utils.pypath_to_realpath(pythonpath, file_ending, settings.BASE_BATCHPROCESS_PATHS) if (not abspaths): raise IOError text = None decoderr = [] for abspath in abspaths: for file_encoding in _ENCODINGS: try: with codecs.open(abspath, 'r', encoding=file_encoding) as fobj: text = fobj.read() except (ValueError, UnicodeDecodeError) as e: decoderr.append(str(e)) continue break if ((not text) and decoderr): raise UnicodeDecodeError('\n'.join(decoderr)) return text
[ "def", "read_batchfile", "(", "pythonpath", ",", "file_ending", "=", "'.py'", ")", ":", "abspaths", "=", "utils", ".", "pypath_to_realpath", "(", "pythonpath", ",", "file_ending", ",", "settings", ".", "BASE_BATCHPROCESS_PATHS", ")", "if", "(", "not", "abspaths", ")", ":", "raise", "IOError", "text", "=", "None", "decoderr", "=", "[", "]", "for", "abspath", "in", "abspaths", ":", "for", "file_encoding", "in", "_ENCODINGS", ":", "try", ":", "with", "codecs", ".", "open", "(", "abspath", ",", "'r'", ",", "encoding", "=", "file_encoding", ")", "as", "fobj", ":", "text", "=", "fobj", ".", "read", "(", ")", "except", "(", "ValueError", ",", "UnicodeDecodeError", ")", "as", "e", ":", "decoderr", ".", "append", "(", "str", "(", "e", ")", ")", "continue", "break", "if", "(", "(", "not", "text", ")", "and", "decoderr", ")", ":", "raise", "UnicodeDecodeError", "(", "'\\n'", ".", "join", "(", "decoderr", ")", ")", "return", "text" ]
this reads the contents of a batch-file .
train
false
47,123
@deprecated_renamed_argument('clobber', 'overwrite', '1.3') def tabledump(filename, datafile=None, cdfile=None, hfile=None, ext=1, overwrite=False): (mode, closed) = _get_file_mode(filename, default='readonly') f = fitsopen(filename, mode=mode) try: if (not datafile): (root, tail) = os.path.splitext(f._HDUList__file.name) datafile = (((root + '_') + repr(ext)) + '.txt') f[ext].dump(datafile, cdfile, hfile, overwrite) finally: if closed: f._close()
[ "@", "deprecated_renamed_argument", "(", "'clobber'", ",", "'overwrite'", ",", "'1.3'", ")", "def", "tabledump", "(", "filename", ",", "datafile", "=", "None", ",", "cdfile", "=", "None", ",", "hfile", "=", "None", ",", "ext", "=", "1", ",", "overwrite", "=", "False", ")", ":", "(", "mode", ",", "closed", ")", "=", "_get_file_mode", "(", "filename", ",", "default", "=", "'readonly'", ")", "f", "=", "fitsopen", "(", "filename", ",", "mode", "=", "mode", ")", "try", ":", "if", "(", "not", "datafile", ")", ":", "(", "root", ",", "tail", ")", "=", "os", ".", "path", ".", "splitext", "(", "f", ".", "_HDUList__file", ".", "name", ")", "datafile", "=", "(", "(", "(", "root", "+", "'_'", ")", "+", "repr", "(", "ext", ")", ")", "+", "'.txt'", ")", "f", "[", "ext", "]", ".", "dump", "(", "datafile", ",", "cdfile", ",", "hfile", ",", "overwrite", ")", "finally", ":", "if", "closed", ":", "f", ".", "_close", "(", ")" ]
dump a table hdu to a file in ascii format .
train
false
47,124
def quantize_image(img, max_colors=256, dither=True, palette=u''): img = image_from_data(img) if img.hasAlphaChannel(): img = blend_image(img) if (palette and isinstance(palette, basestring)): palette = palette.split() return imageops.quantize(img, max_colors, dither, [QColor(x).rgb() for x in palette])
[ "def", "quantize_image", "(", "img", ",", "max_colors", "=", "256", ",", "dither", "=", "True", ",", "palette", "=", "u''", ")", ":", "img", "=", "image_from_data", "(", "img", ")", "if", "img", ".", "hasAlphaChannel", "(", ")", ":", "img", "=", "blend_image", "(", "img", ")", "if", "(", "palette", "and", "isinstance", "(", "palette", ",", "basestring", ")", ")", ":", "palette", "=", "palette", ".", "split", "(", ")", "return", "imageops", ".", "quantize", "(", "img", ",", "max_colors", ",", "dither", ",", "[", "QColor", "(", "x", ")", ".", "rgb", "(", ")", "for", "x", "in", "palette", "]", ")" ]
quantize the image to contain a maximum of max_colors colors .
train
false
47,126
def from_iterable(iterables): for it in iterables: for element in it: (yield element)
[ "def", "from_iterable", "(", "iterables", ")", ":", "for", "it", "in", "iterables", ":", "for", "element", "in", "it", ":", "(", "yield", "element", ")" ]
backport of itertools .
train
false
47,127
def process_entity(entity, datastore, zookeeper): logging.debug('Process entity {}'.format(str(entity))) key = entity.keys()[0] app_id = key.split(dbconstants.KEY_DELIMITER)[0] valid_entity = validate_row(app_id, entity, zookeeper, datastore) if ((valid_entity is None) or (valid_entity[key][APP_ENTITY_SCHEMA[0]] == TOMBSTONE)): delete_entity_from_table(key, datastore) return if (valid_entity != entity): update_entity_in_table(key, valid_entity, datastore)
[ "def", "process_entity", "(", "entity", ",", "datastore", ",", "zookeeper", ")", ":", "logging", ".", "debug", "(", "'Process entity {}'", ".", "format", "(", "str", "(", "entity", ")", ")", ")", "key", "=", "entity", ".", "keys", "(", ")", "[", "0", "]", "app_id", "=", "key", ".", "split", "(", "dbconstants", ".", "KEY_DELIMITER", ")", "[", "0", "]", "valid_entity", "=", "validate_row", "(", "app_id", ",", "entity", ",", "zookeeper", ",", "datastore", ")", "if", "(", "(", "valid_entity", "is", "None", ")", "or", "(", "valid_entity", "[", "key", "]", "[", "APP_ENTITY_SCHEMA", "[", "0", "]", "]", "==", "TOMBSTONE", ")", ")", ":", "delete_entity_from_table", "(", "key", ",", "datastore", ")", "return", "if", "(", "valid_entity", "!=", "entity", ")", ":", "update_entity_in_table", "(", "key", ",", "valid_entity", ",", "datastore", ")" ]
processes an entity by updating it if necessary and removing tombstones .
train
false
47,128
def _fwd_bem_ip_modify_solution(solution, ip_solution, ip_mult, n_tri): n_last = n_tri[(-1)] mult = ((1.0 + ip_mult) / ip_mult) logger.info(' Combining...') offsets = np.cumsum(np.concatenate(([0], n_tri))) for si in range(len(n_tri)): sub = solution[offsets[si]:offsets[(si + 1)], np.sum(n_tri[:(-1)]):] sub -= (2 * np.dot(sub, ip_solution)) sub[(- n_last):, (- n_last):] += (mult * ip_solution) logger.info(' Scaling...') solution *= ip_mult return
[ "def", "_fwd_bem_ip_modify_solution", "(", "solution", ",", "ip_solution", ",", "ip_mult", ",", "n_tri", ")", ":", "n_last", "=", "n_tri", "[", "(", "-", "1", ")", "]", "mult", "=", "(", "(", "1.0", "+", "ip_mult", ")", "/", "ip_mult", ")", "logger", ".", "info", "(", "' Combining...'", ")", "offsets", "=", "np", ".", "cumsum", "(", "np", ".", "concatenate", "(", "(", "[", "0", "]", ",", "n_tri", ")", ")", ")", "for", "si", "in", "range", "(", "len", "(", "n_tri", ")", ")", ":", "sub", "=", "solution", "[", "offsets", "[", "si", "]", ":", "offsets", "[", "(", "si", "+", "1", ")", "]", ",", "np", ".", "sum", "(", "n_tri", "[", ":", "(", "-", "1", ")", "]", ")", ":", "]", "sub", "-=", "(", "2", "*", "np", ".", "dot", "(", "sub", ",", "ip_solution", ")", ")", "sub", "[", "(", "-", "n_last", ")", ":", ",", "(", "-", "n_last", ")", ":", "]", "+=", "(", "mult", "*", "ip_solution", ")", "logger", ".", "info", "(", "' Scaling...'", ")", "solution", "*=", "ip_mult", "return" ]
modify the solution according to the ip approach .
train
false
47,129
def _resolve_lookup((model, lookup, arg_name), view_kwargs): value = view_kwargs.get(arg_name) if (value is None): raise ValueError(("Expected kwarg '%s' not found." % arg_name)) if isinstance(model, basestring): model_class = get_model(*model.split('.')) else: model_class = model if (model_class is None): raise ValueError(("The given argument '%s' is not a valid model." % model)) if (inspect.isclass(model_class) and (not issubclass(model_class, Model))): raise ValueError(("The argument '%s' needs to be a model." % model)) return get_object_or_404(model_class, **{lookup: value})
[ "def", "_resolve_lookup", "(", "(", "model", ",", "lookup", ",", "arg_name", ")", ",", "view_kwargs", ")", ":", "value", "=", "view_kwargs", ".", "get", "(", "arg_name", ")", "if", "(", "value", "is", "None", ")", ":", "raise", "ValueError", "(", "(", "\"Expected kwarg '%s' not found.\"", "%", "arg_name", ")", ")", "if", "isinstance", "(", "model", ",", "basestring", ")", ":", "model_class", "=", "get_model", "(", "*", "model", ".", "split", "(", "'.'", ")", ")", "else", ":", "model_class", "=", "model", "if", "(", "model_class", "is", "None", ")", ":", "raise", "ValueError", "(", "(", "\"The given argument '%s' is not a valid model.\"", "%", "model", ")", ")", "if", "(", "inspect", ".", "isclass", "(", "model_class", ")", "and", "(", "not", "issubclass", "(", "model_class", ",", "Model", ")", ")", ")", ":", "raise", "ValueError", "(", "(", "\"The argument '%s' needs to be a model.\"", "%", "model", ")", ")", "return", "get_object_or_404", "(", "model_class", ",", "**", "{", "lookup", ":", "value", "}", ")" ]
return the object indicated by the lookup triple and the kwargs passed to the view .
train
false
47,131
def test_imports_on_global_namespace_without_path(): completions = Script('import operator').completions() assert ([c.name for c in completions] == ['operator']) completions = Script('import operator', path='example.py').completions() assert ([c.name for c in completions] == ['operator']) completions = Script('import keyword', path='example.py').completions() assert ([c.name for c in completions] == ['keyword']) completions = Script('import keyword').completions() assert ([c.name for c in completions] == ['keyword'])
[ "def", "test_imports_on_global_namespace_without_path", "(", ")", ":", "completions", "=", "Script", "(", "'import operator'", ")", ".", "completions", "(", ")", "assert", "(", "[", "c", ".", "name", "for", "c", "in", "completions", "]", "==", "[", "'operator'", "]", ")", "completions", "=", "Script", "(", "'import operator'", ",", "path", "=", "'example.py'", ")", ".", "completions", "(", ")", "assert", "(", "[", "c", ".", "name", "for", "c", "in", "completions", "]", "==", "[", "'operator'", "]", ")", "completions", "=", "Script", "(", "'import keyword'", ",", "path", "=", "'example.py'", ")", ".", "completions", "(", ")", "assert", "(", "[", "c", ".", "name", "for", "c", "in", "completions", "]", "==", "[", "'keyword'", "]", ")", "completions", "=", "Script", "(", "'import keyword'", ")", ".", "completions", "(", ")", "assert", "(", "[", "c", ".", "name", "for", "c", "in", "completions", "]", "==", "[", "'keyword'", "]", ")" ]
if the path is none .
train
false
47,133
def PercentileRows(ys_seq, percents): nrows = len(ys_seq) ncols = len(ys_seq[0]) array = np.zeros((nrows, ncols)) for (i, ys) in enumerate(ys_seq): array[(i,)] = ys array = np.sort(array, axis=0) rows = [PercentileRow(array, p) for p in percents] return rows
[ "def", "PercentileRows", "(", "ys_seq", ",", "percents", ")", ":", "nrows", "=", "len", "(", "ys_seq", ")", "ncols", "=", "len", "(", "ys_seq", "[", "0", "]", ")", "array", "=", "np", ".", "zeros", "(", "(", "nrows", ",", "ncols", ")", ")", "for", "(", "i", ",", "ys", ")", "in", "enumerate", "(", "ys_seq", ")", ":", "array", "[", "(", "i", ",", ")", "]", "=", "ys", "array", "=", "np", ".", "sort", "(", "array", ",", "axis", "=", "0", ")", "rows", "=", "[", "PercentileRow", "(", "array", ",", "p", ")", "for", "p", "in", "percents", "]", "return", "rows" ]
given a collection of lines .
train
false
47,134
def lint_help(tool_xml, lint_ctx): root = tool_xml.getroot() helps = root.findall('help') if (len(helps) > 1): lint_ctx.error('More than one help section found, behavior undefined.') return if (len(helps) == 0): lint_ctx.warn('No help section found, consider adding a help section to your tool.') return help = (helps[0].text or '') if (not help.strip()): lint_ctx.warn('Help section appears to be empty.') return lint_ctx.valid('Tool contains help section.') invalid_rst = rst_invalid(help) if ('TODO' in help): lint_ctx.warn('Help contains TODO text.') if invalid_rst: lint_ctx.warn(('Invalid reStructuredText found in help - [%s].' % invalid_rst)) else: lint_ctx.valid('Help contains valid reStructuredText.')
[ "def", "lint_help", "(", "tool_xml", ",", "lint_ctx", ")", ":", "root", "=", "tool_xml", ".", "getroot", "(", ")", "helps", "=", "root", ".", "findall", "(", "'help'", ")", "if", "(", "len", "(", "helps", ")", ">", "1", ")", ":", "lint_ctx", ".", "error", "(", "'More than one help section found, behavior undefined.'", ")", "return", "if", "(", "len", "(", "helps", ")", "==", "0", ")", ":", "lint_ctx", ".", "warn", "(", "'No help section found, consider adding a help section to your tool.'", ")", "return", "help", "=", "(", "helps", "[", "0", "]", ".", "text", "or", "''", ")", "if", "(", "not", "help", ".", "strip", "(", ")", ")", ":", "lint_ctx", ".", "warn", "(", "'Help section appears to be empty.'", ")", "return", "lint_ctx", ".", "valid", "(", "'Tool contains help section.'", ")", "invalid_rst", "=", "rst_invalid", "(", "help", ")", "if", "(", "'TODO'", "in", "help", ")", ":", "lint_ctx", ".", "warn", "(", "'Help contains TODO text.'", ")", "if", "invalid_rst", ":", "lint_ctx", ".", "warn", "(", "(", "'Invalid reStructuredText found in help - [%s].'", "%", "invalid_rst", ")", ")", "else", ":", "lint_ctx", ".", "valid", "(", "'Help contains valid reStructuredText.'", ")" ]
ensure tool contains exactly one valid rst help block .
train
false
47,137
def authenticator(function, challenges=()): challenges = (challenges or ('{} realm="simple"'.format(function.__name__),)) def wrapper(verify_user): def authenticate(request, response, **kwargs): result = function(request, response, verify_user, **kwargs) if (result is None): raise HTTPUnauthorized('Authentication Required', 'Please provide valid {0} credentials'.format(function.__doc__.splitlines()[0]), challenges=challenges) if (result is False): raise HTTPUnauthorized('Invalid Authentication', 'Provided {0} credentials were invalid'.format(function.__doc__.splitlines()[0]), challenges=challenges) request.context['user'] = result return True authenticate.__doc__ = function.__doc__ return authenticate return wrapper
[ "def", "authenticator", "(", "function", ",", "challenges", "=", "(", ")", ")", ":", "challenges", "=", "(", "challenges", "or", "(", "'{} realm=\"simple\"'", ".", "format", "(", "function", ".", "__name__", ")", ",", ")", ")", "def", "wrapper", "(", "verify_user", ")", ":", "def", "authenticate", "(", "request", ",", "response", ",", "**", "kwargs", ")", ":", "result", "=", "function", "(", "request", ",", "response", ",", "verify_user", ",", "**", "kwargs", ")", "if", "(", "result", "is", "None", ")", ":", "raise", "HTTPUnauthorized", "(", "'Authentication Required'", ",", "'Please provide valid {0} credentials'", ".", "format", "(", "function", ".", "__doc__", ".", "splitlines", "(", ")", "[", "0", "]", ")", ",", "challenges", "=", "challenges", ")", "if", "(", "result", "is", "False", ")", ":", "raise", "HTTPUnauthorized", "(", "'Invalid Authentication'", ",", "'Provided {0} credentials were invalid'", ".", "format", "(", "function", ".", "__doc__", ".", "splitlines", "(", ")", "[", "0", "]", ")", ",", "challenges", "=", "challenges", ")", "request", ".", "context", "[", "'user'", "]", "=", "result", "return", "True", "authenticate", ".", "__doc__", "=", "function", ".", "__doc__", "return", "authenticate", "return", "wrapper" ]
wraps authentication logic .
train
true
47,138
def my_evalf(expr, chop=False): if isinstance(expr, list): try: return [x.evalf(chop=chop) for x in expr] except Exception: return expr try: return expr.evalf(chop=chop) except Exception: return expr
[ "def", "my_evalf", "(", "expr", ",", "chop", "=", "False", ")", ":", "if", "isinstance", "(", "expr", ",", "list", ")", ":", "try", ":", "return", "[", "x", ".", "evalf", "(", "chop", "=", "chop", ")", "for", "x", "in", "expr", "]", "except", "Exception", ":", "return", "expr", "try", ":", "return", "expr", ".", "evalf", "(", "chop", "=", "chop", ")", "except", "Exception", ":", "return", "expr" ]
enhanced sympy evalf to handle lists of expressions and catch eval failures without dropping out .
train
false
47,139
def collate(expression, collation): expr = _literal_as_binds(expression) return BinaryExpression(expr, _literal_as_text(collation), operators.collate, type_=expr.type)
[ "def", "collate", "(", "expression", ",", "collation", ")", ":", "expr", "=", "_literal_as_binds", "(", "expression", ")", "return", "BinaryExpression", "(", "expr", ",", "_literal_as_text", "(", "collation", ")", ",", "operators", ".", "collate", ",", "type_", "=", "expr", ".", "type", ")" ]
return the clause expression collate collation .
train
false
47,140
def linear_recurrence(n, (a, b)=(2, 0), (u0, u1)=(1, 1)): i = 0 (u, v) = (u0, u1) while (i < n): w = ((a * v) + (b * u)) (u, v) = (v, w) i += 1 return w
[ "def", "linear_recurrence", "(", "n", ",", "(", "a", ",", "b", ")", "=", "(", "2", ",", "0", ")", ",", "(", "u0", ",", "u1", ")", "=", "(", "1", ",", "1", ")", ")", ":", "i", "=", "0", "(", "u", ",", "v", ")", "=", "(", "u0", ",", "u1", ")", "while", "(", "i", "<", "n", ")", ":", "w", "=", "(", "(", "a", "*", "v", ")", "+", "(", "b", "*", "u", ")", ")", "(", "u", ",", "v", ")", "=", "(", "v", ",", "w", ")", "i", "+=", "1", "return", "w" ]
return nth term of the sequence defined by the linear recurrence u = a*u + b*u(n) .
train
false
47,141
def GetNodeAnnotation(node, annotation, default=None): return getattr(node, (_NODE_ANNOTATION_PREFIX + annotation), default)
[ "def", "GetNodeAnnotation", "(", "node", ",", "annotation", ",", "default", "=", "None", ")", ":", "return", "getattr", "(", "node", ",", "(", "_NODE_ANNOTATION_PREFIX", "+", "annotation", ")", ",", "default", ")" ]
get annotation value from a node .
train
false
47,142
def default_route(family=None): if ((family != 'inet') and (family != 'inet6') and (family is not None)): raise CommandExecutionError('Invalid address family {0}'.format(family)) _routes = routes() default_route = {} if (__grains__['kernel'] == 'Linux'): default_route['inet'] = ['0.0.0.0', 'default'] default_route['inet6'] = ['::/0', 'default'] elif ((__grains__['os'] in ['FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS', 'Darwin']) or (__grains__['kernel'] == 'SunOS')): default_route['inet'] = ['default'] default_route['inet6'] = ['default'] else: raise CommandExecutionError('Not yet supported on this platform') ret = [] for route in _routes: if family: if (route['destination'] in default_route[family]): if ((__grains__['kernel'] == 'SunOS') and (route['addr_family'] != family)): continue ret.append(route) elif ((route['destination'] in default_route['inet']) or (route['destination'] in default_route['inet6'])): ret.append(route) return ret
[ "def", "default_route", "(", "family", "=", "None", ")", ":", "if", "(", "(", "family", "!=", "'inet'", ")", "and", "(", "family", "!=", "'inet6'", ")", "and", "(", "family", "is", "not", "None", ")", ")", ":", "raise", "CommandExecutionError", "(", "'Invalid address family {0}'", ".", "format", "(", "family", ")", ")", "_routes", "=", "routes", "(", ")", "default_route", "=", "{", "}", "if", "(", "__grains__", "[", "'kernel'", "]", "==", "'Linux'", ")", ":", "default_route", "[", "'inet'", "]", "=", "[", "'0.0.0.0'", ",", "'default'", "]", "default_route", "[", "'inet6'", "]", "=", "[", "'::/0'", ",", "'default'", "]", "elif", "(", "(", "__grains__", "[", "'os'", "]", "in", "[", "'FreeBSD'", ",", "'NetBSD'", ",", "'OpenBSD'", ",", "'MacOS'", ",", "'Darwin'", "]", ")", "or", "(", "__grains__", "[", "'kernel'", "]", "==", "'SunOS'", ")", ")", ":", "default_route", "[", "'inet'", "]", "=", "[", "'default'", "]", "default_route", "[", "'inet6'", "]", "=", "[", "'default'", "]", "else", ":", "raise", "CommandExecutionError", "(", "'Not yet supported on this platform'", ")", "ret", "=", "[", "]", "for", "route", "in", "_routes", ":", "if", "family", ":", "if", "(", "route", "[", "'destination'", "]", "in", "default_route", "[", "family", "]", ")", ":", "if", "(", "(", "__grains__", "[", "'kernel'", "]", "==", "'SunOS'", ")", "and", "(", "route", "[", "'addr_family'", "]", "!=", "family", ")", ")", ":", "continue", "ret", ".", "append", "(", "route", ")", "elif", "(", "(", "route", "[", "'destination'", "]", "in", "default_route", "[", "'inet'", "]", ")", "or", "(", "route", "[", "'destination'", "]", "in", "default_route", "[", "'inet6'", "]", ")", ")", ":", "ret", ".", "append", "(", "route", ")", "return", "ret" ]
return default route(s) from routing table .
train
true
47,143
def GenSleep(seconds): io_loop = ioloop.IOLoop.current() return gen.Task(io_loop.add_timeout, (io_loop.time() + seconds))
[ "def", "GenSleep", "(", "seconds", ")", ":", "io_loop", "=", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "return", "gen", ".", "Task", "(", "io_loop", ".", "add_timeout", ",", "(", "io_loop", ".", "time", "(", ")", "+", "seconds", ")", ")" ]
wait for a period of time without blocking .
train
false
47,144
def _is_development_candidate(version): candidate_pos = _get_candidate_pos(version) candidate = version[candidate_pos] candidate_extra = version[(candidate_pos + 1)] return ((candidate == 'alpha') and (candidate_extra == 0))
[ "def", "_is_development_candidate", "(", "version", ")", ":", "candidate_pos", "=", "_get_candidate_pos", "(", "version", ")", "candidate", "=", "version", "[", "candidate_pos", "]", "candidate_extra", "=", "version", "[", "(", "candidate_pos", "+", "1", ")", "]", "return", "(", "(", "candidate", "==", "'alpha'", ")", "and", "(", "candidate_extra", "==", "0", ")", ")" ]
is this a pre-alpha release .
train
false
47,145
def pad_to(data, alignment, pad_character='\xff'): pad_mod = (len(data) % alignment) if (pad_mod != 0): data += (pad_character * (alignment - pad_mod)) return data
[ "def", "pad_to", "(", "data", ",", "alignment", ",", "pad_character", "=", "'\\xff'", ")", ":", "pad_mod", "=", "(", "len", "(", "data", ")", "%", "alignment", ")", "if", "(", "pad_mod", "!=", "0", ")", ":", "data", "+=", "(", "pad_character", "*", "(", "alignment", "-", "pad_mod", ")", ")", "return", "data" ]
pad to the next alignment boundary .
train
true
47,146
def read_utf8(filepath): try: f = codecs.open(filepath, encoding='utf_8', mode='r') except IOError as ioe: sys.stderr.write((("[otmod.py] ERROR: Unable to open '" + filepath) + "' for read.\n")) raise ioe try: textstring = f.read() norm_text = unicodedata.normalize('NFKD', textstring) return norm_text except Exception as e: sys.stderr.write((('[otmod.py] ERROR: Unable to read ' + filepath) + ' with UTF-8 encoding using the read_utf8() method.\n')) raise e finally: f.close()
[ "def", "read_utf8", "(", "filepath", ")", ":", "try", ":", "f", "=", "codecs", ".", "open", "(", "filepath", ",", "encoding", "=", "'utf_8'", ",", "mode", "=", "'r'", ")", "except", "IOError", "as", "ioe", ":", "sys", ".", "stderr", ".", "write", "(", "(", "(", "\"[otmod.py] ERROR: Unable to open '\"", "+", "filepath", ")", "+", "\"' for read.\\n\"", ")", ")", "raise", "ioe", "try", ":", "textstring", "=", "f", ".", "read", "(", ")", "norm_text", "=", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "textstring", ")", "return", "norm_text", "except", "Exception", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "(", "(", "'[otmod.py] ERROR: Unable to read '", "+", "filepath", ")", "+", "' with UTF-8 encoding using the read_utf8() method.\\n'", ")", ")", "raise", "e", "finally", ":", "f", ".", "close", "(", ")" ]
read_utf8() is a function that reads text in as utf-8 nfkd normalized text strings from filepath .
train
false
47,149
def GetBlobStorage(): return apiproxy_stub_map.apiproxy.GetStub('blobstore').storage
[ "def", "GetBlobStorage", "(", ")", ":", "return", "apiproxy_stub_map", ".", "apiproxy", ".", "GetStub", "(", "'blobstore'", ")", ".", "storage" ]
get blob-storage from api-proxy stub map .
train
false
47,150
def _check_accept_keywords(approved, flag): if (flag in approved): return False elif ((flag.startswith('~') and (flag[1:] in approved)) or (('~' + flag) in approved)): return False else: return True
[ "def", "_check_accept_keywords", "(", "approved", ",", "flag", ")", ":", "if", "(", "flag", "in", "approved", ")", ":", "return", "False", "elif", "(", "(", "flag", ".", "startswith", "(", "'~'", ")", "and", "(", "flag", "[", "1", ":", "]", "in", "approved", ")", ")", "or", "(", "(", "'~'", "+", "flag", ")", "in", "approved", ")", ")", ":", "return", "False", "else", ":", "return", "True" ]
check compatibility of accept_keywords .
train
true
47,152
def datetimeToLogString(msSinceEpoch=None): if (msSinceEpoch == None): msSinceEpoch = time.time() (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(msSinceEpoch) s = ('[%02d/%3s/%4d:%02d:%02d:%02d +0000]' % (day, monthname[month], year, hh, mm, ss)) return s
[ "def", "datetimeToLogString", "(", "msSinceEpoch", "=", "None", ")", ":", "if", "(", "msSinceEpoch", "==", "None", ")", ":", "msSinceEpoch", "=", "time", ".", "time", "(", ")", "(", "year", ",", "month", ",", "day", ",", "hh", ",", "mm", ",", "ss", ",", "wd", ",", "y", ",", "z", ")", "=", "time", ".", "gmtime", "(", "msSinceEpoch", ")", "s", "=", "(", "'[%02d/%3s/%4d:%02d:%02d:%02d +0000]'", "%", "(", "day", ",", "monthname", "[", "month", "]", ",", "year", ",", "hh", ",", "mm", ",", "ss", ")", ")", "return", "s" ]
convert seconds since epoch to log datetime string .
train
false
47,153
def _GetTargetsDependingOnMatchingTargets(possible_targets): found = [] print 'Targets that matched by dependency:' for target in possible_targets: if _DoesTargetDependOnMatchingTargets(target): found.append(target) return found
[ "def", "_GetTargetsDependingOnMatchingTargets", "(", "possible_targets", ")", ":", "found", "=", "[", "]", "print", "'Targets that matched by dependency:'", "for", "target", "in", "possible_targets", ":", "if", "_DoesTargetDependOnMatchingTargets", "(", "target", ")", ":", "found", ".", "append", "(", "target", ")", "return", "found" ]
returns the list of targets in |possible_targets| that depend on at least one of the targets containing the files supplied as input to analyzer .
train
false
47,154
def get_attrs_flag(attrs): attrs_flag = 0 if (u'bold' in attrs): attrs_flag |= ATTR_BOLD if (u'italic' in attrs): attrs_flag |= ATTR_ITALIC if (u'underline' in attrs): attrs_flag |= ATTR_UNDERLINE return attrs_flag
[ "def", "get_attrs_flag", "(", "attrs", ")", ":", "attrs_flag", "=", "0", "if", "(", "u'bold'", "in", "attrs", ")", ":", "attrs_flag", "|=", "ATTR_BOLD", "if", "(", "u'italic'", "in", "attrs", ")", ":", "attrs_flag", "|=", "ATTR_ITALIC", "if", "(", "u'underline'", "in", "attrs", ")", ":", "attrs_flag", "|=", "ATTR_UNDERLINE", "return", "attrs_flag" ]
convert an attribute array to a renderer flag .
train
false
47,156
def compute_signature(message, secret): digest_maker = hmac.new(secret, '', hashlib.sha256) for (name, value) in utils.recursive_keypairs(message): if (name == 'message_signature'): continue digest_maker.update(name) digest_maker.update(unicode(value).encode('utf-8')) return digest_maker.hexdigest()
[ "def", "compute_signature", "(", "message", ",", "secret", ")", ":", "digest_maker", "=", "hmac", ".", "new", "(", "secret", ",", "''", ",", "hashlib", ".", "sha256", ")", "for", "(", "name", ",", "value", ")", "in", "utils", ".", "recursive_keypairs", "(", "message", ")", ":", "if", "(", "name", "==", "'message_signature'", ")", ":", "continue", "digest_maker", ".", "update", "(", "name", ")", "digest_maker", ".", "update", "(", "unicode", "(", "value", ")", ".", "encode", "(", "'utf-8'", ")", ")", "return", "digest_maker", ".", "hexdigest", "(", ")" ]
return the signature for a message dictionary .
train
false
47,159
def _parse_char_metrics(fh): ascii_d = {} name_d = {} for line in fh: line = line.rstrip().decode(u'ascii') if line.startswith(u'EndCharMetrics'): return (ascii_d, name_d) vals = dict((s.strip().split(u' ', 1) for s in line.split(u';') if s)) if (not {u'C', u'WX', u'N', u'B'}.issubset(vals)): raise RuntimeError((u'Bad char metrics line: %s' % line)) num = _to_int(vals[u'C']) wx = _to_float(vals[u'WX']) name = vals[u'N'] bbox = _to_list_of_floats(vals[u'B']) bbox = list(map(int, bbox)) if (name == u'Euro'): num = 128 if (num != (-1)): ascii_d[num] = (wx, name, bbox) name_d[name] = (wx, bbox) raise RuntimeError(u'Bad parse')
[ "def", "_parse_char_metrics", "(", "fh", ")", ":", "ascii_d", "=", "{", "}", "name_d", "=", "{", "}", "for", "line", "in", "fh", ":", "line", "=", "line", ".", "rstrip", "(", ")", ".", "decode", "(", "u'ascii'", ")", "if", "line", ".", "startswith", "(", "u'EndCharMetrics'", ")", ":", "return", "(", "ascii_d", ",", "name_d", ")", "vals", "=", "dict", "(", "(", "s", ".", "strip", "(", ")", ".", "split", "(", "u' '", ",", "1", ")", "for", "s", "in", "line", ".", "split", "(", "u';'", ")", "if", "s", ")", ")", "if", "(", "not", "{", "u'C'", ",", "u'WX'", ",", "u'N'", ",", "u'B'", "}", ".", "issubset", "(", "vals", ")", ")", ":", "raise", "RuntimeError", "(", "(", "u'Bad char metrics line: %s'", "%", "line", ")", ")", "num", "=", "_to_int", "(", "vals", "[", "u'C'", "]", ")", "wx", "=", "_to_float", "(", "vals", "[", "u'WX'", "]", ")", "name", "=", "vals", "[", "u'N'", "]", "bbox", "=", "_to_list_of_floats", "(", "vals", "[", "u'B'", "]", ")", "bbox", "=", "list", "(", "map", "(", "int", ",", "bbox", ")", ")", "if", "(", "name", "==", "u'Euro'", ")", ":", "num", "=", "128", "if", "(", "num", "!=", "(", "-", "1", ")", ")", ":", "ascii_d", "[", "num", "]", "=", "(", "wx", ",", "name", ",", "bbox", ")", "name_d", "[", "name", "]", "=", "(", "wx", ",", "bbox", ")", "raise", "RuntimeError", "(", "u'Bad parse'", ")" ]
return a character metric dictionary .
train
false
47,160
def _infer_stmts(stmts, context, frame=None): stmt = None infered = False if (context is not None): name = context.lookupname context = context.clone() else: name = None context = InferenceContext() for stmt in stmts: if (stmt is YES): (yield stmt) infered = True continue context.lookupname = stmt._infer_name(frame, name) try: for infered in stmt.infer(context): (yield infered) infered = True except UnresolvableName: continue except InferenceError: (yield YES) infered = True if (not infered): raise InferenceError(str(stmt))
[ "def", "_infer_stmts", "(", "stmts", ",", "context", ",", "frame", "=", "None", ")", ":", "stmt", "=", "None", "infered", "=", "False", "if", "(", "context", "is", "not", "None", ")", ":", "name", "=", "context", ".", "lookupname", "context", "=", "context", ".", "clone", "(", ")", "else", ":", "name", "=", "None", "context", "=", "InferenceContext", "(", ")", "for", "stmt", "in", "stmts", ":", "if", "(", "stmt", "is", "YES", ")", ":", "(", "yield", "stmt", ")", "infered", "=", "True", "continue", "context", ".", "lookupname", "=", "stmt", ".", "_infer_name", "(", "frame", ",", "name", ")", "try", ":", "for", "infered", "in", "stmt", ".", "infer", "(", "context", ")", ":", "(", "yield", "infered", ")", "infered", "=", "True", "except", "UnresolvableName", ":", "continue", "except", "InferenceError", ":", "(", "yield", "YES", ")", "infered", "=", "True", "if", "(", "not", "infered", ")", ":", "raise", "InferenceError", "(", "str", "(", "stmt", ")", ")" ]
return an iterator on statements inferred by each statement in <stmts> .
train
false
47,162
def _reusing_db(): return (os.getenv('REUSE_DB', 'false').lower() in ('true', '1', ''))
[ "def", "_reusing_db", "(", ")", ":", "return", "(", "os", ".", "getenv", "(", "'REUSE_DB'", ",", "'false'", ")", ".", "lower", "(", ")", "in", "(", "'true'", ",", "'1'", ",", "''", ")", ")" ]
return whether the reuse_db flag was passed .
train
false
47,164
def bytes_to_elementtree(bytes_or_file): if isinstance(bytes_or_file, compat.basestring): s = bytes_or_file else: s = bytes_or_file.read() if compat.is_py3: s = _unicode(s, 'utf-8') f = compat.StringIO(s) tree = ET.ElementTree(file=f) return tree
[ "def", "bytes_to_elementtree", "(", "bytes_or_file", ")", ":", "if", "isinstance", "(", "bytes_or_file", ",", "compat", ".", "basestring", ")", ":", "s", "=", "bytes_or_file", "else", ":", "s", "=", "bytes_or_file", ".", "read", "(", ")", "if", "compat", ".", "is_py3", ":", "s", "=", "_unicode", "(", "s", ",", "'utf-8'", ")", "f", "=", "compat", ".", "StringIO", "(", "s", ")", "tree", "=", "ET", ".", "ElementTree", "(", "file", "=", "f", ")", "return", "tree" ]
given a bytestring or a file-like object that will produce them .
train
false
47,165
def spectral_bipartivity(G, nodes=None, weight='weight'): try: import scipy.linalg except ImportError: raise ImportError('spectral_bipartivity() requires SciPy: ', 'http://scipy.org/') nodelist = list(G) A = nx.to_numpy_matrix(G, nodelist, weight=weight) expA = scipy.linalg.expm(A) expmA = scipy.linalg.expm((- A)) coshA = (0.5 * (expA + expmA)) if (nodes is None): return (coshA.diagonal().sum() / expA.diagonal().sum()) else: index = dict(zip(nodelist, range(len(nodelist)))) sb = {} for n in nodes: i = index[n] sb[n] = (coshA[(i, i)] / expA[(i, i)]) return sb
[ "def", "spectral_bipartivity", "(", "G", ",", "nodes", "=", "None", ",", "weight", "=", "'weight'", ")", ":", "try", ":", "import", "scipy", ".", "linalg", "except", "ImportError", ":", "raise", "ImportError", "(", "'spectral_bipartivity() requires SciPy: '", ",", "'http://scipy.org/'", ")", "nodelist", "=", "list", "(", "G", ")", "A", "=", "nx", ".", "to_numpy_matrix", "(", "G", ",", "nodelist", ",", "weight", "=", "weight", ")", "expA", "=", "scipy", ".", "linalg", ".", "expm", "(", "A", ")", "expmA", "=", "scipy", ".", "linalg", ".", "expm", "(", "(", "-", "A", ")", ")", "coshA", "=", "(", "0.5", "*", "(", "expA", "+", "expmA", ")", ")", "if", "(", "nodes", "is", "None", ")", ":", "return", "(", "coshA", ".", "diagonal", "(", ")", ".", "sum", "(", ")", "/", "expA", ".", "diagonal", "(", ")", ".", "sum", "(", ")", ")", "else", ":", "index", "=", "dict", "(", "zip", "(", "nodelist", ",", "range", "(", "len", "(", "nodelist", ")", ")", ")", ")", "sb", "=", "{", "}", "for", "n", "in", "nodes", ":", "i", "=", "index", "[", "n", "]", "sb", "[", "n", "]", "=", "(", "coshA", "[", "(", "i", ",", "i", ")", "]", "/", "expA", "[", "(", "i", ",", "i", ")", "]", ")", "return", "sb" ]
returns the spectral bipartivity .
train
false
47,168
def vibrate(pattern, repeat=None): PythonActivity = jnius.autoclass('org.renpy.android.PythonService') Context = jnius.autoclass('android.content.Context') activity = PythonActivity.mService vibrator = activity.getSystemService(Context.VIBRATOR_SERVICE) if vibrator.hasVibrator(): try: if repeat: vibrator.vibrate(list(pattern), repeat) else: vibrator.vibrate(list(pattern), (-1)) except KeyboardInterrupt: vibrator.cancel() raise else: raise RuntimeError('The device does not have a vibrator')
[ "def", "vibrate", "(", "pattern", ",", "repeat", "=", "None", ")", ":", "PythonActivity", "=", "jnius", ".", "autoclass", "(", "'org.renpy.android.PythonService'", ")", "Context", "=", "jnius", ".", "autoclass", "(", "'android.content.Context'", ")", "activity", "=", "PythonActivity", ".", "mService", "vibrator", "=", "activity", ".", "getSystemService", "(", "Context", ".", "VIBRATOR_SERVICE", ")", "if", "vibrator", ".", "hasVibrator", "(", ")", ":", "try", ":", "if", "repeat", ":", "vibrator", ".", "vibrate", "(", "list", "(", "pattern", ")", ",", "repeat", ")", "else", ":", "vibrator", ".", "vibrate", "(", "list", "(", "pattern", ")", ",", "(", "-", "1", ")", ")", "except", "KeyboardInterrupt", ":", "vibrator", ".", "cancel", "(", ")", "raise", "else", ":", "raise", "RuntimeError", "(", "'The device does not have a vibrator'", ")" ]
take a list of int as pattern .
train
false
47,170
def memory_usage(): return _GetSystemStats().memory()
[ "def", "memory_usage", "(", ")", ":", "return", "_GetSystemStats", "(", ")", ".", "memory", "(", ")" ]
returns a systemstat describing memory usage .
train
false
47,172
def isBin(s): for i in s: i = ord(i) if (i < 9): return True elif ((i > 13) and (i < 32)): return True elif (i > 126): return True return False
[ "def", "isBin", "(", "s", ")", ":", "for", "i", "in", "s", ":", "i", "=", "ord", "(", "i", ")", "if", "(", "i", "<", "9", ")", ":", "return", "True", "elif", "(", "(", "i", ">", "13", ")", "and", "(", "i", "<", "32", ")", ")", ":", "return", "True", "elif", "(", "i", ">", "126", ")", ":", "return", "True", "return", "False" ]
does this string have any non-ascii characters? .
train
false
47,173
def collect_merged_date_field(block_structure, transformer, xblock_field_name, merged_field_name, default_date, func_merge_parents=min, func_merge_ancestors=max): for block_key in block_structure.topological_traversal(): parents = block_structure.get_parents(block_key) block_date = get_field_on_block(block_structure.get_xblock(block_key), xblock_field_name) if (not parents): merged_date_value = (block_date or default_date) else: merged_all_parents_date = func_merge_parents((block_structure.get_transformer_block_field(parent_key, transformer, merged_field_name, default_date) for parent_key in parents)) if (not block_date): merged_date_value = merged_all_parents_date else: merged_date_value = func_merge_ancestors(merged_all_parents_date, block_date) block_structure.set_transformer_block_field(block_key, transformer, merged_field_name, merged_date_value)
[ "def", "collect_merged_date_field", "(", "block_structure", ",", "transformer", ",", "xblock_field_name", ",", "merged_field_name", ",", "default_date", ",", "func_merge_parents", "=", "min", ",", "func_merge_ancestors", "=", "max", ")", ":", "for", "block_key", "in", "block_structure", ".", "topological_traversal", "(", ")", ":", "parents", "=", "block_structure", ".", "get_parents", "(", "block_key", ")", "block_date", "=", "get_field_on_block", "(", "block_structure", ".", "get_xblock", "(", "block_key", ")", ",", "xblock_field_name", ")", "if", "(", "not", "parents", ")", ":", "merged_date_value", "=", "(", "block_date", "or", "default_date", ")", "else", ":", "merged_all_parents_date", "=", "func_merge_parents", "(", "(", "block_structure", ".", "get_transformer_block_field", "(", "parent_key", ",", "transformer", ",", "merged_field_name", ",", "default_date", ")", "for", "parent_key", "in", "parents", ")", ")", "if", "(", "not", "block_date", ")", ":", "merged_date_value", "=", "merged_all_parents_date", "else", ":", "merged_date_value", "=", "func_merge_ancestors", "(", "merged_all_parents_date", ",", "block_date", ")", "block_structure", ".", "set_transformer_block_field", "(", "block_key", ",", "transformer", ",", "merged_field_name", ",", "merged_date_value", ")" ]
collects a date xblock field of name xblock_field_name for the given block_structure and transformer .
train
false
47,174
@register(u'downcase-word') def downcase_word(event): buff = event.current_buffer for i in range(event.arg): pos = buff.document.find_next_word_ending() words = buff.document.text_after_cursor[:pos] buff.insert_text(words.lower(), overwrite=True)
[ "@", "register", "(", "u'downcase-word'", ")", "def", "downcase_word", "(", "event", ")", ":", "buff", "=", "event", ".", "current_buffer", "for", "i", "in", "range", "(", "event", ".", "arg", ")", ":", "pos", "=", "buff", ".", "document", ".", "find_next_word_ending", "(", ")", "words", "=", "buff", ".", "document", ".", "text_after_cursor", "[", ":", "pos", "]", "buff", ".", "insert_text", "(", "words", ".", "lower", "(", ")", ",", "overwrite", "=", "True", ")" ]
lowercase the current word .
train
true
47,175
def transform_xy_coords(xy_coords, sc_plot): sorted_keys = xy_coords.keys() all_cids = [] all_xcoords = [] all_ycoords = [] sc_plot.set_transform(sc_plot.axes.transData) trans = sc_plot.get_transform() for s_label in sorted_keys: s_data = xy_coords[s_label] if (s_data[0] == []): pass else: icoords = trans.transform(zip(s_data[0], s_data[1])) (xcoords, ycoords) = zip(*icoords) all_cids.extend(s_data[2]) all_xcoords.extend(xcoords) all_ycoords.extend(ycoords) return (all_cids, all_xcoords, all_ycoords)
[ "def", "transform_xy_coords", "(", "xy_coords", ",", "sc_plot", ")", ":", "sorted_keys", "=", "xy_coords", ".", "keys", "(", ")", "all_cids", "=", "[", "]", "all_xcoords", "=", "[", "]", "all_ycoords", "=", "[", "]", "sc_plot", ".", "set_transform", "(", "sc_plot", ".", "axes", ".", "transData", ")", "trans", "=", "sc_plot", ".", "get_transform", "(", ")", "for", "s_label", "in", "sorted_keys", ":", "s_data", "=", "xy_coords", "[", "s_label", "]", "if", "(", "s_data", "[", "0", "]", "==", "[", "]", ")", ":", "pass", "else", ":", "icoords", "=", "trans", ".", "transform", "(", "zip", "(", "s_data", "[", "0", "]", ",", "s_data", "[", "1", "]", ")", ")", "(", "xcoords", ",", "ycoords", ")", "=", "zip", "(", "*", "icoords", ")", "all_cids", ".", "extend", "(", "s_data", "[", "2", "]", ")", "all_xcoords", ".", "extend", "(", "xcoords", ")", "all_ycoords", ".", "extend", "(", "ycoords", ")", "return", "(", "all_cids", ",", "all_xcoords", ",", "all_ycoords", ")" ]
transform the coords from the scatterplot into coords that can be referenced in the html page .
train
false
47,179
def detect_language(text): translate_client = translate.Client() result = translate_client.detect_language(text) print 'Text: {}'.format(text) print 'Confidence: {}'.format(result['confidence']) print 'Language: {}'.format(result['language'])
[ "def", "detect_language", "(", "text", ")", ":", "translate_client", "=", "translate", ".", "Client", "(", ")", "result", "=", "translate_client", ".", "detect_language", "(", "text", ")", "print", "'Text: {}'", ".", "format", "(", "text", ")", "print", "'Confidence: {}'", ".", "format", "(", "result", "[", "'confidence'", "]", ")", "print", "'Language: {}'", ".", "format", "(", "result", "[", "'language'", "]", ")" ]
detects the texts language .
train
false
47,180
def _create_namespace(namespace, apiserver_url): url = '{0}/api/v1/namespaces'.format(apiserver_url) data = {'kind': 'Namespace', 'apiVersion': 'v1', 'metadata': {'name': namespace}} log.trace('namespace creation requests: {0}'.format(data)) ret = _kpost(url, data) log.trace('result is: {0}'.format(ret)) return ret
[ "def", "_create_namespace", "(", "namespace", ",", "apiserver_url", ")", ":", "url", "=", "'{0}/api/v1/namespaces'", ".", "format", "(", "apiserver_url", ")", "data", "=", "{", "'kind'", ":", "'Namespace'", ",", "'apiVersion'", ":", "'v1'", ",", "'metadata'", ":", "{", "'name'", ":", "namespace", "}", "}", "log", ".", "trace", "(", "'namespace creation requests: {0}'", ".", "format", "(", "data", ")", ")", "ret", "=", "_kpost", "(", "url", ",", "data", ")", "log", ".", "trace", "(", "'result is: {0}'", ".", "format", "(", "ret", ")", ")", "return", "ret" ]
create namespace on the defined k8s cluster .
train
true
47,181
def test_hsl_to_rgb_part_11(): assert (hsl_to_rgb(240, 20, 50) == (102, 102, 153)) assert (hsl_to_rgb(240, 60, 50) == (51, 51, 204)) assert (hsl_to_rgb(240, 100, 50) == (0, 0, 255))
[ "def", "test_hsl_to_rgb_part_11", "(", ")", ":", "assert", "(", "hsl_to_rgb", "(", "240", ",", "20", ",", "50", ")", "==", "(", "102", ",", "102", ",", "153", ")", ")", "assert", "(", "hsl_to_rgb", "(", "240", ",", "60", ",", "50", ")", "==", "(", "51", ",", "51", ",", "204", ")", ")", "assert", "(", "hsl_to_rgb", "(", "240", ",", "100", ",", "50", ")", "==", "(", "0", ",", "0", ",", "255", ")", ")" ]
test hsl to rgb color function .
train
false
47,182
def create_line(data): return Line(data, x='year', y=countries, legend=True, width=1400, height=300, ylabel='Energy use per capita', palette=['purple', 'green', 'blue', 'pink'])
[ "def", "create_line", "(", "data", ")", ":", "return", "Line", "(", "data", ",", "x", "=", "'year'", ",", "y", "=", "countries", ",", "legend", "=", "True", ",", "width", "=", "1400", ",", "height", "=", "300", ",", "ylabel", "=", "'Energy use per capita'", ",", "palette", "=", "[", "'purple'", ",", "'green'", ",", "'blue'", ",", "'pink'", "]", ")" ]
convenience function to create a new line chart with the right args .
train
false
47,183
@require_POST @login_required @permitted def unfollow_thread(request, course_id, thread_id): user = cc.User.from_django_user(request.user) thread = cc.Thread.find(thread_id) user.unfollow(thread) return JsonResponse({})
[ "@", "require_POST", "@", "login_required", "@", "permitted", "def", "unfollow_thread", "(", "request", ",", "course_id", ",", "thread_id", ")", ":", "user", "=", "cc", ".", "User", ".", "from_django_user", "(", "request", ".", "user", ")", "thread", "=", "cc", ".", "Thread", ".", "find", "(", "thread_id", ")", "user", ".", "unfollow", "(", "thread", ")", "return", "JsonResponse", "(", "{", "}", ")" ]
given a course id and thread id .
train
false
47,184
@given('the default tags "{default_tags:TagExpression}"') def step_given_the_tag_expression(context, default_tags): context.default_tags = default_tags tag_expression = getattr(context, 'tag_expression', None) if (tag_expression is None): context.tag_expression = default_tags
[ "@", "given", "(", "'the default tags \"{default_tags:TagExpression}\"'", ")", "def", "step_given_the_tag_expression", "(", "context", ",", "default_tags", ")", ":", "context", ".", "default_tags", "=", "default_tags", "tag_expression", "=", "getattr", "(", "context", ",", "'tag_expression'", ",", "None", ")", "if", "(", "tag_expression", "is", "None", ")", ":", "context", ".", "tag_expression", "=", "default_tags" ]
define a tag expression that is used later-on .
train
false
47,185
def submit_delete_entrance_exam_state_for_student(request, usage_key, student): modulestore().get_item(usage_key) milestones_helpers.remove_course_content_user_milestones(course_key=usage_key.course_key, content_key=usage_key, user=student, relationship='fulfills') task_type = 'delete_problem_state' task_class = delete_problem_state (task_input, task_key) = encode_entrance_exam_and_student_input(usage_key, student) return submit_task(request, task_type, task_class, usage_key.course_key, task_input, task_key)
[ "def", "submit_delete_entrance_exam_state_for_student", "(", "request", ",", "usage_key", ",", "student", ")", ":", "modulestore", "(", ")", ".", "get_item", "(", "usage_key", ")", "milestones_helpers", ".", "remove_course_content_user_milestones", "(", "course_key", "=", "usage_key", ".", "course_key", ",", "content_key", "=", "usage_key", ",", "user", "=", "student", ",", "relationship", "=", "'fulfills'", ")", "task_type", "=", "'delete_problem_state'", "task_class", "=", "delete_problem_state", "(", "task_input", ",", "task_key", ")", "=", "encode_entrance_exam_and_student_input", "(", "usage_key", ",", "student", ")", "return", "submit_task", "(", "request", ",", "task_type", ",", "task_class", ",", "usage_key", ".", "course_key", ",", "task_input", ",", "task_key", ")" ]
requests reset of state for entrance exam as a background task .
train
false
47,186
def lc_choose(index, *args): try: return args[(int(index) - 1)] except Exception as err: pass if len(args): return args[0] raise Exception('loncapa_check.lc_choose error, index={index}, args={args}'.format(index=index, args=args))
[ "def", "lc_choose", "(", "index", ",", "*", "args", ")", ":", "try", ":", "return", "args", "[", "(", "int", "(", "index", ")", "-", "1", ")", "]", "except", "Exception", "as", "err", ":", "pass", "if", "len", "(", "args", ")", ":", "return", "args", "[", "0", "]", "raise", "Exception", "(", "'loncapa_check.lc_choose error, index={index}, args={args}'", ".", "format", "(", "index", "=", "index", ",", "args", "=", "args", ")", ")" ]
return args[index] .
train
false
47,187
def test_rotation(): tests = [(0, 0, 1), (0.5, 0.5, 0.5), (np.pi, 0, (-1.5))] for rot in tests: (x, y, z) = rot m = rotation3d(x, y, z) m4 = rotation(x, y, z) assert_array_equal(m, m4[:3, :3]) back = rotation_angles(m) assert_equal(back, rot) back4 = rotation_angles(m4) assert_equal(back4, rot)
[ "def", "test_rotation", "(", ")", ":", "tests", "=", "[", "(", "0", ",", "0", ",", "1", ")", ",", "(", "0.5", ",", "0.5", ",", "0.5", ")", ",", "(", "np", ".", "pi", ",", "0", ",", "(", "-", "1.5", ")", ")", "]", "for", "rot", "in", "tests", ":", "(", "x", ",", "y", ",", "z", ")", "=", "rot", "m", "=", "rotation3d", "(", "x", ",", "y", ",", "z", ")", "m4", "=", "rotation", "(", "x", ",", "y", ",", "z", ")", "assert_array_equal", "(", "m", ",", "m4", "[", ":", "3", ",", ":", "3", "]", ")", "back", "=", "rotation_angles", "(", "m", ")", "assert_equal", "(", "back", ",", "rot", ")", "back4", "=", "rotation_angles", "(", "m4", ")", "assert_equal", "(", "back4", ",", "rot", ")" ]
test conversion between rotation angles and transformation matrix .
train
false
47,188
def file_list(load): if ('env' in load): salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.") load.pop('env') ret = [] if ('saltenv' not in load): return ret saltenv = load['saltenv'] metadata = _init() if ((not metadata) or (saltenv not in metadata)): return ret for buckets in six.itervalues(_find_files(metadata[saltenv])): files = [f for f in buckets if (not fs.is_file_ignored(__opts__, f))] ret += _trim_env_off_path(files, saltenv) return ret
[ "def", "file_list", "(", "load", ")", ":", "if", "(", "'env'", "in", "load", ")", ":", "salt", ".", "utils", ".", "warn_until", "(", "'Oxygen'", ",", "\"Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.\"", ")", "load", ".", "pop", "(", "'env'", ")", "ret", "=", "[", "]", "if", "(", "'saltenv'", "not", "in", "load", ")", ":", "return", "ret", "saltenv", "=", "load", "[", "'saltenv'", "]", "metadata", "=", "_init", "(", ")", "if", "(", "(", "not", "metadata", ")", "or", "(", "saltenv", "not", "in", "metadata", ")", ")", ":", "return", "ret", "for", "buckets", "in", "six", ".", "itervalues", "(", "_find_files", "(", "metadata", "[", "saltenv", "]", ")", ")", ":", "files", "=", "[", "f", "for", "f", "in", "buckets", "if", "(", "not", "fs", ".", "is_file_ignored", "(", "__opts__", ",", "f", ")", ")", "]", "ret", "+=", "_trim_env_off_path", "(", "files", ",", "saltenv", ")", "return", "ret" ]
return a list of all files on the file server in a specified environment .
train
true
47,189
def WaitForServiceStatus(serviceName, status, waitSecs, machine=None): for i in range((waitSecs * 4)): now_status = QueryServiceStatus(serviceName, machine)[1] if (now_status == status): break win32api.Sleep(250) else: raise pywintypes.error, (winerror.ERROR_SERVICE_REQUEST_TIMEOUT, 'QueryServiceStatus', win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:(-2)])
[ "def", "WaitForServiceStatus", "(", "serviceName", ",", "status", ",", "waitSecs", ",", "machine", "=", "None", ")", ":", "for", "i", "in", "range", "(", "(", "waitSecs", "*", "4", ")", ")", ":", "now_status", "=", "QueryServiceStatus", "(", "serviceName", ",", "machine", ")", "[", "1", "]", "if", "(", "now_status", "==", "status", ")", ":", "break", "win32api", ".", "Sleep", "(", "250", ")", "else", ":", "raise", "pywintypes", ".", "error", ",", "(", "winerror", ".", "ERROR_SERVICE_REQUEST_TIMEOUT", ",", "'QueryServiceStatus'", ",", "win32api", ".", "FormatMessage", "(", "winerror", ".", "ERROR_SERVICE_REQUEST_TIMEOUT", ")", "[", ":", "(", "-", "2", ")", "]", ")" ]
waits for the service to return the specified status .
train
false
47,190
def iglob(pathname): (dirname, basename) = os.path.split(pathname) if (not has_magic(pathname)): if basename: if os.path.lexists(pathname): (yield pathname) elif os.path.isdir(dirname): (yield pathname) return if (not dirname): for name in glob1(os.curdir, basename): (yield name) return if ((dirname != pathname) and has_magic(dirname)): dirs = iglob(dirname) else: dirs = [dirname] if has_magic(basename): glob_in_dir = glob1 else: glob_in_dir = glob0 for dirname in dirs: for name in glob_in_dir(dirname, basename): (yield os.path.join(dirname, name))
[ "def", "iglob", "(", "pathname", ")", ":", "(", "dirname", ",", "basename", ")", "=", "os", ".", "path", ".", "split", "(", "pathname", ")", "if", "(", "not", "has_magic", "(", "pathname", ")", ")", ":", "if", "basename", ":", "if", "os", ".", "path", ".", "lexists", "(", "pathname", ")", ":", "(", "yield", "pathname", ")", "elif", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "(", "yield", "pathname", ")", "return", "if", "(", "not", "dirname", ")", ":", "for", "name", "in", "glob1", "(", "os", ".", "curdir", ",", "basename", ")", ":", "(", "yield", "name", ")", "return", "if", "(", "(", "dirname", "!=", "pathname", ")", "and", "has_magic", "(", "dirname", ")", ")", ":", "dirs", "=", "iglob", "(", "dirname", ")", "else", ":", "dirs", "=", "[", "dirname", "]", "if", "has_magic", "(", "basename", ")", ":", "glob_in_dir", "=", "glob1", "else", ":", "glob_in_dir", "=", "glob0", "for", "dirname", "in", "dirs", ":", "for", "name", "in", "glob_in_dir", "(", "dirname", ",", "basename", ")", ":", "(", "yield", "os", ".", "path", ".", "join", "(", "dirname", ",", "name", ")", ")" ]
extended globbing function that supports ** and {opt1 .
train
true
47,191
def is_number(n): return (type(n) in (IntType, LongType, FloatType))
[ "def", "is_number", "(", "n", ")", ":", "return", "(", "type", "(", "n", ")", "in", "(", "IntType", ",", "LongType", ",", "FloatType", ")", ")" ]
determines if it is a number or not returns: type .
train
false
47,192
def stop_tomcat(): run_as_root('/etc/init.d/tomcat stop')
[ "def", "stop_tomcat", "(", ")", ":", "run_as_root", "(", "'/etc/init.d/tomcat stop'", ")" ]
stop the tomcat service .
train
false
47,194
def delete_empty_folders(check_empty_dir, keep_dir=None): ignore_items = [] sickrage.srCore.srLogger.info((u'Trying to clean any empty folders under ' + check_empty_dir)) try: while (os.path.isdir(check_empty_dir) and (check_empty_dir != keep_dir)): check_files = os.listdir(check_empty_dir) if ((not check_files) or ((len(check_files) <= len(ignore_items)) and all([(check_file in ignore_items) for check_file in check_files]))): try: sickrage.srCore.srLogger.info((u'Deleting empty folder: ' + check_empty_dir)) os.rmdir(check_empty_dir) sickrage.srCore.notifiersDict.synoindex_notifier.deleteFolder(check_empty_dir) except OSError as e: sickrage.srCore.srLogger.warning((u'Unable to delete %s. Error: %r' % (check_empty_dir, repr(e)))) raise StopIteration check_empty_dir = os.path.dirname(check_empty_dir) else: raise StopIteration except StopIteration: pass
[ "def", "delete_empty_folders", "(", "check_empty_dir", ",", "keep_dir", "=", "None", ")", ":", "ignore_items", "=", "[", "]", "sickrage", ".", "srCore", ".", "srLogger", ".", "info", "(", "(", "u'Trying to clean any empty folders under '", "+", "check_empty_dir", ")", ")", "try", ":", "while", "(", "os", ".", "path", ".", "isdir", "(", "check_empty_dir", ")", "and", "(", "check_empty_dir", "!=", "keep_dir", ")", ")", ":", "check_files", "=", "os", ".", "listdir", "(", "check_empty_dir", ")", "if", "(", "(", "not", "check_files", ")", "or", "(", "(", "len", "(", "check_files", ")", "<=", "len", "(", "ignore_items", ")", ")", "and", "all", "(", "[", "(", "check_file", "in", "ignore_items", ")", "for", "check_file", "in", "check_files", "]", ")", ")", ")", ":", "try", ":", "sickrage", ".", "srCore", ".", "srLogger", ".", "info", "(", "(", "u'Deleting empty folder: '", "+", "check_empty_dir", ")", ")", "os", ".", "rmdir", "(", "check_empty_dir", ")", "sickrage", ".", "srCore", ".", "notifiersDict", ".", "synoindex_notifier", ".", "deleteFolder", "(", "check_empty_dir", ")", "except", "OSError", "as", "e", ":", "sickrage", ".", "srCore", ".", "srLogger", ".", "warning", "(", "(", "u'Unable to delete %s. Error: %r'", "%", "(", "check_empty_dir", ",", "repr", "(", "e", ")", ")", ")", ")", "raise", "StopIteration", "check_empty_dir", "=", "os", ".", "path", ".", "dirname", "(", "check_empty_dir", ")", "else", ":", "raise", "StopIteration", "except", "StopIteration", ":", "pass" ]
walks backwards up the path and deletes any empty folders found .
train
false
47,195
def unregister_alias_type(klass): return ALIAS_TYPES.pop(klass, None)
[ "def", "unregister_alias_type", "(", "klass", ")", ":", "return", "ALIAS_TYPES", ".", "pop", "(", "klass", ",", "None", ")" ]
removes the klass from the l{alias_types} register .
train
false
47,196
def camelcase_to_underscores(argument): result = u'' prev_char_title = True for char in argument: if (char.istitle() and (not prev_char_title)): result += u'_' prev_char_title = char.istitle() if (not char.isspace()): result += char.lower() return result
[ "def", "camelcase_to_underscores", "(", "argument", ")", ":", "result", "=", "u''", "prev_char_title", "=", "True", "for", "char", "in", "argument", ":", "if", "(", "char", ".", "istitle", "(", ")", "and", "(", "not", "prev_char_title", ")", ")", ":", "result", "+=", "u'_'", "prev_char_title", "=", "char", ".", "istitle", "(", ")", "if", "(", "not", "char", ".", "isspace", "(", ")", ")", ":", "result", "+=", "char", ".", "lower", "(", ")", "return", "result" ]
converts a camelcase param like thenewattribute to the equivalent python underscore variable like the_new_attribute .
train
false
47,197
def merge_cache_over_settings(destination, setting, key_prefix): existing = destination.settings.get(setting, {}) value = get_cache(((key_prefix + '.') + setting), {}) if value: existing.update(value) destination.settings[setting] = existing
[ "def", "merge_cache_over_settings", "(", "destination", ",", "setting", ",", "key_prefix", ")", ":", "existing", "=", "destination", ".", "settings", ".", "get", "(", "setting", ",", "{", "}", ")", "value", "=", "get_cache", "(", "(", "(", "key_prefix", "+", "'.'", ")", "+", "setting", ")", ",", "{", "}", ")", "if", "value", ":", "existing", ".", "update", "(", "value", ")", "destination", ".", "settings", "[", "setting", "]", "=", "existing" ]
take the cached value of key and put it into the key setting of the destination .
train
false
47,201
def get_online_users(guest=False): current = (int(time.time()) // 60) minutes = range_method(flaskbb_config['ONLINE_LAST_MINUTES']) if guest: return redis_store.sunion([('online-guests/%d' % (current - x)) for x in minutes]) return redis_store.sunion([('online-users/%d' % (current - x)) for x in minutes])
[ "def", "get_online_users", "(", "guest", "=", "False", ")", ":", "current", "=", "(", "int", "(", "time", ".", "time", "(", ")", ")", "//", "60", ")", "minutes", "=", "range_method", "(", "flaskbb_config", "[", "'ONLINE_LAST_MINUTES'", "]", ")", "if", "guest", ":", "return", "redis_store", ".", "sunion", "(", "[", "(", "'online-guests/%d'", "%", "(", "current", "-", "x", ")", ")", "for", "x", "in", "minutes", "]", ")", "return", "redis_store", ".", "sunion", "(", "[", "(", "'online-users/%d'", "%", "(", "current", "-", "x", ")", ")", "for", "x", "in", "minutes", "]", ")" ]
returns all online users within a specified time range .
train
false
47,203
def ipAdd(i, prefixLen=8, ipBaseNum=167772160): imax = (4294967295 >> prefixLen) assert (i <= imax), 'Not enough IP addresses in the subnet' mask = (4294967295 ^ imax) ipnum = ((ipBaseNum & mask) + i) return ipStr(ipnum)
[ "def", "ipAdd", "(", "i", ",", "prefixLen", "=", "8", ",", "ipBaseNum", "=", "167772160", ")", ":", "imax", "=", "(", "4294967295", ">>", "prefixLen", ")", "assert", "(", "i", "<=", "imax", ")", ",", "'Not enough IP addresses in the subnet'", "mask", "=", "(", "4294967295", "^", "imax", ")", "ipnum", "=", "(", "(", "ipBaseNum", "&", "mask", ")", "+", "i", ")", "return", "ipStr", "(", "ipnum", ")" ]
return ip address string from ints i: int to be added to ipbase prefixlen: optional ip prefix length ipbasenum: option base ip address as int returns ip address as string .
train
false