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
25,701
def get_module_name(category, field, fallback_module_name=None): try: value = cp.get(category, field) except: if (fallback_module_name is not None): value = fallback_module_name else: raise CX((_('Cannot find config file setting for: %s') % field)) return value
[ "def", "get_module_name", "(", "category", ",", "field", ",", "fallback_module_name", "=", "None", ")", ":", "try", ":", "value", "=", "cp", ".", "get", "(", "category", ",", "field", ")", "except", ":", "if", "(", "fallback_module_name", "is", "not", "N...
get the name of the file without the extension .
train
false
25,702
def setButtonFontWeightString(button, isBold): try: weightString = 'normal' if isBold: weightString = 'bold' splitFont = button['font'].split() button['font'] = (splitFont[0], splitFont[1], weightString) except: pass
[ "def", "setButtonFontWeightString", "(", "button", ",", "isBold", ")", ":", "try", ":", "weightString", "=", "'normal'", "if", "isBold", ":", "weightString", "=", "'bold'", "splitFont", "=", "button", "[", "'font'", "]", ".", "split", "(", ")", "button", "...
set button font weight given isbold .
train
false
25,703
def _std_string(s): return str(s.decode('US-ASCII'))
[ "def", "_std_string", "(", "s", ")", ":", "return", "str", "(", "s", ".", "decode", "(", "'US-ASCII'", ")", ")" ]
cast a string or byte string to an ascii string .
train
false
25,704
def tokenize_path(path): separators = [] last_position = 0 i = (-1) in_string = False while (i < (len(path) - 1)): i = (i + 1) if (path[i] == "'"): in_string = (not in_string) if in_string: continue if (path[i] == '/'): if (i > 0): separators.append((last_position, i)) if (path[(i + 1)] == '/'): last_position = i i = (i + 1) else: last_position = (i + 1) separators.append((last_position, len(path))) steps = [] for (start, end) in separators: steps.append(path[start:end]) return steps
[ "def", "tokenize_path", "(", "path", ")", ":", "separators", "=", "[", "]", "last_position", "=", "0", "i", "=", "(", "-", "1", ")", "in_string", "=", "False", "while", "(", "i", "<", "(", "len", "(", "path", ")", "-", "1", ")", ")", ":", "i", ...
tokenize a location path into location steps .
train
false
25,707
def _spacing_preflight(func): def wrapped(self, width, fillchar=None): if (fillchar is None): fillchar = ' ' if ((len(fillchar) != 1) or (not isinstance(fillchar, basestring))): raise TypeError(('must be char, not %s' % type(fillchar))) if (not isinstance(width, int)): raise TypeError(('integer argument expected, got %s' % type(width))) difference = (width - len(self)) if (difference <= 0): return self return func(self, width, fillchar, difference) return wrapped
[ "def", "_spacing_preflight", "(", "func", ")", ":", "def", "wrapped", "(", "self", ",", "width", ",", "fillchar", "=", "None", ")", ":", "if", "(", "fillchar", "is", "None", ")", ":", "fillchar", "=", "' '", "if", "(", "(", "len", "(", "fillchar", ...
this wrapper function is used to do some preflight checks on functions used for padding ansistrings .
train
false
25,709
def levenshtein_distance(a, b): if (a == b): return 0 if (len(a) < len(b)): (a, b) = (b, a) if (not a): return len(b) previous_row = xrange((len(b) + 1)) for (i, column1) in enumerate(a): current_row = [(i + 1)] for (j, column2) in enumerate(b): insertions = (previous_row[(j + 1)] + 1) deletions = (current_row[j] + 1) substitutions = (previous_row[j] + (column1 != column2)) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[(-1)]
[ "def", "levenshtein_distance", "(", "a", ",", "b", ")", ":", "if", "(", "a", "==", "b", ")", ":", "return", "0", "if", "(", "len", "(", "a", ")", "<", "len", "(", "b", ")", ")", ":", "(", "a", ",", "b", ")", "=", "(", "b", ",", "a", ")"...
compare two statements based on the levenshtein distance of each statements text .
train
false
25,710
def sls_build(name, base='opensuse/python', mods=None, saltenv='base', **kwargs): create_kwargs = salt.utils.clean_kwargs(**copy.deepcopy(kwargs)) for key in ('image', 'name', 'cmd', 'interactive', 'tty'): try: del create_kwargs[key] except KeyError: pass ret = __salt__['dockerng.create'](image=base, name=name, cmd='sleep infinity', interactive=True, tty=True, **create_kwargs) id_ = ret['Id'] try: __salt__['dockerng.start'](id_) ret = __salt__['dockerng.sls'](id_, mods, saltenv, **kwargs) if (not salt.utils.check_state_result(ret)): raise CommandExecutionError(ret) finally: __salt__['dockerng.stop'](id_) return __salt__['dockerng.commit'](id_, name)
[ "def", "sls_build", "(", "name", ",", "base", "=", "'opensuse/python'", ",", "mods", "=", "None", ",", "saltenv", "=", "'base'", ",", "**", "kwargs", ")", ":", "create_kwargs", "=", "salt", ".", "utils", ".", "clean_kwargs", "(", "**", "copy", ".", "de...
build a docker image using the specified sls modules and base image .
train
false
25,711
def _valid_for_check(cls): if (cls is Generic): raise TypeError((u'Class %r cannot be used with class or instance checks' % cls)) if ((cls.__origin__ is not None) and (sys._getframe(3).f_globals[u'__name__'] not in [u'abc', u'functools'])): raise TypeError(u'Parameterized generics cannot be used with class or instance checks')
[ "def", "_valid_for_check", "(", "cls", ")", ":", "if", "(", "cls", "is", "Generic", ")", ":", "raise", "TypeError", "(", "(", "u'Class %r cannot be used with class or instance checks'", "%", "cls", ")", ")", "if", "(", "(", "cls", ".", "__origin__", "is", "n...
an internal helper to prohibit isinstance etc .
train
false
25,712
def del_marker(path): if (path and os.path.exists(path)): logging.debug('Removing marker file %s', path) try: os.remove(path) except: logging.info('Cannot remove marker file %s', path) logging.info('Traceback: ', exc_info=True)
[ "def", "del_marker", "(", "path", ")", ":", "if", "(", "path", "and", "os", ".", "path", ".", "exists", "(", "path", ")", ")", ":", "logging", ".", "debug", "(", "'Removing marker file %s'", ",", "path", ")", "try", ":", "os", ".", "remove", "(", "...
remove marker file .
train
false
25,713
def create_grant(key_id, grantee_principal, retiring_principal=None, operations=None, constraints=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if key_id.startswith('alias/'): key_id = _get_key_id(key_id) r = {} try: r['grant'] = conn.create_grant(key_id, grantee_principal, retiring_principal=retiring_principal, operations=operations, constraints=constraints, grant_tokens=grant_tokens) except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
[ "def", "create_grant", "(", "key_id", ",", "grantee_principal", ",", "retiring_principal", "=", "None", ",", "operations", "=", "None", ",", "constraints", "=", "None", ",", "grant_tokens", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ...
adds a grant to a key to specify who can access the key and under what conditions .
train
true
25,714
def extractRow(row): statistic = row[2].strip() if (statistic == 'New cases'): return location = row[1].strip() if (location == 'National'): return elif (' and ' in location): if (location in rejected_loc): rejected_loc[location] += 1 else: rejected_loc[location] = 1 return country = row[0].strip() if (not (location in location_list)): location = string.capwords(location) loc_row = get_loc_from_db(location, country) location_list[location] = loc_row if (location_list[location] is not None): storeRow(location, row, country)
[ "def", "extractRow", "(", "row", ")", ":", "statistic", "=", "row", "[", "2", "]", ".", "strip", "(", ")", "if", "(", "statistic", "==", "'New cases'", ")", ":", "return", "location", "=", "row", "[", "1", "]", ".", "strip", "(", ")", "if", "(", ...
extract a row from our source spreadsheet .
train
false
25,716
def call_temperature(*args, **kwargs): res = dict() if ('value' not in kwargs): raise CommandExecutionError("Parameter 'value' (150~500) is missing") try: value = max(min(int(kwargs['value']), 500), 150) except Exception as err: raise CommandExecutionError("Parameter 'value' does not contains an integer") devices = _get_lights() for dev_id in ((('id' not in kwargs) and sorted(devices.keys())) or _get_devices(kwargs)): res[dev_id] = _set(dev_id, {'ct': value}) return res
[ "def", "call_temperature", "(", "*", "args", ",", "**", "kwargs", ")", ":", "res", "=", "dict", "(", ")", "if", "(", "'value'", "not", "in", "kwargs", ")", ":", "raise", "CommandExecutionError", "(", "\"Parameter 'value' (150~500) is missing\"", ")", "try", ...
set the mired color temperature .
train
true
25,717
def assert_server_running(server): if (server.poll() is not None): raise RuntimeError('Server died unexpectedly!')
[ "def", "assert_server_running", "(", "server", ")", ":", "if", "(", "server", ".", "poll", "(", ")", "is", "not", "None", ")", ":", "raise", "RuntimeError", "(", "'Server died unexpectedly!'", ")" ]
get the exit code of the server .
train
false
25,718
def set_shipping(request, shipping_type, shipping_total): request.session[u'shipping_type'] = _str(shipping_type) request.session[u'shipping_total'] = _str(shipping_total)
[ "def", "set_shipping", "(", "request", ",", "shipping_type", ",", "shipping_total", ")", ":", "request", ".", "session", "[", "u'shipping_type'", "]", "=", "_str", "(", "shipping_type", ")", "request", ".", "session", "[", "u'shipping_total'", "]", "=", "_str"...
stores the shipping type and total in the session .
train
false
25,719
def get_installed_pythons_pkgname(): return [d for d in sorted(os.listdir(PATH_PYTHONS))]
[ "def", "get_installed_pythons_pkgname", "(", ")", ":", "return", "[", "d", "for", "d", "in", "sorted", "(", "os", ".", "listdir", "(", "PATH_PYTHONS", ")", ")", "]" ]
get the installed python versions list .
train
false
25,721
@login_required def weblate_logout(request): messages.info(request, _(u'Thanks for using Weblate!')) return auth_views.logout(request, next_page=reverse(u'home'))
[ "@", "login_required", "def", "weblate_logout", "(", "request", ")", ":", "messages", ".", "info", "(", "request", ",", "_", "(", "u'Thanks for using Weblate!'", ")", ")", "return", "auth_views", ".", "logout", "(", "request", ",", "next_page", "=", "reverse",...
logout handler .
train
false
25,722
def match_config(regex): if _TRAFFICCTL: cmd = _traffic_ctl('config', 'match', regex) else: cmd = _traffic_line('-m', regex) log.debug('Running: %s', cmd) return _subprocess(cmd)
[ "def", "match_config", "(", "regex", ")", ":", "if", "_TRAFFICCTL", ":", "cmd", "=", "_traffic_ctl", "(", "'config'", ",", "'match'", ",", "regex", ")", "else", ":", "cmd", "=", "_traffic_line", "(", "'-m'", ",", "regex", ")", "log", ".", "debug", "(",...
display the current values of all configuration variables whose names match the given regular expression .
train
false
25,723
@FileSystem.in_directory(current_directory, 'django', 'bamboo') def test_mail_fail(): (status, out) = run_scenario('leaves', 'mock-failure', 1) assert_not_equals(status, 0) assert ('SMTPException: Failure mocked by lettuce' in out)
[ "@", "FileSystem", ".", "in_directory", "(", "current_directory", ",", "'django'", ",", "'bamboo'", ")", "def", "test_mail_fail", "(", ")", ":", "(", "status", ",", "out", ")", "=", "run_scenario", "(", "'leaves'", ",", "'mock-failure'", ",", "1", ")", "as...
mock mail failure dies with error .
train
false
25,724
def is_library_missing(name): (path, module) = name.rsplit(u'.', 1) try: package = import_module(path) return (not module_has_submodule(package, module)) except ImportError: return is_library_missing(path)
[ "def", "is_library_missing", "(", "name", ")", ":", "(", "path", ",", "module", ")", "=", "name", ".", "rsplit", "(", "u'.'", ",", "1", ")", "try", ":", "package", "=", "import_module", "(", "path", ")", "return", "(", "not", "module_has_submodule", "(...
check if library that failed to load cannot be found under any templatetags directory or does exist but fails to import .
train
false
25,726
def clim(vmin=None, vmax=None): im = gci() if (im is None): raise RuntimeError('You must first define an image, eg with imshow') im.set_clim(vmin, vmax) draw_if_interactive()
[ "def", "clim", "(", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "im", "=", "gci", "(", ")", "if", "(", "im", "is", "None", ")", ":", "raise", "RuntimeError", "(", "'You must first define an image, eg with imshow'", ")", "im", ".", "set_clim"...
set the color limits of the current image to apply clim to all axes images do:: clim if either *vmin* or *vmax* is none .
train
false
25,727
def add_config(lines): if (not isinstance(lines, list)): lines = [lines] try: sendline('config terminal') for line in lines: sendline(line) sendline('end') sendline('copy running-config startup-config') except TerminalException as e: log.error(e) return False return True
[ "def", "add_config", "(", "lines", ")", ":", "if", "(", "not", "isinstance", "(", "lines", ",", "list", ")", ")", ":", "lines", "=", "[", "lines", "]", "try", ":", "sendline", "(", "'config terminal'", ")", "for", "line", "in", "lines", ":", "sendlin...
add one or more config lines to the switch running config .
train
false
25,729
def runWithPermutationsScript(permutationsFilePath, options, outputLabel, permWorkDir): global g_currentVerbosityLevel if ('verbosityCount' in options): g_currentVerbosityLevel = options['verbosityCount'] del options['verbosityCount'] else: g_currentVerbosityLevel = 1 _setupInterruptHandling() options['permutationsScriptPath'] = permutationsFilePath options['outputLabel'] = outputLabel options['outDir'] = permWorkDir options['permWorkDir'] = permWorkDir runOptions = _injectDefaultOptions(options) _validateOptions(runOptions) return _runAction(runOptions)
[ "def", "runWithPermutationsScript", "(", "permutationsFilePath", ",", "options", ",", "outputLabel", ",", "permWorkDir", ")", ":", "global", "g_currentVerbosityLevel", "if", "(", "'verbosityCount'", "in", "options", ")", ":", "g_currentVerbosityLevel", "=", "options", ...
starts a swarm .
train
true
25,730
def name_to_gid(name): try: gid = int(name) except ValueError: try: grprec = grp.getgrnam(name) except KeyError: raise ValueError(('Invalid group name %s' % name)) gid = grprec[2] else: try: grp.getgrgid(gid) except KeyError: raise ValueError(('Invalid group id %s' % name)) return gid
[ "def", "name_to_gid", "(", "name", ")", ":", "try", ":", "gid", "=", "int", "(", "name", ")", "except", "ValueError", ":", "try", ":", "grprec", "=", "grp", ".", "getgrnam", "(", "name", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "("...
find a group id from a string containing a group name or id .
train
false
25,731
def register_site(app_name, site_name, site): if (app_name not in _sites_cache): _sites_cache[app_name] = {} _sites_cache[app_name][site_name] = site
[ "def", "register_site", "(", "app_name", ",", "site_name", ",", "site", ")", ":", "if", "(", "app_name", "not", "in", "_sites_cache", ")", ":", "_sites_cache", "[", "app_name", "]", "=", "{", "}", "_sites_cache", "[", "app_name", "]", "[", "site_name", "...
add a site into the site dict .
train
false
25,733
@register(u'backward-char') def backward_char(event): buff = event.current_buffer buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg)
[ "@", "register", "(", "u'backward-char'", ")", "def", "backward_char", "(", "event", ")", ":", "buff", "=", "event", ".", "current_buffer", "buff", ".", "cursor_position", "+=", "buff", ".", "document", ".", "get_cursor_left_position", "(", "count", "=", "even...
move back a character .
train
true
25,735
def update_connection(request, graph): converter = get_instance_for('user_conversion', graph) user = _connect_user(request, converter, overwrite=False) _update_likes_and_friends(request, user, converter) _update_access_token(user, graph) return user
[ "def", "update_connection", "(", "request", ",", "graph", ")", ":", "converter", "=", "get_instance_for", "(", "'user_conversion'", ",", "graph", ")", "user", "=", "_connect_user", "(", "request", ",", "converter", ",", "overwrite", "=", "False", ")", "_update...
a special purpose view for updating the connection with an existing user - updates the access token - sets the facebook_id if nothing is specified - stores friends and likes if possible .
train
false
25,737
def is_valid_jsonp_callback_value(value): for identifier in value.split(u'.'): while (u'[' in identifier): if (not has_valid_array_index(identifier)): return False identifier = replace_array_index(u'', identifier) if (not is_valid_javascript_identifier(identifier)): return False return True
[ "def", "is_valid_jsonp_callback_value", "(", "value", ")", ":", "for", "identifier", "in", "value", ".", "split", "(", "u'.'", ")", ":", "while", "(", "u'['", "in", "identifier", ")", ":", "if", "(", "not", "has_valid_array_index", "(", "identifier", ")", ...
return whether the given value can be used as a json-p callback .
train
false
25,739
def _check_no_rewrite(func, arg): return (func(arg).args[0] == arg)
[ "def", "_check_no_rewrite", "(", "func", ",", "arg", ")", ":", "return", "(", "func", "(", "arg", ")", ".", "args", "[", "0", "]", "==", "arg", ")" ]
checks that the expr is not rewritten .
train
false
25,740
def normalizeURL(url): try: normalized = urinorm.urinorm(url) except ValueError as why: raise DiscoveryFailure(('Normalizing identifier: %s' % (why[0],)), None) else: return urlparse.urldefrag(normalized)[0]
[ "def", "normalizeURL", "(", "url", ")", ":", "try", ":", "normalized", "=", "urinorm", ".", "urinorm", "(", "url", ")", "except", "ValueError", "as", "why", ":", "raise", "DiscoveryFailure", "(", "(", "'Normalizing identifier: %s'", "%", "(", "why", "[", "...
normalize a url .
train
true
25,741
def dequote(string): if ((string.startswith('"') and string.endswith('"')) or (string.startswith("'") and string.endswith("'"))): return string[1:(-1)] else: return string
[ "def", "dequote", "(", "string", ")", ":", "if", "(", "(", "string", ".", "startswith", "(", "'\"'", ")", "and", "string", ".", "endswith", "(", "'\"'", ")", ")", "or", "(", "string", ".", "startswith", "(", "\"'\"", ")", "and", "string", ".", "end...
takes string which may or may not be quoted and unquotes it .
train
false
25,743
def build_command(runner, job_wrapper, container=None, modify_command_for_container=True, include_metadata=False, include_work_dir_outputs=True, create_tool_working_directory=True, remote_command_params={}, metadata_directory=None): shell = job_wrapper.shell base_command_line = job_wrapper.get_command_line() if (not base_command_line): raise Exception('Attempting to run a tool with empty command definition.') commands_builder = CommandsBuilder(base_command_line) if (not commands_builder.commands): return None __handle_version_command(commands_builder, job_wrapper) __handle_task_splitting(commands_builder, job_wrapper) if ((not container) or container.resolve_dependencies): __handle_dependency_resolution(commands_builder, job_wrapper, remote_command_params) if ((container and modify_command_for_container) or job_wrapper.commands_in_new_shell): if (container and modify_command_for_container): external_command_shell = container.shell else: external_command_shell = shell externalized_commands = __externalize_commands(job_wrapper, external_command_shell, commands_builder, remote_command_params) if (container and modify_command_for_container): run_in_container_command = container.containerize_command(externalized_commands) commands_builder = CommandsBuilder(run_in_container_command) else: commands_builder = CommandsBuilder(externalized_commands) if create_tool_working_directory: commands_builder.prepend_command('rm -rf working; mkdir -p working; cd working') if include_work_dir_outputs: __handle_work_dir_outputs(commands_builder, job_wrapper, runner, remote_command_params) commands_builder.capture_return_code() if (include_metadata and job_wrapper.requires_setting_metadata): metadata_directory = (metadata_directory or job_wrapper.working_directory) commands_builder.append_command(("cd '%s'" % metadata_directory)) __handle_metadata(commands_builder, job_wrapper, runner, remote_command_params) return commands_builder.build()
[ "def", "build_command", "(", "runner", ",", "job_wrapper", ",", "container", "=", "None", ",", "modify_command_for_container", "=", "True", ",", "include_metadata", "=", "False", ",", "include_work_dir_outputs", "=", "True", ",", "create_tool_working_directory", "=", ...
builds and returns a getfacl/setfacl command .
train
false
25,744
def generate_vm_name(options): if ('BUILD_NUMBER' in os.environ): random_part = 'BUILD{0:0>6}'.format(os.environ.get('BUILD_NUMBER')) else: random_part = os.urandom(3).encode('hex') return '{0}-{1}-{2}'.format(options.vm_prefix, options.platform, random_part)
[ "def", "generate_vm_name", "(", "options", ")", ":", "if", "(", "'BUILD_NUMBER'", "in", "os", ".", "environ", ")", ":", "random_part", "=", "'BUILD{0:0>6}'", ".", "format", "(", "os", ".", "environ", ".", "get", "(", "'BUILD_NUMBER'", ")", ")", "else", "...
generate a random enough vm name .
train
false
25,745
def single_file_cup(otu_filepath, metrics, outfilepath, r): calcs = [] params = {'r': r} metrics_list = metrics try: metrics_list = metrics_list.split(',') except AttributeError: pass for metric in metrics_list: try: metric_f = get_cup_metric(metric) except AttributeError: stderr.write(('Could not find metric %s.\n Known metrics are: %s\n' % (metric, ', '.join(list_known_cup_metrics())))) exit(1) c = AlphaDiversityCalc(metric_f, params=params) calcs.append(c) all_calcs = AlphaDiversityCalcs(calcs) try: result = all_calcs(data_path=otu_filepath, result_path=outfilepath, log_path=None) if result: print all_calcs.formatResult(result) except IOError as e: stderr.write('Failed because of missing files.\n') stderr.write((str(e) + '\n')) exit(1)
[ "def", "single_file_cup", "(", "otu_filepath", ",", "metrics", ",", "outfilepath", ",", "r", ")", ":", "calcs", "=", "[", "]", "params", "=", "{", "'r'", ":", "r", "}", "metrics_list", "=", "metrics", "try", ":", "metrics_list", "=", "metrics_list", ".",...
compute variations of the conditional uncovered probability .
train
false
25,746
@world.absorb def create_component_instance(step, category, component_type=None, is_advanced=False, advanced_component=None): assert_in(category, ['advanced', 'problem', 'html', 'video', 'discussion']) component_button_css = 'span.large-{}-icon'.format(category.lower()) if (category == 'problem'): module_css = 'div.xmodule_CapaModule' elif (category == 'advanced'): module_css = 'div.xmodule_{}Module'.format(advanced_component.title()) elif (category == 'discussion'): module_css = 'div.xblock-author_view-{}'.format(category.lower()) else: module_css = 'div.xmodule_{}Module'.format(category.title()) module_count_before = len(world.browser.find_by_css(module_css)) world.disable_jquery_animations() world.css_click(component_button_css) if (category in ('problem', 'html', 'advanced')): world.wait_for_invisible(component_button_css) click_component_from_menu(category, component_type, is_advanced) expected_count = (module_count_before + 1) world.wait_for((lambda _: (len(world.css_find(module_css)) == expected_count)), timeout=20)
[ "@", "world", ".", "absorb", "def", "create_component_instance", "(", "step", ",", "category", ",", "component_type", "=", "None", ",", "is_advanced", "=", "False", ",", "advanced_component", "=", "None", ")", ":", "assert_in", "(", "category", ",", "[", "'a...
create a new component in a unit .
train
false
25,748
def get_dataset_file(dataset, default_dataset, origin): (data_dir, data_file) = os.path.split(dataset) if ((data_dir == '') and (not os.path.isfile(dataset))): new_path = os.path.join(os.path.split(__file__)[0], '..', 'data', dataset) if (os.path.isfile(new_path) or (data_file == default_dataset)): dataset = new_path if ((not os.path.isfile(dataset)) and (data_file == default_dataset)): from six.moves import urllib print(('Downloading data from %s' % origin)) urllib.request.urlretrieve(origin, dataset) return dataset
[ "def", "get_dataset_file", "(", "dataset", ",", "default_dataset", ",", "origin", ")", ":", "(", "data_dir", ",", "data_file", ")", "=", "os", ".", "path", ".", "split", "(", "dataset", ")", "if", "(", "(", "data_dir", "==", "''", ")", "and", "(", "n...
look for it as if it was a full path .
train
false
25,749
def download_files(source_url_root, target_dir, source_filenames): assert isinstance(source_filenames, list) common.ensure_directory_exists(target_dir) for filename in source_filenames: if (not os.path.exists(os.path.join(target_dir, filename))): print ('Downloading file %s to %s' % (filename, target_dir)) urllib.urlretrieve(('%s/%s' % (source_url_root, filename)), os.path.join(target_dir, filename))
[ "def", "download_files", "(", "source_url_root", ",", "target_dir", ",", "source_filenames", ")", ":", "assert", "isinstance", "(", "source_filenames", ",", "list", ")", "common", ".", "ensure_directory_exists", "(", "target_dir", ")", "for", "filename", "in", "so...
download an array of files .
train
false
25,751
def tf2zpk(b, a): (b, a) = normalize(b, a) b = ((b + 0.0) / a[0]) a = ((a + 0.0) / a[0]) k = b[0] b /= b[0] z = roots(b) p = roots(a) return (z, p, k)
[ "def", "tf2zpk", "(", "b", ",", "a", ")", ":", "(", "b", ",", "a", ")", "=", "normalize", "(", "b", ",", "a", ")", "b", "=", "(", "(", "b", "+", "0.0", ")", "/", "a", "[", "0", "]", ")", "a", "=", "(", "(", "a", "+", "0.0", ")", "/"...
return zero .
train
false
25,752
def indicates_division(token): if (token.type == 'operator'): return (token.value in (')', ']', '}', '++', '--')) return (token.type in ('name', 'number', 'string', 'regexp'))
[ "def", "indicates_division", "(", "token", ")", ":", "if", "(", "token", ".", "type", "==", "'operator'", ")", ":", "return", "(", "token", ".", "value", "in", "(", "')'", ",", "']'", ",", "'}'", ",", "'++'", ",", "'--'", ")", ")", "return", "(", ...
a helper function that helps the tokenizer to decide if the current token may be followed by a division operator .
train
false
25,754
def get_wait_timeout(vm_): return config.get_cloud_config_value('wait_for_timeout', vm_, __opts__, default=(15 * 60), search_global=False)
[ "def", "get_wait_timeout", "(", "vm_", ")", ":", "return", "config", ".", "get_cloud_config_value", "(", "'wait_for_timeout'", ",", "vm_", ",", "__opts__", ",", "default", "=", "(", "15", "*", "60", ")", ",", "search_global", "=", "False", ")" ]
return the wait_for_timeout for resource provisioning .
train
false
25,755
def _init_ypred(n_train, n_test, n_orig_epochs, n_dim): if (len(set(n_test)) == 1): y_pred = np.empty((n_train, n_test[0], n_orig_epochs, n_dim)) else: y_pred = np.array([np.empty((this_n, n_orig_epochs, n_dim)) for this_n in n_test]) return y_pred
[ "def", "_init_ypred", "(", "n_train", ",", "n_test", ",", "n_orig_epochs", ",", "n_dim", ")", ":", "if", "(", "len", "(", "set", "(", "n_test", ")", ")", "==", "1", ")", ":", "y_pred", "=", "np", ".", "empty", "(", "(", "n_train", ",", "n_test", ...
initialize the predictions for each train/test time points .
train
false
25,756
def timing_stats(**dec_kwargs): def decorating_func(func): method = func.__name__ @functools.wraps(func) def _timing_stats(ctrl, *args, **kwargs): start_time = time.time() resp = func(ctrl, *args, **kwargs) if server_handled_successfully(resp.status_int): ctrl.logger.timing_since((method + '.timing'), start_time, **dec_kwargs) else: ctrl.logger.timing_since((method + '.errors.timing'), start_time, **dec_kwargs) return resp return _timing_stats return decorating_func
[ "def", "timing_stats", "(", "**", "dec_kwargs", ")", ":", "def", "decorating_func", "(", "func", ")", ":", "method", "=", "func", ".", "__name__", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_timing_stats", "(", "ctrl", ",", "*", "args", ...
returns a decorator that logs timing events or errors for public methods in swifts wsgi server controllers .
train
false
25,757
def signal_name(signum): return SIGMAP[signum][3:]
[ "def", "signal_name", "(", "signum", ")", ":", "return", "SIGMAP", "[", "signum", "]", "[", "3", ":", "]" ]
get a cleaned up name of a signal .
train
false
25,758
def AccountListEntryFromString(xml_string): return atom.CreateClassFromXMLString(AccountListEntry, xml_string)
[ "def", "AccountListEntryFromString", "(", "xml_string", ")", ":", "return", "atom", ".", "CreateClassFromXMLString", "(", "AccountListEntry", ",", "xml_string", ")" ]
converts an xml string into an accountlistentry object .
train
false
25,759
def _cpu_busy_time(times): busy = _cpu_tot_time(times) busy -= times.idle busy -= getattr(times, 'iowait', 0) return busy
[ "def", "_cpu_busy_time", "(", "times", ")", ":", "busy", "=", "_cpu_tot_time", "(", "times", ")", "busy", "-=", "times", ".", "idle", "busy", "-=", "getattr", "(", "times", ",", "'iowait'", ",", "0", ")", "return", "busy" ]
given a cpu_time() ntuple calculates the busy cpu time .
train
false
25,760
def _finish_ok(response_data=None, content_type=u'json', resource_location=None): status_int = 200 headers = None if resource_location: status_int = 201 try: resource_location = str(resource_location) except Exception as inst: msg = (u"Couldn't convert '%s' header value '%s' to string: %s" % (u'Location', resource_location, inst)) raise Exception(msg) headers = {u'Location': resource_location} return _finish(status_int, response_data, content_type, headers)
[ "def", "_finish_ok", "(", "response_data", "=", "None", ",", "content_type", "=", "u'json'", ",", "resource_location", "=", "None", ")", ":", "status_int", "=", "200", "headers", "=", "None", "if", "resource_location", ":", "status_int", "=", "201", "try", "...
if a controller method has completed successfully then calling this method will prepare the response .
train
false
25,763
def quota_handler(): logging.debug('Checking quota') BPSMeter.do.reset_quota()
[ "def", "quota_handler", "(", ")", ":", "logging", ".", "debug", "(", "'Checking quota'", ")", "BPSMeter", ".", "do", ".", "reset_quota", "(", ")" ]
to be called from scheduler .
train
false
25,764
def start_cassandra(db_ips, db_master, keyname): logging.info('Starting Cassandra...') for ip in db_ips: init_config = '{script} --local-ip {ip} --master-ip {db_master}'.format(script=SETUP_CASSANDRA_SCRIPT, ip=ip, db_master=db_master) try: utils.ssh(ip, keyname, init_config) except subprocess.CalledProcessError: message = 'Unable to configure Cassandra on {}'.format(ip) logging.exception(message) raise dbconstants.AppScaleDBError(message) try: start_service_cmd = (START_SERVICE_SCRIPT + CASSANDRA_WATCH_NAME) utils.ssh(ip, keyname, start_service_cmd) except subprocess.CalledProcessError: message = 'Unable to start Cassandra on {}'.format(ip) logging.exception(message) raise dbconstants.AppScaleDBError(message) logging.info('Waiting for Cassandra to be ready') status_cmd = '{} status'.format(cassandra_interface.NODE_TOOL) while (utils.ssh(db_master, keyname, status_cmd, method=subprocess.call) != 0): time.sleep(5) logging.info('Successfully started Cassandra.')
[ "def", "start_cassandra", "(", "db_ips", ",", "db_master", ",", "keyname", ")", ":", "logging", ".", "info", "(", "'Starting Cassandra...'", ")", "for", "ip", "in", "db_ips", ":", "init_config", "=", "'{script} --local-ip {ip} --master-ip {db_master}'", ".", "format...
creates a monit configuration file and prompts monit to start cassandra .
train
false
25,765
def _convert_to_varsPOS(maxterm, variables): temp = [] for (i, m) in enumerate(maxterm): if (m == 1): temp.append(Not(variables[i])) elif (m == 0): temp.append(variables[i]) else: pass return Or(*temp)
[ "def", "_convert_to_varsPOS", "(", "maxterm", ",", "variables", ")", ":", "temp", "=", "[", "]", "for", "(", "i", ",", "m", ")", "in", "enumerate", "(", "maxterm", ")", ":", "if", "(", "m", "==", "1", ")", ":", "temp", ".", "append", "(", "Not", ...
converts a term in the expansion of a function from binary to its variable form .
train
false
25,766
def validator_errors_dict(): return {('other key',): ['other error']}
[ "def", "validator_errors_dict", "(", ")", ":", "return", "{", "(", "'other key'", ",", ")", ":", "[", "'other error'", "]", "}" ]
return an errors dict with some arbitrary errors in it .
train
false
25,767
def _clear_community_details(community_details): for key in ['acl', 'mode']: _str_elem(community_details, key) _mode = community_details.get['mode'] = community_details.get('mode').lower() if (_mode in _COMMUNITY_MODE_MAP.keys()): community_details['mode'] = _COMMUNITY_MODE_MAP.get(_mode) if (community_details['mode'] not in ['ro', 'rw']): community_details['mode'] = 'ro' return community_details
[ "def", "_clear_community_details", "(", "community_details", ")", ":", "for", "key", "in", "[", "'acl'", ",", "'mode'", "]", ":", "_str_elem", "(", "community_details", ",", "key", ")", "_mode", "=", "community_details", ".", "get", "[", "'mode'", "]", "=", ...
clears community details .
train
true
25,768
@handle_response_format @treeio_login_required def category_edit(request, knowledgeCategory_id, response_format='html'): category = get_object_or_404(KnowledgeCategory, pk=knowledgeCategory_id) items = Object.filter_permitted(manager=KnowledgeItem.objects, user=request.user.profile, mode='r') if (not request.user.profile.has_permission(category, mode='w')): return user_denied(request, message="You don't have access to this Knowledge Category") if request.POST: if ('cancel' not in request.POST): form = KnowledgeCategoryForm(request.POST, instance=category) if form.is_valid(): category = form.save() return HttpResponseRedirect(reverse('knowledge_category_view', args=[category.treepath])) else: return HttpResponseRedirect(reverse('knowledge_category_view', args=[category.treepath])) else: form = KnowledgeCategoryForm(instance=category) context = _get_default_context(request) context.update({'form': form, 'category': category, 'items': items}) return render_to_response('knowledge/category_edit', context, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "category_edit", "(", "request", ",", "knowledgeCategory_id", ",", "response_format", "=", "'html'", ")", ":", "category", "=", "get_object_or_404", "(", "KnowledgeCategory", ",", "pk", "=", "knowledg...
category edit page .
train
false
25,769
def _close_epochs_event(events, params): info = params['info'] exclude = [info['ch_names'].index(x) for x in info['bads'] if x.startswith('IC')] params['ica'].exclude = exclude
[ "def", "_close_epochs_event", "(", "events", ",", "params", ")", ":", "info", "=", "params", "[", "'info'", "]", "exclude", "=", "[", "info", "[", "'ch_names'", "]", ".", "index", "(", "x", ")", "for", "x", "in", "info", "[", "'bads'", "]", "if", "...
exclude the selected components on close .
train
false
25,770
def skip_leading_wsp(f): return StringIO('\n'.join(map(string.strip, f.readlines())))
[ "def", "skip_leading_wsp", "(", "f", ")", ":", "return", "StringIO", "(", "'\\n'", ".", "join", "(", "map", "(", "string", ".", "strip", ",", "f", ".", "readlines", "(", ")", ")", ")", ")" ]
works on a file .
train
false
25,772
def json_error_formatter(body, status, title, environ): body = webob.exc.strip_tags(body) status_code = int(status.split(None, 1)[0]) error_dict = {'status': status_code, 'title': title, 'detail': body} if (request_id.ENV_REQUEST_ID in environ): error_dict['request_id'] = environ[request_id.ENV_REQUEST_ID] microversion = nova.api.openstack.placement.microversion if ((status_code == 406) and (microversion.MICROVERSION_ENVIRON not in environ)): error_dict['max_version'] = microversion.max_version_string() error_dict['min_version'] = microversion.min_version_string() return {'errors': [error_dict]}
[ "def", "json_error_formatter", "(", "body", ",", "status", ",", "title", ",", "environ", ")", ":", "body", "=", "webob", ".", "exc", ".", "strip_tags", "(", "body", ")", "status_code", "=", "int", "(", "status", ".", "split", "(", "None", ",", "1", "...
a json_formatter for webob exceptions .
train
false
25,775
def valid_timestamp(request): try: return request.timestamp except exceptions.InvalidTimestamp as e: raise HTTPBadRequest(body=str(e), request=request, content_type='text/plain')
[ "def", "valid_timestamp", "(", "request", ")", ":", "try", ":", "return", "request", ".", "timestamp", "except", "exceptions", ".", "InvalidTimestamp", "as", "e", ":", "raise", "HTTPBadRequest", "(", "body", "=", "str", "(", "e", ")", ",", "request", "=", ...
helper function to extract a timestamp from requests that require one .
train
false
25,776
def get_server_versions(): global cass_version, cql_version if (cass_version is not None): return (cass_version, cql_version) c = Cluster() s = c.connect() row = s.execute('SELECT cql_version, release_version FROM system.local')[0] cass_version = _tuple_version(row.release_version) cql_version = _tuple_version(row.cql_version) c.shutdown() return (cass_version, cql_version)
[ "def", "get_server_versions", "(", ")", ":", "global", "cass_version", ",", "cql_version", "if", "(", "cass_version", "is", "not", "None", ")", ":", "return", "(", "cass_version", ",", "cql_version", ")", "c", "=", "Cluster", "(", ")", "s", "=", "c", "."...
probe system .
train
false
25,777
def parse_kappas(lines, parameters): kappa_found = False for line in lines: line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] if ('Parameters (kappa)' in line): kappa_found = True elif (kappa_found and line_floats): branch_res = re.match('\\s(\\d+\\.\\.\\d+)', line) if (branch_res is None): if (len(line_floats) == 1): parameters['kappa'] = line_floats[0] else: parameters['kappa'] = line_floats kappa_found = False else: if (parameters.get('branches') is None): parameters['branches'] = {} branch = branch_res.group(1) if line_floats: parameters['branches'][branch] = {'t': line_floats[0], 'kappa': line_floats[1], 'TS': line_floats[2], 'TV': line_floats[3]} elif (('kappa under' in line) and line_floats): if (len(line_floats) == 1): parameters['kappa'] = line_floats[0] else: parameters['kappa'] = line_floats return parameters
[ "def", "parse_kappas", "(", "lines", ",", "parameters", ")", ":", "kappa_found", "=", "False", "for", "line", "in", "lines", ":", "line_floats_res", "=", "line_floats_re", ".", "findall", "(", "line", ")", "line_floats", "=", "[", "float", "(", "val", ")",...
parse out the kappa parameters .
train
false
25,780
def test_hosts_as_tuples(): def command(): pass eq_hosts(command, ['foo', 'bar'], env={'hosts': ('foo', 'bar')})
[ "def", "test_hosts_as_tuples", "(", ")", ":", "def", "command", "(", ")", ":", "pass", "eq_hosts", "(", "command", ",", "[", "'foo'", ",", "'bar'", "]", ",", "env", "=", "{", "'hosts'", ":", "(", "'foo'", ",", "'bar'", ")", "}", ")" ]
test that a list of hosts as a tuple succeeds .
train
false
25,781
def time_(format='%A, %d. %B %Y %I:%M%p'): dt = datetime.datetime.today() return dt.strftime(format)
[ "def", "time_", "(", "format", "=", "'%A, %d. %B %Y %I:%M%p'", ")", ":", "dt", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "return", "dt", ".", "strftime", "(", "format", ")" ]
return time information from osquery cli example: .
train
false
25,782
def wronskian(functions, var, method='bareis'): from .dense import Matrix for index in range(0, len(functions)): functions[index] = sympify(functions[index]) n = len(functions) if (n == 0): return 1 W = Matrix(n, n, (lambda i, j: functions[i].diff(var, j))) return W.det(method)
[ "def", "wronskian", "(", "functions", ",", "var", ",", "method", "=", "'bareis'", ")", ":", "from", ".", "dense", "import", "Matrix", "for", "index", "in", "range", "(", "0", ",", "len", "(", "functions", ")", ")", ":", "functions", "[", "index", "]"...
compute wronskian for [] of functions | f1 f2 .
train
false
25,783
def _hex_to_bin_str(hex_string): unpadded_bin_string_list = (bin(to_byte(c)) for c in hex_string) padded_bin_string_list = map(_pad_binary, unpadded_bin_string_list) bitwise_message = ''.join(padded_bin_string_list) return bitwise_message
[ "def", "_hex_to_bin_str", "(", "hex_string", ")", ":", "unpadded_bin_string_list", "=", "(", "bin", "(", "to_byte", "(", "c", ")", ")", "for", "c", "in", "hex_string", ")", "padded_bin_string_list", "=", "map", "(", "_pad_binary", ",", "unpadded_bin_string_list"...
given a python bytestring .
train
false
25,784
def handle_dashboard_error(view): def wrapper(request, course_id): '\n Wrap the view.\n ' try: return view(request, course_id=course_id) except DashboardError as error: return error.response() return wrapper
[ "def", "handle_dashboard_error", "(", "view", ")", ":", "def", "wrapper", "(", "request", ",", "course_id", ")", ":", "try", ":", "return", "view", "(", "request", ",", "course_id", "=", "course_id", ")", "except", "DashboardError", "as", "error", ":", "re...
decorator which adds seamless dashboarderror handling to a view .
train
false
25,786
def ansi_partial_color_format(template, style='default', cmap=None, hide=False): try: return _ansi_partial_color_format_main(template, style=style, cmap=cmap, hide=hide) except Exception: return template
[ "def", "ansi_partial_color_format", "(", "template", ",", "style", "=", "'default'", ",", "cmap", "=", "None", ",", "hide", "=", "False", ")", ":", "try", ":", "return", "_ansi_partial_color_format_main", "(", "template", ",", "style", "=", "style", ",", "cm...
formats a template string but only with respect to the colors .
train
false
25,787
def get_scale_change_value(label): return _get_array_element('scale change', label, (0.78, 1.0))
[ "def", "get_scale_change_value", "(", "label", ")", ":", "return", "_get_array_element", "(", "'scale change'", ",", "label", ",", "(", "0.78", ",", "1.0", ")", ")" ]
returns the float value represented by a scale change label int .
train
false
25,788
def idempotent_id(id): if (not isinstance(id, six.string_types)): raise TypeError(('Test idempotent_id must be string not %s' % type(id).__name__)) uuid.UUID(id) def decorator(f): f = testtools.testcase.attr(('id-%s' % id))(f) if f.__doc__: f.__doc__ = ('Test idempotent id: %s\n%s' % (id, f.__doc__)) else: f.__doc__ = ('Test idempotent id: %s' % id) return f return decorator
[ "def", "idempotent_id", "(", "id", ")", ":", "if", "(", "not", "isinstance", "(", "id", ",", "six", ".", "string_types", ")", ")", ":", "raise", "TypeError", "(", "(", "'Test idempotent_id must be string not %s'", "%", "type", "(", "id", ")", ".", "__name_...
stub for metadata decorator .
train
false
25,789
def issequence(item): return (type(item) in (ListType, StringType, TupleType))
[ "def", "issequence", "(", "item", ")", ":", "return", "(", "type", "(", "item", ")", "in", "(", "ListType", ",", "StringType", ",", "TupleType", ")", ")" ]
return true iff _item_ is a sequence .
train
false
25,790
def test_conv_wrapper(backend_default): conv = Conv((4, 4, 3), Uniform()) assert isinstance(conv, list) assert (len(conv) == 1) assert isinstance(conv[0], Convolution) conv = Conv((4, 4, 3), Uniform(), bias=Uniform()) assert isinstance(conv, list) assert (len(conv) == 2) assert isinstance(conv[0], Convolution) assert isinstance(conv[1], Bias) conv = Conv((4, 4, 3), Uniform(), activation=Rectlin()) assert isinstance(conv, list) assert (len(conv) == 2) assert isinstance(conv[0], Convolution) assert isinstance(conv[1], Activation) conv = Conv((4, 4, 3), Uniform(), bias=Uniform(), activation=Rectlin()) assert isinstance(conv, list) assert isinstance(conv[0], Convolution) assert isinstance(conv[1], Bias) assert isinstance(conv[2], Activation) assert (len(conv) == 3)
[ "def", "test_conv_wrapper", "(", "backend_default", ")", ":", "conv", "=", "Conv", "(", "(", "4", ",", "4", ",", "3", ")", ",", "Uniform", "(", ")", ")", "assert", "isinstance", "(", "conv", ",", "list", ")", "assert", "(", "len", "(", "conv", ")",...
verify that the conv wrapper constructs the right layer objects .
train
false
25,791
def clip_path(path): if (sabnzbd.WIN32 and path and ('?' in path)): path = path.replace(u'\\\\?\\UNC\\', u'\\\\').replace(u'\\\\?\\', u'') return path
[ "def", "clip_path", "(", "path", ")", ":", "if", "(", "sabnzbd", ".", "WIN32", "and", "path", "and", "(", "'?'", "in", "path", ")", ")", ":", "path", "=", "path", ".", "replace", "(", "u'\\\\\\\\?\\\\UNC\\\\'", ",", "u'\\\\\\\\'", ")", ".", "replace", ...
remove ? or ?unc prefix from windows path .
train
false
25,794
def GetMacBundleResources(product_dir, xcode_settings, resources): dest = os.path.join(product_dir, xcode_settings.GetBundleResourceFolder()) for res in resources: output = dest assert (' ' not in res), ('Spaces in resource filenames not supported (%s)' % res) res_parts = os.path.split(res) lproj_parts = os.path.split(res_parts[0]) if lproj_parts[1].endswith('.lproj'): output = os.path.join(output, lproj_parts[1]) output = os.path.join(output, res_parts[1]) if output.endswith('.xib'): output = (os.path.splitext(output)[0] + '.nib') if output.endswith('.storyboard'): output = (os.path.splitext(output)[0] + '.storyboardc') (yield (output, res))
[ "def", "GetMacBundleResources", "(", "product_dir", ",", "xcode_settings", ",", "resources", ")", ":", "dest", "=", "os", ".", "path", ".", "join", "(", "product_dir", ",", "xcode_settings", ".", "GetBundleResourceFolder", "(", ")", ")", "for", "res", "in", ...
yields pairs for every resource in |resources| .
train
false
25,795
def _propagate_root_output(graph, node, field, connections): for (destnode, inport, src) in connections: value = getattr(node.inputs, field) if isinstance(src, tuple): value = evaluate_connect_function(src[1], src[2], value) destnode.set_input(inport, value)
[ "def", "_propagate_root_output", "(", "graph", ",", "node", ",", "field", ",", "connections", ")", ":", "for", "(", "destnode", ",", "inport", ",", "src", ")", "in", "connections", ":", "value", "=", "getattr", "(", "node", ".", "inputs", ",", "field", ...
propagates the given graph root node output port field connections to the out-edge destination nodes .
train
false
25,796
def describe_cache_clusters(name=None, conn=None, region=None, key=None, keyid=None, profile=None, **args): return _describe_resource(name=name, name_param='CacheClusterId', res_type='cache_cluster', info_node='CacheClusters', conn=conn, region=region, key=key, keyid=keyid, profile=profile, **args)
[ "def", "describe_cache_clusters", "(", "name", "=", "None", ",", "conn", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "**", "args", ")", ":", "return", "_describe_resourc...
return details about all elasticache cache clusters .
train
true
25,797
def before(action): def _before(responder_or_resource): if isinstance(responder_or_resource, six.class_types): resource = responder_or_resource for method in HTTP_METHODS: responder_name = ('on_' + method.lower()) try: responder = getattr(resource, responder_name) except AttributeError: pass else: if callable(responder): def let(responder=responder): do_before_all = _wrap_with_before(action, responder) setattr(resource, responder_name, do_before_all) let() return resource else: responder = responder_or_resource do_before_one = _wrap_with_before(action, responder) return do_before_one return _before
[ "def", "before", "(", "action", ")", ":", "def", "_before", "(", "responder_or_resource", ")", ":", "if", "isinstance", "(", "responder_or_resource", ",", "six", ".", "class_types", ")", ":", "resource", "=", "responder_or_resource", "for", "method", "in", "HT...
true if point datetime specification is before now .
train
false
25,798
def _get_proxy_net_location(proxy_settings): if ('@' in proxy_settings): protocol = proxy_settings.split(':')[0] netloc = proxy_settings.split('@')[1] return ('%s://%s' % (protocol, netloc)) else: return proxy_settings
[ "def", "_get_proxy_net_location", "(", "proxy_settings", ")", ":", "if", "(", "'@'", "in", "proxy_settings", ")", ":", "protocol", "=", "proxy_settings", ".", "split", "(", "':'", ")", "[", "0", "]", "netloc", "=", "proxy_settings", ".", "split", "(", "'@'...
returns proxy host and port .
train
false
25,800
def _split_comma_separated(string): return set((text.strip() for text in string.split(u',') if text.strip()))
[ "def", "_split_comma_separated", "(", "string", ")", ":", "return", "set", "(", "(", "text", ".", "strip", "(", ")", "for", "text", "in", "string", ".", "split", "(", "u','", ")", "if", "text", ".", "strip", "(", ")", ")", ")" ]
return a set of strings .
train
true
25,801
@register.filter def naturaltime(value): if (not isinstance(value, date)): return value now = datetime.now((utc if is_aware(value) else None)) if (value < now): delta = (now - value) if (delta.days != 0): return (pgettext('naturaltime', '%(delta)s ago') % {'delta': defaultfilters.timesince(value, now)}) elif (delta.seconds == 0): return _('now') elif (delta.seconds < 60): return (ungettext('a second ago', '%(count)s\xc2\xa0seconds ago', delta.seconds) % {'count': delta.seconds}) elif ((delta.seconds // 60) < 60): count = (delta.seconds // 60) return (ungettext('a minute ago', '%(count)s\xc2\xa0minutes ago', count) % {'count': count}) else: count = ((delta.seconds // 60) // 60) return (ungettext('an hour ago', '%(count)s\xc2\xa0hours ago', count) % {'count': count}) else: delta = (value - now) if (delta.days != 0): return (pgettext('naturaltime', '%(delta)s from now') % {'delta': defaultfilters.timeuntil(value, now)}) elif (delta.seconds == 0): return _('now') elif (delta.seconds < 60): return (ungettext('a second from now', '%(count)s\xc2\xa0seconds from now', delta.seconds) % {'count': delta.seconds}) elif ((delta.seconds // 60) < 60): count = (delta.seconds // 60) return (ungettext('a minute from now', '%(count)s\xc2\xa0minutes from now', count) % {'count': count}) else: count = ((delta.seconds // 60) // 60) return (ungettext('an hour from now', '%(count)s\xc2\xa0hours from now', count) % {'count': count})
[ "@", "register", ".", "filter", "def", "naturaltime", "(", "value", ")", ":", "if", "(", "not", "isinstance", "(", "value", ",", "date", ")", ")", ":", "return", "value", "now", "=", "datetime", ".", "now", "(", "(", "utc", "if", "is_aware", "(", "...
heavily based on djangos django .
train
false
25,802
def _topological_sort(pairlist): numpreds = {} successors = {} for (second, target) in pairlist.items(): if (second not in numpreds): numpreds[second] = 0 if (second not in successors): successors[second] = [] deps = target.expanded_deps for first in deps: if (first not in numpreds): numpreds[first] = 0 numpreds[second] = (numpreds[second] + 1) if (first in successors): successors[first].append(second) else: successors[first] = [second] answer = filter((lambda x, numpreds=numpreds: (numpreds[x] == 0)), numpreds.keys()) for x in answer: assert (numpreds[x] == 0) del numpreds[x] if (x in successors): for y in successors[x]: numpreds[y] = (numpreds[y] - 1) if (numpreds[y] == 0): answer.append(y) return (answer, successors)
[ "def", "_topological_sort", "(", "pairlist", ")", ":", "numpreds", "=", "{", "}", "successors", "=", "{", "}", "for", "(", "second", ",", "target", ")", "in", "pairlist", ".", "items", "(", ")", ":", "if", "(", "second", "not", "in", "numpreds", ")",...
sort the targets .
train
false
25,803
@contextmanager def swallow_psutil_exceptions(): try: (yield) except (psutil.AccessDenied, psutil.NoSuchProcess): pass
[ "@", "contextmanager", "def", "swallow_psutil_exceptions", "(", ")", ":", "try", ":", "(", "yield", ")", "except", "(", "psutil", ".", "AccessDenied", ",", "psutil", ".", "NoSuchProcess", ")", ":", "pass" ]
a contextmanager that swallows standard psutil access exceptions .
train
false
25,804
def striphtml(text): return Markup(text).striptags()
[ "def", "striphtml", "(", "text", ")", ":", "return", "Markup", "(", "text", ")", ".", "striptags", "(", ")" ]
strip html tags from text .
train
false
25,805
def servicegroup_server_delete(sg_name, s_name, s_port, **connection_args): ret = True server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args) if (server is None): return False nitro = _connect(**connection_args) if (nitro is None): return False sgsb = NSServiceGroupServerBinding() sgsb.set_servicegroupname(sg_name) sgsb.set_servername(s_name) sgsb.set_port(s_port) try: NSServiceGroupServerBinding.delete(nitro, sgsb) except NSNitroError as error: log.debug('netscaler module error - NSServiceGroupServerBinding() failed: {0}'.format(error)) ret = False _disconnect(nitro) return ret
[ "def", "servicegroup_server_delete", "(", "sg_name", ",", "s_name", ",", "s_port", ",", "**", "connection_args", ")", ":", "ret", "=", "True", "server", "=", "_servicegroup_get_server", "(", "sg_name", ",", "s_name", ",", "s_port", ",", "**", "connection_args", ...
remove a server:port member from a servicegroup cli example: .
train
true
25,806
def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options): rules_filename = ('%s%s.rules' % (spec['target_name'], options.suffix)) rules_file = MSVSToolFile.Writer(os.path.join(output_dir, rules_filename), spec['target_name']) for r in rules: rule_name = r['rule_name'] rule_ext = r['extension'] inputs = _FixPaths(r.get('inputs', [])) outputs = _FixPaths(r.get('outputs', [])) if (('action' not in r) and (not r.get('rule_sources', []))): continue cmd = _BuildCommandLineForRule(spec, r, has_input_path=True, do_setup_env=True) rules_file.AddCustomBuildRule(name=rule_name, description=r.get('message', rule_name), extensions=[rule_ext], additional_dependencies=inputs, outputs=outputs, cmd=cmd) rules_file.WriteIfChanged() p.AddToolFile(rules_filename)
[ "def", "_GenerateNativeRulesForMSVS", "(", "p", ",", "rules", ",", "output_dir", ",", "spec", ",", "options", ")", ":", "rules_filename", "=", "(", "'%s%s.rules'", "%", "(", "spec", "[", "'target_name'", "]", ",", "options", ".", "suffix", ")", ")", "rules...
generate a native rules file .
train
false
25,807
def sphere(individual): return (sum(((gene * gene) for gene in individual)),)
[ "def", "sphere", "(", "individual", ")", ":", "return", "(", "sum", "(", "(", "(", "gene", "*", "gene", ")", "for", "gene", "in", "individual", ")", ")", ",", ")" ]
sphere test objective function .
train
false
25,808
def test_multiset_partitions_versions(): multiplicities = [5, 2, 2, 1] m = MultisetPartitionTraverser() for (s1, s2) in zip_longest(m.enum_all(multiplicities), multiset_partitions_taocp(multiplicities)): assert compare_multiset_states(s1, s2)
[ "def", "test_multiset_partitions_versions", "(", ")", ":", "multiplicities", "=", "[", "5", ",", "2", ",", "2", ",", "1", "]", "m", "=", "MultisetPartitionTraverser", "(", ")", "for", "(", "s1", ",", "s2", ")", "in", "zip_longest", "(", "m", ".", "enum...
compares knuth-based versions of multiset_partitions .
train
false
25,810
def sgf_to_gamestate(sgf_string): for (gs, move, player) in sgf_iter_states(sgf_string, True): pass return gs
[ "def", "sgf_to_gamestate", "(", "sgf_string", ")", ":", "for", "(", "gs", ",", "move", ",", "player", ")", "in", "sgf_iter_states", "(", "sgf_string", ",", "True", ")", ":", "pass", "return", "gs" ]
creates a gamestate object from the first game in the given collection .
train
false
25,811
def course_context_from_url(url): url = (url or '') match = COURSE_REGEX.match(url) course_id = None if match: course_id_string = match.group('course_id') try: course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id_string) except InvalidKeyError: log.warning('unable to parse course_id "{course_id}"'.format(course_id=course_id_string), exc_info=True) return course_context_from_course_id(course_id)
[ "def", "course_context_from_url", "(", "url", ")", ":", "url", "=", "(", "url", "or", "''", ")", "match", "=", "COURSE_REGEX", ".", "match", "(", "url", ")", "course_id", "=", "None", "if", "match", ":", "course_id_string", "=", "match", ".", "group", ...
extracts the course_context from the given url and passes it on to course_context_from_course_id() .
train
false
25,812
def header(hdr, value): context.headers.append((hdr, value))
[ "def", "header", "(", "hdr", ",", "value", ")", ":", "context", ".", "headers", ".", "append", "(", "(", "hdr", ",", "value", ")", ")" ]
adds the header hdr: value with the response .
train
false
25,814
def ParameterAsNumpy(param): return np.fromstring(param.mat, dtype='float32').reshape(*tuple(param.dimensions))
[ "def", "ParameterAsNumpy", "(", "param", ")", ":", "return", "np", ".", "fromstring", "(", "param", ".", "mat", ",", "dtype", "=", "'float32'", ")", ".", "reshape", "(", "*", "tuple", "(", "param", ".", "dimensions", ")", ")" ]
converts a serialized parameter string into a numpy array .
train
false
25,815
def get_device_counters(**kwargs): assert ((('zone' in kwargs) + ('devices' in kwargs)) == 1), 'Must specify zone or devices, and not both.' from ..devices.models import Device devices = (kwargs.get('devices') or Device.all_objects.by_zone(kwargs['zone'])) device_counters = {} for device in list(devices): if (device.id not in device_counters): device_counters[device.id] = device.get_counter_position() if device.is_own_device(): cnt = 0 for Model in _syncing_models: cnt += Model.all_objects.filter((Q(counter__isnull=True) | Q(signature__isnull=True))).count() device_counters[device.id] += cnt return device_counters
[ "def", "get_device_counters", "(", "**", "kwargs", ")", ":", "assert", "(", "(", "(", "'zone'", "in", "kwargs", ")", "+", "(", "'devices'", "in", "kwargs", ")", ")", "==", "1", ")", ",", "'Must specify zone or devices, and not both.'", "from", ".", ".", "d...
get device counters .
train
false
25,817
def _GetDefaultParams(template_params): if (not template_params): template_params = {} template_params.update({'base_path': config.BASE_PATH, 'mapreduce_path': config.MAPREDUCE_PATH}) return template_params
[ "def", "_GetDefaultParams", "(", "template_params", ")", ":", "if", "(", "not", "template_params", ")", ":", "template_params", "=", "{", "}", "template_params", ".", "update", "(", "{", "'base_path'", ":", "config", ".", "BASE_PATH", ",", "'mapreduce_path'", ...
update template_params to always contain necessary paths and never none .
train
false
25,818
def collect_exception(t, v, tb, limit=None): return col.collectException(t, v, tb, limit=limit)
[ "def", "collect_exception", "(", "t", ",", "v", ",", "tb", ",", "limit", "=", "None", ")", ":", "return", "col", ".", "collectException", "(", "t", ",", "v", ",", "tb", ",", "limit", "=", "limit", ")" ]
collection an exception from sys .
train
false
25,819
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
initialise module .
train
false
25,820
def escape_url(url): url_parsed = compat_urllib_parse_urlparse(url) return url_parsed._replace(path=escape_rfc3986(url_parsed.path), params=escape_rfc3986(url_parsed.params), query=escape_rfc3986(url_parsed.query), fragment=escape_rfc3986(url_parsed.fragment)).geturl()
[ "def", "escape_url", "(", "url", ")", ":", "url_parsed", "=", "compat_urllib_parse_urlparse", "(", "url", ")", "return", "url_parsed", ".", "_replace", "(", "path", "=", "escape_rfc3986", "(", "url_parsed", ".", "path", ")", ",", "params", "=", "escape_rfc3986...
escape url as suggested by rfc 3986 .
train
false
25,822
def find_cliques_recursive(G): if (len(G) == 0): return iter([]) adj = {u: {v for v in G[u] if (v != u)} for u in G} Q = [] def expand(subg, cand): u = max(subg, key=(lambda u: len((cand & adj[u])))) for q in (cand - adj[u]): cand.remove(q) Q.append(q) adj_q = adj[q] subg_q = (subg & adj_q) if (not subg_q): (yield Q[:]) else: cand_q = (cand & adj_q) if cand_q: for clique in expand(subg_q, cand_q): (yield clique) Q.pop() return expand(set(G), set(G))
[ "def", "find_cliques_recursive", "(", "G", ")", ":", "if", "(", "len", "(", "G", ")", "==", "0", ")", ":", "return", "iter", "(", "[", "]", ")", "adj", "=", "{", "u", ":", "{", "v", "for", "v", "in", "G", "[", "u", "]", "if", "(", "v", "!...
returns all maximal cliques in a graph .
train
false
25,824
def _find_fiducials_files(subject, subjects_dir): fid = [] if os.path.exists(fid_fname.format(subjects_dir=subjects_dir, subject=subject)): fid.append(fid_fname) pattern = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='*') regex = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='(.+)') for path in iglob(pattern): match = re.match(regex, path) head = match.group(1).replace(subject, '{subject}') fid.append(pformat(fid_fname_general, head=head)) return fid
[ "def", "_find_fiducials_files", "(", "subject", ",", "subjects_dir", ")", ":", "fid", "=", "[", "]", "if", "os", ".", "path", ".", "exists", "(", "fid_fname", ".", "format", "(", "subjects_dir", "=", "subjects_dir", ",", "subject", "=", "subject", ")", "...
find fiducial files .
train
false
25,825
def is_kvm_hyper(): try: with salt.utils.fopen('/proc/modules') as fp_: if ('kvm_' not in fp_.read()): return False except IOError: return False return ('libvirtd' in __salt__['cmd.run'](__grains__['ps']))
[ "def", "is_kvm_hyper", "(", ")", ":", "try", ":", "with", "salt", ".", "utils", ".", "fopen", "(", "'/proc/modules'", ")", "as", "fp_", ":", "if", "(", "'kvm_'", "not", "in", "fp_", ".", "read", "(", ")", ")", ":", "return", "False", "except", "IOE...
returns a bool whether or not this node is a kvm hypervisor cli example: .
train
false
25,827
def pytest_namespace(): return {'placeholders': placeholders}
[ "def", "pytest_namespace", "(", ")", ":", "return", "{", "'placeholders'", ":", "placeholders", "}" ]
add attributes to pytest in all tests .
train
false
25,828
def build_from_import(fromname, names): return From(fromname, [(name, None) for name in names])
[ "def", "build_from_import", "(", "fromname", ",", "names", ")", ":", "return", "From", "(", "fromname", ",", "[", "(", "name", ",", "None", ")", "for", "name", "in", "names", "]", ")" ]
create and initialize an astroid from import statement .
train
false
25,829
def parse_legacy(version='Version 1.99.0 (2011-09-19 08:23:26)'): re_version = re.compile('[^\\d]+ (\\d+)\\.(\\d+)\\.(\\d+)\\s*\\((?P<datetime>.+?)\\)\\s*(?P<type>[a-z]+)?') m = re_version.match(version) (a, b, c) = (int(m.group(1)), int(m.group(2)), int(m.group(3))) pre_release = (m.group('type') or 'dev') build = datetime.datetime.strptime(m.group('datetime'), '%Y-%m-%d %H:%M:%S') return (a, b, c, pre_release, build)
[ "def", "parse_legacy", "(", "version", "=", "'Version 1.99.0 (2011-09-19 08:23:26)'", ")", ":", "re_version", "=", "re", ".", "compile", "(", "'[^\\\\d]+ (\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)\\\\s*\\\\((?P<datetime>.+?)\\\\)\\\\s*(?P<type>[a-z]+)?'", ")", "m", "=", "re_version", "...
parses "legacy" version string args: version: the version string returns: tuple: major .
train
false
25,830
def find_malt_model(model_filename): if (model_filename == None): return u'malt_temp.mco' elif os.path.exists(model_filename): return model_filename else: return find_file(model_filename, env_vars=(u'MALT_MODEL',), verbose=False)
[ "def", "find_malt_model", "(", "model_filename", ")", ":", "if", "(", "model_filename", "==", "None", ")", ":", "return", "u'malt_temp.mco'", "elif", "os", ".", "path", ".", "exists", "(", "model_filename", ")", ":", "return", "model_filename", "else", ":", ...
a module to find pre-trained maltparser model .
train
false
25,831
def _rebuild_code(marshal_version, bytecode_magic, marshalled): if (marshal.version != marshal_version): raise RuntimeError(('incompatible marshal version: interpreter has %r, marshalled code has %r' % (marshal.version, marshal_version))) if (imp.get_magic() != bytecode_magic): raise RuntimeError('incompatible bytecode version') return marshal.loads(marshalled)
[ "def", "_rebuild_code", "(", "marshal_version", ",", "bytecode_magic", ",", "marshalled", ")", ":", "if", "(", "marshal", ".", "version", "!=", "marshal_version", ")", ":", "raise", "RuntimeError", "(", "(", "'incompatible marshal version: interpreter has %r, marshalled...
rebuild a code object from its _reduce_code() results .
train
false
25,832
def agent_service_maintenance(consul_url=None, serviceid=None, **kwargs): ret = {} query_params = {} if (not consul_url): consul_url = _get_config() if (not consul_url): log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if (not serviceid): raise SaltInvocationError('Required argument "serviceid" is missing.') if ('enable' in kwargs): query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if ('reason' in kwargs): query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Service {0} set in maintenance mode.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to set service {0} to maintenance mode.'.format(serviceid) return ret
[ "def", "agent_service_maintenance", "(", "consul_url", "=", "None", ",", "serviceid", "=", "None", ",", "**", "kwargs", ")", ":", "ret", "=", "{", "}", "query_params", "=", "{", "}", "if", "(", "not", "consul_url", ")", ":", "consul_url", "=", "_get_conf...
used to place a service into maintenance mode .
train
true