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
14,339
def generate_album_info(album_id, track_ids): tracks = [generate_track_info(id) for id in track_ids] album = AlbumInfo(album_id=u'album info', album=u'album info', artist=u'album info', artist_id=u'album info', tracks=tracks) for field in ALBUM_INFO_FIELDS: setattr(album, field, u'album info') return album
[ "def", "generate_album_info", "(", "album_id", ",", "track_ids", ")", ":", "tracks", "=", "[", "generate_track_info", "(", "id", ")", "for", "id", "in", "track_ids", "]", "album", "=", "AlbumInfo", "(", "album_id", "=", "u'album info'", ",", "album", "=", ...
return albuminfo populated with mock data .
train
false
14,340
def project_jnap_opts(): T = current.T return {1: T('JNAP-1: Strategic Area 1: Governance'), 2: T('JNAP-2: Strategic Area 2: Monitoring'), 3: T('JNAP-3: Strategic Area 3: Disaster Management'), 4: T('JNAP-4: Strategic Area 4: Risk Reduction and Climate Change Adaptation')}
[ "def", "project_jnap_opts", "(", ")", ":", "T", "=", "current", ".", "T", "return", "{", "1", ":", "T", "(", "'JNAP-1: Strategic Area 1: Governance'", ")", ",", "2", ":", "T", "(", "'JNAP-2: Strategic Area 2: Monitoring'", ")", ",", "3", ":", "T", "(", "'J...
provide the options for the jnap filter jnap : applies to cook islands only .
train
false
14,343
def read_int(s, start_position): m = _READ_INT_RE.match(s, start_position) if (not m): raise ReadError('integer', start_position) return (int(m.group()), m.end())
[ "def", "read_int", "(", "s", ",", "start_position", ")", ":", "m", "=", "_READ_INT_RE", ".", "match", "(", "s", ",", "start_position", ")", "if", "(", "not", "m", ")", ":", "raise", "ReadError", "(", "'integer'", ",", "start_position", ")", "return", "...
reads n ints from a file .
train
false
14,344
@api_wrapper def create_filesystem(module, system): if (not module.check_mode): filesystem = system.filesystems.create(name=module.params['name'], pool=get_pool(module, system)) if module.params['size']: size = Capacity(module.params['size']).roundup((64 * KiB)) filesystem.update_size(size) module.exit_json...
[ "@", "api_wrapper", "def", "create_filesystem", "(", "module", ",", "system", ")", ":", "if", "(", "not", "module", ".", "check_mode", ")", ":", "filesystem", "=", "system", ".", "filesystems", ".", "create", "(", "name", "=", "module", ".", "params", "[...
create filesystem .
train
false
14,348
def unchanged_required(argument): if (argument is None): raise ValueError('argument required but none supplied') else: return argument
[ "def", "unchanged_required", "(", "argument", ")", ":", "if", "(", "argument", "is", "None", ")", ":", "raise", "ValueError", "(", "'argument required but none supplied'", ")", "else", ":", "return", "argument" ]
return the argument text .
train
false
14,349
@pytest.mark.parametrize('sep', [None, ' sep ']) def test_str_cat(sep): if (sep is None): expr = t_str_cat.name.str_cat(t_str_cat.comment) expected = '\n SELECT accounts2.name || accounts2.comment\n AS anon_1 FROM accounts2\n ' else: expr = t_str_cat.name.st...
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'sep'", ",", "[", "None", ",", "' sep '", "]", ")", "def", "test_str_cat", "(", "sep", ")", ":", "if", "(", "sep", "is", "None", ")", ":", "expr", "=", "t_str_cat", ".", "name", ".", "str_cat", ...
need at least two string columns to test str_cat .
train
false
14,350
def test_classification_report_imbalanced_multiclass_with_long_string_label(): (y_true, y_pred, _) = make_prediction(binary=False) labels = np.array(['blue', ('green' * 5), 'red']) y_true = labels[y_true] y_pred = labels[y_pred] expected_report = 'pre rec spe f1 geo iba sup blue 0.83 0.79 0.92 0.81 0.86 0.74 24 gr...
[ "def", "test_classification_report_imbalanced_multiclass_with_long_string_label", "(", ")", ":", "(", "y_true", ",", "y_pred", ",", "_", ")", "=", "make_prediction", "(", "binary", "=", "False", ")", "labels", "=", "np", ".", "array", "(", "[", "'blue'", ",", ...
test classification report with long string label .
train
false
14,351
@with_session def config_changed(task=None, session=None): log.debug((u'Marking config for %s as changed.' % (task or u'all tasks'))) task_hash = session.query(TaskConfigHash) if task: task_hash = task_hash.filter((TaskConfigHash.task == task)) task_hash.delete()
[ "@", "with_session", "def", "config_changed", "(", "task", "=", "None", ",", "session", "=", "None", ")", ":", "log", ".", "debug", "(", "(", "u'Marking config for %s as changed.'", "%", "(", "task", "or", "u'all tasks'", ")", ")", ")", "task_hash", "=", "...
returns true if config has changed .
train
false
14,353
def _get_decimal128(data, position, dummy0, dummy1, dummy2): end = (position + 16) return (Decimal128.from_bid(data[position:end]), end)
[ "def", "_get_decimal128", "(", "data", ",", "position", ",", "dummy0", ",", "dummy1", ",", "dummy2", ")", ":", "end", "=", "(", "position", "+", "16", ")", "return", "(", "Decimal128", ".", "from_bid", "(", "data", "[", "position", ":", "end", "]", "...
decode a bson decimal128 to bson .
train
true
14,354
def get_note_message(note): assert (note <= 10), ("Note is %.2f. Either you cheated, or pylint's broken!" % note) if (note < 0): msg = 'You have to do something quick !' elif (note < 1): msg = 'Hey! This is really dreadful. Or maybe pylint is buggy?' elif (note < 2): msg = "Come on! You can't be proud of this...
[ "def", "get_note_message", "(", "note", ")", ":", "assert", "(", "note", "<=", "10", ")", ",", "(", "\"Note is %.2f. Either you cheated, or pylint's broken!\"", "%", "note", ")", "if", "(", "note", "<", "0", ")", ":", "msg", "=", "'You have to do something quick...
return a message according to note note is a float < 10 .
train
false
14,355
def b64_string(input_string): return b64encode(input_string.encode('utf-8')).decode('utf-8')
[ "def", "b64_string", "(", "input_string", ")", ":", "return", "b64encode", "(", "input_string", ".", "encode", "(", "'utf-8'", ")", ")", ".", "decode", "(", "'utf-8'", ")" ]
return a base64 encoded string from input_string .
train
false
14,357
def joined(subset=None, show_ipv4=False): return list_state(subset=subset, show_ipv4=show_ipv4, state='joined')
[ "def", "joined", "(", "subset", "=", "None", ",", "show_ipv4", "=", "False", ")", ":", "return", "list_state", "(", "subset", "=", "subset", ",", "show_ipv4", "=", "show_ipv4", ",", "state", "=", "'joined'", ")" ]
ensure the current node joined to a cluster with node user@host name irrelevant .
train
false
14,358
def _check_instance_uid_match(user): return (os.geteuid() == __salt__['file.user_to_uid'](user))
[ "def", "_check_instance_uid_match", "(", "user", ")", ":", "return", "(", "os", ".", "geteuid", "(", ")", "==", "__salt__", "[", "'file.user_to_uid'", "]", "(", "user", ")", ")" ]
returns true if running instances uid matches the specified user uid .
train
false
14,359
def pre_begin(opt): global options options = opt for fn in pre_configure: fn(options, file_config)
[ "def", "pre_begin", "(", "opt", ")", ":", "global", "options", "options", "=", "opt", "for", "fn", "in", "pre_configure", ":", "fn", "(", "options", ",", "file_config", ")" ]
things to set up early .
train
false
14,360
def confidence_interval_dichotomous(point_estimate, sample_size, confidence=0.95, bias=False, percentage=True, **kwargs): alpha = ppf(((confidence + 1) / 2), (sample_size - 1)) p = point_estimate if percentage: p /= 100 margin = sqrt(((p * (1 - p)) / sample_size)) if bias: margin += (0.5 / sample_size) if per...
[ "def", "confidence_interval_dichotomous", "(", "point_estimate", ",", "sample_size", ",", "confidence", "=", "0.95", ",", "bias", "=", "False", ",", "percentage", "=", "True", ",", "**", "kwargs", ")", ":", "alpha", "=", "ppf", "(", "(", "(", "confidence", ...
dichotomous confidence interval from sample size and maybe a bias .
train
true
14,362
def pre_prompt_hook(self): return None
[ "def", "pre_prompt_hook", "(", "self", ")", ":", "return", "None" ]
run before displaying the next prompt use this e .
train
false
14,365
@handle_response_format @treeio_login_required def equity_add(request, response_format='html'): equities = Object.filter_by_request(request, Equity.objects, mode='r') if request.POST: if ('cancel' not in request.POST): equity = Equity() form = EquityForm(request.user.profile, request.POST, instance=equity) ...
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "equity_add", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "equities", "=", "Object", ".", "filter_by_request", "(", "request", ",", "Equity", ".", "objects", ",", "mode", "=...
new equity form .
train
false
14,367
@register.simple_tag(takes_context=True) def pageurl(context, page): return page.relative_url(context[u'request'].site)
[ "@", "register", ".", "simple_tag", "(", "takes_context", "=", "True", ")", "def", "pageurl", "(", "context", ",", "page", ")", ":", "return", "page", ".", "relative_url", "(", "context", "[", "u'request'", "]", ".", "site", ")" ]
outputs a pages url as relative if its within the same site as the current page .
train
false
14,371
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
14,372
def ensure_metadata_ip(): _execute('ip', 'addr', 'add', '169.254.169.254/32', 'scope', 'link', 'dev', 'lo', run_as_root=True, check_exit_code=[0, 2, 254])
[ "def", "ensure_metadata_ip", "(", ")", ":", "_execute", "(", "'ip'", ",", "'addr'", ",", "'add'", ",", "'169.254.169.254/32'", ",", "'scope'", ",", "'link'", ",", "'dev'", ",", "'lo'", ",", "run_as_root", "=", "True", ",", "check_exit_code", "=", "[", "0",...
sets up local metadata ip .
train
false
14,373
def expand_db_html(html, for_editor=False): def replace_a_tag(m): attrs = extract_attrs(m.group(1)) if (u'linktype' not in attrs): return m.group(0) handler = get_link_handler(attrs[u'linktype']) return handler.expand_db_attributes(attrs, for_editor) def replace_embed_tag(m): attrs = extract_attrs(m.grou...
[ "def", "expand_db_html", "(", "html", ",", "for_editor", "=", "False", ")", ":", "def", "replace_a_tag", "(", "m", ")", ":", "attrs", "=", "extract_attrs", "(", "m", ".", "group", "(", "1", ")", ")", "if", "(", "u'linktype'", "not", "in", "attrs", ")...
expand database-representation html into proper html usable in either templates or the rich text editor .
train
false
14,375
def pretty_xml(container, name, raw): root = container.parse_xml(raw) if (name == container.opf_name): pretty_opf(root) pretty_xml_tree(root) return serialize(root, u'text/xml')
[ "def", "pretty_xml", "(", "container", ",", "name", ",", "raw", ")", ":", "root", "=", "container", ".", "parse_xml", "(", "raw", ")", "if", "(", "name", "==", "container", ".", "opf_name", ")", ":", "pretty_opf", "(", "root", ")", "pretty_xml_tree", "...
pretty print the xml represented as a string in raw .
train
false
14,376
def _notifications_from_dashboard_activity_list(user_dict, since): context = {'model': model, 'session': model.Session, 'user': user_dict['id']} activity_list = logic.get_action('dashboard_activity_list')(context, {}) activity_list = [activity for activity in activity_list if (activity['user_id'] != user_dict['id'])...
[ "def", "_notifications_from_dashboard_activity_list", "(", "user_dict", ",", "since", ")", ":", "context", "=", "{", "'model'", ":", "model", ",", "'session'", ":", "model", ".", "Session", ",", "'user'", ":", "user_dict", "[", "'id'", "]", "}", "activity_list...
return any email notifications from the given users dashboard activity list since since .
train
false
14,377
def dump_neigh_entries(ip_version, device=None, namespace=None, **kwargs): return list(privileged.dump_neigh_entries(ip_version, device, namespace, **kwargs))
[ "def", "dump_neigh_entries", "(", "ip_version", ",", "device", "=", "None", ",", "namespace", "=", "None", ",", "**", "kwargs", ")", ":", "return", "list", "(", "privileged", ".", "dump_neigh_entries", "(", "ip_version", ",", "device", ",", "namespace", ",",...
dump all neighbour entries .
train
false
14,379
def disable_share(cookie, tokens, shareid_list): url = ''.join([const.PAN_URL, 'share/cancel?channel=chunlei&clienttype=0&web=1', '&bdstoken=', tokens['bdstoken']]) data = ('shareid_list=' + encoder.encode_uri(json.dumps(shareid_list))) req = net.urlopen(url, headers={'Cookie': cookie.header_output(), 'Content-type'...
[ "def", "disable_share", "(", "cookie", ",", "tokens", ",", "shareid_list", ")", ":", "url", "=", "''", ".", "join", "(", "[", "const", ".", "PAN_URL", ",", "'share/cancel?channel=chunlei&clienttype=0&web=1'", ",", "'&bdstoken='", ",", "tokens", "[", "'bdstoken'"...
shareid_list 是一个list .
train
true
14,380
def get_data_from_request(): return {'request': {'url': ('%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path'])), 'query_string': web.ctx.query, 'method': web.ctx.method, 'data': web.data(), 'headers': dict(get_headers(web.ctx.environ)), 'env': dict(get_environ(web.ctx.environ))}}
[ "def", "get_data_from_request", "(", ")", ":", "return", "{", "'request'", ":", "{", "'url'", ":", "(", "'%s://%s%s'", "%", "(", "web", ".", "ctx", "[", "'protocol'", "]", ",", "web", ".", "ctx", "[", "'host'", "]", ",", "web", ".", "ctx", "[", "'p...
returns request data extracted from web .
train
true
14,381
def compute_cluster_state(node_state, additional_node_states, nonmanifest_datasets): return DeploymentState(nodes=({node_state} | additional_node_states), nonmanifest_datasets={dataset.dataset_id: dataset for dataset in nonmanifest_datasets})
[ "def", "compute_cluster_state", "(", "node_state", ",", "additional_node_states", ",", "nonmanifest_datasets", ")", ":", "return", "DeploymentState", "(", "nodes", "=", "(", "{", "node_state", "}", "|", "additional_node_states", ")", ",", "nonmanifest_datasets", "=", ...
computes the cluster_state from the passed in arguments .
train
false
14,382
@library.filter def datetime(value, kind=u'datetime', format=u'medium', tz=True): locale = get_current_babel_locale() if (type(value) is date): return format_date(value, format=format, locale=locale) if tz: value = localtime(value, (None if (tz is True) else tz)) if (kind == u'datetime'): return format_dateti...
[ "@", "library", ".", "filter", "def", "datetime", "(", "value", ",", "kind", "=", "u'datetime'", ",", "format", "=", "u'medium'", ",", "tz", "=", "True", ")", ":", "locale", "=", "get_current_babel_locale", "(", ")", "if", "(", "type", "(", "value", ")...
format a datetime for human consumption .
train
false
14,384
def PossessiveRepeat(element, min_count, max_count): return Atomic(GreedyRepeat(element, min_count, max_count))
[ "def", "PossessiveRepeat", "(", "element", ",", "min_count", ",", "max_count", ")", ":", "return", "Atomic", "(", "GreedyRepeat", "(", "element", ",", "min_count", ",", "max_count", ")", ")" ]
builds a possessive repeat .
train
false
14,386
def submit_detailed_enrollment_features_csv(request, course_key): task_type = 'detailed_enrollment_report' task_class = enrollment_report_features_csv task_input = {} task_key = '' return submit_task(request, task_type, task_class, course_key, task_input, task_key)
[ "def", "submit_detailed_enrollment_features_csv", "(", "request", ",", "course_key", ")", ":", "task_type", "=", "'detailed_enrollment_report'", "task_class", "=", "enrollment_report_features_csv", "task_input", "=", "{", "}", "task_key", "=", "''", "return", "submit_task...
submits a task to generate a csv containing detailed enrollment info .
train
false
14,388
def longest_line_length(code): return max((len(line) for line in code.splitlines()))
[ "def", "longest_line_length", "(", "code", ")", ":", "return", "max", "(", "(", "len", "(", "line", ")", "for", "line", "in", "code", ".", "splitlines", "(", ")", ")", ")" ]
return length of longest line .
train
false
14,389
def combine_xyz(vec, square=False): if (vec.ndim != 2): raise ValueError('Input must be 2D') if ((vec.shape[0] % 3) != 0): raise ValueError('Input must have 3N rows') (n, p) = vec.shape if np.iscomplexobj(vec): vec = np.abs(vec) comb = (vec[0::3] ** 2) comb += (vec[1::3] ** 2) comb += (vec[2::3] ** 2) if ...
[ "def", "combine_xyz", "(", "vec", ",", "square", "=", "False", ")", ":", "if", "(", "vec", ".", "ndim", "!=", "2", ")", ":", "raise", "ValueError", "(", "'Input must be 2D'", ")", "if", "(", "(", "vec", ".", "shape", "[", "0", "]", "%", "3", ")",...
compute the three cartesian components of a vector or matrix together .
train
false
14,390
def ssh_main(): ip = raw_input('Enter IP Address: ') username = 'pyclass' password = getpass() test_device = NetworkDevice(ip, username, password) (remote_conn_pre, remote_conn, _) = ssh.establish_connection(ip, username, password) ssh.disable_paging(remote_conn) remote_conn.send('\n') remote_conn.send('show ve...
[ "def", "ssh_main", "(", ")", ":", "ip", "=", "raw_input", "(", "'Enter IP Address: '", ")", "username", "=", "'pyclass'", "password", "=", "getpass", "(", ")", "test_device", "=", "NetworkDevice", "(", "ip", ",", "username", ",", "password", ")", "(", "rem...
process show version using ssh .
train
false
14,391
def naughty_strings(filepath=FILEPATH): strings = [] with open(filepath, 'r') as f: strings = f.readlines() strings = [x.strip(u'\n') for x in strings] strings = [x for x in strings if (x and (not x.startswith(u'#')))] strings.insert(0, u'') return strings
[ "def", "naughty_strings", "(", "filepath", "=", "FILEPATH", ")", ":", "strings", "=", "[", "]", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "f", ":", "strings", "=", "f", ".", "readlines", "(", ")", "strings", "=", "[", "x", ".", "strip...
get the list of naughty_strings .
train
false
14,392
def trimmed_mean_ci(data, limits=(0.2, 0.2), inclusive=(True, True), alpha=0.05, axis=None): data = ma.array(data, copy=False) trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis) tmean = trimmed.mean(axis) tstde = mstats.trimmed_stde(data, limits=limits, inclusive=inclusive, axis=axis) df =...
[ "def", "trimmed_mean_ci", "(", "data", ",", "limits", "=", "(", "0.2", ",", "0.2", ")", ",", "inclusive", "=", "(", "True", ",", "True", ")", ",", "alpha", "=", "0.05", ",", "axis", "=", "None", ")", ":", "data", "=", "ma", ".", "array", "(", "...
selected confidence interval of the trimmed mean along the given axis .
train
false
14,393
def Delete(keys, **kwargs): return DeleteAsync(keys, **kwargs).get_result()
[ "def", "Delete", "(", "keys", ",", "**", "kwargs", ")", ":", "return", "DeleteAsync", "(", "keys", ",", "**", "kwargs", ")", ".", "get_result", "(", ")" ]
deletes one or more entities from the datastore .
train
false
14,395
def p_initializer_2(t): pass
[ "def", "p_initializer_2", "(", "t", ")", ":", "pass" ]
initializer : lbrace initializer_list rbrace | lbrace initializer_list comma rbrace .
train
false
14,396
def underscore(text): return UNDERSCORE[1].sub('\\1_\\2', UNDERSCORE[0].sub('\\1_\\2', text)).lower()
[ "def", "underscore", "(", "text", ")", ":", "return", "UNDERSCORE", "[", "1", "]", ".", "sub", "(", "'\\\\1_\\\\2'", ",", "UNDERSCORE", "[", "0", "]", ".", "sub", "(", "'\\\\1_\\\\2'", ",", "text", ")", ")", ".", "lower", "(", ")" ]
convert dots to underscore in a string .
train
true
14,397
def _invert(eq, *symbols, **kwargs): eq = sympify(eq) free = eq.free_symbols if (not symbols): symbols = free if (not (free & set(symbols))): return (eq, S.Zero) dointpow = bool(kwargs.get('integer_power', False)) lhs = eq rhs = S.Zero while True: was = lhs while True: (indep, dep) = lhs.as_independe...
[ "def", "_invert", "(", "eq", ",", "*", "symbols", ",", "**", "kwargs", ")", ":", "eq", "=", "sympify", "(", "eq", ")", "free", "=", "eq", ".", "free_symbols", "if", "(", "not", "symbols", ")", ":", "symbols", "=", "free", "if", "(", "not", "(", ...
reduce the complex valued equation f(x) = y to a set of equations {g(x) = h_1(y) .
train
false
14,398
def _CheckStatus(status): if (status.code() != search_service_pb.SearchServiceError.OK): if (status.code() in _ERROR_MAP): raise _ERROR_MAP[status.code()](status.error_detail()) else: raise InternalError(status.error_detail())
[ "def", "_CheckStatus", "(", "status", ")", ":", "if", "(", "status", ".", "code", "(", ")", "!=", "search_service_pb", ".", "SearchServiceError", ".", "OK", ")", ":", "if", "(", "status", ".", "code", "(", ")", "in", "_ERROR_MAP", ")", ":", "raise", ...
checks whether a requeststatus has a value of ok .
train
false
14,399
def addVector3Loop(loop, loops, vertexes, z): vector3Loop = [] for point in loop: vector3Index = Vector3Index(len(vertexes), point.real, point.imag, z) vector3Loop.append(vector3Index) vertexes.append(vector3Index) if (len(vector3Loop) > 0): loops.append(vector3Loop)
[ "def", "addVector3Loop", "(", "loop", ",", "loops", ",", "vertexes", ",", "z", ")", ":", "vector3Loop", "=", "[", "]", "for", "point", "in", "loop", ":", "vector3Index", "=", "Vector3Index", "(", "len", "(", "vertexes", ")", ",", "point", ".", "real", ...
add vector3loop to loops if there is something in it .
train
false
14,400
def setup_console_logger(log_level='error', log_format=None, date_format=None): if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return __remove_temp_logging_handler() if (log_level is None): log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), l...
[ "def", "setup_console_logger", "(", "log_level", "=", "'error'", ",", "log_format", "=", "None", ",", "date_format", "=", "None", ")", ":", "if", "is_console_configured", "(", ")", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "warning", "(", ...
setup the console logger .
train
true
14,403
def load_soups(config): soups = {} for (page, path) in config[u'sources'].items(): with open(path, u'rb') as orig_file: soups[page] = beautiful_soup(orig_file.read().decode(u'utf-8')) return soups
[ "def", "load_soups", "(", "config", ")", ":", "soups", "=", "{", "}", "for", "(", "page", ",", "path", ")", "in", "config", "[", "u'sources'", "]", ".", "items", "(", ")", ":", "with", "open", "(", "path", ",", "u'rb'", ")", "as", "orig_file", ":...
generate beautifulsoup ast for each page listed in config .
train
false
14,404
def must_answer_survey(course_descriptor, user): if (not is_survey_required_for_course(course_descriptor)): return False survey = SurveyForm.get(course_descriptor.course_survey_name) has_staff_access = has_access(user, 'staff', course_descriptor) answered_survey = SurveyAnswer.do_survey_answers_exist(survey, user...
[ "def", "must_answer_survey", "(", "course_descriptor", ",", "user", ")", ":", "if", "(", "not", "is_survey_required_for_course", "(", "course_descriptor", ")", ")", ":", "return", "False", "survey", "=", "SurveyForm", ".", "get", "(", "course_descriptor", ".", "...
returns whether a user needs to answer a required survey .
train
false
14,405
def device_exists(device): (_out, err) = _execute('ip', 'link', 'show', 'dev', device, check_exit_code=False, run_as_root=True) return (not err)
[ "def", "device_exists", "(", "device", ")", ":", "(", "_out", ",", "err", ")", "=", "_execute", "(", "'ip'", ",", "'link'", ",", "'show'", ",", "'dev'", ",", "device", ",", "check_exit_code", "=", "False", ",", "run_as_root", "=", "True", ")", "return"...
return true if the device exists in the namespace .
train
false
14,406
def print_duration(method): def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() print ('%r %2.2f sec' % (method.__name__, (te - ts))) return result return timed
[ "def", "print_duration", "(", "method", ")", ":", "def", "timed", "(", "*", "args", ",", "**", "kw", ")", ":", "ts", "=", "time", ".", "time", "(", ")", "result", "=", "method", "(", "*", "args", ",", "**", "kw", ")", "te", "=", "time", ".", ...
prints out the runtime duration of a method in seconds .
train
true
14,407
def _runMultiple(tupleList): for (f, args, kwargs) in tupleList: f(*args, **kwargs)
[ "def", "_runMultiple", "(", "tupleList", ")", ":", "for", "(", "f", ",", "args", ",", "kwargs", ")", "in", "tupleList", ":", "f", "(", "*", "args", ",", "**", "kwargs", ")" ]
run a list of functions .
train
false
14,408
def _string_to_record_type(string): string = string.upper() record_type = getattr(RecordType, string) return record_type
[ "def", "_string_to_record_type", "(", "string", ")", ":", "string", "=", "string", ".", "upper", "(", ")", "record_type", "=", "getattr", "(", "RecordType", ",", "string", ")", "return", "record_type" ]
return a string representation of a dns record type to a libcloud recordtype enum .
train
true
14,409
def _restore_str(unused_name, value): return (None if (value == 'None') else value)
[ "def", "_restore_str", "(", "unused_name", ",", "value", ")", ":", "return", "(", "None", "if", "(", "value", "==", "'None'", ")", "else", "value", ")" ]
restores an string key-value pair from a renewal config file .
train
false
14,410
def test_saving_state_exclude_domains(hass_recorder): hass = hass_recorder({'exclude': {'domains': 'test'}}) states = _add_entities(hass, ['test.recorder', 'test2.recorder']) assert (len(states) == 1) assert (hass.states.get('test2.recorder') == states[0])
[ "def", "test_saving_state_exclude_domains", "(", "hass_recorder", ")", ":", "hass", "=", "hass_recorder", "(", "{", "'exclude'", ":", "{", "'domains'", ":", "'test'", "}", "}", ")", "states", "=", "_add_entities", "(", "hass", ",", "[", "'test.recorder'", ",",...
test saving and restoring a state .
train
false
14,411
def test_make_imbalance_bad_ratio(): min_c_ = 1 ratio = 0.0 assert_raises(ValueError, make_imbalance, X, Y, ratio, min_c_) ratio = (-2.0) assert_raises(ValueError, make_imbalance, X, Y, ratio, min_c_) ratio = 2.0 assert_raises(ValueError, make_imbalance, X, Y, ratio, min_c_) ratio = [0.5, 0.5] assert_raises(Va...
[ "def", "test_make_imbalance_bad_ratio", "(", ")", ":", "min_c_", "=", "1", "ratio", "=", "0.0", "assert_raises", "(", "ValueError", ",", "make_imbalance", ",", "X", ",", "Y", ",", "ratio", ",", "min_c_", ")", "ratio", "=", "(", "-", "2.0", ")", "assert_r...
test either if an error is raised with bad ratio argument .
train
false
14,412
def multiset_partitions_baseline(multiplicities, components): canon = [] for (ct, elem) in zip(multiplicities, components): canon.extend(([elem] * ct)) cache = set() n = len(canon) for (nc, q) in _set_partitions(n): rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(canon[i]) canonical = tu...
[ "def", "multiset_partitions_baseline", "(", "multiplicities", ",", "components", ")", ":", "canon", "=", "[", "]", "for", "(", "ct", ",", "elem", ")", "in", "zip", "(", "multiplicities", ",", "components", ")", ":", "canon", ".", "extend", "(", "(", "[",...
enumerates partitions of a multiset parameters multiplicities list of integer multiplicities of the components of the multiset .
train
false
14,413
def config_java(bin=None, options=None, verbose=False): global _java_bin, _java_options _java_bin = find_binary('java', bin, env_vars=['JAVAHOME', 'JAVA_HOME'], verbose=verbose, binary_names=['java.exe']) if (options is not None): if isinstance(options, compat.string_types): options = options.split() _java_op...
[ "def", "config_java", "(", "bin", "=", "None", ",", "options", "=", "None", ",", "verbose", "=", "False", ")", ":", "global", "_java_bin", ",", "_java_options", "_java_bin", "=", "find_binary", "(", "'java'", ",", "bin", ",", "env_vars", "=", "[", "'JAVA...
configure nltks java interface .
train
false
14,415
def membership_type(): if (not auth.s3_has_role(ADMIN)): s3.filter = auth.filter_by_root_org(s3db.member_membership_type) output = s3_rest_controller() return output
[ "def", "membership_type", "(", ")", ":", "if", "(", "not", "auth", ".", "s3_has_role", "(", "ADMIN", ")", ")", ":", "s3", ".", "filter", "=", "auth", ".", "filter_by_root_org", "(", "s3db", ".", "member_membership_type", ")", "output", "=", "s3_rest_contro...
rest controller .
train
false
14,417
def populate_project_info(attributes): if (('tenant_id' in attributes) and ('project_id' not in attributes)): attributes['project_id'] = attributes['tenant_id'] elif (('project_id' in attributes) and ('tenant_id' not in attributes)): attributes['tenant_id'] = attributes['project_id'] if (attributes.get('project_...
[ "def", "populate_project_info", "(", "attributes", ")", ":", "if", "(", "(", "'tenant_id'", "in", "attributes", ")", "and", "(", "'project_id'", "not", "in", "attributes", ")", ")", ":", "attributes", "[", "'project_id'", "]", "=", "attributes", "[", "'tenan...
ensure that both project_id and tenant_id attributes are present .
train
false
14,419
def enable_color(): global LIGHT_GREEN LIGHT_GREEN = '\x1b[1;32m' global LIGHT_RED LIGHT_RED = '\x1b[1;31m' global LIGHT_BLUE LIGHT_BLUE = '\x1b[1;34m' global DARK_RED DARK_RED = '\x1b[0;31m' global END_COLOR END_COLOR = '\x1b[0m'
[ "def", "enable_color", "(", ")", ":", "global", "LIGHT_GREEN", "LIGHT_GREEN", "=", "'\\x1b[1;32m'", "global", "LIGHT_RED", "LIGHT_RED", "=", "'\\x1b[1;31m'", "global", "LIGHT_BLUE", "LIGHT_BLUE", "=", "'\\x1b[1;34m'", "global", "DARK_RED", "DARK_RED", "=", "'\\x1b[0;3...
enable colors by setting colour code constants to ansi color codes .
train
false
14,420
def prop_show(prop, extra_args=None, cibfile=None): return item_show(item='property', item_id=prop, extra_args=extra_args, cibfile=cibfile)
[ "def", "prop_show", "(", "prop", ",", "extra_args", "=", "None", ",", "cibfile", "=", "None", ")", ":", "return", "item_show", "(", "item", "=", "'property'", ",", "item_id", "=", "prop", ",", "extra_args", "=", "extra_args", ",", "cibfile", "=", "cibfil...
show the value of a cluster property prop name of the property extra_args additional options for the pcs property command cibfile use cibfile instead of the live cib cli example: .
train
true
14,421
def check_net_address(addr, family): if (enum and PY3): assert isinstance(family, enum.IntEnum), family if (family == AF_INET): octs = [int(x) for x in addr.split('.')] assert (len(octs) == 4), addr for num in octs: assert (0 <= num <= 255), addr if (not PY3): addr = unicode(addr) ipaddress.IPv4Addr...
[ "def", "check_net_address", "(", "addr", ",", "family", ")", ":", "if", "(", "enum", "and", "PY3", ")", ":", "assert", "isinstance", "(", "family", ",", "enum", ".", "IntEnum", ")", ",", "family", "if", "(", "family", "==", "AF_INET", ")", ":", "octs...
check a net address validity .
train
false
14,422
def getUserContact(master, contact_types, uid): d = master.db.users.getUser(uid) d.addCallback(_extractContact, contact_types, uid) return d
[ "def", "getUserContact", "(", "master", ",", "contact_types", ",", "uid", ")", ":", "d", "=", "master", ".", "db", ".", "users", ".", "getUser", "(", "uid", ")", "d", ".", "addCallback", "(", "_extractContact", ",", "contact_types", ",", "uid", ")", "r...
this is a simple getter function that returns a user attribute that matches the contact_types argument .
train
true
14,423
def check_dna_chars_primers(header, mapping_data, errors, disable_primer_check=False): valid_dna_chars = DNASequence.iupac_characters() valid_dna_chars.add(',') header_fields_to_check = ['ReversePrimer'] if (not disable_primer_check): header_fields_to_check.append('LinkerPrimerSequence') check_indices = [] for ...
[ "def", "check_dna_chars_primers", "(", "header", ",", "mapping_data", ",", "errors", ",", "disable_primer_check", "=", "False", ")", ":", "valid_dna_chars", "=", "DNASequence", ".", "iupac_characters", "(", ")", "valid_dna_chars", ".", "add", "(", "','", ")", "h...
checks for valid dna characters in primer fields also flags empty fields as errors unless flags are passed to suppress barcode or primer checks .
train
false
14,425
def denormalize_form_dict(data_dict, form, attr_list): assert isinstance(form, forms.Form) res = django.http.QueryDict('', mutable=True) for attr in attr_list: try: res[str(form.add_prefix(attr))] = data_dict[attr] except KeyError: pass return res
[ "def", "denormalize_form_dict", "(", "data_dict", ",", "form", ",", "attr_list", ")", ":", "assert", "isinstance", "(", "form", ",", "forms", ".", "Form", ")", "res", "=", "django", ".", "http", ".", "QueryDict", "(", "''", ",", "mutable", "=", "True", ...
denormalize_form_dict -> a querydict with the attributes set .
train
false
14,426
def find_python_files(path): try: return sorted([file[:(-3)] for file in os.listdir(path) if ((not file.startswith(('_', '.'))) and file.endswith('.py'))]) except OSError: return []
[ "def", "find_python_files", "(", "path", ")", ":", "try", ":", "return", "sorted", "(", "[", "file", "[", ":", "(", "-", "3", ")", "]", "for", "file", "in", "os", ".", "listdir", "(", "path", ")", "if", "(", "(", "not", "file", ".", "startswith",...
return a list of the python files in a directory .
train
false
14,427
@treeio_login_required @handle_response_format def service_record_edit(request, service_record_id, response_format='html'): service_record = get_object_or_404(ItemServicing, pk=service_record_id) if (not request.user.profile.has_permission(service_record, mode='w')): return user_denied(request, message="You don't h...
[ "@", "treeio_login_required", "@", "handle_response_format", "def", "service_record_edit", "(", "request", ",", "service_record_id", ",", "response_format", "=", "'html'", ")", ":", "service_record", "=", "get_object_or_404", "(", "ItemServicing", ",", "pk", "=", "ser...
servicerecord edit page .
train
false
14,428
def topological_sort(graph, key=None): (V, E) = graph L = [] S = set(V) E = list(E) for (v, u) in E: S.discard(u) if (key is None): key = (lambda value: value) S = sorted(S, key=key, reverse=True) while S: node = S.pop() L.append(node) for (u, v) in list(E): if (u == node): E.remove((u, v)) ...
[ "def", "topological_sort", "(", "graph", ",", "key", "=", "None", ")", ":", "(", "V", ",", "E", ")", "=", "graph", "L", "=", "[", "]", "S", "=", "set", "(", "V", ")", "E", "=", "list", "(", "E", ")", "for", "(", "v", ",", "u", ")", "in", ...
returns a depth first sorted order if depth_first is true .
train
false
14,429
@login_required def edxnotes(request, course_id): course_key = CourseKey.from_string(course_id) course = get_course_with_access(request.user, 'load', course_key) if (not is_feature_enabled(course)): raise Http404 notes_info = get_notes(request, course) has_notes = (len(notes_info.get('results')) > 0) context = ...
[ "@", "login_required", "def", "edxnotes", "(", "request", ",", "course_id", ")", ":", "course_key", "=", "CourseKey", ".", "from_string", "(", "course_id", ")", "course", "=", "get_course_with_access", "(", "request", ".", "user", ",", "'load'", ",", "course_k...
decorator that makes components annotatable .
train
false
14,431
def get_num_cpus(): return multiprocessing.cpu_count()
[ "def", "get_num_cpus", "(", ")", ":", "return", "multiprocessing", ".", "cpu_count", "(", ")" ]
get the number of cpu processes on the current machine .
train
false
14,432
def isProfileSetting(name): global settingsDictionary if ((name in settingsDictionary) and settingsDictionary[name].isProfile()): return True return False
[ "def", "isProfileSetting", "(", "name", ")", ":", "global", "settingsDictionary", "if", "(", "(", "name", "in", "settingsDictionary", ")", "and", "settingsDictionary", "[", "name", "]", ".", "isProfile", "(", ")", ")", ":", "return", "True", "return", "False...
check if a certain key name is actually a profile value .
train
false
14,433
def SizeToReadableString(filesize): for x in ['bytes', 'KiB', 'MiB', 'GiB', 'TiB']: if (filesize < 1000.0): return ('%3.1f %s' % (filesize, x)) filesize /= 1000.0
[ "def", "SizeToReadableString", "(", "filesize", ")", ":", "for", "x", "in", "[", "'bytes'", ",", "'KiB'", ",", "'MiB'", ",", "'GiB'", ",", "'TiB'", "]", ":", "if", "(", "filesize", "<", "1000.0", ")", ":", "return", "(", "'%3.1f %s'", "%", "(", "file...
turn a filesize int into a human readable filesize .
train
false
14,434
def _make_query(client, query, submission_type='Execute', udfs=None, settings=None, resources=[], wait=False, name=None, desc=None, local=True, is_parameterized=True, max=30.0, database='default', email_notify=False, **kwargs): res = make_query(client, query, submission_type, udfs, settings, resources, wait, name, des...
[ "def", "_make_query", "(", "client", ",", "query", ",", "submission_type", "=", "'Execute'", ",", "udfs", "=", "None", ",", "settings", "=", "None", ",", "resources", "=", "[", "]", ",", "wait", "=", "False", ",", "name", "=", "None", ",", "desc", "=...
wrapper around the real make_query .
train
false
14,436
def write_float(fid, kind, data): data_size = 4 data = np.array(data, dtype='>f4').T _write(fid, data, kind, data_size, FIFF.FIFFT_FLOAT, '>f4')
[ "def", "write_float", "(", "fid", ",", "kind", ",", "data", ")", ":", "data_size", "=", "4", "data", "=", "np", ".", "array", "(", "data", ",", "dtype", "=", "'>f4'", ")", ".", "T", "_write", "(", "fid", ",", "data", ",", "kind", ",", "data_size"...
write a single-precision floating point tag to a fif file .
train
false
14,439
def downsize_quota_delta(context, instance): old_flavor = instance.get_flavor('old') new_flavor = instance.get_flavor('new') return resize_quota_delta(context, new_flavor, old_flavor, 1, (-1))
[ "def", "downsize_quota_delta", "(", "context", ",", "instance", ")", ":", "old_flavor", "=", "instance", ".", "get_flavor", "(", "'old'", ")", "new_flavor", "=", "instance", ".", "get_flavor", "(", "'new'", ")", "return", "resize_quota_delta", "(", "context", ...
calculate deltas required to adjust quota for an instance downsize .
train
false
14,441
def get_server_messages(app): messages = [] for (basepath, folders, files) in os.walk(frappe.get_pymodule_path(app)): for dontwalk in (u'.git', u'public', u'locale'): if (dontwalk in folders): folders.remove(dontwalk) for f in files: if (f.endswith(u'.py') or f.endswith(u'.html') or f.endswith(u'.js')):...
[ "def", "get_server_messages", "(", "app", ")", ":", "messages", "=", "[", "]", "for", "(", "basepath", ",", "folders", ",", "files", ")", "in", "os", ".", "walk", "(", "frappe", ".", "get_pymodule_path", "(", "app", ")", ")", ":", "for", "dontwalk", ...
extracts all translatable strings from python modules inside an app .
train
false
14,442
def butter_lp(n, Wn): zeros = [] poles = _butter_analog_poles(n) k = 1 fs = 2 warped = ((2 * fs) * mpmath.tan(((mpmath.pi * Wn) / fs))) (z, p, k) = _zpklp2lp(zeros, poles, k, wo=warped) (z, p, k) = _zpkbilinear(z, p, k, fs=fs) return (z, p, k)
[ "def", "butter_lp", "(", "n", ",", "Wn", ")", ":", "zeros", "=", "[", "]", "poles", "=", "_butter_analog_poles", "(", "n", ")", "k", "=", "1", "fs", "=", "2", "warped", "=", "(", "(", "2", "*", "fs", ")", "*", "mpmath", ".", "tan", "(", "(", ...
lowpass butterworth digital filter design .
train
false
14,444
def read_packed_refs_with_peeled(f): last = None for l in f: if (l[0] == '#'): continue l = l.rstrip('\r\n') if l.startswith('^'): if (not last): raise PackedRefsException('unexpected peeled ref line') if (not valid_hexsha(l[1:])): raise PackedRefsException(('Invalid hex sha %r' % l[1:])) (s...
[ "def", "read_packed_refs_with_peeled", "(", "f", ")", ":", "last", "=", "None", "for", "l", "in", "f", ":", "if", "(", "l", "[", "0", "]", "==", "'#'", ")", ":", "continue", "l", "=", "l", ".", "rstrip", "(", "'\\r\\n'", ")", "if", "l", ".", "s...
read a packed refs file including peeled refs .
train
false
14,445
def is_hex_digits(entry, count): try: if (len(entry) != count): return False int(entry, 16) return True except (ValueError, TypeError): return False
[ "def", "is_hex_digits", "(", "entry", ",", "count", ")", ":", "try", ":", "if", "(", "len", "(", "entry", ")", "!=", "count", ")", ":", "return", "False", "int", "(", "entry", ",", "16", ")", "return", "True", "except", "(", "ValueError", ",", "Typ...
checks if a string is the given number of hex digits .
train
false
14,446
def dmp_degree(f, u): if dmp_zero_p(f, u): return (- oo) else: return (len(f) - 1)
[ "def", "dmp_degree", "(", "f", ",", "u", ")", ":", "if", "dmp_zero_p", "(", "f", ",", "u", ")", ":", "return", "(", "-", "oo", ")", "else", ":", "return", "(", "len", "(", "f", ")", "-", "1", ")" ]
return the leading degree of f in x_0 in k[x] .
train
false
14,447
def MakeCASignedCert(common_name, private_key, ca_cert, ca_private_key, serial_number=2): public_key = private_key.GetPublicKey() builder = x509.CertificateBuilder() builder = builder.issuer_name(ca_cert.GetIssuer()) subject = x509.Name([x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)]) builder = builder....
[ "def", "MakeCASignedCert", "(", "common_name", ",", "private_key", ",", "ca_cert", ",", "ca_private_key", ",", "serial_number", "=", "2", ")", ":", "public_key", "=", "private_key", ".", "GetPublicKey", "(", ")", "builder", "=", "x509", ".", "CertificateBuilder"...
make a cert and sign it with the cas private key .
train
true
14,448
@pytest.mark.network def test_install_with_ignoreinstalled_requested(script): script.pip('install', 'INITools==0.1', expect_error=True) result = script.pip('install', '-I', 'INITools==0.3', expect_error=True) assert result.files_created, 'pip install -I did not install' assert os.path.exists(((script.site_packages_...
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_install_with_ignoreinstalled_requested", "(", "script", ")", ":", "script", ".", "pip", "(", "'install'", ",", "'INITools==0.1'", ",", "expect_error", "=", "True", ")", "result", "=", "script", ".", "pip...
test old conflicting package is completely ignored .
train
false
14,452
def call_tadm(args): if isinstance(args, compat.string_types): raise TypeError(u'args should be a list of strings') if (_tadm_bin is None): config_tadm() cmd = ([_tadm_bin] + args) p = subprocess.Popen(cmd, stdout=sys.stdout) (stdout, stderr) = p.communicate() if (p.returncode != 0): print() print(stderr)...
[ "def", "call_tadm", "(", "args", ")", ":", "if", "isinstance", "(", "args", ",", "compat", ".", "string_types", ")", ":", "raise", "TypeError", "(", "u'args should be a list of strings'", ")", "if", "(", "_tadm_bin", "is", "None", ")", ":", "config_tadm", "(...
call the tadm binary with the given arguments .
train
false
14,456
def expm(A, q=None): if (q is not None): msg = 'argument q=... in scipy.linalg.expm is deprecated.' warnings.warn(msg, DeprecationWarning) import scipy.sparse.linalg return scipy.sparse.linalg.expm(A)
[ "def", "expm", "(", "A", ",", "q", "=", "None", ")", ":", "if", "(", "q", "is", "not", "None", ")", ":", "msg", "=", "'argument q=... in scipy.linalg.expm is deprecated.'", "warnings", ".", "warn", "(", "msg", ",", "DeprecationWarning", ")", "import", "sci...
compute the matrix exponential using pade approximation .
train
false
14,457
def setup_default_session(**kwargs): global DEFAULT_SESSION DEFAULT_SESSION = Session(**kwargs)
[ "def", "setup_default_session", "(", "**", "kwargs", ")", ":", "global", "DEFAULT_SESSION", "DEFAULT_SESSION", "=", "Session", "(", "**", "kwargs", ")" ]
set up a default session .
train
false
14,458
def displayFiles(filenames): for filename in filenames: displayFile(filename)
[ "def", "displayFiles", "(", "filenames", ")", ":", "for", "filename", "in", "filenames", ":", "displayFile", "(", "filename", ")" ]
parse gcode files and display the commands .
train
false
14,461
def can_create_more(data): data = dict(data) user = data['user'] course_key = data['usage_key'].course_key if (Bookmark.objects.filter(user=user, course_key=course_key).count() >= settings.MAX_BOOKMARKS_PER_COURSE): return False return True
[ "def", "can_create_more", "(", "data", ")", ":", "data", "=", "dict", "(", "data", ")", "user", "=", "data", "[", "'user'", "]", "course_key", "=", "data", "[", "'usage_key'", "]", ".", "course_key", "if", "(", "Bookmark", ".", "objects", ".", "filter"...
determine if a new bookmark can be created for the course based on limit defined in django .
train
false
14,462
def plat_specific_errors(*errnames): errno_names = dir(errno) nums = [getattr(errno, k) for k in errnames if (k in errno_names)] return list(dict.fromkeys(nums).keys())
[ "def", "plat_specific_errors", "(", "*", "errnames", ")", ":", "errno_names", "=", "dir", "(", "errno", ")", "nums", "=", "[", "getattr", "(", "errno", ",", "k", ")", "for", "k", "in", "errnames", "if", "(", "k", "in", "errno_names", ")", "]", "retur...
return error numbers for all errors in errnames on this platform .
train
true
14,463
def assert_table_name_col_equal(t, name, col): if isinstance(col, coordinates.SkyCoord): assert np.all((t[name].ra == col.ra)) assert np.all((t[name].dec == col.dec)) elif isinstance(col, u.Quantity): if (type(t) is QTable): assert np.all((t[name].value == col.value)) elif isinstance(col, table_helpers.Arra...
[ "def", "assert_table_name_col_equal", "(", "t", ",", "name", ",", "col", ")", ":", "if", "isinstance", "(", "col", ",", "coordinates", ".", "SkyCoord", ")", ":", "assert", "np", ".", "all", "(", "(", "t", "[", "name", "]", ".", "ra", "==", "col", "...
assert all .
train
false
14,465
def get_email_backend(real_email=False): if (real_email or settings.SEND_REAL_EMAIL): backend = None else: backend = 'olympia.amo.mail.DevEmailBackend' return django.core.mail.get_connection(backend)
[ "def", "get_email_backend", "(", "real_email", "=", "False", ")", ":", "if", "(", "real_email", "or", "settings", ".", "SEND_REAL_EMAIL", ")", ":", "backend", "=", "None", "else", ":", "backend", "=", "'olympia.amo.mail.DevEmailBackend'", "return", "django", "."...
get a connection to an email backend .
train
false
14,466
def _doc_link(rawtext, text, options={}, content=[]): (has_explicit_title, title, slug) = split_explicit_title(text) twin_slugs = False post = None for p in doc_role.site.timeline: if (p.meta('slug') == slug): if (post is None): post = p else: twin_slugs = True break try: if (post is None): ...
[ "def", "_doc_link", "(", "rawtext", ",", "text", ",", "options", "=", "{", "}", ",", "content", "=", "[", "]", ")", ":", "(", "has_explicit_title", ",", "title", ",", "slug", ")", "=", "split_explicit_title", "(", "text", ")", "twin_slugs", "=", "False...
handle the doc role .
train
false
14,467
def rich_text_publisher(registry, xml_parent, data): parsers = ['HTML', 'Confluence', 'WikiText'] reporter = XML.SubElement(xml_parent, 'org.korosoft.jenkins.plugin.rtp.RichTextPublisher') reporter.set('plugin', 'rich-text-publisher-plugin') mappings = [('stable-text', 'stableText', None), ('unstable-text', 'unstab...
[ "def", "rich_text_publisher", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "parsers", "=", "[", "'HTML'", ",", "'Confluence'", ",", "'WikiText'", "]", "reporter", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'org.korosoft.jenkins.plugin....
yaml: rich-text-publisher this plugin puts custom rich text message to the build pages and job main page .
train
false
14,468
def mplot2d(f, var, show=True): import warnings warnings.filterwarnings('ignore', 'Could not match \\S') p = import_module('pylab') if (not p): sys.exit('Matplotlib is required to use mplot2d.') if (not is_sequence(f)): f = [f] for f_i in f: (x, y) = sample(f_i, var) p.plot(x, y) p.draw() if show: p.s...
[ "def", "mplot2d", "(", "f", ",", "var", ",", "show", "=", "True", ")", ":", "import", "warnings", "warnings", ".", "filterwarnings", "(", "'ignore'", ",", "'Could not match \\\\S'", ")", "p", "=", "import_module", "(", "'pylab'", ")", "if", "(", "not", "...
plot a 2d function using matplotlib/tk .
train
false
14,469
@pytest.fixture def po_directory(request, po_test_dir, settings): from pootle_store.models import fs translation_directory = settings.POOTLE_TRANSLATION_DIRECTORY settings.POOTLE_TRANSLATION_DIRECTORY = po_test_dir fs.location = po_test_dir def _cleanup(): settings.POOTLE_TRANSLATION_DIRECTORY = translation_dire...
[ "@", "pytest", ".", "fixture", "def", "po_directory", "(", "request", ",", "po_test_dir", ",", "settings", ")", ":", "from", "pootle_store", ".", "models", "import", "fs", "translation_directory", "=", "settings", ".", "POOTLE_TRANSLATION_DIRECTORY", "settings", "...
sets up a tmp directory for po files .
train
false
14,471
def customConvertJson(value): if isinstance(value, float): return int(value) elif isinstance(value, unicode): return str(value) elif isinstance(value, list): return [customConvertJson(item) for item in value] elif isinstance(value, dict): new_dict = {} for (key, val) in value.iteritems(): new_key = cus...
[ "def", "customConvertJson", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", ":", "return", "int", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "unicode", ")", ":", "return", "str", "(", "value", ")", "elif", ...
recursively process json values and do type conversions .
train
false
14,472
@utils.arg('flavor', metavar='<flavor>', help=_('Name or ID of flavor.')) def do_flavor_show(cs, args): flavor = _find_flavor(cs, args.flavor) _print_flavor(flavor)
[ "@", "utils", ".", "arg", "(", "'flavor'", ",", "metavar", "=", "'<flavor>'", ",", "help", "=", "_", "(", "'Name or ID of flavor.'", ")", ")", "def", "do_flavor_show", "(", "cs", ",", "args", ")", ":", "flavor", "=", "_find_flavor", "(", "cs", ",", "ar...
show details about the given flavor .
train
false
14,474
def idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its=20): return _id.idd_diffsnorm(m, n, matvect, matvect2, matvec, matvec2, its)
[ "def", "idd_diffsnorm", "(", "m", ",", "n", ",", "matvect", ",", "matvect2", ",", "matvec", ",", "matvec2", ",", "its", "=", "20", ")", ":", "return", "_id", ".", "idd_diffsnorm", "(", "m", ",", "n", ",", "matvect", ",", "matvect2", ",", "matvec", ...
estimate spectral norm of the difference of two real matrices by the randomized power method .
train
false
14,475
def encrypt_header_val(crypto, value, key): if (not value): raise ValueError('empty value is not acceptable') crypto_meta = crypto.create_crypto_meta() crypto_ctxt = crypto.create_encryption_ctxt(key, crypto_meta['iv']) enc_val = base64.b64encode(crypto_ctxt.update(value)) return (enc_val, crypto_meta)
[ "def", "encrypt_header_val", "(", "crypto", ",", "value", ",", "key", ")", ":", "if", "(", "not", "value", ")", ":", "raise", "ValueError", "(", "'empty value is not acceptable'", ")", "crypto_meta", "=", "crypto", ".", "create_crypto_meta", "(", ")", "crypto_...
encrypt a header value using the supplied key .
train
false
14,476
def authen(): twitter_credential = ((os.environ.get('HOME', os.environ.get('USERPROFILE', '')) + os.sep) + '.rainbow_oauth') if (not os.path.exists(twitter_credential)): oauth_dance('Rainbow Stream', CONSUMER_KEY, CONSUMER_SECRET, twitter_credential) (oauth_token, oauth_token_secret) = read_token_file(twitter_cred...
[ "def", "authen", "(", ")", ":", "twitter_credential", "=", "(", "(", "os", ".", "environ", ".", "get", "(", "'HOME'", ",", "os", ".", "environ", ".", "get", "(", "'USERPROFILE'", ",", "''", ")", ")", "+", "os", ".", "sep", ")", "+", "'.rainbow_oaut...
authenticate with twitter oauth .
train
false
14,477
def getUserDocumentsPath(): if sys.platform.startswith('win'): if sys.platform.startswith('win32'): try: from win32com.shell import shell alt = False except ImportError: try: import ctypes dll = ctypes.windll.shell32 alt = True except: raise Exception("Could not find 'My Doc...
[ "def", "getUserDocumentsPath", "(", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win32'", ")", ":", "try", ":", "from", "win32com", ".", "shell", "import", "s...
find the users "documents" directory .
train
false
14,480
def checkAlias(alias): if (',' in alias): raise AXError(('Alias %r must not contain comma' % (alias,))) if ('.' in alias): raise AXError(('Alias %r must not contain period' % (alias,)))
[ "def", "checkAlias", "(", "alias", ")", ":", "if", "(", "','", "in", "alias", ")", ":", "raise", "AXError", "(", "(", "'Alias %r must not contain comma'", "%", "(", "alias", ",", ")", ")", ")", "if", "(", "'.'", "in", "alias", ")", ":", "raise", "AXE...
check an alias for invalid characters; raise axerror if any are found .
train
false
14,481
def _preprocess_for_cut(x): x_is_series = isinstance(x, Series) series_index = None name = None if x_is_series: series_index = x.index name = x.name x = np.asarray(x) return (x_is_series, series_index, name, x)
[ "def", "_preprocess_for_cut", "(", "x", ")", ":", "x_is_series", "=", "isinstance", "(", "x", ",", "Series", ")", "series_index", "=", "None", "name", "=", "None", "if", "x_is_series", ":", "series_index", "=", "x", ".", "index", "name", "=", "x", ".", ...
handles preprocessing for cut where we convert passed input to array .
train
false
14,483
def GetAllClients(token=None): index = client_index.CreateClientIndex(token=token) return index.LookupClients(['.'])
[ "def", "GetAllClients", "(", "token", "=", "None", ")", ":", "index", "=", "client_index", ".", "CreateClientIndex", "(", "token", "=", "token", ")", "return", "index", ".", "LookupClients", "(", "[", "'.'", "]", ")" ]
return a list of all client urns .
train
false
14,484
def gpke(bw, data, data_predict, var_type, ckertype='gaussian', okertype='wangryzin', ukertype='aitchisonaitken', tosum=True): kertypes = dict(c=ckertype, o=okertype, u=ukertype) Kval = np.empty(data.shape) for (ii, vtype) in enumerate(var_type): func = kernel_func[kertypes[vtype]] Kval[:, ii] = func(bw[ii], dat...
[ "def", "gpke", "(", "bw", ",", "data", ",", "data_predict", ",", "var_type", ",", "ckertype", "=", "'gaussian'", ",", "okertype", "=", "'wangryzin'", ",", "ukertype", "=", "'aitchisonaitken'", ",", "tosum", "=", "True", ")", ":", "kertypes", "=", "dict", ...
returns the non-normalized generalized product kernel estimator parameters bw: 1-d ndarray the user-specified bandwidth parameters .
train
true