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
17,655
def reset_worker_optimizations(): global trace_task_ret trace_task_ret = _trace_task_ret try: delattr(BaseTask, u'_stackprotected') except AttributeError: pass try: BaseTask.__call__ = _patched.pop(u'BaseTask.__call__') except KeyError: pass from celery.worker import request as request_module request_mo...
[ "def", "reset_worker_optimizations", "(", ")", ":", "global", "trace_task_ret", "trace_task_ret", "=", "_trace_task_ret", "try", ":", "delattr", "(", "BaseTask", ",", "u'_stackprotected'", ")", "except", "AttributeError", ":", "pass", "try", ":", "BaseTask", ".", ...
reset previously configured optimizations .
train
false
17,656
def nopackage(pkg_name): if is_installed(pkg_name): uninstall(pkg_name)
[ "def", "nopackage", "(", "pkg_name", ")", ":", "if", "is_installed", "(", "pkg_name", ")", ":", "uninstall", "(", "pkg_name", ")" ]
require an rpm package to be uninstalled .
train
false
17,657
def fetch_requirements(requirements_file_path): links = [] reqs = [] for req in parse_requirements(requirements_file_path, session=False): if req.link: links.append(str(req.link)) reqs.append(str(req.req)) return (reqs, links)
[ "def", "fetch_requirements", "(", "requirements_file_path", ")", ":", "links", "=", "[", "]", "reqs", "=", "[", "]", "for", "req", "in", "parse_requirements", "(", "requirements_file_path", ",", "session", "=", "False", ")", ":", "if", "req", ".", "link", ...
return a list of requirements and links by parsing the provided requirements file .
train
false
17,658
def concatenate3(arrays): arrays = concrete(arrays) ndim = ndimlist(arrays) if (not ndim): return arrays if (not arrays): return np.empty(0) chunks = chunks_from_arrays(arrays) shape = tuple(map(sum, chunks)) def dtype(x): try: return x.dtype except AttributeError: return type(x) result = np.empty...
[ "def", "concatenate3", "(", "arrays", ")", ":", "arrays", "=", "concrete", "(", "arrays", ")", "ndim", "=", "ndimlist", "(", "arrays", ")", "if", "(", "not", "ndim", ")", ":", "return", "arrays", "if", "(", "not", "arrays", ")", ":", "return", "np", ...
recursive np .
train
false
17,659
def find_file(path, saltenv='base', **kwargs): if ('env' in kwargs): 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.") kwargs.pop('env') ...
[ "def", "find_file", "(", "path", ",", "saltenv", "=", "'base'", ",", "**", "kwargs", ")", ":", "if", "(", "'env'", "in", "kwargs", ")", ":", "salt", ".", "utils", ".", "warn_until", "(", "'Oxygen'", ",", "\"Parameter 'env' has been detected in the argument lis...
recursively find matching file from the current working path .
train
true
17,660
def start_version(module, version): rpc = start_version_async(module, version) rpc.get_result()
[ "def", "start_version", "(", "module", ",", "version", ")", ":", "rpc", "=", "start_version_async", "(", "module", ",", "version", ")", "rpc", ".", "get_result", "(", ")" ]
start all instances for the given version of the module .
train
false
17,661
def _is_national_number_suffix_of_other(numobj1, numobj2): nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) return (nn1.endswith(nn2) or nn2.endswith(nn1))
[ "def", "_is_national_number_suffix_of_other", "(", "numobj1", ",", "numobj2", ")", ":", "nn1", "=", "str", "(", "numobj1", ".", "national_number", ")", "nn2", "=", "str", "(", "numobj2", ".", "national_number", ")", "return", "(", "nn1", ".", "endswith", "("...
returns true when one national number is the suffix of the other or both are the same .
train
true
17,662
def rotation_angles(m): x = np.arctan2(m[(2, 1)], m[(2, 2)]) c2 = np.sqrt(((m[(0, 0)] ** 2) + (m[(1, 0)] ** 2))) y = np.arctan2((- m[(2, 0)]), c2) s1 = np.sin(x) c1 = np.cos(x) z = np.arctan2(((s1 * m[(0, 2)]) - (c1 * m[(0, 1)])), ((c1 * m[(1, 1)]) - (s1 * m[(1, 2)]))) return (x, y, z)
[ "def", "rotation_angles", "(", "m", ")", ":", "x", "=", "np", ".", "arctan2", "(", "m", "[", "(", "2", ",", "1", ")", "]", ",", "m", "[", "(", "2", ",", "2", ")", "]", ")", "c2", "=", "np", ".", "sqrt", "(", "(", "(", "m", "[", "(", "...
find rotation angles from a transformation matrix .
train
false
17,663
def _jobs(): response = salt.utils.http.query('{0}/scheduler/jobs'.format(_base_url()), decode_type='json', decode=True) jobs = {} for job in response['dict']: jobs[job.pop('name')] = job return jobs
[ "def", "_jobs", "(", ")", ":", "response", "=", "salt", ".", "utils", ".", "http", ".", "query", "(", "'{0}/scheduler/jobs'", ".", "format", "(", "_base_url", "(", ")", ")", ",", "decode_type", "=", "'json'", ",", "decode", "=", "True", ")", "jobs", ...
return the currently configured jobs .
train
true
17,664
def get_next_url_for_login_page(request): redirect_to = request.GET.get('next', None) if (redirect_to and (not http.is_safe_url(redirect_to))): log.error(u'Unsafe redirect parameter detected: %(redirect_to)r', {'redirect_to': redirect_to}) redirect_to = None if (not redirect_to): try: redirect_to = reverse(...
[ "def", "get_next_url_for_login_page", "(", "request", ")", ":", "redirect_to", "=", "request", ".", "GET", ".", "get", "(", "'next'", ",", "None", ")", "if", "(", "redirect_to", "and", "(", "not", "http", ".", "is_safe_url", "(", "redirect_to", ")", ")", ...
determine the url to redirect to following login/registration/third_party_auth the user is currently on a login or registration page .
train
false
17,665
def cycle_list(k, n): k = (k % n) return (list(range(k, n)) + list(range(k)))
[ "def", "cycle_list", "(", "k", ",", "n", ")", ":", "k", "=", "(", "k", "%", "n", ")", "return", "(", "list", "(", "range", "(", "k", ",", "n", ")", ")", "+", "list", "(", "range", "(", "k", ")", ")", ")" ]
returns the elements of the list range(n) shifted to the left by k (so the list starts with k ) .
train
false
17,666
def jssafe(text=u''): if (text.__class__ != unicode): text = _force_unicode(text) return _Unsafe(text.translate(_js_escapes))
[ "def", "jssafe", "(", "text", "=", "u''", ")", ":", "if", "(", "text", ".", "__class__", "!=", "unicode", ")", ":", "text", "=", "_force_unicode", "(", "text", ")", "return", "_Unsafe", "(", "text", ".", "translate", "(", "_js_escapes", ")", ")" ]
prevents text from breaking outside of string literals in js .
train
false
17,668
def action_event_start(context, values): return IMPL.action_event_start(context, values)
[ "def", "action_event_start", "(", "context", ",", "values", ")", ":", "return", "IMPL", ".", "action_event_start", "(", "context", ",", "values", ")" ]
start an event on an instance action .
train
false
17,669
def check_regexs(filename, matchers): extras = [] for expressions in matchers: (expression, extramatchers) = expressions match1 = expression.search(filename) if match1: for m in extramatchers: match2 = m.findall(filename, match1.end()) if match2: for match in match2: if ((type(match) == ty...
[ "def", "check_regexs", "(", "filename", ",", "matchers", ")", ":", "extras", "=", "[", "]", "for", "expressions", "in", "matchers", ":", "(", "expression", ",", "extramatchers", ")", "=", "expressions", "match1", "=", "expression", ".", "search", "(", "fil...
regular expression match for a list of regexes returns the matchobject if a match is made this version checks for an additional match .
train
false
17,670
def prefix_indexes(config): if hasattr(config, 'slaveinput'): prefix = 'test_{[slaveid]}'.format(config.slaveinput) else: prefix = 'test' for (key, index) in settings.ES_INDEXES.items(): if (not index.startswith(prefix)): settings.ES_INDEXES[key] = '{prefix}_amo_{index}'.format(prefix=prefix, index=index) ...
[ "def", "prefix_indexes", "(", "config", ")", ":", "if", "hasattr", "(", "config", ",", "'slaveinput'", ")", ":", "prefix", "=", "'test_{[slaveid]}'", ".", "format", "(", "config", ".", "slaveinput", ")", "else", ":", "prefix", "=", "'test'", "for", "(", ...
prefix all es index names and cache keys with test_ and .
train
false
17,671
@docfiller def whosmat(file_name, appendmat=True, **kwargs): ML = mat_reader_factory(file_name, **kwargs) variables = ML.list_variables() if isinstance(file_name, string_types): ML.mat_stream.close() return variables
[ "@", "docfiller", "def", "whosmat", "(", "file_name", ",", "appendmat", "=", "True", ",", "**", "kwargs", ")", ":", "ML", "=", "mat_reader_factory", "(", "file_name", ",", "**", "kwargs", ")", "variables", "=", "ML", ".", "list_variables", "(", ")", "if"...
list variables inside a matlab file .
train
false
17,672
def get_code2lang_map(lang_code=None, force=False): global CODE2LANG_MAP if (force or (not CODE2LANG_MAP)): lmap = softload_json(settings.LANG_LOOKUP_FILEPATH, logger=logging.debug) CODE2LANG_MAP = {} for (lc, entry) in lmap.iteritems(): CODE2LANG_MAP[lcode_to_ietf(lc)] = entry return (CODE2LANG_MAP.get(lco...
[ "def", "get_code2lang_map", "(", "lang_code", "=", "None", ",", "force", "=", "False", ")", ":", "global", "CODE2LANG_MAP", "if", "(", "force", "or", "(", "not", "CODE2LANG_MAP", ")", ")", ":", "lmap", "=", "softload_json", "(", "settings", ".", "LANG_LOOK...
given a language code .
train
false
17,673
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get new repository .
train
false
17,676
def flattenString(request, root): io = StringIO() d = flatten(request, root, io.write) d.addCallback((lambda _: io.getvalue())) return d
[ "def", "flattenString", "(", "request", ",", "root", ")", ":", "io", "=", "StringIO", "(", ")", "d", "=", "flatten", "(", "request", ",", "root", ",", "io", ".", "write", ")", "d", ".", "addCallback", "(", "(", "lambda", "_", ":", "io", ".", "get...
collate a string representation of c{root} into a single string .
train
false
17,677
def adjusted_mutual_info_score(labels_true, labels_pred): (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) n_samples = labels_true.shape[0] classes = np.unique(labels_true) clusters = np.unique(labels_pred) if ((classes.shape[0] == clusters.shape[0] == 1) or (classes.shape[0] == clusters.sh...
[ "def", "adjusted_mutual_info_score", "(", "labels_true", ",", "labels_pred", ")", ":", "(", "labels_true", ",", "labels_pred", ")", "=", "check_clusterings", "(", "labels_true", ",", "labels_pred", ")", "n_samples", "=", "labels_true", ".", "shape", "[", "0", "]...
adjusted mutual information between two clusterings .
train
false
17,678
def replace_nonprintables(string): new_string = '' modified = 0 for c in string: o = ord(c) if (o <= 31): new_string += ('^' + chr((ord('@') + o))) modified += 1 elif (o == 127): new_string += '^?' modified += 1 else: new_string += c if (modified and (S3.Config.Config().urlencoding_mode != 'f...
[ "def", "replace_nonprintables", "(", "string", ")", ":", "new_string", "=", "''", "modified", "=", "0", "for", "c", "in", "string", ":", "o", "=", "ord", "(", "c", ")", "if", "(", "o", "<=", "31", ")", ":", "new_string", "+=", "(", "'^'", "+", "c...
replace_nonprintables replaces all non-printable characters ch in string where ord <= 26 with ^@ .
train
false
17,679
def handle_sigint(signal, frame): for thread in threading.enumerate(): if thread.isAlive(): thread._Thread__stop() sys.exit(0)
[ "def", "handle_sigint", "(", "signal", ",", "frame", ")", ":", "for", "thread", "in", "threading", ".", "enumerate", "(", ")", ":", "if", "thread", ".", "isAlive", "(", ")", ":", "thread", ".", "_Thread__stop", "(", ")", "sys", ".", "exit", "(", "0",...
attempt to kill all child threads and exit .
train
false
17,680
def strategy_connected_sequential_dfs(G, colors): return strategy_connected_sequential(G, colors, 'dfs')
[ "def", "strategy_connected_sequential_dfs", "(", "G", ",", "colors", ")", ":", "return", "strategy_connected_sequential", "(", "G", ",", "colors", ",", "'dfs'", ")" ]
returns an iterable over nodes in g in the order given by a depth-first traversal .
train
false
17,681
def mod_run_check_cmd(cmd, filename, **check_cmd_opts): log.debug('running our check_cmd') _cmd = '{0} {1}'.format(cmd, filename) cret = __salt__['cmd.run_all'](_cmd, **check_cmd_opts) if (cret['retcode'] != 0): ret = {'comment': 'check_cmd execution failed', 'skip_watch': True, 'result': False} if cret.get('st...
[ "def", "mod_run_check_cmd", "(", "cmd", ",", "filename", ",", "**", "check_cmd_opts", ")", ":", "log", ".", "debug", "(", "'running our check_cmd'", ")", "_cmd", "=", "'{0} {1}'", ".", "format", "(", "cmd", ",", "filename", ")", "cret", "=", "__salt__", "[...
execute the check_cmd logic .
train
true
17,682
def pre_upgrade(name): if (name not in _tracker['pre_upgrade']): return False return _tracker['pre_upgrade'][name]
[ "def", "pre_upgrade", "(", "name", ")", ":", "if", "(", "name", "not", "in", "_tracker", "[", "'pre_upgrade'", "]", ")", ":", "return", "False", "return", "_tracker", "[", "'pre_upgrade'", "]", "[", "name", "]" ]
check if a package is about to be upgraded (in plugin_unloaded()) .
train
false
17,683
def send_commit(): return s3db.req_send_commit()
[ "def", "send_commit", "(", ")", ":", "return", "s3db", ".", "req_send_commit", "(", ")" ]
send a shipment containing all items in a commitment .
train
false
17,684
def sql_destroy_indexes(app, style, connection): output = [] for model in models.get_models(app, include_auto_created=True): output.extend(connection.creation.sql_destroy_indexes_for_model(model, style)) return output
[ "def", "sql_destroy_indexes", "(", "app", ",", "style", ",", "connection", ")", ":", "output", "=", "[", "]", "for", "model", "in", "models", ".", "get_models", "(", "app", ",", "include_auto_created", "=", "True", ")", ":", "output", ".", "extend", "(",...
returns a list of the drop index sql statements for all models in the given app .
train
false
17,685
@real_memoize def is_freebsd(): return sys.platform.startswith('freebsd')
[ "@", "real_memoize", "def", "is_freebsd", "(", ")", ":", "return", "sys", ".", "platform", ".", "startswith", "(", "'freebsd'", ")" ]
simple function to return if host is freebsd or not .
train
false
17,686
def to_dict_of_dicts(G, nodelist=None, edge_data=None): dod = {} if (nodelist is None): if (edge_data is None): for (u, nbrdict) in G.adjacency(): dod[u] = nbrdict.copy() else: for (u, nbrdict) in G.adjacency(): dod[u] = dod.fromkeys(nbrdict, edge_data) elif (edge_data is None): for u in nodelist...
[ "def", "to_dict_of_dicts", "(", "G", ",", "nodelist", "=", "None", ",", "edge_data", "=", "None", ")", ":", "dod", "=", "{", "}", "if", "(", "nodelist", "is", "None", ")", ":", "if", "(", "edge_data", "is", "None", ")", ":", "for", "(", "u", ",",...
return adjacency representation of graph as a dictionary of dictionaries .
train
false
17,688
def group_connections(connections): grouped_conns = defaultdict(list) if isinstance(connections, QuerySet): languages = connections.values_list('contact__language', flat=True) for language in languages.distinct(): lang_conns = connections.filter(contact__language=language) grouped_conns[language].extend(lan...
[ "def", "group_connections", "(", "connections", ")", ":", "grouped_conns", "=", "defaultdict", "(", "list", ")", "if", "isinstance", "(", "connections", ",", "QuerySet", ")", ":", "languages", "=", "connections", ".", "values_list", "(", "'contact__language'", "...
return a list of pairs .
train
false
17,690
def unique_window(iterable, window, key=None): seen = collections.deque(maxlen=window) seen_add = seen.append if (key is None): for element in iterable: if (element not in seen): (yield element) seen_add(element) else: for element in iterable: k = key(element) if (k not in seen): (yield elem...
[ "def", "unique_window", "(", "iterable", ",", "window", ",", "key", "=", "None", ")", ":", "seen", "=", "collections", ".", "deque", "(", "maxlen", "=", "window", ")", "seen_add", "=", "seen", ".", "append", "if", "(", "key", "is", "None", ")", ":", ...
unique_everseen -> iterator get unique elements .
train
false
17,692
@should_dump_processes def start_process_dump(): dump_data_every_thread(dump_processes, DELAY_MINUTES, SAVE_PROCESS_PTR)
[ "@", "should_dump_processes", "def", "start_process_dump", "(", ")", ":", "dump_data_every_thread", "(", "dump_processes", ",", "DELAY_MINUTES", ",", "SAVE_PROCESS_PTR", ")" ]
if the environment variable w3af_processes is set to 1 .
train
false
17,693
def _stream_encoding(stream, default='utf-8'): encoding = config['terminal_encoding'].get() if encoding: return encoding if (not hasattr(stream, 'encoding')): return default return (stream.encoding or default)
[ "def", "_stream_encoding", "(", "stream", ",", "default", "=", "'utf-8'", ")", ":", "encoding", "=", "config", "[", "'terminal_encoding'", "]", ".", "get", "(", ")", "if", "encoding", ":", "return", "encoding", "if", "(", "not", "hasattr", "(", "stream", ...
a helper for _in_encoding and _out_encoding: get the streams preferred encoding .
train
false
17,694
def bw_usage_get_by_uuids(context, uuids, start_period): return IMPL.bw_usage_get_by_uuids(context, uuids, start_period)
[ "def", "bw_usage_get_by_uuids", "(", "context", ",", "uuids", ",", "start_period", ")", ":", "return", "IMPL", ".", "bw_usage_get_by_uuids", "(", "context", ",", "uuids", ",", "start_period", ")" ]
return bw usages for instance(s) in a given audit period .
train
false
17,695
def block_device_mapping_update(context, bdm_id, values, legacy=True): return IMPL.block_device_mapping_update(context, bdm_id, values, legacy)
[ "def", "block_device_mapping_update", "(", "context", ",", "bdm_id", ",", "values", ",", "legacy", "=", "True", ")", ":", "return", "IMPL", ".", "block_device_mapping_update", "(", "context", ",", "bdm_id", ",", "values", ",", "legacy", ")" ]
update an entry of block device mapping .
train
false
17,701
@check_login_required @check_local_site_access def download_orig_file(*args, **kwargs): return _download_diff_file(False, *args, **kwargs)
[ "@", "check_login_required", "@", "check_local_site_access", "def", "download_orig_file", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "_download_diff_file", "(", "False", ",", "*", "args", ",", "**", "kwargs", ")" ]
downloads an original file from a diff .
train
false
17,703
def scalar_potential(field, frame): if (not is_conservative(field)): raise ValueError('Field is not conservative') if (field == Vector(0)): return S(0) _check_frame(frame) field = express(field, frame, variables=True) dimensions = [x for x in frame] temp_function = integrate(field.dot(dimensions[0]), frame[0]...
[ "def", "scalar_potential", "(", "field", ",", "frame", ")", ":", "if", "(", "not", "is_conservative", "(", "field", ")", ")", ":", "raise", "ValueError", "(", "'Field is not conservative'", ")", "if", "(", "field", "==", "Vector", "(", "0", ")", ")", ":"...
returns the scalar potential function of a field in a given coordinate system .
train
false
17,706
def gaussian_nll(x, mean, ln_var): assert isinstance(x, variable.Variable) assert isinstance(mean, variable.Variable) assert isinstance(ln_var, variable.Variable) D = x.size x_prec = exponential.exp((- ln_var)) x_diff = (x - mean) x_power = (((x_diff * x_diff) * x_prec) * (-0.5)) return (((sum.sum(ln_var) + (D ...
[ "def", "gaussian_nll", "(", "x", ",", "mean", ",", "ln_var", ")", ":", "assert", "isinstance", "(", "x", ",", "variable", ".", "Variable", ")", "assert", "isinstance", "(", "mean", ",", "variable", ".", "Variable", ")", "assert", "isinstance", "(", "ln_v...
computes the negative log-likelihood of a gaussian distribution .
train
false
17,707
def set_current_comp(info, comp): comp_now = get_current_comp(info) for (k, chan) in enumerate(info['chs']): if (chan['kind'] == FIFF.FIFFV_MEG_CH): rem = (chan['coil_type'] - (comp_now << 16)) chan['coil_type'] = int((rem + (comp << 16)))
[ "def", "set_current_comp", "(", "info", ",", "comp", ")", ":", "comp_now", "=", "get_current_comp", "(", "info", ")", "for", "(", "k", ",", "chan", ")", "in", "enumerate", "(", "info", "[", "'chs'", "]", ")", ":", "if", "(", "chan", "[", "'kind'", ...
set the current compensation in effect in the data .
train
false
17,708
def save_to_db(item, msg='Saved to db', print_error=True): try: logging.info(msg) db.session.add(item) logging.info('added to session') db.session.commit() return True except Exception as e: if print_error: print e traceback.print_exc() logging.error(('DB Exception! %s' % e)) db.session.rollback...
[ "def", "save_to_db", "(", "item", ",", "msg", "=", "'Saved to db'", ",", "print_error", "=", "True", ")", ":", "try", ":", "logging", ".", "info", "(", "msg", ")", "db", ".", "session", ".", "add", "(", "item", ")", "logging", ".", "info", "(", "'a...
convenience function to wrap a proper db save .
train
false
17,711
def nice_size(size, include_bytes=False): niced = False nice_string = ('%s bytes' % size) try: nsize = Decimal(size) for x in ['bytes', 'KB', 'MB', 'GB']: if (nsize.compare(Decimal('1024.0')) == Decimal('-1')): nice_string = ('%3.1f %s' % (nsize, x)) niced = True break nsize /= Decimal('1024.0'...
[ "def", "nice_size", "(", "size", ",", "include_bytes", "=", "False", ")", ":", "niced", "=", "False", "nice_string", "=", "(", "'%s bytes'", "%", "size", ")", "try", ":", "nsize", "=", "Decimal", "(", "size", ")", "for", "x", "in", "[", "'bytes'", ",...
returns a readably formatted string with the size .
train
false
17,712
def is_position_inf(pos1, pos2): return (pos1 < pos2)
[ "def", "is_position_inf", "(", "pos1", ",", "pos2", ")", ":", "return", "(", "pos1", "<", "pos2", ")" ]
return true is pos1 < pos2 .
train
false
17,713
def load_tile_features(lock, host, port, path_fmt, tiles, features): while True: try: tile = tiles.pop() except IndexError: break conn = HTTPConnection(host, port) head = {'Accept-Encoding': 'gzip'} path = (path_fmt % tile) conn.request('GET', path, headers=head) resp = conn.getresponse() file = ...
[ "def", "load_tile_features", "(", "lock", ",", "host", ",", "port", ",", "path_fmt", ",", "tiles", ",", "features", ")", ":", "while", "True", ":", "try", ":", "tile", "=", "tiles", ".", "pop", "(", ")", "except", "IndexError", ":", "break", "conn", ...
load data from tiles to features .
train
false
17,714
def dmp_rr_lcm(f, g, u, K): (fc, f) = dmp_ground_primitive(f, u, K) (gc, g) = dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h = dmp_quo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h, c, u, K)
[ "def", "dmp_rr_lcm", "(", "f", ",", "g", ",", "u", ",", "K", ")", ":", "(", "fc", ",", "f", ")", "=", "dmp_ground_primitive", "(", "f", ",", "u", ",", "K", ")", "(", "gc", ",", "g", ")", "=", "dmp_ground_primitive", "(", "g", ",", "u", ",", ...
computes polynomial lcm over a ring in k[x] .
train
false
17,716
def makeopts_contains(value): return var_contains('MAKEOPTS', value)
[ "def", "makeopts_contains", "(", "value", ")", ":", "return", "var_contains", "(", "'MAKEOPTS'", ",", "value", ")" ]
verify if makeopts variable contains a value in make .
train
false
17,717
def text_filter(regex_base, value): regex = (regex_base % {u're_cap': u'[a-zA-Z0-9\\.\\,:;/_ \\(\\)\\-\\!\\?"]+', u're_img': u'[a-zA-Z0-9\\.:/_\\-\\% ]+'}) images = re.findall(regex, value) for i in images: image = i[1] if image.startswith(settings.MEDIA_URL): image = image[len(settings.MEDIA_URL):] im = ge...
[ "def", "text_filter", "(", "regex_base", ",", "value", ")", ":", "regex", "=", "(", "regex_base", "%", "{", "u're_cap'", ":", "u'[a-zA-Z0-9\\\\.\\\\,:;/_ \\\\(\\\\)\\\\-\\\\!\\\\?\"]+'", ",", "u're_img'", ":", "u'[a-zA-Z0-9\\\\.:/_\\\\-\\\\% ]+'", "}", ")", "images", ...
helper method to regex replace images with captions in different markups .
train
false
17,718
def text_blocks_to_pandas(reader, block_lists, header, head, kwargs, collection=True, enforce=False): dtypes = head.dtypes.to_dict() columns = list(head.columns) delayed_pandas_read_text = delayed(pandas_read_text) dfs = [] for blocks in block_lists: if (not blocks): continue df = delayed_pandas_read_text(r...
[ "def", "text_blocks_to_pandas", "(", "reader", ",", "block_lists", ",", "header", ",", "head", ",", "kwargs", ",", "collection", "=", "True", ",", "enforce", "=", "False", ")", ":", "dtypes", "=", "head", ".", "dtypes", ".", "to_dict", "(", ")", "columns...
convert blocks of bytes to a dask .
train
false
17,719
def database(dburl=None, **params): dbn = params.pop('dbn') if (dbn in _databases): return _databases[dbn](**params) else: raise UnknownDB, dbn
[ "def", "database", "(", "dburl", "=", "None", ",", "**", "params", ")", ":", "dbn", "=", "params", ".", "pop", "(", "'dbn'", ")", "if", "(", "dbn", "in", "_databases", ")", ":", "return", "_databases", "[", "dbn", "]", "(", "**", "params", ")", "...
database setup .
train
false
17,720
@login_required @require_POST @xframe_options_sameorigin def upload_async(request, media_type='image'): try: if (media_type == 'image'): file_info = upload_image(request) else: msg = _(u'Unrecognized media type.') return HttpResponseBadRequest(json.dumps({'status': 'error', 'message': msg})) except FileT...
[ "@", "login_required", "@", "require_POST", "@", "xframe_options_sameorigin", "def", "upload_async", "(", "request", ",", "media_type", "=", "'image'", ")", ":", "try", ":", "if", "(", "media_type", "==", "'image'", ")", ":", "file_info", "=", "upload_image", ...
upload images or videos from request .
train
false
17,722
def set_enabled_units(units): context = _UnitContext(equivalencies=get_current_unit_registry().equivalencies) get_current_unit_registry().set_enabled_units(units) return context
[ "def", "set_enabled_units", "(", "units", ")", ":", "context", "=", "_UnitContext", "(", "equivalencies", "=", "get_current_unit_registry", "(", ")", ".", "equivalencies", ")", "get_current_unit_registry", "(", ")", ".", "set_enabled_units", "(", "units", ")", "re...
sets the units enabled in the unit registry .
train
false
17,725
def circmean(samples, high=(2 * pi), low=0, axis=None): (samples, ang) = _circfuncs_common(samples, high, low) S = sin(ang).sum(axis=axis) C = cos(ang).sum(axis=axis) res = arctan2(S, C) mask = (res < 0) if (mask.ndim > 0): res[mask] += (2 * pi) elif mask: res += (2 * pi) return ((((res * (high - low)) / 2....
[ "def", "circmean", "(", "samples", ",", "high", "=", "(", "2", "*", "pi", ")", ",", "low", "=", "0", ",", "axis", "=", "None", ")", ":", "(", "samples", ",", "ang", ")", "=", "_circfuncs_common", "(", "samples", ",", "high", ",", "low", ")", "S...
computes the circular mean angle of an array of circular data .
train
false
17,726
def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix) return _delete_using_thumbs_list(thumbs)
[ "def", "delete_thumbnails", "(", "relative_source_path", ",", "root", "=", "None", ",", "basedir", "=", "None", ",", "subdir", "=", "None", ",", "prefix", "=", "None", ")", ":", "thumbs", "=", "thumbnails_for_file", "(", "relative_source_path", ",", "root", ...
delete all thumbnails for a source image .
train
true
17,727
def map_dict_keys(dict_, key_map): mapped = {} for (key, value) in dict_.iteritems(): mapped_key = (key_map[key] if (key in key_map) else key) mapped[mapped_key] = value return mapped
[ "def", "map_dict_keys", "(", "dict_", ",", "key_map", ")", ":", "mapped", "=", "{", "}", "for", "(", "key", ",", "value", ")", "in", "dict_", ".", "iteritems", "(", ")", ":", "mapped_key", "=", "(", "key_map", "[", "key", "]", "if", "(", "key", "...
return a dict in which the dictionaries keys are mapped to new keys .
train
false
17,729
def generate_names(): adjectives = ['Exquisite', 'Delicious', 'Elegant', 'Swanky', 'Spicy', 'Food Truck', 'Artisanal', 'Tasty'] nouns = ['Sandwich', 'Pizza', 'Curry', 'Pierogi', 'Sushi', 'Salad', 'Stew', 'Pasta', 'Barbeque', 'Bacon', 'Pancake', 'Waffle', 'Chocolate', 'Gyro', 'Cookie', 'Burrito', 'Pie'] return [' '.j...
[ "def", "generate_names", "(", ")", ":", "adjectives", "=", "[", "'Exquisite'", ",", "'Delicious'", ",", "'Elegant'", ",", "'Swanky'", ",", "'Spicy'", ",", "'Food Truck'", ",", "'Artisanal'", ",", "'Tasty'", "]", "nouns", "=", "[", "'Sandwich'", ",", "'Pizza'...
generate a list of random adjective + noun strings .
train
false
17,730
def linkify(text, nofollow=True, target=None, filter_url=identity, filter_text=identity, skip_pre=False, parse_email=False, tokenizer=HTMLSanitizer): text = force_unicode(text) if (not text): return u'' parser = html5lib.HTMLParser(tokenizer=tokenizer) forest = parser.parseFragment(text) if nofollow: rel = u'r...
[ "def", "linkify", "(", "text", ",", "nofollow", "=", "True", ",", "target", "=", "None", ",", "filter_url", "=", "identity", ",", "filter_text", "=", "identity", ",", "skip_pre", "=", "False", ",", "parse_email", "=", "False", ",", "tokenizer", "=", "HTM...
adds the documentation site root to doc paths .
train
false
17,731
def accept_key(pki_dir, pub, id_): for key_dir in ('minions', 'minions_pre', 'minions_rejected'): key_path = os.path.join(pki_dir, key_dir) if (not os.path.exists(key_path)): os.makedirs(key_path) key = os.path.join(pki_dir, 'minions', id_) with salt.utils.fopen(key, 'w+') as fp_: fp_.write(pub) oldkey = o...
[ "def", "accept_key", "(", "pki_dir", ",", "pub", ",", "id_", ")", ":", "for", "key_dir", "in", "(", "'minions'", ",", "'minions_pre'", ",", "'minions_rejected'", ")", ":", "key_path", "=", "os", ".", "path", ".", "join", "(", "pki_dir", ",", "key_dir", ...
if the master config was available then we will have a pki_dir key in the opts directory .
train
true
17,732
def worker_edit(worker, lbn, settings, profile='default'): settings['cmd'] = 'update' settings['mime'] = 'prop' settings['w'] = lbn settings['sw'] = worker return (_do_http(settings, profile)['worker.result.type'] == 'OK')
[ "def", "worker_edit", "(", "worker", ",", "lbn", ",", "settings", ",", "profile", "=", "'default'", ")", ":", "settings", "[", "'cmd'", "]", "=", "'update'", "settings", "[", "'mime'", "]", "=", "'prop'", "settings", "[", "'w'", "]", "=", "lbn", "setti...
edit the worker settings note: URL data parameters for the standard update action cli examples: .
train
true
17,733
def write_request_load_scenario(reactor, cluster, request_rate=10, sample_size=DEFAULT_SAMPLE_SIZE, timeout=45, tolerance_percentage=0.2): return RequestLoadScenario(reactor, WriteRequest(reactor, cluster.get_control_service(reactor)), request_rate=request_rate, sample_size=sample_size, timeout=timeout, tolerance_perc...
[ "def", "write_request_load_scenario", "(", "reactor", ",", "cluster", ",", "request_rate", "=", "10", ",", "sample_size", "=", "DEFAULT_SAMPLE_SIZE", ",", "timeout", "=", "45", ",", "tolerance_percentage", "=", "0.2", ")", ":", "return", "RequestLoadScenario", "("...
factory that will initialise and return a scenario that places load on the cluster by performing write requests at a specified rate .
train
false
17,734
def check_key_path_and_mode(provider, key_path): if (not os.path.exists(key_path)): log.error("The key file '{0}' used in the '{1}' provider configuration does not exist.\n".format(key_path, provider)) return False key_mode = str(oct(stat.S_IMODE(os.stat(key_path).st_mode))) if (key_mode not in ('0400', '0600'))...
[ "def", "check_key_path_and_mode", "(", "provider", ",", "key_path", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "key_path", ")", ")", ":", "log", ".", "error", "(", "\"The key file '{0}' used in the '{1}' provider configuration does not exist....
checks that the key_path exists and the key_mode is either 0400 or 0600 .
train
true
17,736
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None): from matplotlib import figure from matplotlib.backends import backend_agg if (prop is None): prop = FontProperties() parser = MathTextParser(u'path') (width, height, depth, _, _) = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(fig...
[ "def", "math_to_image", "(", "s", ",", "filename_or_obj", ",", "prop", "=", "None", ",", "dpi", "=", "None", ",", "format", "=", "None", ")", ":", "from", "matplotlib", "import", "figure", "from", "matplotlib", ".", "backends", "import", "backend_agg", "if...
given a math expression .
train
true
17,737
def assert_array_index_eq(left, right): assert_eq(left, (pd.Index(right) if isinstance(right, np.ndarray) else right))
[ "def", "assert_array_index_eq", "(", "left", ",", "right", ")", ":", "assert_eq", "(", "left", ",", "(", "pd", ".", "Index", "(", "right", ")", "if", "isinstance", "(", "right", ",", "np", ".", "ndarray", ")", "else", "right", ")", ")" ]
left and right are equal .
train
false
17,740
@default_selem def erosion(image, selem=None, out=None, shift_x=False, shift_y=False): selem = np.array(selem) selem = _shift_selem(selem, shift_x, shift_y) if (out is None): out = np.empty_like(image) ndi.grey_erosion(image, footprint=selem, output=out) return out
[ "@", "default_selem", "def", "erosion", "(", "image", ",", "selem", "=", "None", ",", "out", "=", "None", ",", "shift_x", "=", "False", ",", "shift_y", "=", "False", ")", ":", "selem", "=", "np", ".", "array", "(", "selem", ")", "selem", "=", "_shi...
return greyscale morphological erosion of an image .
train
false
17,741
def job_get_by_id(job_id): try: job = Job.objects.get(pk=job_id) return job except Job.DoesNotExist: return None
[ "def", "job_get_by_id", "(", "job_id", ")", ":", "try", ":", "job", "=", "Job", ".", "objects", ".", "get", "(", "pk", "=", "job_id", ")", "return", "job", "except", "Job", ".", "DoesNotExist", ":", "return", "None" ]
return a job based on its id .
train
false
17,742
def read_uint16(fid): return _unpack_simple(fid, '>u2', np.uint16)
[ "def", "read_uint16", "(", "fid", ")", ":", "return", "_unpack_simple", "(", "fid", ",", "'>u2'", ",", "np", ".", "uint16", ")" ]
read unsigned 16bit integer from bti file .
train
false
17,743
def on_create(connection): def on_connect(session): session.on_join(on_join) session.join(u'public') connection.on_connect(on_connect)
[ "def", "on_create", "(", "connection", ")", ":", "def", "on_connect", "(", "session", ")", ":", "session", ".", "on_join", "(", "on_join", ")", "session", ".", "join", "(", "u'public'", ")", "connection", ".", "on_connect", "(", "on_connect", ")" ]
this is the main entry into user code .
train
false
17,744
def iterate_base4(d): return product(xrange(4), repeat=d)
[ "def", "iterate_base4", "(", "d", ")", ":", "return", "product", "(", "xrange", "(", "4", ")", ",", "repeat", "=", "d", ")" ]
iterates over a base 4 number with d digits .
train
false
17,745
def sync_ldap_groups(connection, failed_users=None): groups = Group.objects.filter(group__in=LdapGroup.objects.all()) for group in groups: _import_ldap_groups(connection, group.name, failed_users=failed_users) return groups
[ "def", "sync_ldap_groups", "(", "connection", ",", "failed_users", "=", "None", ")", ":", "groups", "=", "Group", ".", "objects", ".", "filter", "(", "group__in", "=", "LdapGroup", ".", "objects", ".", "all", "(", ")", ")", "for", "group", "in", "groups"...
syncs ldap group memberships .
train
false
17,748
def volume_create(**kwargs): return create_volume(kwargs, 'function')
[ "def", "volume_create", "(", "**", "kwargs", ")", ":", "return", "create_volume", "(", "kwargs", ",", "'function'", ")" ]
create a volume from the values dictionary .
train
false
17,749
def logistic(x, A, u, d, v, y0): y = ((A / (1 + np.exp(((((4 * u) / A) * (d - x)) + 2)))) + y0) return y
[ "def", "logistic", "(", "x", ",", "A", ",", "u", ",", "d", ",", "v", ",", "y0", ")", ":", "y", "=", "(", "(", "A", "/", "(", "1", "+", "np", ".", "exp", "(", "(", "(", "(", "(", "4", "*", "u", ")", "/", "A", ")", "*", "(", "d", "-...
logistic growth model proposed in zwietering et al .
train
false
17,751
def grep(pattern, items, squash=True): isdict = (type(items) is dict) if (pattern in __grep_cache): regex = __grep_cache[pattern] else: regex = __grep_cache[pattern] = re.compile(pattern) matched = [] matchdict = {} for item in items: match = regex.match(item) if (not match): continue groups = match....
[ "def", "grep", "(", "pattern", ",", "items", ",", "squash", "=", "True", ")", ":", "isdict", "=", "(", "type", "(", "items", ")", "is", "dict", ")", "if", "(", "pattern", "in", "__grep_cache", ")", ":", "regex", "=", "__grep_cache", "[", "pattern", ...
search for ports using a regular expression .
train
false
17,752
@inspect_command(alias=u'dump_revoked') def revoked(state, **kwargs): return list(worker_state.revoked)
[ "@", "inspect_command", "(", "alias", "=", "u'dump_revoked'", ")", "def", "revoked", "(", "state", ",", "**", "kwargs", ")", ":", "return", "list", "(", "worker_state", ".", "revoked", ")" ]
list of revoked task-ids .
train
false
17,753
def upcast_char(*args): t = _upcast_memo.get(args) if (t is not None): return t t = upcast(*map(np.dtype, args)) _upcast_memo[args] = t return t
[ "def", "upcast_char", "(", "*", "args", ")", ":", "t", "=", "_upcast_memo", ".", "get", "(", "args", ")", "if", "(", "t", "is", "not", "None", ")", ":", "return", "t", "t", "=", "upcast", "(", "*", "map", "(", "np", ".", "dtype", ",", "args", ...
same as upcast but taking dtype .
train
false
17,755
def _load_and_process_metadata(captions_file, image_dir): with tf.gfile.FastGFile(captions_file, 'r') as f: caption_data = json.load(f) id_to_filename = [(x['id'], x['file_name']) for x in caption_data['images']] id_to_captions = {} for annotation in caption_data['annotations']: image_id = annotation['image_id'...
[ "def", "_load_and_process_metadata", "(", "captions_file", ",", "image_dir", ")", ":", "with", "tf", ".", "gfile", ".", "FastGFile", "(", "captions_file", ",", "'r'", ")", "as", "f", ":", "caption_data", "=", "json", ".", "load", "(", "f", ")", "id_to_file...
loads image metadata from a json file and processes the captions .
train
false
17,756
def cluster_quorum(**kwargs): return ceph_cfg.cluster_quorum(**kwargs)
[ "def", "cluster_quorum", "(", "**", "kwargs", ")", ":", "return", "ceph_cfg", ".", "cluster_quorum", "(", "**", "kwargs", ")" ]
get the clusters quorum status cli example: .
train
false
17,757
def regexp_extract(pattern, method=re.match, group=1): def regexp_extract_lambda(value): if (not value): return None matches = method(pattern, value) if (not matches): return None return matches.group(group) return regexp_extract_lambda
[ "def", "regexp_extract", "(", "pattern", ",", "method", "=", "re", ".", "match", ",", "group", "=", "1", ")", ":", "def", "regexp_extract_lambda", "(", "value", ")", ":", "if", "(", "not", "value", ")", ":", "return", "None", "matches", "=", "method", ...
return first group in the value matching the pattern using re .
train
false
17,758
def _ParseInputSpec(input_spec): pattern = re.compile('(\\d+),(\\d+),(\\d+),(\\d+)') m = pattern.match(input_spec) if (m is None): raise ValueError(('Failed to parse input spec:' + input_spec)) batch_size = int(m.group(1)) y_size = (int(m.group(2)) if (int(m.group(2)) > 0) else None) x_size = (int(m.group(3)) i...
[ "def", "_ParseInputSpec", "(", "input_spec", ")", ":", "pattern", "=", "re", ".", "compile", "(", "'(\\\\d+),(\\\\d+),(\\\\d+),(\\\\d+)'", ")", "m", "=", "pattern", ".", "match", "(", "input_spec", ")", "if", "(", "m", "is", "None", ")", ":", "raise", "Val...
parses input_spec and returns the numbers obtained therefrom .
train
false
17,760
def send_request(url, method='GET', headers=None, param_get=None, data=None): final_hostname = urlsplit(url).netloc dbgprint('FinalRequestUrl', url, 'FinalHostname', final_hostname) if ((final_hostname not in allowed_domains_set) and (not developer_temporary_disable_ssrf_prevention)): raise ConnectionAbortedError(...
[ "def", "send_request", "(", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "param_get", "=", "None", ",", "data", "=", "None", ")", ":", "final_hostname", "=", "urlsplit", "(", "url", ")", ".", "netloc", "dbgprint", "(", "'FinalR...
sends a request to notes api with appropriate parameters and headers .
train
false
17,761
def force_header_for_response(response, header, value): force_headers = {} if hasattr(response, 'force_headers'): force_headers = response.force_headers force_headers[header] = value response.force_headers = force_headers
[ "def", "force_header_for_response", "(", "response", ",", "header", ",", "value", ")", ":", "force_headers", "=", "{", "}", "if", "hasattr", "(", "response", ",", "'force_headers'", ")", ":", "force_headers", "=", "response", ".", "force_headers", "force_headers...
forces the given header for the given response using the header_control middleware .
train
false
17,762
def getComplexByDictionaryListValue(value, valueComplex): if (value.__class__ == complex): return value if (value.__class__ == dict): return getComplexByDictionary(value, valueComplex) if (value.__class__ == list): return getComplexByFloatList(value, valueComplex) floatFromValue = euclidean.getFloatFromValue(...
[ "def", "getComplexByDictionaryListValue", "(", "value", ",", "valueComplex", ")", ":", "if", "(", "value", ".", "__class__", "==", "complex", ")", ":", "return", "value", "if", "(", "value", ".", "__class__", "==", "dict", ")", ":", "return", "getComplexByDi...
get complex by dictionary .
train
false
17,763
def _GetKeyKind(key): return key.path().element_list()[(-1)].type()
[ "def", "_GetKeyKind", "(", "key", ")", ":", "return", "key", ".", "path", "(", ")", ".", "element_list", "(", ")", "[", "(", "-", "1", ")", "]", ".", "type", "(", ")" ]
return the kind of the given key .
train
false
17,765
def set_stubs(test): test.stub_out('nova.virt.vmwareapi.network_util.get_network_with_the_name', fake.fake_get_network) test.stub_out('nova.virt.vmwareapi.images.upload_image_stream_optimized', fake.fake_upload_image) test.stub_out('nova.virt.vmwareapi.images.fetch_image', fake.fake_fetch_image) test.stub_out('nova...
[ "def", "set_stubs", "(", "test", ")", ":", "test", ".", "stub_out", "(", "'nova.virt.vmwareapi.network_util.get_network_with_the_name'", ",", "fake", ".", "fake_get_network", ")", "test", ".", "stub_out", "(", "'nova.virt.vmwareapi.images.upload_image_stream_optimized'", ",...
set the stubs .
train
false
17,766
def _write_mri_config(fname, subject_from, subject_to, scale): scale = np.asarray(scale) if (np.isscalar(scale) or (scale.shape == ())): n_params = 1 else: n_params = 3 config = configparser.RawConfigParser() config.add_section('MRI Scaling') config.set('MRI Scaling', 'subject_from', subject_from) config.set...
[ "def", "_write_mri_config", "(", "fname", ",", "subject_from", ",", "subject_to", ",", "scale", ")", ":", "scale", "=", "np", ".", "asarray", "(", "scale", ")", "if", "(", "np", ".", "isscalar", "(", "scale", ")", "or", "(", "scale", ".", "shape", "=...
write the cfg file describing a scaled mri subject .
train
false
17,767
@needs('pavelib.prereqs.install_prereqs', 'pavelib.utils.test.utils.clean_reports_dir') @cmdopts([('failed', 'f', 'Run only failed tests'), ('fail-fast', 'x', 'Run only failed tests'), make_option('-c', '--cov-args', default='', help='adds as args to coverage for the test run'), make_option('--verbose', action='store_c...
[ "@", "needs", "(", "'pavelib.prereqs.install_prereqs'", ",", "'pavelib.utils.test.utils.clean_reports_dir'", ")", "@", "cmdopts", "(", "[", "(", "'failed'", ",", "'f'", ",", "'Run only failed tests'", ")", ",", "(", "'fail-fast'", ",", "'x'", ",", "'Run only failed te...
run all python tests .
train
false
17,768
def test_write_noformat_arbitrary(): _identifiers.update(_IDENTIFIERS_ORIGINAL) with pytest.raises(io_registry.IORegistryError) as exc: TestData().write(object()) assert str(exc.value).startswith(u'Format could not be identified.')
[ "def", "test_write_noformat_arbitrary", "(", ")", ":", "_identifiers", ".", "update", "(", "_IDENTIFIERS_ORIGINAL", ")", "with", "pytest", ".", "raises", "(", "io_registry", ".", "IORegistryError", ")", "as", "exc", ":", "TestData", "(", ")", ".", "write", "("...
test that all identifier functions can accept arbitrary input .
train
false
17,769
def extras_msg(extras): if (len(extras) == 1): verb = 'was' else: verb = 'were' return (', '.join((repr(extra) for extra in extras)), verb)
[ "def", "extras_msg", "(", "extras", ")", ":", "if", "(", "len", "(", "extras", ")", "==", "1", ")", ":", "verb", "=", "'was'", "else", ":", "verb", "=", "'were'", "return", "(", "', '", ".", "join", "(", "(", "repr", "(", "extra", ")", "for", "...
create an error message for extra items or properties .
train
true
17,771
def urepr(value): if isinstance(value, list): return (('[' + ', '.join(map(urepr, value))) + ']') if isinstance(value, unicode): return (('u"' + value.encode('utf-8').replace('"', '\\"').replace('\\', '\\\\')) + '"') return repr(value)
[ "def", "urepr", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "(", "(", "'['", "+", "', '", ".", "join", "(", "map", "(", "urepr", ",", "value", ")", ")", ")", "+", "']'", ")", "if", "isinstance", "(...
like repr() .
train
false
17,772
def _ListIndexesResponsePbToGetResponse(response, include_schema): return GetResponse(results=[_NewIndexFromPb(index, include_schema) for index in response.index_metadata_list()])
[ "def", "_ListIndexesResponsePbToGetResponse", "(", "response", ",", "include_schema", ")", ":", "return", "GetResponse", "(", "results", "=", "[", "_NewIndexFromPb", "(", "index", ",", "include_schema", ")", "for", "index", "in", "response", ".", "index_metadata_lis...
returns a getresponse constructed from get_indexes response pb .
train
false
17,773
@csrf_exempt def default_render_failure(request, message, status=403, template_name='extauth_failure.html', exception=None): log.debug(('In openid_failure ' + message)) data = render_to_string(template_name, dict(message=message, exception=exception)) return HttpResponse(data, status=status)
[ "@", "csrf_exempt", "def", "default_render_failure", "(", "request", ",", "message", ",", "status", "=", "403", ",", "template_name", "=", "'extauth_failure.html'", ",", "exception", "=", "None", ")", ":", "log", ".", "debug", "(", "(", "'In openid_failure '", ...
render an error page to the user .
train
false
17,774
def append_features(value): return append_var('FEATURES', value)
[ "def", "append_features", "(", "value", ")", ":", "return", "append_var", "(", "'FEATURES'", ",", "value", ")" ]
add to or create a new features in the make .
train
false
17,775
def set_dataset_root(path): global _dataset_root _dataset_root = path
[ "def", "set_dataset_root", "(", "path", ")", ":", "global", "_dataset_root", "_dataset_root", "=", "path" ]
sets the root directory to download and cache datasets .
train
false
17,777
def decrypt_keyfile(): print('Running in Travis during merge, decrypting stored key file.') encrypted_key = os.getenv(ENCRYPTED_KEY_ENV) encrypted_iv = os.getenv(ENCRYPTED_INIT_VECTOR_ENV) out_file = os.getenv(CREDENTIALS) subprocess.call(['openssl', 'aes-256-cbc', '-K', encrypted_key, '-iv', encrypted_iv, '-in', ...
[ "def", "decrypt_keyfile", "(", ")", ":", "print", "(", "'Running in Travis during merge, decrypting stored key file.'", ")", "encrypted_key", "=", "os", ".", "getenv", "(", "ENCRYPTED_KEY_ENV", ")", "encrypted_iv", "=", "os", ".", "getenv", "(", "ENCRYPTED_INIT_VECTOR_E...
decrypt a keyfile .
train
false
17,778
def naf(n): while n: z = ((2 - (n % 4)) if (n & 1) else 0) n = ((n - z) // 2) (yield z)
[ "def", "naf", "(", "n", ")", ":", "while", "n", ":", "z", "=", "(", "(", "2", "-", "(", "n", "%", "4", ")", ")", "if", "(", "n", "&", "1", ")", "else", "0", ")", "n", "=", "(", "(", "n", "-", "z", ")", "//", "2", ")", "(", "yield", ...
naf -> int generator returns a generator for the non-adjacent form of a number .
train
false
17,779
def _get_connection(): global COUCHBASE_CONN if (COUCHBASE_CONN is None): opts = _get_options() if opts['password']: COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password']) else: COUCHBASE_CONN = couchbase.Couchbase.connect(host=...
[ "def", "_get_connection", "(", ")", ":", "global", "COUCHBASE_CONN", "if", "(", "COUCHBASE_CONN", "is", "None", ")", ":", "opts", "=", "_get_options", "(", ")", "if", "opts", "[", "'password'", "]", ":", "COUCHBASE_CONN", "=", "couchbase", ".", "Couchbase", ...
global function to access the couchbase connection .
train
true
17,780
def _compute_host(host, instance): if host: return host if (not instance): raise exception.NovaException(_('No compute host specified')) if (not instance.host): raise exception.NovaException((_('Unable to find host for Instance %s') % instance.uuid)) return instance.host
[ "def", "_compute_host", "(", "host", ",", "instance", ")", ":", "if", "host", ":", "return", "host", "if", "(", "not", "instance", ")", ":", "raise", "exception", ".", "NovaException", "(", "_", "(", "'No compute host specified'", ")", ")", "if", "(", "n...
get the destination host for a message .
train
false
17,782
def Win32Input(prompt=None): return eval(input(prompt))
[ "def", "Win32Input", "(", "prompt", "=", "None", ")", ":", "return", "eval", "(", "input", "(", "prompt", ")", ")" ]
provide input() for gui apps .
train
false
17,783
def utf8_keys(dictionary): return dict([(key.encode('utf8'), val) for (key, val) in dictionary.items()])
[ "def", "utf8_keys", "(", "dictionary", ")", ":", "return", "dict", "(", "[", "(", "key", ".", "encode", "(", "'utf8'", ")", ",", "val", ")", "for", "(", "key", ",", "val", ")", "in", "dictionary", ".", "items", "(", ")", "]", ")" ]
convert dictionary keys to utf8-encoded strings for mapnik .
train
false
17,784
def filter_users_by_email(email): from .models import EmailAddress User = get_user_model() mails = EmailAddress.objects.filter(email__iexact=email) users = [e.user for e in mails.prefetch_related('user')] if app_settings.USER_MODEL_EMAIL_FIELD: q_dict = {(app_settings.USER_MODEL_EMAIL_FIELD + '__iexact'): email}...
[ "def", "filter_users_by_email", "(", "email", ")", ":", "from", ".", "models", "import", "EmailAddress", "User", "=", "get_user_model", "(", ")", "mails", "=", "EmailAddress", ".", "objects", ".", "filter", "(", "email__iexact", "=", "email", ")", "users", "...
return list of users by email address typically one .
train
true
17,787
def _param_from_config(key, data): param = {} if isinstance(data, dict): for (k, v) in six.iteritems(data): param.update(_param_from_config('{0}.{1}'.format(key, k), v)) elif (isinstance(data, list) or isinstance(data, tuple)): for (idx, conf_item) in enumerate(data): prefix = '{0}.{1}'.format(key, idx) ...
[ "def", "_param_from_config", "(", "key", ",", "data", ")", ":", "param", "=", "{", "}", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "data", ")", ":", "param", ".", ...
return ec2 api parameters based on the given config data .
train
true
17,788
def test_singleton(): AreEqual((frozenset([]) is frozenset([])), True) x = frozenset([1, 2, 3]) AreEqual((x is frozenset(x)), True)
[ "def", "test_singleton", "(", ")", ":", "AreEqual", "(", "(", "frozenset", "(", "[", "]", ")", "is", "frozenset", "(", "[", "]", ")", ")", ",", "True", ")", "x", "=", "frozenset", "(", "[", "1", ",", "2", ",", "3", "]", ")", "AreEqual", "(", ...
verify that an empty frozenset is a singleton .
train
false
17,789
def getFirstChildElementByTagName(self, tagName): for child in self.childNodes: if isinstance(child, Element): if (child.tagName == tagName): return child return None
[ "def", "getFirstChildElementByTagName", "(", "self", ",", "tagName", ")", ":", "for", "child", "in", "self", ".", "childNodes", ":", "if", "isinstance", "(", "child", ",", "Element", ")", ":", "if", "(", "child", ".", "tagName", "==", "tagName", ")", ":"...
return the first element of type tagname if found .
train
true