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
29,175
@app.route('/ip') def view_origin(): return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))
[ "@", "app", ".", "route", "(", "'/ip'", ")", "def", "view_origin", "(", ")", ":", "return", "jsonify", "(", "origin", "=", "request", ".", "headers", ".", "get", "(", "'X-Forwarded-For'", ",", "request", ".", "remote_addr", ")", ")" ]
returns origin ip .
train
false
29,177
def server_side(func): def inner(*args, **kwargs): if (args and hasattr(args[0], 'is_server') and (not voltron.debugger)): raise ServerSideOnlyException('This method can only be called on a server-side instance') return func(*args, **kwargs) return inner
[ "def", "server_side", "(", "func", ")", ":", "def", "inner", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "args", "and", "hasattr", "(", "args", "[", "0", "]", ",", "'is_server'", ")", "and", "(", "not", "voltron", ".", "debugger", ...
decorator to designate an api method applicable only to server-side instances .
train
true
29,180
def create_cmd(args, basename_binary=False): if basename_binary: args[0] = os.path.basename(args[0]) if (os.name == 'nt'): return subprocess.list2cmdline(args) else: escaped_args = [] for arg in args: if (re.search('^[a-zA-Z0-9/_^\\-\\.:=]+$', arg) is None): arg = ((u"'" + arg.replace(u"'", u"'\\''")) + u"'") escaped_args.append(arg) return u' '.join(escaped_args)
[ "def", "create_cmd", "(", "args", ",", "basename_binary", "=", "False", ")", ":", "if", "basename_binary", ":", "args", "[", "0", "]", "=", "os", ".", "path", ".", "basename", "(", "args", "[", "0", "]", ")", "if", "(", "os", ".", "name", "==", "...
takes an array of strings to be passed to subprocess .
train
false
29,181
def monitor_messages(connection, topic): def process_event(msg): body = msg['args']['data'] if ('resource_id' in body): print ('%s: %s/%-15s: %s' % (body.get('timestamp'), body.get('resource_id'), body.get('event_type'), body.get('counter_volume'))) else: print ('%s: %s' % (body.get('timestamp'), body.get('event_type'))) connection.declare_topic_consumer(topic, process_event) try: connection.consume() except KeyboardInterrupt: pass
[ "def", "monitor_messages", "(", "connection", ",", "topic", ")", ":", "def", "process_event", "(", "msg", ")", ":", "body", "=", "msg", "[", "'args'", "]", "[", "'data'", "]", "if", "(", "'resource_id'", "in", "body", ")", ":", "print", "(", "'%s: %s/%...
listen to notification .
train
false
29,182
def _ros_plot_pos(row, censorship, cohn): DL_index = row['det_limit_index'] rank = row['rank'] censored = row[censorship] dl_1 = cohn.iloc[DL_index] dl_2 = cohn.iloc[(DL_index + 1)] if censored: return (((1 - dl_1['prob_exceedance']) * rank) / (dl_1['ncen_equal'] + 1)) else: return ((1 - dl_1['prob_exceedance']) + (((dl_1['prob_exceedance'] - dl_2['prob_exceedance']) * rank) / (dl_1['nuncen_above'] + 1)))
[ "def", "_ros_plot_pos", "(", "row", ",", "censorship", ",", "cohn", ")", ":", "DL_index", "=", "row", "[", "'det_limit_index'", "]", "rank", "=", "row", "[", "'rank'", "]", "censored", "=", "row", "[", "censorship", "]", "dl_1", "=", "cohn", ".", "iloc...
ros-specific plotting positions .
train
false
29,183
def getTransformXMLElement(coords, transformName): transformXMLElement = coords.getFirstChildWithClassName(transformName) if (len(transformXMLElement.attributeDictionary) < 16): if ('bf:ref' in transformXMLElement.attributeDictionary): idReference = transformXMLElement.attributeDictionary['bf:ref'] return coords.getRoot().getSubChildWithID(idReference) return transformXMLElement
[ "def", "getTransformXMLElement", "(", "coords", ",", "transformName", ")", ":", "transformXMLElement", "=", "coords", ".", "getFirstChildWithClassName", "(", "transformName", ")", "if", "(", "len", "(", "transformXMLElement", ".", "attributeDictionary", ")", "<", "1...
get the transform attributes .
train
false
29,185
def write_corrected_mapping(output_corrected_fp, header, run_description, corrected_mapping_data): out_f = open(output_corrected_fp, 'w') out_f.write((('#' + ' DCTB '.join(header).replace('\n', '')) + '\n')) for curr_comment in run_description: out_f.write((('#' + curr_comment.replace('\n', '')) + '\n')) for curr_data in corrected_mapping_data: out_f.write((' DCTB '.join(curr_data).replace('\n', '') + '\n'))
[ "def", "write_corrected_mapping", "(", "output_corrected_fp", ",", "header", ",", "run_description", ",", "corrected_mapping_data", ")", ":", "out_f", "=", "open", "(", "output_corrected_fp", ",", "'w'", ")", "out_f", ".", "write", "(", "(", "(", "'#'", "+", "...
writes corrected mapping file with invalid characters replaced output_corrected_fp: filepath to write corrected mapping file to .
train
false
29,186
def system_alias(system, release, version): if (system == 'Rhapsody'): return ('MacOS X Server', (system + release), version) elif (system == 'SunOS'): if (release < '5'): return (system, release, version) l = release.split('.') if l: try: major = int(l[0]) except ValueError: pass else: major = (major - 3) l[0] = str(major) release = '.'.join(l) if (release < '6'): system = 'Solaris' else: system = 'Solaris' elif (system == 'IRIX64'): system = 'IRIX' if version: version = (version + ' (64bit)') else: version = '64bit' elif (system in ('win32', 'win16')): system = 'Windows' return (system, release, version)
[ "def", "system_alias", "(", "system", ",", "release", ",", "version", ")", ":", "if", "(", "system", "==", "'Rhapsody'", ")", ":", "return", "(", "'MacOS X Server'", ",", "(", "system", "+", "release", ")", ",", "version", ")", "elif", "(", "system", "...
returns aliased to common marketing names used for some systems .
train
false
29,188
def win32select(r, w, e, timeout=None): if (not (r or w)): if (timeout is None): timeout = 0.01 else: timeout = min(timeout, 0.001) sleep(timeout) return ([], [], []) if ((timeout is None) or (timeout > 0.5)): timeout = 0.5 (r, w, e) = select.select(r, w, w, timeout) return (r, (w + e), [])
[ "def", "win32select", "(", "r", ",", "w", ",", "e", ",", "timeout", "=", "None", ")", ":", "if", "(", "not", "(", "r", "or", "w", ")", ")", ":", "if", "(", "timeout", "is", "None", ")", ":", "timeout", "=", "0.01", "else", ":", "timeout", "="...
win32 select wrapper .
train
false
29,190
def is_public_subnet(ip): return (not is_private_subnet(ip=ip))
[ "def", "is_public_subnet", "(", "ip", ")", ":", "return", "(", "not", "is_private_subnet", "(", "ip", "=", "ip", ")", ")" ]
utility function to check if an ip address is inside a public subnet .
train
false
29,192
def _prune_blobs(blobs_array, overlap): for (blob1, blob2) in itt.combinations(blobs_array, 2): if (_blob_overlap(blob1, blob2) > overlap): if (blob1[2] > blob2[2]): blob2[2] = (-1) else: blob1[2] = (-1) return np.array([b for b in blobs_array if (b[2] > 0)])
[ "def", "_prune_blobs", "(", "blobs_array", ",", "overlap", ")", ":", "for", "(", "blob1", ",", "blob2", ")", "in", "itt", ".", "combinations", "(", "blobs_array", ",", "2", ")", ":", "if", "(", "_blob_overlap", "(", "blob1", ",", "blob2", ")", ">", "...
eliminated blobs with area overlap .
train
false
29,193
def pardir(): return os.path.pardir
[ "def", "pardir", "(", ")", ":", "return", "os", ".", "path", ".", "pardir" ]
return the relative parent directory path symbol for underlying os .
train
false
29,194
def get_absolute_number_from_season_and_episode(show, season, episode): absolute_number = None if (season and episode): main_db_con = db.DBConnection() sql = u'SELECT * FROM tv_episodes WHERE showid = ? and season = ? and episode = ?' sql_results = main_db_con.select(sql, [show.indexerid, season, episode]) if (len(sql_results) == 1): absolute_number = int(sql_results[0]['absolute_number']) logger.log(u'Found absolute number {absolute} for show {show} {ep}'.format(absolute=absolute_number, show=show.name, ep=episode_num(season, episode)), logger.DEBUG) else: logger.log(u'No entries for absolute number for show {show} {ep}'.format(show=show.name, ep=episode_num(season, episode)), logger.DEBUG) return absolute_number
[ "def", "get_absolute_number_from_season_and_episode", "(", "show", ",", "season", ",", "episode", ")", ":", "absolute_number", "=", "None", "if", "(", "season", "and", "episode", ")", ":", "main_db_con", "=", "db", ".", "DBConnection", "(", ")", "sql", "=", ...
find the absolute number for a show episode .
train
false
29,196
def merge_explicit(matadd): groups = sift(matadd.args, (lambda arg: isinstance(arg, MatrixBase))) if (len(groups[True]) > 1): return MatAdd(*(groups[False] + [reduce(add, groups[True])])) else: return matadd
[ "def", "merge_explicit", "(", "matadd", ")", ":", "groups", "=", "sift", "(", "matadd", ".", "args", ",", "(", "lambda", "arg", ":", "isinstance", "(", "arg", ",", "MatrixBase", ")", ")", ")", "if", "(", "len", "(", "groups", "[", "True", "]", ")",...
merge explicit matrixbase arguments .
train
false
29,198
def dup_sub_ground(f, c, K): return dup_sub_term(f, c, 0, K)
[ "def", "dup_sub_ground", "(", "f", ",", "c", ",", "K", ")", ":", "return", "dup_sub_term", "(", "f", ",", "c", ",", "0", ",", "K", ")" ]
subtract an element of the ground domain from f .
train
false
29,201
def _FindPythonFiles(filenames, recursive, exclude): python_files = [] for filename in filenames: if os.path.isdir(filename): if recursive: python_files.extend((os.path.join(dirpath, f) for (dirpath, _, filelist) in os.walk(filename) for f in filelist if IsPythonFile(os.path.join(dirpath, f)))) else: raise errors.YapfError(("directory specified without '--recursive' flag: %s" % filename)) elif os.path.isfile(filename): python_files.append(filename) if exclude: return [f for f in python_files if (not any((fnmatch.fnmatch(f, p) for p in exclude)))] return python_files
[ "def", "_FindPythonFiles", "(", "filenames", ",", "recursive", ",", "exclude", ")", ":", "python_files", "=", "[", "]", "for", "filename", "in", "filenames", ":", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "if", "recursive", ":", ...
find all python files .
train
false
29,202
def ansicolor(registry, xml_parent, data): cwrapper = XML.SubElement(xml_parent, 'hudson.plugins.ansicolor.AnsiColorBuildWrapper') colormap = data.get('colormap') if colormap: XML.SubElement(cwrapper, 'colorMapName').text = colormap
[ "def", "ansicolor", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "cwrapper", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.ansicolor.AnsiColorBuildWrapper'", ")", "colormap", "=", "data", ".", "get", "(", "'colormap'", ")"...
yaml: ansicolor translate ansi color codes to html in the console log .
train
false
29,203
def is_instance_factory(_type): if isinstance(_type, (tuple, list)): _type = tuple(_type) from pandas.formats.printing import pprint_thing type_repr = '|'.join(map(pprint_thing, _type)) else: type_repr = ("'%s'" % _type) def inner(x): if (not isinstance(x, _type)): raise ValueError(('Value must be an instance of %s' % type_repr)) return inner
[ "def", "is_instance_factory", "(", "_type", ")", ":", "if", "isinstance", "(", "_type", ",", "(", "tuple", ",", "list", ")", ")", ":", "_type", "=", "tuple", "(", "_type", ")", "from", "pandas", ".", "formats", ".", "printing", "import", "pprint_thing", ...
parameters _type - the type to be checked against returns validator - a function of a single argument x .
train
false
29,204
def _parse_hstore(hstore_str): result = {} pos = 0 pair_match = HSTORE_PAIR_RE.match(hstore_str) while (pair_match is not None): key = pair_match.group('key').replace('\\"', '"').replace('\\\\', '\\') if pair_match.group('value_null'): value = None else: value = pair_match.group('value').replace('\\"', '"').replace('\\\\', '\\') result[key] = value pos += pair_match.end() delim_match = HSTORE_DELIMITER_RE.match(hstore_str[pos:]) if (delim_match is not None): pos += delim_match.end() pair_match = HSTORE_PAIR_RE.match(hstore_str[pos:]) if (pos != len(hstore_str)): raise ValueError(_parse_error(hstore_str, pos)) return result
[ "def", "_parse_hstore", "(", "hstore_str", ")", ":", "result", "=", "{", "}", "pos", "=", "0", "pair_match", "=", "HSTORE_PAIR_RE", ".", "match", "(", "hstore_str", ")", "while", "(", "pair_match", "is", "not", "None", ")", ":", "key", "=", "pair_match",...
parse an hstore from its literal string representation .
train
false
29,205
def dictfetchall(cursor): desc = cursor.description return [dict(list(zip([col[0] for col in desc], row))) for row in cursor.fetchall()]
[ "def", "dictfetchall", "(", "cursor", ")", ":", "desc", "=", "cursor", ".", "description", "return", "[", "dict", "(", "list", "(", "zip", "(", "[", "col", "[", "0", "]", "for", "col", "in", "desc", "]", ",", "row", ")", ")", ")", "for", "row", ...
returns all rows from a cursor as a dict .
train
true
29,206
def calculate_resource_timeseries(events, resource): import pandas as pd res = OrderedDict() all_res = 0.0 for (tdelta, event) in sorted(events.items()): if (event[u'event'] == u'start'): if ((resource in event) and (event[resource] != u'Unknown')): all_res += float(event[resource]) current_time = event[u'start'] elif (event[u'event'] == u'finish'): if ((resource in event) and (event[resource] != u'Unknown')): all_res -= float(event[resource]) current_time = event[u'finish'] res[current_time] = all_res time_series = pd.Series(data=list(res.values()), index=list(res.keys())) ts_diff = time_series.diff() time_series = time_series[(ts_diff != 0)] return time_series
[ "def", "calculate_resource_timeseries", "(", "events", ",", "resource", ")", ":", "import", "pandas", "as", "pd", "res", "=", "OrderedDict", "(", ")", "all_res", "=", "0.0", "for", "(", "tdelta", ",", "event", ")", "in", "sorted", "(", "events", ".", "it...
given as event dictionary .
train
false
29,207
def load_by_type(msgtype, package_context=''): (pkg, basetype) = roslib.names.package_resource_name(msgtype) pkg = (pkg or package_context) try: m_f = msg_file(pkg, basetype) except roslib.packages.InvalidROSPkgException: raise MsgSpecException(('Cannot locate message type [%s], package [%s] does not exist' % (msgtype, pkg))) return load_from_file(m_f, pkg)
[ "def", "load_by_type", "(", "msgtype", ",", "package_context", "=", "''", ")", ":", "(", "pkg", ",", "basetype", ")", "=", "roslib", ".", "names", ".", "package_resource_name", "(", "msgtype", ")", "pkg", "=", "(", "pkg", "or", "package_context", ")", "t...
load message specification for specified type .
train
false
29,209
def _parseServer(description, factory, default=None): (args, kw) = _parse(description) if ((not args) or ((len(args) == 1) and (not kw))): deprecationMessage = ("Unqualified strport description passed to 'service'.Use qualified endpoint descriptions; for example, 'tcp:%s'." % (description,)) if (default is None): default = 'tcp' warnings.warn(deprecationMessage, category=DeprecationWarning, stacklevel=4) elif (default is _NO_DEFAULT): raise ValueError(deprecationMessage) args[0:0] = [default] endpointType = args[0] parser = _serverParsers.get(endpointType) if (parser is None): for plugin in getPlugins(IStreamServerEndpointStringParser): if (plugin.prefix == endpointType): return (plugin, args[1:], kw) raise ValueError(("Unknown endpoint type: '%s'" % (endpointType,))) return ((endpointType.upper(),) + parser(factory, *args[1:], **kw))
[ "def", "_parseServer", "(", "description", ",", "factory", ",", "default", "=", "None", ")", ":", "(", "args", ",", "kw", ")", "=", "_parse", "(", "description", ")", "if", "(", "(", "not", "args", ")", "or", "(", "(", "len", "(", "args", ")", "=...
parse a stports description into a 2-tuple of arguments and keyword values .
train
false
29,210
def _abbc(txt): return _center(_bold((((((('<br>' * 10) + ('*' * 10)) + ' ') + txt) + ' ') + ('*' * 10))))
[ "def", "_abbc", "(", "txt", ")", ":", "return", "_center", "(", "_bold", "(", "(", "(", "(", "(", "(", "(", "'<br>'", "*", "10", ")", "+", "(", "'*'", "*", "10", ")", ")", "+", "' '", ")", "+", "txt", ")", "+", "' '", ")", "+", "(", "'*'"...
abbc = asterisks .
train
false
29,211
def get_student(username_or_email, course_key): try: student = get_user_by_username_or_email(username_or_email) except ObjectDoesNotExist: raise ValueError(_('{user} does not exist in the LMS. Please check your spelling and retry.').format(user=username_or_email)) if (not CourseEnrollment.is_enrolled(student, course_key)): raise ValueError(_('{user} is not enrolled in this course. Please check your spelling and retry.').format(user=username_or_email)) return student
[ "def", "get_student", "(", "username_or_email", ",", "course_key", ")", ":", "try", ":", "student", "=", "get_user_by_username_or_email", "(", "username_or_email", ")", "except", "ObjectDoesNotExist", ":", "raise", "ValueError", "(", "_", "(", "'{user} does not exist ...
retrieve and return user object from db .
train
false
29,212
def subs(d, **kwargs): if d: return top_down(do_one(*map(rl.subs, *zip(*d.items()))), **kwargs) else: return (lambda x: x)
[ "def", "subs", "(", "d", ",", "**", "kwargs", ")", ":", "if", "d", ":", "return", "top_down", "(", "do_one", "(", "*", "map", "(", "rl", ".", "subs", ",", "*", "zip", "(", "*", "d", ".", "items", "(", ")", ")", ")", ")", ",", "**", "kwargs"...
full simultaneous exact substitution examples .
train
false
29,213
def get_volume_summary_by_project(context, project_id): return IMPL.get_volume_summary_by_project(context, project_id)
[ "def", "get_volume_summary_by_project", "(", "context", ",", "project_id", ")", ":", "return", "IMPL", ".", "get_volume_summary_by_project", "(", "context", ",", "project_id", ")" ]
get all volume summary belonging to a project .
train
false
29,215
@contextfunction def modules_active(context): request = context['request'] (modules, active) = _get_modules(request) if active: return active.name.replace('.', '-') return 'treeio-home'
[ "@", "contextfunction", "def", "modules_active", "(", "context", ")", ":", "request", "=", "context", "[", "'request'", "]", "(", "modules", ",", "active", ")", "=", "_get_modules", "(", "request", ")", "if", "active", ":", "return", "active", ".", "name",...
active modules .
train
false
29,216
def next_batch(targ_capacity, curr_capacity, num_up_to_date, batch_size, min_in_service): assert (num_up_to_date <= curr_capacity) efft_min_sz = min(min_in_service, targ_capacity, curr_capacity) efft_bat_sz = min(batch_size, max((targ_capacity - num_up_to_date), 0)) new_capacity = (efft_bat_sz + max(min(curr_capacity, (targ_capacity - efft_bat_sz)), efft_min_sz)) return (new_capacity, efft_bat_sz)
[ "def", "next_batch", "(", "targ_capacity", ",", "curr_capacity", ",", "num_up_to_date", ",", "batch_size", ",", "min_in_service", ")", ":", "assert", "(", "num_up_to_date", "<=", "curr_capacity", ")", "efft_min_sz", "=", "min", "(", "min_in_service", ",", "targ_ca...
return details of the next batch in a batched update .
train
false
29,217
def write_launchd_plist(program): plist_sample_text = '\n<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n <dict>\n <key>Label</key>\n <string>org.saltstack.{program}</string>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>ProgramArguments</key>\n <array>\n <string>{script}</string>\n </array>\n <key>SoftResourceLimits</key>\n <dict>\n <key>NumberOfFiles</key>\n <integer>100000</integer>\n </dict>\n <key>HardResourceLimits</key>\n <dict>\n <key>NumberOfFiles</key>\n <integer>100000</integer>\n </dict>\n </dict>\n</plist>\n '.strip() supported_programs = ['salt-master', 'salt-minion'] if (program not in supported_programs): sys.stderr.write("Supported programs: '{0}'\n".format(supported_programs)) sys.exit((-1)) return plist_sample_text.format(program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program))
[ "def", "write_launchd_plist", "(", "program", ")", ":", "plist_sample_text", "=", "'\\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\\n<plist version=\"1.0\">\\n <dict>\\n <key>Label</key>\\...
write a launchd plist for managing salt-master or salt-minion cli example: .
train
true
29,218
@handle_response_format @treeio_login_required def agent_index(request, response_format='html'): if (not request.user.profile.is_admin('treeio.services')): return user_denied(request, message="You don't have administrator access to the Service Support module") if request.GET: query = _get_filter_query(request.GET, ServiceAgent) agents = Object.filter_by_request(request, ServiceAgent.objects.filter(query)) else: agents = Object.filter_by_request(request, ServiceAgent.objects) filters = AgentFilterForm(request.user.profile, '', request.GET) context = _get_default_context(request) context.update({'agents': agents, 'filters': filters}) return render_to_response('services/agent_index', context, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "agent_index", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "if", "(", "not", "request", ".", "user", ".", "profile", ".", "is_admin", "(", "'treeio.services'", ")", ")", "...
all available agents .
train
false
29,219
def eval_sum(parse_result): total = 0.0 current_op = operator.add for token in parse_result: if (token == '+'): current_op = operator.add elif (token == '-'): current_op = operator.sub else: total = current_op(total, token) return total
[ "def", "eval_sum", "(", "parse_result", ")", ":", "total", "=", "0.0", "current_op", "=", "operator", ".", "add", "for", "token", "in", "parse_result", ":", "if", "(", "token", "==", "'+'", ")", ":", "current_op", "=", "operator", ".", "add", "elif", "...
add the inputs .
train
false
29,220
def _get_tslice(epochs, tmin, tmax): mask = _time_mask(epochs.times, tmin, tmax, sfreq=epochs.info['sfreq']) tstart = (np.where(mask)[0][0] if (tmin is not None) else None) tend = ((np.where(mask)[0][(-1)] + 1) if (tmax is not None) else None) tslice = slice(tstart, tend, None) return tslice
[ "def", "_get_tslice", "(", "epochs", ",", "tmin", ",", "tmax", ")", ":", "mask", "=", "_time_mask", "(", "epochs", ".", "times", ",", "tmin", ",", "tmax", ",", "sfreq", "=", "epochs", ".", "info", "[", "'sfreq'", "]", ")", "tstart", "=", "(", "np",...
get the slice .
train
false
29,222
def normal(state, text, i, formats, user_data): m = space_pat.match(text, i) if (m is not None): return [(len(m.group()), None)] cdo = cdo_pat.match(text, i) if (cdo is not None): state.parse = IN_COMMENT_NORMAL return [(len(cdo.group()), formats[u'comment'])] if (text[i] == u'"'): state.parse = IN_DQS return [(1, formats[u'string'])] if (text[i] == u"'"): state.parse = IN_SQS return [(1, formats[u'string'])] if (text[i] == u'{'): state.parse = IN_CONTENT state.blocks += 1 return [(1, formats[u'bracket'])] for (token, fmt, name) in sheet_tokens: m = token.match(text, i) if (m is not None): return [(len(m.group()), formats[fmt])] return [((len(text) - i), formats[u'unknown-normal'])]
[ "def", "normal", "(", "state", ",", "text", ",", "i", ",", "formats", ",", "user_data", ")", ":", "m", "=", "space_pat", ".", "match", "(", "text", ",", "i", ")", "if", "(", "m", "is", "not", "None", ")", ":", "return", "[", "(", "len", "(", ...
process will try to reset to normal priority .
train
false
29,224
def munge_filename_legacy(filename): filename = substitute_ascii_equivalents(filename) filename = filename.strip() filename = re.sub('[^a-zA-Z0-9.\\- ]', '', filename).replace(' ', '-') filename = _munge_to_length(filename, 3, 100) return filename
[ "def", "munge_filename_legacy", "(", "filename", ")", ":", "filename", "=", "substitute_ascii_equivalents", "(", "filename", ")", "filename", "=", "filename", ".", "strip", "(", ")", "filename", "=", "re", ".", "sub", "(", "'[^a-zA-Z0-9.\\\\- ]'", ",", "''", "...
tidies a filename .
train
false
29,225
def _wedge(): return Image()._new(core.wedge('L'))
[ "def", "_wedge", "(", ")", ":", "return", "Image", "(", ")", ".", "_new", "(", "core", ".", "wedge", "(", "'L'", ")", ")" ]
create greyscale wedge .
train
false
29,228
def json_error(status_code, message): r = jsonify(message=message) r.status_code = status_code return r
[ "def", "json_error", "(", "status_code", ",", "message", ")", ":", "r", "=", "jsonify", "(", "message", "=", "message", ")", "r", ".", "status_code", "=", "status_code", "return", "r" ]
return a json object with a http error code .
train
false
29,229
def _instances_fill_metadata(context, instances, manual_joins=None): uuids = [inst['uuid'] for inst in instances] if (manual_joins is None): manual_joins = ['metadata', 'system_metadata'] meta = collections.defaultdict(list) if ('metadata' in manual_joins): for row in _instance_metadata_get_multi(context, uuids): meta[row['instance_uuid']].append(row) sys_meta = collections.defaultdict(list) if ('system_metadata' in manual_joins): for row in _instance_system_metadata_get_multi(context, uuids): sys_meta[row['instance_uuid']].append(row) pcidevs = collections.defaultdict(list) if ('pci_devices' in manual_joins): for row in _instance_pcidevs_get_multi(context, uuids): pcidevs[row['instance_uuid']].append(row) filled_instances = [] for inst in instances: inst = dict(inst) inst['system_metadata'] = sys_meta[inst['uuid']] inst['metadata'] = meta[inst['uuid']] if ('pci_devices' in manual_joins): inst['pci_devices'] = pcidevs[inst['uuid']] filled_instances.append(inst) return filled_instances
[ "def", "_instances_fill_metadata", "(", "context", ",", "instances", ",", "manual_joins", "=", "None", ")", ":", "uuids", "=", "[", "inst", "[", "'uuid'", "]", "for", "inst", "in", "instances", "]", "if", "(", "manual_joins", "is", "None", ")", ":", "man...
selectively fill instances with manually-joined metadata .
train
false
29,230
def test_key_extensibility(): raises(AttributeError, (lambda : ask(Q.my_key(x)))) class MyAskHandler(AskHandler, ): @staticmethod def Symbol(expr, assumptions): return True register_handler('my_key', MyAskHandler) assert (ask(Q.my_key(x)) is True) assert (ask(Q.my_key((x + 1))) is None) remove_handler('my_key', MyAskHandler) del Q.my_key raises(AttributeError, (lambda : ask(Q.my_key(x))))
[ "def", "test_key_extensibility", "(", ")", ":", "raises", "(", "AttributeError", ",", "(", "lambda", ":", "ask", "(", "Q", ".", "my_key", "(", "x", ")", ")", ")", ")", "class", "MyAskHandler", "(", "AskHandler", ",", ")", ":", "@", "staticmethod", "def...
test that you can add keys to the ask system at runtime .
train
false
29,231
def getTranslateMatrixTetragrid(prefix, xmlElement): translation = getCumulativeVector3Remove(prefix, Vector3(), xmlElement) if translation.getIsDefault(): return None return [[1.0, 0.0, 0.0, translation.x], [0.0, 1.0, 0.0, translation.y], [0.0, 0.0, 1.0, translation.z], [0.0, 0.0, 0.0, 1.0]]
[ "def", "getTranslateMatrixTetragrid", "(", "prefix", ",", "xmlElement", ")", ":", "translation", "=", "getCumulativeVector3Remove", "(", "prefix", ",", "Vector3", "(", ")", ",", "xmlElement", ")", "if", "translation", ".", "getIsDefault", "(", ")", ":", "return"...
get translate matrix and delete the translate attributes .
train
false
29,232
def _fix_data_paths(package_data_dict): result = {} for (package_name, package_content) in package_data_dict.items(): package_structure = package_name.split('.') package_structure_1st_level = package_structure[1] result[package_name] = [] for p in package_content: path_structure = p.split(os.path.sep) path_structure_1st_level = path_structure[0] if (package_structure_1st_level == path_structure_1st_level): path = os.path.join(*path_structure[1:]) else: path = p result[package_name].append(path) return result
[ "def", "_fix_data_paths", "(", "package_data_dict", ")", ":", "result", "=", "{", "}", "for", "(", "package_name", ",", "package_content", ")", "in", "package_data_dict", ".", "items", "(", ")", ":", "package_structure", "=", "package_name", ".", "split", "(",...
corrects package data paths when the package name is compound .
train
false
29,233
def test_config_change(config_stub, basedir, download_stub, data_tmpdir, tmpdir): filtered_blocked_hosts = BLOCKLIST_HOSTS[1:] blocklist = QUrl(create_blocklist(tmpdir, blocked_hosts=filtered_blocked_hosts, name='blocked-hosts', line_format='one_per_line')) config_stub.data = {'content': {'host-block-lists': [blocklist], 'host-blocking-enabled': True, 'host-blocking-whitelist': None}} host_blocker = adblock.HostBlocker() host_blocker.read_hosts() config_stub.set('content', 'host-block-lists', None) host_blocker.read_hosts() for str_url in URLS_TO_CHECK: assert (not host_blocker.is_blocked(QUrl(str_url)))
[ "def", "test_config_change", "(", "config_stub", ",", "basedir", ",", "download_stub", ",", "data_tmpdir", ",", "tmpdir", ")", ":", "filtered_blocked_hosts", "=", "BLOCKLIST_HOSTS", "[", "1", ":", "]", "blocklist", "=", "QUrl", "(", "create_blocklist", "(", "tmp...
ensure blocked-hosts resets if host-block-list is changed to none .
train
false
29,235
def test_ports(): tests = (('http://foo.com:8000', ('http://foo.com:8000', '')), ('http://foo.com:8000/', ('http://foo.com:8000/', '')), ('http://bar.com:xkcd', ('http://bar.com', ':xkcd')), ('http://foo.com:81/bar', ('http://foo.com:81/bar', '')), ('http://foo.com:', ('http://foo.com', ':'))) def check(test, output): eq_(u'<a href="{0}" rel="nofollow">{0}</a>{1}'.format(*output), linkify(test)) for (test, output) in tests: (yield (check, test, output))
[ "def", "test_ports", "(", ")", ":", "tests", "=", "(", "(", "'http://foo.com:8000'", ",", "(", "'http://foo.com:8000'", ",", "''", ")", ")", ",", "(", "'http://foo.com:8000/'", ",", "(", "'http://foo.com:8000/'", ",", "''", ")", ")", ",", "(", "'http://bar.c...
urls can contain port numbers .
train
false
29,237
def build_zipmanifest(path): zipinfo = dict() zfile = zipfile.ZipFile(path) try: for zitem in zfile.namelist(): zpath = zitem.replace('/', os.sep) zipinfo[zpath] = zfile.getinfo(zitem) assert (zipinfo[zpath] is not None) finally: zfile.close() return zipinfo
[ "def", "build_zipmanifest", "(", "path", ")", ":", "zipinfo", "=", "dict", "(", ")", "zfile", "=", "zipfile", ".", "ZipFile", "(", "path", ")", "try", ":", "for", "zitem", "in", "zfile", ".", "namelist", "(", ")", ":", "zpath", "=", "zitem", ".", "...
this builds a similar dictionary to the zipimport directory caches .
train
false
29,238
@manager.command def deploy(): from flask_migrate import upgrade from app.models import Role, User upgrade() Role.insert_roles() User.add_self_follows()
[ "@", "manager", ".", "command", "def", "deploy", "(", ")", ":", "from", "flask_migrate", "import", "upgrade", "from", "app", ".", "models", "import", "Role", ",", "User", "upgrade", "(", ")", "Role", ".", "insert_roles", "(", ")", "User", ".", "add_self_...
deploy latest environment and code and restart backends .
train
false
29,239
def retrieve_arn(config): if config.get('arn'): return config.get('arn') if config.get('Arn'): return config.get('Arn') if config.get('CertificateArn'): return config.get('CertificateArn') if config.get('group', {}).get('arn'): return config.get('group', {}).get('arn') if config.get('role', {}).get('arn'): return config.get('role', {}).get('arn') if config.get('user', {}).get('arn'): return config.get('user', {}).get('arn') return None
[ "def", "retrieve_arn", "(", "config", ")", ":", "if", "config", ".", "get", "(", "'arn'", ")", ":", "return", "config", ".", "get", "(", "'arn'", ")", "if", "config", ".", "get", "(", "'Arn'", ")", ":", "return", "config", ".", "get", "(", "'Arn'",...
see issue #374 .
train
false
29,242
def reverse_version(version): if version: try: return reverse('version-detail', kwargs={'pk': version.pk}) except AttributeError: return version return
[ "def", "reverse_version", "(", "version", ")", ":", "if", "version", ":", "try", ":", "return", "reverse", "(", "'version-detail'", ",", "kwargs", "=", "{", "'pk'", ":", "version", ".", "pk", "}", ")", "except", "AttributeError", ":", "return", "version", ...
the try/except attributeerror allows this to be used where the input is ambiguous .
train
false
29,243
def _getStyle(node): if ((node.nodeType == 1) and (len(node.getAttribute('style')) > 0)): styleMap = {} rawStyles = node.getAttribute('style').split(';') for style in rawStyles: propval = style.split(':') if (len(propval) == 2): styleMap[propval[0].strip()] = propval[1].strip() return styleMap else: return {}
[ "def", "_getStyle", "(", "node", ")", ":", "if", "(", "(", "node", ".", "nodeType", "==", "1", ")", "and", "(", "len", "(", "node", ".", "getAttribute", "(", "'style'", ")", ")", ">", "0", ")", ")", ":", "styleMap", "=", "{", "}", "rawStyles", ...
returns the style attribute of a node as a dictionary .
train
true
29,245
def restart(name, jail=None): cmd = '{0} {1} onerestart'.format(_cmd(jail), name) return (not __salt__['cmd.retcode'](cmd, python_shell=False))
[ "def", "restart", "(", "name", ",", "jail", "=", "None", ")", ":", "cmd", "=", "'{0} {1} onerestart'", ".", "format", "(", "_cmd", "(", "jail", ")", ",", "name", ")", "return", "(", "not", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmd", ",", "pyth...
restart a service .
train
true
29,246
def libvlc_video_get_track_count(p_mi): f = (_Cfunctions.get('libvlc_video_get_track_count', None) or _Cfunction('libvlc_video_get_track_count', ((1,),), None, ctypes.c_int, MediaPlayer)) return f(p_mi)
[ "def", "libvlc_video_get_track_count", "(", "p_mi", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_video_get_track_count'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_get_track_count'", ",", "(", "(", "1", ",", ")", ",", ")", ...
get number of available video tracks .
train
true
29,247
def makeKVPost(request_message, server_url): resp = fetchers.fetch(server_url, body=request_message.toURLEncoded()) return _httpResponseToMessage(resp, server_url)
[ "def", "makeKVPost", "(", "request_message", ",", "server_url", ")", ":", "resp", "=", "fetchers", ".", "fetch", "(", "server_url", ",", "body", "=", "request_message", ".", "toURLEncoded", "(", ")", ")", "return", "_httpResponseToMessage", "(", "resp", ",", ...
make a direct request to an openid provider and return the result as a message object .
train
true
29,248
@handle_response_format @treeio_login_required def contact_delete(request, contact_id, response_format='html'): contact = get_object_or_404(Contact, pk=contact_id) if (not request.user.profile.has_permission(contact, mode='w')): return user_denied(request, message="You don't have access to this Contact") if request.POST: if ('delete' in request.POST): if ('trash' in request.POST): contact.trash = True contact.save() else: contact.delete() return HttpResponseRedirect(reverse('identities_index')) elif ('cancel' in request.POST): return HttpResponseRedirect(reverse('identities_contact_view', args=[contact.id])) types = Object.filter_by_request(request, ContactType.objects.order_by('name')) return render_to_response('identities/contact_delete', {'contact': contact, 'types': types}, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "contact_delete", "(", "request", ",", "contact_id", ",", "response_format", "=", "'html'", ")", ":", "contact", "=", "get_object_or_404", "(", "Contact", ",", "pk", "=", "contact_id", ")", "if", ...
contact delete .
train
false
29,249
def get_network_settings(): return _read_file(_RH_NETWORK_FILE)
[ "def", "get_network_settings", "(", ")", ":", "return", "_read_file", "(", "_RH_NETWORK_FILE", ")" ]
return the contents of the global network script .
train
false
29,251
def selective_find(str, char, index, pos): l = len(str) while 1: pos += 1 if (pos == l): return ((-1), (-1)) c = str[pos] if (c == char): return ((index + 1), pos) elif (c < char): index += 1
[ "def", "selective_find", "(", "str", ",", "char", ",", "index", ",", "pos", ")", ":", "l", "=", "len", "(", "str", ")", "while", "1", ":", "pos", "+=", "1", "if", "(", "pos", "==", "l", ")", ":", "return", "(", "(", "-", "1", ")", ",", "(",...
return a pair .
train
false
29,252
def coding_spec(str): str = str.split('\n')[:2] str = '\n'.join(str) match = coding_re.search(str) if (not match): return None name = match.group(1) import codecs try: codecs.lookup(name) except LookupError: raise LookupError, ('Unknown encoding ' + name) return name
[ "def", "coding_spec", "(", "str", ")", ":", "str", "=", "str", ".", "split", "(", "'\\n'", ")", "[", ":", "2", "]", "str", "=", "'\\n'", ".", "join", "(", "str", ")", "match", "=", "coding_re", ".", "search", "(", "str", ")", "if", "(", "not", ...
return the encoding declaration according to pep 263 .
train
false
29,253
def migrate_tasks(source, dest, migrate=migrate_task, app=None, queues=None, **kwargs): app = app_or_default(app) queues = prepare_queues(queues) producer = app.amqp.Producer(dest, auto_declare=False) migrate = partial(migrate, producer, queues=queues) def on_declare_queue(queue): new_queue = queue(producer.channel) new_queue.name = queues.get(queue.name, queue.name) if (new_queue.routing_key == queue.name): new_queue.routing_key = queues.get(queue.name, new_queue.routing_key) if (new_queue.exchange.name == queue.name): new_queue.exchange.name = queues.get(queue.name, queue.name) new_queue.declare() return start_filter(app, source, migrate, queues=queues, on_declare_queue=on_declare_queue, **kwargs)
[ "def", "migrate_tasks", "(", "source", ",", "dest", ",", "migrate", "=", "migrate_task", ",", "app", "=", "None", ",", "queues", "=", "None", ",", "**", "kwargs", ")", ":", "app", "=", "app_or_default", "(", "app", ")", "queues", "=", "prepare_queues", ...
migrate tasks from one broker to another .
train
false
29,254
def difference(G, H): if (not (G.is_multigraph() == H.is_multigraph())): raise nx.NetworkXError('G and H must both be graphs or multigraphs.') R = nx.create_empty_copy(G) R.name = ('Difference of (%s and %s)' % (G.name, H.name)) if (set(G) != set(H)): raise nx.NetworkXError('Node sets of graphs not equal') if G.is_multigraph(): edges = G.edges(keys=True) else: edges = G.edges() for e in edges: if (not H.has_edge(*e)): R.add_edge(*e) return R
[ "def", "difference", "(", "G", ",", "H", ")", ":", "if", "(", "not", "(", "G", ".", "is_multigraph", "(", ")", "==", "H", ".", "is_multigraph", "(", ")", ")", ")", ":", "raise", "nx", ".", "NetworkXError", "(", "'G and H must both be graphs or multigraph...
returns all elements in seq1 which are not in seq2: i .
train
false
29,255
def write_pack_data(f, num_records, records): entries = {} f = SHA1Writer(f) write_pack_header(f, num_records) for (type_num, object_id, delta_base, raw) in records: offset = f.offset() if (delta_base is not None): try: (base_offset, base_crc32) = entries[delta_base] except KeyError: type_num = REF_DELTA raw = (delta_base, raw) else: type_num = OFS_DELTA raw = ((offset - base_offset), raw) crc32 = write_pack_object(f, type_num, raw) entries[object_id] = (offset, crc32) return (entries, f.write_sha())
[ "def", "write_pack_data", "(", "f", ",", "num_records", ",", "records", ")", ":", "entries", "=", "{", "}", "f", "=", "SHA1Writer", "(", "f", ")", "write_pack_header", "(", "f", ",", "num_records", ")", "for", "(", "type_num", ",", "object_id", ",", "d...
write a new pack data file .
train
false
29,256
def load_googlenews_vectors(): embed_map = word2vec.load_word2vec_format(path_to_word2vec, binary=True) return embed_map
[ "def", "load_googlenews_vectors", "(", ")", ":", "embed_map", "=", "word2vec", ".", "load_word2vec_format", "(", "path_to_word2vec", ",", "binary", "=", "True", ")", "return", "embed_map" ]
load the word2vec googlenews vectors .
train
false
29,258
def dropTables(tables, ifExists=True): DB_TABLES_DROP = list(tables) DB_TABLES_DROP.reverse() for table in DB_TABLES_DROP: _dbschema_logger.info('dropping table %s', table._imdbpyName) table.dropTable(ifExists)
[ "def", "dropTables", "(", "tables", ",", "ifExists", "=", "True", ")", ":", "DB_TABLES_DROP", "=", "list", "(", "tables", ")", "DB_TABLES_DROP", ".", "reverse", "(", ")", "for", "table", "in", "DB_TABLES_DROP", ":", "_dbschema_logger", ".", "info", "(", "'...
drop the tables .
train
false
29,259
def test_on_content_type(): formatter = hug.output_format.on_content_type({'application/json': hug.output_format.json, 'text/plain': hug.output_format.text}) class FakeRequest(object, ): content_type = 'application/json' request = FakeRequest() response = FakeRequest() converted = hug.input_format.json(formatter(BytesIO(hug.output_format.json({'name': 'name'})), request, response)) assert (converted == {'name': 'name'}) request.content_type = 'text/plain' assert (formatter('hi', request, response) == 'hi') with pytest.raises(hug.HTTPNotAcceptable): request.content_type = 'undefined; always' formatter('hi', request, response)
[ "def", "test_on_content_type", "(", ")", ":", "formatter", "=", "hug", ".", "output_format", ".", "on_content_type", "(", "{", "'application/json'", ":", "hug", ".", "output_format", ".", "json", ",", "'text/plain'", ":", "hug", ".", "output_format", ".", "tex...
ensure that its possible to route the output type format by the requested content-type .
train
false
29,260
def apply_template(template_dir, output_dir, context): _mergetreejinja(template_dir, output_dir, context)
[ "def", "apply_template", "(", "template_dir", ",", "output_dir", ",", "context", ")", ":", "_mergetreejinja", "(", "template_dir", ",", "output_dir", ",", "context", ")" ]
apply the template from the template directory to the output using the supplied context dict .
train
false
29,261
def try_parse_date(value): if (value is None): return None try: return parse_date(value) except ValueError: return None
[ "def", "try_parse_date", "(", "value", ")", ":", "if", "(", "value", "is", "None", ")", ":", "return", "None", "try", ":", "return", "parse_date", "(", "value", ")", "except", "ValueError", ":", "return", "None" ]
tries to make a time out of the value .
train
false
29,262
def typename(obj): if hasattr(obj, '__class__'): return getattr(obj, '__class__').__name__ else: return type(obj).__name__
[ "def", "typename", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'__class__'", ")", ":", "return", "getattr", "(", "obj", ",", "'__class__'", ")", ".", "__name__", "else", ":", "return", "type", "(", "obj", ")", ".", "__name__" ]
robust class-name utility-function .
train
true
29,264
def test_encounter_slots(session): version_group_a = aliased(tables.VersionGroup) version_group_b = aliased(tables.VersionGroup) sanity_q = session.query(tables.Encounter).join((tables.EncounterSlot, tables.Encounter.slot)).join((version_group_a, tables.EncounterSlot.version_group)).join((tables.Version, tables.Encounter.version)).join((version_group_b, tables.Version.version_group)).filter((version_group_a.id != version_group_b.id)) assert (sanity_q.count() == 0)
[ "def", "test_encounter_slots", "(", "session", ")", ":", "version_group_a", "=", "aliased", "(", "tables", ".", "VersionGroup", ")", "version_group_b", "=", "aliased", "(", "tables", ".", "VersionGroup", ")", "sanity_q", "=", "session", ".", "query", "(", "tab...
encounters have a version .
train
false
29,265
def login_as_coach(context, coach_name='mrpibb', coach_pass='abc123'): if (not FacilityUser.objects.filter(username=coach_name)): class ContextWithMixin(FacilityMixins, ): def __init__(self): self.browser = context.browser context_wm = ContextWithMixin() context_wm.create_teacher(username=coach_name, password=coach_pass) facility = FacilityUser.objects.get(username=coach_name).facility.id _login_user(context, coach_name, coach_pass, facility=facility)
[ "def", "login_as_coach", "(", "context", ",", "coach_name", "=", "'mrpibb'", ",", "coach_pass", "=", "'abc123'", ")", ":", "if", "(", "not", "FacilityUser", ".", "objects", ".", "filter", "(", "username", "=", "coach_name", ")", ")", ":", "class", "Context...
log in as a coach specified by the optional arguments .
train
false
29,266
def _vector_to_sdm_helper(v, order): from sympy.polys.distributedmodules import sdm_from_dict d = {} for (i, e) in enumerate(v): for (key, value) in e.to_dict().items(): d[((i,) + key)] = value return sdm_from_dict(d, order)
[ "def", "_vector_to_sdm_helper", "(", "v", ",", "order", ")", ":", "from", "sympy", ".", "polys", ".", "distributedmodules", "import", "sdm_from_dict", "d", "=", "{", "}", "for", "(", "i", ",", "e", ")", "in", "enumerate", "(", "v", ")", ":", "for", "...
helper method for common code in global and local poly rings .
train
false
29,267
def rc_file(fname): rcParams.update(rc_params_from_file(fname))
[ "def", "rc_file", "(", "fname", ")", ":", "rcParams", ".", "update", "(", "rc_params_from_file", "(", "fname", ")", ")" ]
update rc params from file .
train
false
29,268
def configure_vlan(eapi_conn, vlan_id, vlan_name=None): command_str1 = 'vlan {}'.format(vlan_id) cmd = [command_str1] if (vlan_name is not None): command_str2 = 'name {}'.format(vlan_name) cmd.append(command_str2) return eapi_conn.config(cmd)
[ "def", "configure_vlan", "(", "eapi_conn", ",", "vlan_id", ",", "vlan_name", "=", "None", ")", ":", "command_str1", "=", "'vlan {}'", ".", "format", "(", "vlan_id", ")", "cmd", "=", "[", "command_str1", "]", "if", "(", "vlan_name", "is", "not", "None", "...
add the given vlan_id to the switch set the vlan_name note .
train
false
29,269
@register.function @jinja2.contextfunction def sort_link(context, pretty_name, sort_field): request = context['request'] (sort, order) = clean_sort_param(request) get_params = [(k, v) for (k, v) in urlparse.parse_qsl(smart_str(request.META['QUERY_STRING'])) if (k not in ('sort', 'order'))] return create_sort_link(pretty_name, sort_field, get_params, sort, order)
[ "@", "register", ".", "function", "@", "jinja2", ".", "contextfunction", "def", "sort_link", "(", "context", ",", "pretty_name", ",", "sort_field", ")", ":", "request", "=", "context", "[", "'request'", "]", "(", "sort", ",", "order", ")", "=", "clean_sort...
get table header sort links .
train
false
29,270
def migrate_osx_xdg_data(config): assert is_osx(), 'This function should only be run on OS X.' xdg_data_home = os.path.join(os.path.expanduser('~'), '.local', 'share') xdg_aj_home = os.path.join(xdg_data_home, 'autojump') data_path = os.path.join(xdg_aj_home, 'autojump.txt') backup_path = os.path.join(xdg_aj_home, 'autojump.txt.bak') if os.path.exists(data_path): move_file(data_path, config['data_path']) if os.path.exists(backup_path): move_file(backup_path, config['backup_path']) shutil.rmtree(xdg_aj_home) if (len(os.listdir(xdg_data_home)) == 0): shutil.rmtree(xdg_data_home)
[ "def", "migrate_osx_xdg_data", "(", "config", ")", ":", "assert", "is_osx", "(", ")", ",", "'This function should only be run on OS X.'", "xdg_data_home", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "...
older versions incorrectly used linux xdg_data_home paths on os x .
train
false
29,271
def get_theme_bundles(themes): bundles = {} for theme_name in themes: bundles_path = os.path.join(utils.get_theme_path(theme_name), u'bundles') if os.path.isfile(bundles_path): with open(bundles_path) as fd: for line in fd: try: (name, files) = line.split(u'=') files = [f.strip() for f in files.split(u',')] bundles[name.strip().replace(u'/', os.sep)] = files except ValueError: pass break return bundles
[ "def", "get_theme_bundles", "(", "themes", ")", ":", "bundles", "=", "{", "}", "for", "theme_name", "in", "themes", ":", "bundles_path", "=", "os", ".", "path", ".", "join", "(", "utils", ".", "get_theme_path", "(", "theme_name", ")", ",", "u'bundles'", ...
given a theme chain .
train
false
29,272
@instrumented_task(name='sentry.tasks.options.sync_options', queue='options') def sync_options(cutoff=ONE_HOUR): cutoff_dt = (timezone.now() - timedelta(seconds=cutoff)) for option in Option.objects.filter(last_updated__gte=cutoff_dt).iterator(): try: opt = default_manager.lookup_key(option.key) default_manager.store.set_cache(opt, option.value) except UnknownOption as e: logger.exception(six.text_type(e))
[ "@", "instrumented_task", "(", "name", "=", "'sentry.tasks.options.sync_options'", ",", "queue", "=", "'options'", ")", "def", "sync_options", "(", "cutoff", "=", "ONE_HOUR", ")", ":", "cutoff_dt", "=", "(", "timezone", ".", "now", "(", ")", "-", "timedelta", ...
ensures all options that have been updated since cutoff have their correct values stored in the cache .
train
false
29,273
def bulk_update_nodes(serialize, nodes, index=None): index = (index or INDEX) actions = [] for node in nodes: serialized = serialize(node) if serialized: actions.append({'_op_type': 'update', '_index': index, '_id': node._id, '_type': get_doctype_from_node(node), 'doc': serialized, 'doc_as_upsert': True}) if actions: return helpers.bulk(client(), actions)
[ "def", "bulk_update_nodes", "(", "serialize", ",", "nodes", ",", "index", "=", "None", ")", ":", "index", "=", "(", "index", "or", "INDEX", ")", "actions", "=", "[", "]", "for", "node", "in", "nodes", ":", "serialized", "=", "serialize", "(", "node", ...
updates the list of input projects .
train
false
29,274
@task def remove_userspace(): run('rm -rf repos') if os.path.exists('release'): error('release directory already exists locally. Remove it to continue.')
[ "@", "task", "def", "remove_userspace", "(", ")", ":", "run", "(", "'rm -rf repos'", ")", "if", "os", ".", "path", ".", "exists", "(", "'release'", ")", ":", "error", "(", "'release directory already exists locally. Remove it to continue.'", ")" ]
deletes (!) the sympy changes .
train
false
29,275
def _feed_cli_with_input(text, editing_mode=EditingMode.EMACS, clipboard=None, history=None, multiline=False, check_line_ending=True, pre_run_callback=None): if check_line_ending: assert text.endswith(u'\n') loop = PosixEventLoop() try: inp = PipeInput() inp.send_text(text) cli = CommandLineInterface(application=Application(buffer=Buffer(accept_action=AcceptAction.RETURN_DOCUMENT, history=history, is_multiline=multiline), editing_mode=editing_mode, clipboard=(clipboard or InMemoryClipboard()), key_bindings_registry=KeyBindingManager.for_prompt().registry), eventloop=loop, input=inp, output=DummyOutput()) if pre_run_callback: pre_run_callback(cli) result = cli.run() return (result, cli) finally: loop.close() inp.close()
[ "def", "_feed_cli_with_input", "(", "text", ",", "editing_mode", "=", "EditingMode", ".", "EMACS", ",", "clipboard", "=", "None", ",", "history", "=", "None", ",", "multiline", "=", "False", ",", "check_line_ending", "=", "True", ",", "pre_run_callback", "=", ...
create a commandlineinterface .
train
false
29,276
def get_cross_validation_datasets(dataset, n_fold, order=None): if (order is None): order = numpy.arange(len(dataset)) else: order = numpy.array(order) whole_size = len(dataset) borders = [((whole_size * i) // n_fold) for i in six.moves.range((n_fold + 1))] test_sizes = [(borders[(i + 1)] - borders[i]) for i in six.moves.range(n_fold)] splits = [] for test_size in reversed(test_sizes): size = (whole_size - test_size) splits.append(split_dataset(dataset, size, order)) new_order = numpy.empty_like(order) new_order[:test_size] = order[(- test_size):] new_order[test_size:] = order[:(- test_size)] order = new_order return splits
[ "def", "get_cross_validation_datasets", "(", "dataset", ",", "n_fold", ",", "order", "=", "None", ")", ":", "if", "(", "order", "is", "None", ")", ":", "order", "=", "numpy", ".", "arange", "(", "len", "(", "dataset", ")", ")", "else", ":", "order", ...
creates a set of training/test splits for cross validation .
train
false
29,277
def _make_vals(val, klass, seccont, klass_inst=None, prop=None, part=False, base64encode=False, elements_to_sign=None): cinst = None if isinstance(val, dict): cinst = _instance(klass, val, seccont, base64encode=base64encode, elements_to_sign=elements_to_sign) else: try: cinst = klass().set_text(val) except ValueError: if (not part): cis = [_make_vals(sval, klass, seccont, klass_inst, prop, True, base64encode, elements_to_sign) for sval in val] setattr(klass_inst, prop, cis) else: raise if part: return cinst elif cinst: cis = [cinst] setattr(klass_inst, prop, cis)
[ "def", "_make_vals", "(", "val", ",", "klass", ",", "seccont", ",", "klass_inst", "=", "None", ",", "prop", "=", "None", ",", "part", "=", "False", ",", "base64encode", "=", "False", ",", "elements_to_sign", "=", "None", ")", ":", "cinst", "=", "None",...
creates a class instance with a specified value .
train
true
29,278
def create_mpl_ax(ax=None): if (ax is None): plt = _import_mpl() fig = plt.figure() ax = fig.add_subplot(111) else: fig = ax.figure return (fig, ax)
[ "def", "create_mpl_ax", "(", "ax", "=", "None", ")", ":", "if", "(", "ax", "is", "None", ")", ":", "plt", "=", "_import_mpl", "(", ")", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "else", "...
helper function for when a single plot axis is needed .
train
false
29,279
def server_del_user(username): bash(('userdel -r -f %s' % username)) logger.debug(('rm -f %s/%s_*.pem' % (os.path.join(KEY_DIR, 'user'), username))) bash(('rm -f %s/%s_*.pem' % (os.path.join(KEY_DIR, 'user'), username))) bash(('rm -f %s/%s.pem*' % (os.path.join(KEY_DIR, 'user'), username)))
[ "def", "server_del_user", "(", "username", ")", ":", "bash", "(", "(", "'userdel -r -f %s'", "%", "username", ")", ")", "logger", ".", "debug", "(", "(", "'rm -f %s/%s_*.pem'", "%", "(", "os", ".", "path", ".", "join", "(", "KEY_DIR", ",", "'user'", ")",...
delete a user from jumpserver linux system .
train
false
29,280
def _normalize_tags(chunk): ret = [] for (word, tag) in chunk: if ((tag == u'NP-TL') or (tag == u'NP')): ret.append((word, u'NNP')) continue if tag.endswith(u'-TL'): ret.append((word, tag[:(-3)])) continue if tag.endswith(u'S'): ret.append((word, tag[:(-1)])) continue ret.append((word, tag)) return ret
[ "def", "_normalize_tags", "(", "chunk", ")", ":", "ret", "=", "[", "]", "for", "(", "word", ",", "tag", ")", "in", "chunk", ":", "if", "(", "(", "tag", "==", "u'NP-TL'", ")", "or", "(", "tag", "==", "u'NP'", ")", ")", ":", "ret", ".", "append",...
normalize the corpus tags .
train
false
29,281
def start_threaded_server(*args, **kwargs): t = Thread(target=threaded_server, args=args, kwargs=kwargs) t.setDaemon(True) t.start()
[ "def", "start_threaded_server", "(", "*", "args", ",", "**", "kwargs", ")", ":", "t", "=", "Thread", "(", "target", "=", "threaded_server", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "t", ".", "setDaemon", "(", "True", ")", "t", "."...
starts the threaded_server on a separate thread .
train
false
29,282
def decode_receipt(receipt): with statsd.timer('services.decode'): if settings.SIGNING_SERVER_ACTIVE: verifier = certs.ReceiptVerifier(valid_issuers=settings.SIGNING_VALID_ISSUERS) try: result = verifier.verify(receipt) except ExpiredSignatureError: return jwt.decode(receipt.split('~')[1], verify=False) if (not result): raise VerificationError() return jwt.decode(receipt.split('~')[1], verify=False) else: key = jwt.rsa_load(settings.WEBAPPS_RECEIPT_KEY) raw = jwt.decode(receipt, key, algorithms=settings.SUPPORTED_JWT_ALGORITHMS) return raw
[ "def", "decode_receipt", "(", "receipt", ")", ":", "with", "statsd", ".", "timer", "(", "'services.decode'", ")", ":", "if", "settings", ".", "SIGNING_SERVER_ACTIVE", ":", "verifier", "=", "certs", ".", "ReceiptVerifier", "(", "valid_issuers", "=", "settings", ...
cracks the receipt using the private key .
train
false
29,285
def add_env_headers(headers, env_vars): headers.update(dict(((('x-kumascript-env-%s' % k), base64.b64encode(json.dumps(v))) for (k, v) in env_vars.items()))) return headers
[ "def", "add_env_headers", "(", "headers", ",", "env_vars", ")", ":", "headers", ".", "update", "(", "dict", "(", "(", "(", "(", "'x-kumascript-env-%s'", "%", "k", ")", ",", "base64", ".", "b64encode", "(", "json", ".", "dumps", "(", "v", ")", ")", ")...
encode env_vars as kumascript headers .
train
false
29,286
def _set_partitions(n): p = ([0] * n) q = ([0] * n) nc = 1 (yield (nc, q)) while (nc != n): m = n while 1: m -= 1 i = q[m] if (p[i] != 1): break q[m] = 0 i += 1 q[m] = i m += 1 nc += (m - n) p[0] += (n - m) if (i == nc): p[nc] = 0 nc += 1 p[(i - 1)] -= 1 p[i] += 1 (yield (nc, q))
[ "def", "_set_partitions", "(", "n", ")", ":", "p", "=", "(", "[", "0", "]", "*", "n", ")", "q", "=", "(", "[", "0", "]", "*", "n", ")", "nc", "=", "1", "(", "yield", "(", "nc", ",", "q", ")", ")", "while", "(", "nc", "!=", "n", ")", "...
cycle through all partions of n elements .
train
false
29,287
def get_instance_type(instance_type_id, ctxt=None, inactive=False): if (instance_type_id is None): return get_default_instance_type() if (ctxt is None): ctxt = context.get_admin_context() if inactive: ctxt = ctxt.elevated(read_deleted='yes') return db.instance_type_get(ctxt, instance_type_id)
[ "def", "get_instance_type", "(", "instance_type_id", ",", "ctxt", "=", "None", ",", "inactive", "=", "False", ")", ":", "if", "(", "instance_type_id", "is", "None", ")", ":", "return", "get_default_instance_type", "(", ")", "if", "(", "ctxt", "is", "None", ...
retrieves single instance type by id .
train
false
29,289
def _models_generator(): for model in get_models(): (yield (unicode(model._meta.verbose_name), model)) (yield (unicode(model._meta.verbose_name_plural), model))
[ "def", "_models_generator", "(", ")", ":", "for", "model", "in", "get_models", "(", ")", ":", "(", "yield", "(", "unicode", "(", "model", ".", "_meta", ".", "verbose_name", ")", ",", "model", ")", ")", "(", "yield", "(", "unicode", "(", "model", ".",...
build a hash of model verbose names to models .
train
false
29,290
def test_collect_functools_partial(testdir): testdir.makepyfile("\n import functools\n import pytest\n\n @pytest.fixture\n def fix1():\n return 'fix1'\n\n @pytest.fixture\n def fix2():\n return 'fix2'\n\n def check1(i, fix1):\n assert i == 2\n assert fix1 == 'fix1'\n\n def check2(fix1, i):\n assert i == 2\n assert fix1 == 'fix1'\n\n def check3(fix1, i, fix2):\n assert i == 2\n assert fix1 == 'fix1'\n assert fix2 == 'fix2'\n\n test_ok_1 = functools.partial(check1, i=2)\n test_ok_2 = functools.partial(check1, i=2, fix1='fix1')\n test_ok_3 = functools.partial(check1, 2)\n test_ok_4 = functools.partial(check2, i=2)\n test_ok_5 = functools.partial(check3, i=2)\n test_ok_6 = functools.partial(check3, i=2, fix1='fix1')\n\n test_fail_1 = functools.partial(check2, 2)\n test_fail_2 = functools.partial(check3, 2)\n ") result = testdir.inline_run() result.assertoutcome(passed=6, failed=2)
[ "def", "test_collect_functools_partial", "(", "testdir", ")", ":", "testdir", ".", "makepyfile", "(", "\"\\n import functools\\n import pytest\\n\\n @pytest.fixture\\n def fix1():\\n return 'fix1'\\n\\n @pytest.fixture\\n def fix2():\\n ...
test that collection of functools .
train
false
29,291
@permission_required([('AccountLookup', 'View')]) def user_purchases(request, user_id): user = get_object_or_404(UserProfile, pk=user_id) is_admin = acl.action_allowed(request, 'Users', 'Edit') products = purchase_list(request, user) return render(request, 'lookup/user_purchases.html', {'pager': products, 'account': user, 'is_admin': is_admin, 'single': bool(None), 'show_link': False})
[ "@", "permission_required", "(", "[", "(", "'AccountLookup'", ",", "'View'", ")", "]", ")", "def", "user_purchases", "(", "request", ",", "user_id", ")", ":", "user", "=", "get_object_or_404", "(", "UserProfile", ",", "pk", "=", "user_id", ")", "is_admin", ...
shows the purchase page for another user .
train
false
29,292
def processor(): return uname()[5]
[ "def", "processor", "(", ")", ":", "return", "uname", "(", ")", "[", "5", "]" ]
run processor .
train
false
29,293
def _parameter_values(parameter_values_from_pillars, parameter_value_overrides): from_pillars = copy.deepcopy(__salt__['pillar.get'](parameter_values_from_pillars)) from_pillars.update(parameter_value_overrides) parameter_values = _standardize(from_pillars) return _properties_from_dict(parameter_values, key_name='id')
[ "def", "_parameter_values", "(", "parameter_values_from_pillars", ",", "parameter_value_overrides", ")", ":", "from_pillars", "=", "copy", ".", "deepcopy", "(", "__salt__", "[", "'pillar.get'", "]", "(", "parameter_values_from_pillars", ")", ")", "from_pillars", ".", ...
return a dictionary of parameter values that configure the pipeline parameter_values_from_pillars the pillar key to use for lookup parameter_value_overrides parameter values to use .
train
true
29,294
def generate_external_user_with_resp(service_url, user=True, release=True): cas_resp = make_external_response(release=release) validated_credentials = cas.validate_external_credential(cas_resp.user) if user: user = UserFactory.build() user.external_identity = {validated_credentials['provider']: {validated_credentials['id']: 'VERIFIED'}} user.save() return (user, validated_credentials, cas_resp) else: user = {'external_id_provider': validated_credentials['provider'], 'external_id': validated_credentials['id'], 'fullname': validated_credentials['id'], 'access_token': cas_resp.attributes['accessToken'], 'service_url': service_url} return (user, validated_credentials, cas_resp)
[ "def", "generate_external_user_with_resp", "(", "service_url", ",", "user", "=", "True", ",", "release", "=", "True", ")", ":", "cas_resp", "=", "make_external_response", "(", "release", "=", "release", ")", "validated_credentials", "=", "cas", ".", "validate_exte...
generate mock user .
train
false
29,298
def update_source_unit_index(writer, unit): writer.update_document(pk=unit.pk, source=force_text(unit.source), context=force_text(unit.context), location=force_text(unit.location))
[ "def", "update_source_unit_index", "(", "writer", ",", "unit", ")", ":", "writer", ".", "update_document", "(", "pk", "=", "unit", ".", "pk", ",", "source", "=", "force_text", "(", "unit", ".", "source", ")", ",", "context", "=", "force_text", "(", "unit...
updates source index for given unit .
train
false
29,300
def load_image(path, height, width, mode='RGB'): image = PIL.Image.open(path) image = image.convert(mode) image = np.array(image) image = scipy.misc.imresize(image, (height, width), 'bilinear') return image
[ "def", "load_image", "(", "path", ",", "height", ",", "width", ",", "mode", "=", "'RGB'", ")", ":", "image", "=", "PIL", ".", "Image", ".", "open", "(", "path", ")", "image", "=", "image", ".", "convert", "(", "mode", ")", "image", "=", "np", "."...
load an image from disk returns an np .
train
false
29,301
def apply_json_patch(record, ops): data = record.copy() permissions = {'read': set(), 'write': set()} permissions.update(data.pop('__permissions__', {})) permissions = {k: {i: i for i in v} for (k, v) in permissions.items()} resource = {'data': data, 'permissions': permissions} for op in ops: if ('path' in op): if op['path'].startswith(('/permissions/read/', '/permissions/write/')): op['value'] = op['path'].split('/')[(-1)] try: result = jsonpatch.apply_patch(resource, ops) except (jsonpatch.JsonPatchException, jsonpatch.JsonPointerException) as e: raise ValueError(e) return result
[ "def", "apply_json_patch", "(", "record", ",", "ops", ")", ":", "data", "=", "record", ".", "copy", "(", ")", "permissions", "=", "{", "'read'", ":", "set", "(", ")", ",", "'write'", ":", "set", "(", ")", "}", "permissions", ".", "update", "(", "da...
apply json patch operations using jsonpatch .
train
false
29,304
def circle_grid(image, pattern_size=(4, 11)): (status, centers) = cv2.findCirclesGridDefault(image, pattern_size, flags=cv2.CALIB_CB_ASYMMETRIC_GRID) if status: return centers else: return None
[ "def", "circle_grid", "(", "image", ",", "pattern_size", "=", "(", "4", ",", "11", ")", ")", ":", "(", "status", ",", "centers", ")", "=", "cv2", ".", "findCirclesGridDefault", "(", "image", ",", "pattern_size", ",", "flags", "=", "cv2", ".", "CALIB_CB...
circle grid: finds an assymetric circle pattern - circle_id: sorted from bottom left to top right - if no circle_id is given .
train
false
29,305
def convert_es_fmt_to_uuid(es_label): if isinstance(es_label, six.text_type): es_label = es_label.encode('utf-8') if es_label.startswith('tmp-'): es_label = es_label[4:] es_label = es_label.ljust(32, '=') es_label = binascii.hexlify(base64.b32decode(es_label)) if six.PY3: es_label = es_label.decode('ascii') return uuid.UUID(es_label)
[ "def", "convert_es_fmt_to_uuid", "(", "es_label", ")", ":", "if", "isinstance", "(", "es_label", ",", "six", ".", "text_type", ")", ":", "es_label", "=", "es_label", ".", "encode", "(", "'utf-8'", ")", "if", "es_label", ".", "startswith", "(", "'tmp-'", ")...
converts e-series name format to uuid .
train
false
29,306
def _split_explanation(explanation): raw_lines = (explanation or u('')).split('\n') lines = [raw_lines[0]] for l in raw_lines[1:]: if (l and (l[0] in ['{', '}', '~', '>'])): lines.append(l) else: lines[(-1)] += ('\\n' + l) return lines
[ "def", "_split_explanation", "(", "explanation", ")", ":", "raw_lines", "=", "(", "explanation", "or", "u", "(", "''", ")", ")", ".", "split", "(", "'\\n'", ")", "lines", "=", "[", "raw_lines", "[", "0", "]", "]", "for", "l", "in", "raw_lines", "[", ...
return a list of individual lines in the explanation this will return a list of lines split on } and any other newlines will be escaped and appear in the line as the literal characters .
train
true
29,307
@profiler.trace def add_group_role(request, role, group, domain=None, project=None): manager = keystoneclient(request, admin=True).roles return manager.grant(role=role, group=group, domain=domain, project=project)
[ "@", "profiler", ".", "trace", "def", "add_group_role", "(", "request", ",", "role", ",", "group", ",", "domain", "=", "None", ",", "project", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".",...
adds a role for a group on a domain or project .
train
true
29,308
def latin(s): if (not isinstance(s, unicode)): s = s.decode('utf-8') return all((unicodedata.name(ch).startswith('LATIN') for ch in s if ch.isalpha()))
[ "def", "latin", "(", "s", ")", ":", "if", "(", "not", "isinstance", "(", "s", ",", "unicode", ")", ")", ":", "s", "=", "s", ".", "decode", "(", "'utf-8'", ")", "return", "all", "(", "(", "unicodedata", ".", "name", "(", "ch", ")", ".", "startsw...
returns true if the string contains only latin-1 characters .
train
false