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
8,635
def p_flow_stmt(p): p[0] = p[1]
[ "def", "p_flow_stmt", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
flow_stmt : return_stmt .
train
false
8,636
def raw_config_parse(config_filename, parse_subsections=True): config = {} path = config_filename if (path is not None): path = os.path.expandvars(path) path = os.path.expanduser(path) if (not os.path.isfile(path)): raise botocore.exceptions.ConfigNotFound(path=path) cp = configparser.RawConfigParser() try: cp.read(path) except configparser.Error: raise botocore.exceptions.ConfigParseError(path=path) else: for section in cp.sections(): config[section] = {} for option in cp.options(section): config_value = cp.get(section, option) if (parse_subsections and config_value.startswith('\n')): try: config_value = _parse_nested(config_value) except ValueError: raise botocore.exceptions.ConfigParseError(path=path) config[section][option] = config_value return config
[ "def", "raw_config_parse", "(", "config_filename", ",", "parse_subsections", "=", "True", ")", ":", "config", "=", "{", "}", "path", "=", "config_filename", "if", "(", "path", "is", "not", "None", ")", ":", "path", "=", "os", ".", "path", ".", "expandvars", "(", "path", ")", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "(", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ")", ":", "raise", "botocore", ".", "exceptions", ".", "ConfigNotFound", "(", "path", "=", "path", ")", "cp", "=", "configparser", ".", "RawConfigParser", "(", ")", "try", ":", "cp", ".", "read", "(", "path", ")", "except", "configparser", ".", "Error", ":", "raise", "botocore", ".", "exceptions", ".", "ConfigParseError", "(", "path", "=", "path", ")", "else", ":", "for", "section", "in", "cp", ".", "sections", "(", ")", ":", "config", "[", "section", "]", "=", "{", "}", "for", "option", "in", "cp", ".", "options", "(", "section", ")", ":", "config_value", "=", "cp", ".", "get", "(", "section", ",", "option", ")", "if", "(", "parse_subsections", "and", "config_value", ".", "startswith", "(", "'\\n'", ")", ")", ":", "try", ":", "config_value", "=", "_parse_nested", "(", "config_value", ")", "except", "ValueError", ":", "raise", "botocore", ".", "exceptions", ".", "ConfigParseError", "(", "path", "=", "path", ")", "config", "[", "section", "]", "[", "option", "]", "=", "config_value", "return", "config" ]
returns the parsed ini config contents .
train
false
8,637
def add_multi_representer(data_type, multi_representer, Dumper=Dumper): Dumper.add_multi_representer(data_type, multi_representer)
[ "def", "add_multi_representer", "(", "data_type", ",", "multi_representer", ",", "Dumper", "=", "Dumper", ")", ":", "Dumper", ".", "add_multi_representer", "(", "data_type", ",", "multi_representer", ")" ]
add a representer for the given type .
train
false
8,638
def hypersimilar(f, g, k): (f, g) = list(map(sympify, (f, g))) h = (f / g).rewrite(gamma) h = h.expand(func=True, basic=False) return h.is_rational_function(k)
[ "def", "hypersimilar", "(", "f", ",", "g", ",", "k", ")", ":", "(", "f", ",", "g", ")", "=", "list", "(", "map", "(", "sympify", ",", "(", "f", ",", "g", ")", ")", ")", "h", "=", "(", "f", "/", "g", ")", ".", "rewrite", "(", "gamma", ")", "h", "=", "h", ".", "expand", "(", "func", "=", "True", ",", "basic", "=", "False", ")", "return", "h", ".", "is_rational_function", "(", "k", ")" ]
returns true if f and g are hyper-similar .
train
false
8,639
def ReduceOpacity(im, opacity): assert ((opacity >= 0) and (opacity <= 1)) if isalpha(im): im = im.copy() else: im = im.convert(u'RGBA') alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return im
[ "def", "ReduceOpacity", "(", "im", ",", "opacity", ")", ":", "assert", "(", "(", "opacity", ">=", "0", ")", "and", "(", "opacity", "<=", "1", ")", ")", "if", "isalpha", "(", "im", ")", ":", "im", "=", "im", ".", "copy", "(", ")", "else", ":", "im", "=", "im", ".", "convert", "(", "u'RGBA'", ")", "alpha", "=", "im", ".", "split", "(", ")", "[", "3", "]", "alpha", "=", "ImageEnhance", ".", "Brightness", "(", "alpha", ")", ".", "enhance", "(", "opacity", ")", "im", ".", "putalpha", "(", "alpha", ")", "return", "im" ]
reduces opacity .
train
true
8,641
def rr_op(left, right): if (len(right) > 0): rr_gate = right[(len(right) - 1)] rr_gate_is_unitary = is_scalar_matrix((Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True) if ((len(right) > 0) and rr_gate_is_unitary): new_right = right[0:(len(right) - 1)] new_left = (left + (Dagger(rr_gate),)) return (new_left, new_right) return None
[ "def", "rr_op", "(", "left", ",", "right", ")", ":", "if", "(", "len", "(", "right", ")", ">", "0", ")", ":", "rr_gate", "=", "right", "[", "(", "len", "(", "right", ")", "-", "1", ")", "]", "rr_gate_is_unitary", "=", "is_scalar_matrix", "(", "(", "Dagger", "(", "rr_gate", ")", ",", "rr_gate", ")", ",", "_get_min_qubits", "(", "rr_gate", ")", ",", "True", ")", "if", "(", "(", "len", "(", "right", ")", ">", "0", ")", "and", "rr_gate_is_unitary", ")", ":", "new_right", "=", "right", "[", "0", ":", "(", "len", "(", "right", ")", "-", "1", ")", "]", "new_left", "=", "(", "left", "+", "(", "Dagger", "(", "rr_gate", ")", ",", ")", ")", "return", "(", "new_left", ",", "new_right", ")", "return", "None" ]
perform a rr operation .
train
false
8,642
def is_module_satisfies(requirements, version=None, version_attr='__version__'): if (version is None): try: pkg_resources.get_distribution(requirements) except pkg_resources.DistributionNotFound: pass except (pkg_resources.UnknownExtra, pkg_resources.VersionConflict): return False else: return True requirements_parsed = pkg_resources.Requirement.parse(requirements) if (version is None): module_name = requirements_parsed.project_name version = get_module_attribute(module_name, version_attr) return (version in requirements_parsed)
[ "def", "is_module_satisfies", "(", "requirements", ",", "version", "=", "None", ",", "version_attr", "=", "'__version__'", ")", ":", "if", "(", "version", "is", "None", ")", ":", "try", ":", "pkg_resources", ".", "get_distribution", "(", "requirements", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "pass", "except", "(", "pkg_resources", ".", "UnknownExtra", ",", "pkg_resources", ".", "VersionConflict", ")", ":", "return", "False", "else", ":", "return", "True", "requirements_parsed", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "requirements", ")", "if", "(", "version", "is", "None", ")", ":", "module_name", "=", "requirements_parsed", ".", "project_name", "version", "=", "get_module_attribute", "(", "module_name", ",", "version_attr", ")", "return", "(", "version", "in", "requirements_parsed", ")" ]
true if the module .
train
false
8,643
def lambertw(z, k=0, tol=1e-08): return _lambertw(z, k, tol)
[ "def", "lambertw", "(", "z", ",", "k", "=", "0", ",", "tol", "=", "1e-08", ")", ":", "return", "_lambertw", "(", "z", ",", "k", ",", "tol", ")" ]
lambertw lambert w function .
train
false
8,645
def deactivate_all(): _active[currentThread()] = gettext_module.NullTranslations()
[ "def", "deactivate_all", "(", ")", ":", "_active", "[", "currentThread", "(", ")", "]", "=", "gettext_module", ".", "NullTranslations", "(", ")" ]
makes the active translation object a nulltranslations() instance .
train
false
8,647
def _do_update_record(profile, request, object): if profile.has_permission(object, mode='x'): if request.POST: record = UpdateRecord() record.object = object record.record_type = 'manual' form = UpdateRecordForm(request.POST, instance=record) if form.is_valid(): record = form.save() record.set_user_from_request(request) record.save() record.about.add(object) object.set_last_updated() else: form = UpdateRecordForm() else: form = None return form
[ "def", "_do_update_record", "(", "profile", ",", "request", ",", "object", ")", ":", "if", "profile", ".", "has_permission", "(", "object", ",", "mode", "=", "'x'", ")", ":", "if", "request", ".", "POST", ":", "record", "=", "UpdateRecord", "(", ")", "record", ".", "object", "=", "object", "record", ".", "record_type", "=", "'manual'", "form", "=", "UpdateRecordForm", "(", "request", ".", "POST", ",", "instance", "=", "record", ")", "if", "form", ".", "is_valid", "(", ")", ":", "record", "=", "form", ".", "save", "(", ")", "record", ".", "set_user_from_request", "(", "request", ")", "record", ".", "save", "(", ")", "record", ".", "about", ".", "add", "(", "object", ")", "object", ".", "set_last_updated", "(", ")", "else", ":", "form", "=", "UpdateRecordForm", "(", ")", "else", ":", "form", "=", "None", "return", "form" ]
get the update record form .
train
false
8,648
def _condition_3_13(A_1_norm, n0, m_max, ell): p_max = _compute_p_max(m_max) a = (((2 * ell) * p_max) * (p_max + 3)) b = (_theta[m_max] / float((n0 * m_max))) return (A_1_norm <= (a * b))
[ "def", "_condition_3_13", "(", "A_1_norm", ",", "n0", ",", "m_max", ",", "ell", ")", ":", "p_max", "=", "_compute_p_max", "(", "m_max", ")", "a", "=", "(", "(", "(", "2", "*", "ell", ")", "*", "p_max", ")", "*", "(", "p_max", "+", "3", ")", ")", "b", "=", "(", "_theta", "[", "m_max", "]", "/", "float", "(", "(", "n0", "*", "m_max", ")", ")", ")", "return", "(", "A_1_norm", "<=", "(", "a", "*", "b", ")", ")" ]
a helper function for the _expm_multiply_* functions .
train
false
8,651
def stopped(): if (not is_stopped()): stop('shorewall')
[ "def", "stopped", "(", ")", ":", "if", "(", "not", "is_stopped", "(", ")", ")", ":", "stop", "(", "'shorewall'", ")" ]
kills syslog-ng .
train
false
8,652
def get_next_ha_mrcluster(): global MR_NAME_CACHE candidates = all_mrclusters() has_ha = (sum([conf.MR_CLUSTERS[name].SUBMIT_TO.get() for name in conf.MR_CLUSTERS.keys()]) >= 2) mrcluster = get_default_mrcluster() if (mrcluster is None): return None current_user = mrcluster.user for name in conf.MR_CLUSTERS.keys(): config = conf.MR_CLUSTERS[name] if config.SUBMIT_TO.get(): jt = candidates[name] if has_ha: try: jt.setuser(current_user) status = jt.cluster_status() if (status.stateAsString == 'RUNNING'): MR_NAME_CACHE = name LOG.warn(('Picking HA JobTracker: %s' % name)) return (config, jt) else: LOG.info(('JobTracker %s is not RUNNING, skipping it: %s' % (name, status))) except Exception as ex: LOG.exception(('JobTracker %s is not available, skipping it: %s' % (name, ex))) else: return (config, jt) return None
[ "def", "get_next_ha_mrcluster", "(", ")", ":", "global", "MR_NAME_CACHE", "candidates", "=", "all_mrclusters", "(", ")", "has_ha", "=", "(", "sum", "(", "[", "conf", ".", "MR_CLUSTERS", "[", "name", "]", ".", "SUBMIT_TO", ".", "get", "(", ")", "for", "name", "in", "conf", ".", "MR_CLUSTERS", ".", "keys", "(", ")", "]", ")", ">=", "2", ")", "mrcluster", "=", "get_default_mrcluster", "(", ")", "if", "(", "mrcluster", "is", "None", ")", ":", "return", "None", "current_user", "=", "mrcluster", ".", "user", "for", "name", "in", "conf", ".", "MR_CLUSTERS", ".", "keys", "(", ")", ":", "config", "=", "conf", ".", "MR_CLUSTERS", "[", "name", "]", "if", "config", ".", "SUBMIT_TO", ".", "get", "(", ")", ":", "jt", "=", "candidates", "[", "name", "]", "if", "has_ha", ":", "try", ":", "jt", ".", "setuser", "(", "current_user", ")", "status", "=", "jt", ".", "cluster_status", "(", ")", "if", "(", "status", ".", "stateAsString", "==", "'RUNNING'", ")", ":", "MR_NAME_CACHE", "=", "name", "LOG", ".", "warn", "(", "(", "'Picking HA JobTracker: %s'", "%", "name", ")", ")", "return", "(", "config", ",", "jt", ")", "else", ":", "LOG", ".", "info", "(", "(", "'JobTracker %s is not RUNNING, skipping it: %s'", "%", "(", "name", ",", "status", ")", ")", ")", "except", "Exception", "as", "ex", ":", "LOG", ".", "exception", "(", "(", "'JobTracker %s is not available, skipping it: %s'", "%", "(", "name", ",", "ex", ")", ")", ")", "else", ":", "return", "(", "config", ",", "jt", ")", "return", "None" ]
return the next available jt instance and cache its name .
train
false
8,653
def update_package_db(module, xbps_path): cmd = ('%s -S' % xbps_path['install']) (rc, stdout, stderr) = module.run_command(cmd, check_rc=False) if (rc != 0): module.fail_json(msg='Could not update package db') if ('avg rate' in stdout): return True else: return False
[ "def", "update_package_db", "(", "module", ",", "xbps_path", ")", ":", "cmd", "=", "(", "'%s -S'", "%", "xbps_path", "[", "'install'", "]", ")", "(", "rc", ",", "stdout", ",", "stderr", ")", "=", "module", ".", "run_command", "(", "cmd", ",", "check_rc", "=", "False", ")", "if", "(", "rc", "!=", "0", ")", ":", "module", ".", "fail_json", "(", "msg", "=", "'Could not update package db'", ")", "if", "(", "'avg rate'", "in", "stdout", ")", ":", "return", "True", "else", ":", "return", "False" ]
updates packages list .
train
false
8,654
def get_init(dirname): fbase = os.path.join(dirname, '__init__') for ext in ['.py', '.pyw']: fname = (fbase + ext) if os.path.isfile(fname): return fname
[ "def", "get_init", "(", "dirname", ")", ":", "fbase", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "'__init__'", ")", "for", "ext", "in", "[", "'.py'", ",", "'.pyw'", "]", ":", "fname", "=", "(", "fbase", "+", "ext", ")", "if", "os", ".", "path", ".", "isfile", "(", "fname", ")", ":", "return", "fname" ]
get __init__ file path for module directory parameters dirname : str find the __init__ file in directory dirname returns init_path : str path to __init__ file .
train
true
8,655
@blueprint.route('/large_graph', methods=['GET']) def large_graph(): job = job_from_request() return flask.render_template('models/images/classification/large_graph.html', job=job)
[ "@", "blueprint", ".", "route", "(", "'/large_graph'", ",", "methods", "=", "[", "'GET'", "]", ")", "def", "large_graph", "(", ")", ":", "job", "=", "job_from_request", "(", ")", "return", "flask", ".", "render_template", "(", "'models/images/classification/large_graph.html'", ",", "job", "=", "job", ")" ]
show the loss/accuracy graph .
train
false
8,656
def _parse_datetime(s): if s: return datetime.strptime(s, ISO8601) else: return datetime.fromtimestamp(0)
[ "def", "_parse_datetime", "(", "s", ")", ":", "if", "s", ":", "return", "datetime", ".", "strptime", "(", "s", ",", "ISO8601", ")", "else", ":", "return", "datetime", ".", "fromtimestamp", "(", "0", ")" ]
parse dates in the format returned by the github api .
train
false
8,657
def remove_packageJSON_file(): for filename in ['package.json']: os.remove(os.path.join(PROJECT_DIRECTORY, filename))
[ "def", "remove_packageJSON_file", "(", ")", ":", "for", "filename", "in", "[", "'package.json'", "]", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "PROJECT_DIRECTORY", ",", "filename", ")", ")" ]
removes files needed for grunt if it isnt going to be used .
train
false
8,659
def convert_xor(tokens, local_dict, global_dict): result = [] for (toknum, tokval) in tokens: if (toknum == OP): if (tokval == '^'): result.append((OP, '**')) else: result.append((toknum, tokval)) else: result.append((toknum, tokval)) return result
[ "def", "convert_xor", "(", "tokens", ",", "local_dict", ",", "global_dict", ")", ":", "result", "=", "[", "]", "for", "(", "toknum", ",", "tokval", ")", "in", "tokens", ":", "if", "(", "toknum", "==", "OP", ")", ":", "if", "(", "tokval", "==", "'^'", ")", ":", "result", ".", "append", "(", "(", "OP", ",", "'**'", ")", ")", "else", ":", "result", ".", "append", "(", "(", "toknum", ",", "tokval", ")", ")", "else", ":", "result", ".", "append", "(", "(", "toknum", ",", "tokval", ")", ")", "return", "result" ]
treats xor .
train
false
8,660
def fix_paths(app_path, python_lib_path): if os.path.isfile(os.path.join(app_path, AUTO_IMPORT_FIXER_FILE)): return for (module_name, module) in sys.modules.items(): if (getattr(module, '__path__', None) is None): continue module_app_path = os.path.join(app_path, *module_name.split('.')) module_init_file = os.path.join(module_app_path, '__init__.py') if (not os.path.isfile(module_init_file)): continue found_python_lib_path = False found_app_path = False for path in module.__path__: if path.startswith(python_lib_path): found_python_lib_path = True if path.startswith(app_path): found_app_path = True if (found_python_lib_path and (not found_app_path)): module.__path__.append(module_app_path)
[ "def", "fix_paths", "(", "app_path", ",", "python_lib_path", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "app_path", ",", "AUTO_IMPORT_FIXER_FILE", ")", ")", ":", "return", "for", "(", "module_name", ",", "module", ")", "in", "sys", ".", "modules", ".", "items", "(", ")", ":", "if", "(", "getattr", "(", "module", ",", "'__path__'", ",", "None", ")", "is", "None", ")", ":", "continue", "module_app_path", "=", "os", ".", "path", ".", "join", "(", "app_path", ",", "*", "module_name", ".", "split", "(", "'.'", ")", ")", "module_init_file", "=", "os", ".", "path", ".", "join", "(", "module_app_path", ",", "'__init__.py'", ")", "if", "(", "not", "os", ".", "path", ".", "isfile", "(", "module_init_file", ")", ")", ":", "continue", "found_python_lib_path", "=", "False", "found_app_path", "=", "False", "for", "path", "in", "module", ".", "__path__", ":", "if", "path", ".", "startswith", "(", "python_lib_path", ")", ":", "found_python_lib_path", "=", "True", "if", "path", ".", "startswith", "(", "app_path", ")", ":", "found_app_path", "=", "True", "if", "(", "found_python_lib_path", "and", "(", "not", "found_app_path", ")", ")", ":", "module", ".", "__path__", ".", "append", "(", "module_app_path", ")" ]
coerce input arguments to use temporary files when used for output .
train
false
8,661
def default_hash(): return ('*' if (__grains__['os'].lower() == 'freebsd') else '*************')
[ "def", "default_hash", "(", ")", ":", "return", "(", "'*'", "if", "(", "__grains__", "[", "'os'", "]", ".", "lower", "(", ")", "==", "'freebsd'", ")", "else", "'*************'", ")" ]
returns the default hash used for unset passwords cli example: .
train
false
8,662
def as_enum(enum): if isinstance(enum, string_types): try: enum = getattr(gl, ('GL_' + enum.upper())) except AttributeError: try: enum = _internalformats[('GL_' + enum.upper())] except KeyError: raise ValueError(('Could not find int value for enum %r' % enum)) return enum
[ "def", "as_enum", "(", "enum", ")", ":", "if", "isinstance", "(", "enum", ",", "string_types", ")", ":", "try", ":", "enum", "=", "getattr", "(", "gl", ",", "(", "'GL_'", "+", "enum", ".", "upper", "(", ")", ")", ")", "except", "AttributeError", ":", "try", ":", "enum", "=", "_internalformats", "[", "(", "'GL_'", "+", "enum", ".", "upper", "(", ")", ")", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "(", "'Could not find int value for enum %r'", "%", "enum", ")", ")", "return", "enum" ]
turn a possibly string enum into an integer enum .
train
true
8,663
def conesearch(center, radius, verb=1, **kwargs): from .. import conf (ra, dec) = _validate_coord(center) sr = _validate_sr(radius) verb = _local_conversion(int, verb) if (verb not in (1, 2, 3)): raise ConeSearchError(u'Verbosity must be 1, 2, or 3') args = {u'RA': ra, u'DEC': dec, u'SR': sr, u'VERB': verb} return vos_catalog.call_vo_service(conf.conesearch_dbname, kwargs=args, **kwargs)
[ "def", "conesearch", "(", "center", ",", "radius", ",", "verb", "=", "1", ",", "**", "kwargs", ")", ":", "from", ".", ".", "import", "conf", "(", "ra", ",", "dec", ")", "=", "_validate_coord", "(", "center", ")", "sr", "=", "_validate_sr", "(", "radius", ")", "verb", "=", "_local_conversion", "(", "int", ",", "verb", ")", "if", "(", "verb", "not", "in", "(", "1", ",", "2", ",", "3", ")", ")", ":", "raise", "ConeSearchError", "(", "u'Verbosity must be 1, 2, or 3'", ")", "args", "=", "{", "u'RA'", ":", "ra", ",", "u'DEC'", ":", "dec", ",", "u'SR'", ":", "sr", ",", "u'VERB'", ":", "verb", "}", "return", "vos_catalog", ".", "call_vo_service", "(", "conf", ".", "conesearch_dbname", ",", "kwargs", "=", "args", ",", "**", "kwargs", ")" ]
perform cone search and returns the result of the first successful query .
train
false
8,664
def delvol_on_destroy(name, kwargs=None, call=None): if (call != 'action'): raise SaltCloudSystemExit('The delvol_on_destroy action must be called with -a or --action.') if (not kwargs): kwargs = {} device = kwargs.get('device', None) volume_id = kwargs.get('volume_id', None) return _toggle_delvol(name=name, device=device, volume_id=volume_id, value='true')
[ "def", "delvol_on_destroy", "(", "name", ",", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "(", "call", "!=", "'action'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The delvol_on_destroy action must be called with -a or --action.'", ")", "if", "(", "not", "kwargs", ")", ":", "kwargs", "=", "{", "}", "device", "=", "kwargs", ".", "get", "(", "'device'", ",", "None", ")", "volume_id", "=", "kwargs", ".", "get", "(", "'volume_id'", ",", "None", ")", "return", "_toggle_delvol", "(", "name", "=", "name", ",", "device", "=", "device", ",", "volume_id", "=", "volume_id", ",", "value", "=", "'true'", ")" ]
delete all/specified ebs volumes upon instance termination cli example: .
train
true
8,665
def _collect_all_synsets(word, pos, synset_relations=dict()): return ('<ul>%s\n</ul>\n' % ''.join((_collect_one_synset(word, synset, synset_relations) for synset in wn.synsets(word, pos))))
[ "def", "_collect_all_synsets", "(", "word", ",", "pos", ",", "synset_relations", "=", "dict", "(", ")", ")", ":", "return", "(", "'<ul>%s\\n</ul>\\n'", "%", "''", ".", "join", "(", "(", "_collect_one_synset", "(", "word", ",", "synset", ",", "synset_relations", ")", "for", "synset", "in", "wn", ".", "synsets", "(", "word", ",", "pos", ")", ")", ")", ")" ]
return a html unordered list of synsets for the given word and part of speech .
train
false
8,666
def test_explicit_absolute_imports(): parser = ParserWithRecovery(load_grammar(), u('from __future__ import absolute_import'), 'test.py') assert parser.module.has_explicit_absolute_import
[ "def", "test_explicit_absolute_imports", "(", ")", ":", "parser", "=", "ParserWithRecovery", "(", "load_grammar", "(", ")", ",", "u", "(", "'from __future__ import absolute_import'", ")", ",", "'test.py'", ")", "assert", "parser", ".", "module", ".", "has_explicit_absolute_import" ]
detect modules with from __future__ import absolute_import .
train
false
8,667
def _fix_up_method_description(method_desc, root_desc): path_url = method_desc['path'] http_method = method_desc['httpMethod'] method_id = method_desc['id'] parameters = _fix_up_parameters(method_desc, root_desc, http_method) (accept, max_size, media_path_url) = _fix_up_media_upload(method_desc, root_desc, path_url, parameters) return (path_url, http_method, method_id, accept, max_size, media_path_url)
[ "def", "_fix_up_method_description", "(", "method_desc", ",", "root_desc", ")", ":", "path_url", "=", "method_desc", "[", "'path'", "]", "http_method", "=", "method_desc", "[", "'httpMethod'", "]", "method_id", "=", "method_desc", "[", "'id'", "]", "parameters", "=", "_fix_up_parameters", "(", "method_desc", ",", "root_desc", ",", "http_method", ")", "(", "accept", ",", "max_size", ",", "media_path_url", ")", "=", "_fix_up_media_upload", "(", "method_desc", ",", "root_desc", ",", "path_url", ",", "parameters", ")", "return", "(", "path_url", ",", "http_method", ",", "method_id", ",", "accept", ",", "max_size", ",", "media_path_url", ")" ]
updates a method description in a discovery document .
train
false
8,668
def test_vector_rotation(): x = np.array([1.0, 0.0, 0.0]) y = np.array([0.0, 1.0, 0.0]) rot = _find_vector_rotation(x, y) assert_array_equal(rot, [[0, (-1), 0], [1, 0, 0], [0, 0, 1]]) quat_1 = rot_to_quat(rot) quat_2 = rot_to_quat(np.eye(3)) assert_allclose(_angle_between_quats(quat_1, quat_2), (np.pi / 2.0))
[ "def", "test_vector_rotation", "(", ")", ":", "x", "=", "np", ".", "array", "(", "[", "1.0", ",", "0.0", ",", "0.0", "]", ")", "y", "=", "np", ".", "array", "(", "[", "0.0", ",", "1.0", ",", "0.0", "]", ")", "rot", "=", "_find_vector_rotation", "(", "x", ",", "y", ")", "assert_array_equal", "(", "rot", ",", "[", "[", "0", ",", "(", "-", "1", ")", ",", "0", "]", ",", "[", "1", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "1", "]", "]", ")", "quat_1", "=", "rot_to_quat", "(", "rot", ")", "quat_2", "=", "rot_to_quat", "(", "np", ".", "eye", "(", "3", ")", ")", "assert_allclose", "(", "_angle_between_quats", "(", "quat_1", ",", "quat_2", ")", ",", "(", "np", ".", "pi", "/", "2.0", ")", ")" ]
test basic rotation matrix math .
train
false
8,669
def logDiffExp(A, B, out=None): if (out is None): out = numpy.zeros(A.shape) indicator1 = (A >= B) assert indicator1.all(), 'Values in the first array should be greater than the values in the second' out[indicator1] = (A[indicator1] + numpy.log((1 - numpy.exp((B[indicator1] - A[indicator1]))))) return out
[ "def", "logDiffExp", "(", "A", ",", "B", ",", "out", "=", "None", ")", ":", "if", "(", "out", "is", "None", ")", ":", "out", "=", "numpy", ".", "zeros", "(", "A", ".", "shape", ")", "indicator1", "=", "(", "A", ">=", "B", ")", "assert", "indicator1", ".", "all", "(", ")", ",", "'Values in the first array should be greater than the values in the second'", "out", "[", "indicator1", "]", "=", "(", "A", "[", "indicator1", "]", "+", "numpy", ".", "log", "(", "(", "1", "-", "numpy", ".", "exp", "(", "(", "B", "[", "indicator1", "]", "-", "A", "[", "indicator1", "]", ")", ")", ")", ")", ")", "return", "out" ]
returns log(exp(a) - exp(b)) .
train
true
8,671
def _set_italian_leading_zeros_for_phone_number(national_number, numobj): if ((len(national_number) > 1) and (national_number[0] == U_ZERO)): numobj.italian_leading_zero = True number_of_leading_zeros = 1 while ((number_of_leading_zeros < (len(national_number) - 1)) and (national_number[number_of_leading_zeros] == U_ZERO)): number_of_leading_zeros += 1 if (number_of_leading_zeros != 1): numobj.number_of_leading_zeros = number_of_leading_zeros
[ "def", "_set_italian_leading_zeros_for_phone_number", "(", "national_number", ",", "numobj", ")", ":", "if", "(", "(", "len", "(", "national_number", ")", ">", "1", ")", "and", "(", "national_number", "[", "0", "]", "==", "U_ZERO", ")", ")", ":", "numobj", ".", "italian_leading_zero", "=", "True", "number_of_leading_zeros", "=", "1", "while", "(", "(", "number_of_leading_zeros", "<", "(", "len", "(", "national_number", ")", "-", "1", ")", ")", "and", "(", "national_number", "[", "number_of_leading_zeros", "]", "==", "U_ZERO", ")", ")", ":", "number_of_leading_zeros", "+=", "1", "if", "(", "number_of_leading_zeros", "!=", "1", ")", ":", "numobj", ".", "number_of_leading_zeros", "=", "number_of_leading_zeros" ]
a helper function to set the values related to leading zeros in a phonenumber .
train
true
8,673
def authorize_request_token(request_token, url): (token, verifier) = oauth_token_info_from_url(url) request_token.token = token request_token.verifier = verifier request_token.auth_state = AUTHORIZED_REQUEST_TOKEN return request_token
[ "def", "authorize_request_token", "(", "request_token", ",", "url", ")", ":", "(", "token", ",", "verifier", ")", "=", "oauth_token_info_from_url", "(", "url", ")", "request_token", ".", "token", "=", "token", "request_token", ".", "verifier", "=", "verifier", "request_token", ".", "auth_state", "=", "AUTHORIZED_REQUEST_TOKEN", "return", "request_token" ]
adds information to request token to allow it to become an access token .
train
false
8,674
def last_in_date_group(df, dates, assets, reindex=True, have_sids=True, extra_groupers=[]): idx = [dates[dates.searchsorted(df[TS_FIELD_NAME].values.astype('datetime64[D]'))]] if have_sids: idx += [SID_FIELD_NAME] idx += extra_groupers last_in_group = df.drop(TS_FIELD_NAME, axis=1).groupby(idx, sort=False).last() for _ in range((len(idx) - 1)): last_in_group = last_in_group.unstack((-1)) if reindex: if have_sids: cols = last_in_group.columns last_in_group = last_in_group.reindex(index=dates, columns=pd.MultiIndex.from_product((tuple(cols.levels[0:(len(extra_groupers) + 1)]) + (assets,)), names=cols.names)) else: last_in_group = last_in_group.reindex(dates) return last_in_group
[ "def", "last_in_date_group", "(", "df", ",", "dates", ",", "assets", ",", "reindex", "=", "True", ",", "have_sids", "=", "True", ",", "extra_groupers", "=", "[", "]", ")", ":", "idx", "=", "[", "dates", "[", "dates", ".", "searchsorted", "(", "df", "[", "TS_FIELD_NAME", "]", ".", "values", ".", "astype", "(", "'datetime64[D]'", ")", ")", "]", "]", "if", "have_sids", ":", "idx", "+=", "[", "SID_FIELD_NAME", "]", "idx", "+=", "extra_groupers", "last_in_group", "=", "df", ".", "drop", "(", "TS_FIELD_NAME", ",", "axis", "=", "1", ")", ".", "groupby", "(", "idx", ",", "sort", "=", "False", ")", ".", "last", "(", ")", "for", "_", "in", "range", "(", "(", "len", "(", "idx", ")", "-", "1", ")", ")", ":", "last_in_group", "=", "last_in_group", ".", "unstack", "(", "(", "-", "1", ")", ")", "if", "reindex", ":", "if", "have_sids", ":", "cols", "=", "last_in_group", ".", "columns", "last_in_group", "=", "last_in_group", ".", "reindex", "(", "index", "=", "dates", ",", "columns", "=", "pd", ".", "MultiIndex", ".", "from_product", "(", "(", "tuple", "(", "cols", ".", "levels", "[", "0", ":", "(", "len", "(", "extra_groupers", ")", "+", "1", ")", "]", ")", "+", "(", "assets", ",", ")", ")", ",", "names", "=", "cols", ".", "names", ")", ")", "else", ":", "last_in_group", "=", "last_in_group", ".", "reindex", "(", "dates", ")", "return", "last_in_group" ]
determine the last piece of information known on each date in the date index for each group .
train
true
8,675
def check_repair_request(): path = os.path.join(cfg.admin_dir.get_path(), REPAIR_REQUEST) if os.path.exists(path): try: os.remove(path) except: pass return True return False
[ "def", "check_repair_request", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "cfg", ".", "admin_dir", ".", "get_path", "(", ")", ",", "REPAIR_REQUEST", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "try", ":", "os", ".", "remove", "(", "path", ")", "except", ":", "pass", "return", "True", "return", "False" ]
return true if repair request found .
train
false
8,676
def _reduce_order(ap, bq, gen, key): ap = list(ap) bq = list(bq) ap.sort(key=key) bq.sort(key=key) nap = [] operators = [] for a in ap: op = None for i in range(len(bq)): op = gen(a, bq[i]) if (op is not None): bq.pop(i) break if (op is None): nap.append(a) else: operators.append(op) return (nap, bq, operators)
[ "def", "_reduce_order", "(", "ap", ",", "bq", ",", "gen", ",", "key", ")", ":", "ap", "=", "list", "(", "ap", ")", "bq", "=", "list", "(", "bq", ")", "ap", ".", "sort", "(", "key", "=", "key", ")", "bq", ".", "sort", "(", "key", "=", "key", ")", "nap", "=", "[", "]", "operators", "=", "[", "]", "for", "a", "in", "ap", ":", "op", "=", "None", "for", "i", "in", "range", "(", "len", "(", "bq", ")", ")", ":", "op", "=", "gen", "(", "a", ",", "bq", "[", "i", "]", ")", "if", "(", "op", "is", "not", "None", ")", ":", "bq", ".", "pop", "(", "i", ")", "break", "if", "(", "op", "is", "None", ")", ":", "nap", ".", "append", "(", "a", ")", "else", ":", "operators", ".", "append", "(", "op", ")", "return", "(", "nap", ",", "bq", ",", "operators", ")" ]
order reduction algorithm used in hypergeometric and meijer g .
train
false
8,680
def mobify_image(data): fmt = what(None, data) if (fmt == 'png'): if (not isinstance(data, StringIO)): data = StringIO(data) im = Image.open(data) data = StringIO() im.save(data, 'GIF') data = data.getvalue() return data
[ "def", "mobify_image", "(", "data", ")", ":", "fmt", "=", "what", "(", "None", ",", "data", ")", "if", "(", "fmt", "==", "'png'", ")", ":", "if", "(", "not", "isinstance", "(", "data", ",", "StringIO", ")", ")", ":", "data", "=", "StringIO", "(", "data", ")", "im", "=", "Image", ".", "open", "(", "data", ")", "data", "=", "StringIO", "(", ")", "im", ".", "save", "(", "data", ",", "'GIF'", ")", "data", "=", "data", ".", "getvalue", "(", ")", "return", "data" ]
convert png images to gif as the idiotic kindle cannot display some png .
train
false
8,682
def tour_rheader(r): if (r.representation == 'html'): tour = r.record if tour: T = current.T tabs = [(T('Edit Details'), None), (T('Details'), 'details'), (T('People'), 'user')] rheader_tabs = s3_rheader_tabs(r, tabs) table = r.table rheader = DIV(TABLE(TR(TH(('%s: ' % table.name.label)), tour.name), TR(TH(('%s: ' % table.code.label)), tour.code)), rheader_tabs) return rheader return None
[ "def", "tour_rheader", "(", "r", ")", ":", "if", "(", "r", ".", "representation", "==", "'html'", ")", ":", "tour", "=", "r", ".", "record", "if", "tour", ":", "T", "=", "current", ".", "T", "tabs", "=", "[", "(", "T", "(", "'Edit Details'", ")", ",", "None", ")", ",", "(", "T", "(", "'Details'", ")", ",", "'details'", ")", ",", "(", "T", "(", "'People'", ")", ",", "'user'", ")", "]", "rheader_tabs", "=", "s3_rheader_tabs", "(", "r", ",", "tabs", ")", "table", "=", "r", ".", "table", "rheader", "=", "DIV", "(", "TABLE", "(", "TR", "(", "TH", "(", "(", "'%s: '", "%", "table", ".", "name", ".", "label", ")", ")", ",", "tour", ".", "name", ")", ",", "TR", "(", "TH", "(", "(", "'%s: '", "%", "table", ".", "code", ".", "label", ")", ")", ",", "tour", ".", "code", ")", ")", ",", "rheader_tabs", ")", "return", "rheader", "return", "None" ]
resource header for guided tour .
train
false
8,684
def parse_options_header(value): def _tokenize(string): for match in _option_header_piece_re.finditer(string): (key, value) = match.groups() key = unquote_header_value(key) if (value is not None): value = unquote_header_value(value) (yield (key, value)) if (not value): return ('', {}) parts = _tokenize((';' + value)) name = next(parts)[0] extra = dict(parts) return (name, extra)
[ "def", "parse_options_header", "(", "value", ")", ":", "def", "_tokenize", "(", "string", ")", ":", "for", "match", "in", "_option_header_piece_re", ".", "finditer", "(", "string", ")", ":", "(", "key", ",", "value", ")", "=", "match", ".", "groups", "(", ")", "key", "=", "unquote_header_value", "(", "key", ")", "if", "(", "value", "is", "not", "None", ")", ":", "value", "=", "unquote_header_value", "(", "value", ")", "(", "yield", "(", "key", ",", "value", ")", ")", "if", "(", "not", "value", ")", ":", "return", "(", "''", ",", "{", "}", ")", "parts", "=", "_tokenize", "(", "(", "';'", "+", "value", ")", ")", "name", "=", "next", "(", "parts", ")", "[", "0", "]", "extra", "=", "dict", "(", "parts", ")", "return", "(", "name", ",", "extra", ")" ]
parse a content-type like header into a tuple with the content type and the options: .
train
true
8,685
def getIsPointInsideZoneAwayOthers(diameterReciprocal, loopsComplex, point, pixelDictionary): if (not euclidean.getIsInFilledRegion(loopsComplex, point)): return False pointOverDiameter = complex((point.real * diameterReciprocal.real), (point.imag * diameterReciprocal.imag)) squareValues = euclidean.getSquareValuesFromPoint(pixelDictionary, pointOverDiameter) for squareValue in squareValues: if (abs((squareValue - pointOverDiameter)) < 1.0): return False euclidean.addElementToPixelListFromPoint(pointOverDiameter, pixelDictionary, pointOverDiameter) return True
[ "def", "getIsPointInsideZoneAwayOthers", "(", "diameterReciprocal", ",", "loopsComplex", ",", "point", ",", "pixelDictionary", ")", ":", "if", "(", "not", "euclidean", ".", "getIsInFilledRegion", "(", "loopsComplex", ",", "point", ")", ")", ":", "return", "False", "pointOverDiameter", "=", "complex", "(", "(", "point", ".", "real", "*", "diameterReciprocal", ".", "real", ")", ",", "(", "point", ".", "imag", "*", "diameterReciprocal", ".", "imag", ")", ")", "squareValues", "=", "euclidean", ".", "getSquareValuesFromPoint", "(", "pixelDictionary", ",", "pointOverDiameter", ")", "for", "squareValue", "in", "squareValues", ":", "if", "(", "abs", "(", "(", "squareValue", "-", "pointOverDiameter", ")", ")", "<", "1.0", ")", ":", "return", "False", "euclidean", ".", "addElementToPixelListFromPoint", "(", "pointOverDiameter", ",", "pixelDictionary", ",", "pointOverDiameter", ")", "return", "True" ]
determine if the point is inside the loops zone and and away from the other points .
train
false
8,686
def doCleanupAction(self, domain='', webroot='', dbname='', dbuser='', dbhost=''): if domain: if os.path.isfile('/etc/nginx/sites-available/{0}'.format(domain)): removeNginxConf(self, domain) if webroot: deleteWebRoot(self, webroot) if dbname: if (not dbuser): raise SiteError('dbuser not provided') if (not dbhost): raise SiteError('dbhost not provided') deleteDB(self, dbname, dbuser, dbhost)
[ "def", "doCleanupAction", "(", "self", ",", "domain", "=", "''", ",", "webroot", "=", "''", ",", "dbname", "=", "''", ",", "dbuser", "=", "''", ",", "dbhost", "=", "''", ")", ":", "if", "domain", ":", "if", "os", ".", "path", ".", "isfile", "(", "'/etc/nginx/sites-available/{0}'", ".", "format", "(", "domain", ")", ")", ":", "removeNginxConf", "(", "self", ",", "domain", ")", "if", "webroot", ":", "deleteWebRoot", "(", "self", ",", "webroot", ")", "if", "dbname", ":", "if", "(", "not", "dbuser", ")", ":", "raise", "SiteError", "(", "'dbuser not provided'", ")", "if", "(", "not", "dbhost", ")", ":", "raise", "SiteError", "(", "'dbhost not provided'", ")", "deleteDB", "(", "self", ",", "dbname", ",", "dbuser", ",", "dbhost", ")" ]
removes the nginx configuration and database for the domain provided .
train
false
8,687
def _unquote_match(match): s = match.group(0) return unquote(s)
[ "def", "_unquote_match", "(", "match", ")", ":", "s", "=", "match", ".", "group", "(", "0", ")", "return", "unquote", "(", "s", ")" ]
turn a match in the form =ab to the ascii character with value 0xab .
train
false
8,689
def s3datetime_to_timestamp(datetime): try: stripped = time.strptime(datetime[:(-4)], '%a, %d %b %Y %H:%M:%S') assert (datetime[(-4):] == ' GMT'), ('Time [%s] is not in GMT.' % datetime) except ValueError: stripped = time.strptime(datetime[:(-5)], '%Y-%m-%dT%H:%M:%S') assert (datetime[(-5):] == '.000Z'), ('Time [%s] is not in GMT.' % datetime) return int(calendar.timegm(stripped))
[ "def", "s3datetime_to_timestamp", "(", "datetime", ")", ":", "try", ":", "stripped", "=", "time", ".", "strptime", "(", "datetime", "[", ":", "(", "-", "4", ")", "]", ",", "'%a, %d %b %Y %H:%M:%S'", ")", "assert", "(", "datetime", "[", "(", "-", "4", ")", ":", "]", "==", "' GMT'", ")", ",", "(", "'Time [%s] is not in GMT.'", "%", "datetime", ")", "except", "ValueError", ":", "stripped", "=", "time", ".", "strptime", "(", "datetime", "[", ":", "(", "-", "5", ")", "]", ",", "'%Y-%m-%dT%H:%M:%S'", ")", "assert", "(", "datetime", "[", "(", "-", "5", ")", ":", "]", "==", "'.000Z'", ")", ",", "(", "'Time [%s] is not in GMT.'", "%", "datetime", ")", "return", "int", "(", "calendar", ".", "timegm", "(", "stripped", ")", ")" ]
returns timestamp by datetime string from s3 api responses .
train
false
8,690
@pytest.fixture(scope='session') def user_config_file(user_dir, user_config_data): config_file = user_dir.join('config') config_text = USER_CONFIG.format(**user_config_data) config_file.write(config_text) return str(config_file)
[ "@", "pytest", ".", "fixture", "(", "scope", "=", "'session'", ")", "def", "user_config_file", "(", "user_dir", ",", "user_config_data", ")", ":", "config_file", "=", "user_dir", ".", "join", "(", "'config'", ")", "config_text", "=", "USER_CONFIG", ".", "format", "(", "**", "user_config_data", ")", "config_file", ".", "write", "(", "config_text", ")", "return", "str", "(", "config_file", ")" ]
fixture that creates a config file called config in the users home directory .
train
false
8,692
def lookupMailExchange(name, timeout=None): return getResolver().lookupMailExchange(name, timeout)
[ "def", "lookupMailExchange", "(", "name", ",", "timeout", "=", "None", ")", ":", "return", "getResolver", "(", ")", ".", "lookupMailExchange", "(", "name", ",", "timeout", ")" ]
perform an mx record lookup .
train
false
8,694
def decimal_to_float(x): if isinstance(x, Decimal): return float(x) return x
[ "def", "decimal_to_float", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "Decimal", ")", ":", "return", "float", "(", "x", ")", "return", "x" ]
cast decimal values to float .
train
false
8,695
def reverse_move_repos(apps, schema_editor): db = schema_editor.connection.alias RemoteRepository = apps.get_model(u'oauth', u'RemoteRepository') RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization') RemoteRepository.objects.using(db).delete() RemoteOrganization.objects.using(db).delete()
[ "def", "reverse_move_repos", "(", "apps", ",", "schema_editor", ")", ":", "db", "=", "schema_editor", ".", "connection", ".", "alias", "RemoteRepository", "=", "apps", ".", "get_model", "(", "u'oauth'", ",", "u'RemoteRepository'", ")", "RemoteOrganization", "=", "apps", ".", "get_model", "(", "u'oauth'", ",", "u'RemoteOrganization'", ")", "RemoteRepository", ".", "objects", ".", "using", "(", "db", ")", ".", "delete", "(", ")", "RemoteOrganization", ".", "objects", ".", "using", "(", "db", ")", ".", "delete", "(", ")" ]
drop oauth repos .
train
false
8,696
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
8,697
def create_python_script_action(parent, text, icon, package, module, args=[]): if is_text_string(icon): icon = get_icon(icon) if programs.python_script_exists(package, module): return create_action(parent, text, icon=icon, triggered=(lambda : programs.run_python_script(package, module, args)))
[ "def", "create_python_script_action", "(", "parent", ",", "text", ",", "icon", ",", "package", ",", "module", ",", "args", "=", "[", "]", ")", ":", "if", "is_text_string", "(", "icon", ")", ":", "icon", "=", "get_icon", "(", "icon", ")", "if", "programs", ".", "python_script_exists", "(", "package", ",", "module", ")", ":", "return", "create_action", "(", "parent", ",", "text", ",", "icon", "=", "icon", ",", "triggered", "=", "(", "lambda", ":", "programs", ".", "run_python_script", "(", "package", ",", "module", ",", "args", ")", ")", ")" ]
create action to run a gui based python script .
train
true
8,699
def _ScrubUpdateDevice(op_args): _ScrubForClass(Device, op_args['device_dict'])
[ "def", "_ScrubUpdateDevice", "(", "op_args", ")", ":", "_ScrubForClass", "(", "Device", ",", "op_args", "[", "'device_dict'", "]", ")" ]
scrub the device name from the logs .
train
false
8,700
def isAdminFromPrivileges(privileges): retVal = (Backend.isDbms(DBMS.PGSQL) and ('super' in privileges)) retVal |= (Backend.isDbms(DBMS.ORACLE) and ('DBA' in privileges)) retVal |= (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema and ('SUPER' in privileges)) retVal |= (Backend.isDbms(DBMS.MYSQL) and (not kb.data.has_information_schema) and ('super_priv' in privileges)) retVal |= (Backend.isDbms(DBMS.FIREBIRD) and all(((_ in privileges) for _ in ('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'REFERENCES', 'EXECUTE')))) return retVal
[ "def", "isAdminFromPrivileges", "(", "privileges", ")", ":", "retVal", "=", "(", "Backend", ".", "isDbms", "(", "DBMS", ".", "PGSQL", ")", "and", "(", "'super'", "in", "privileges", ")", ")", "retVal", "|=", "(", "Backend", ".", "isDbms", "(", "DBMS", ".", "ORACLE", ")", "and", "(", "'DBA'", "in", "privileges", ")", ")", "retVal", "|=", "(", "Backend", ".", "isDbms", "(", "DBMS", ".", "MYSQL", ")", "and", "kb", ".", "data", ".", "has_information_schema", "and", "(", "'SUPER'", "in", "privileges", ")", ")", "retVal", "|=", "(", "Backend", ".", "isDbms", "(", "DBMS", ".", "MYSQL", ")", "and", "(", "not", "kb", ".", "data", ".", "has_information_schema", ")", "and", "(", "'super_priv'", "in", "privileges", ")", ")", "retVal", "|=", "(", "Backend", ".", "isDbms", "(", "DBMS", ".", "FIREBIRD", ")", "and", "all", "(", "(", "(", "_", "in", "privileges", ")", "for", "_", "in", "(", "'SELECT'", ",", "'INSERT'", ",", "'UPDATE'", ",", "'DELETE'", ",", "'REFERENCES'", ",", "'EXECUTE'", ")", ")", ")", ")", "return", "retVal" ]
inspects privileges to see if those are coming from an admin user .
train
false
8,703
def line_search_BFGS(f, xk, pk, gfk, old_fval, args=(), c1=0.0001, alpha0=1): r = line_search_armijo(f, xk, pk, gfk, old_fval, args=args, c1=c1, alpha0=alpha0) return (r[0], r[1], 0, r[2])
[ "def", "line_search_BFGS", "(", "f", ",", "xk", ",", "pk", ",", "gfk", ",", "old_fval", ",", "args", "=", "(", ")", ",", "c1", "=", "0.0001", ",", "alpha0", "=", "1", ")", ":", "r", "=", "line_search_armijo", "(", "f", ",", "xk", ",", "pk", ",", "gfk", ",", "old_fval", ",", "args", "=", "args", ",", "c1", "=", "c1", ",", "alpha0", "=", "alpha0", ")", "return", "(", "r", "[", "0", "]", ",", "r", "[", "1", "]", ",", "0", ",", "r", "[", "2", "]", ")" ]
compatibility wrapper for line_search_armijo .
train
false
8,704
def command_dispatch(request): command = request.POST.get('command') if command: response = handle_command(request, command) if response: return response raise Problem(('Unknown command: %r' % command))
[ "def", "command_dispatch", "(", "request", ")", ":", "command", "=", "request", ".", "POST", ".", "get", "(", "'command'", ")", "if", "command", ":", "response", "=", "handle_command", "(", "request", ",", "command", ")", "if", "response", ":", "return", "response", "raise", "Problem", "(", "(", "'Unknown command: %r'", "%", "command", ")", ")" ]
xtheme command dispatch view .
train
false
8,705
def context_to_airflow_vars(context): params = dict() dag = context.get('dag') if (dag and dag.dag_id): params['airflow.ctx.dag.dag_id'] = dag.dag_id dag_run = context.get('dag_run') if (dag_run and dag_run.execution_date): params['airflow.ctx.dag_run.execution_date'] = dag_run.execution_date.isoformat() task = context.get('task') if (task and task.task_id): params['airflow.ctx.task.task_id'] = task.task_id task_instance = context.get('task_instance') if (task_instance and task_instance.execution_date): params['airflow.ctx.task_instance.execution_date'] = task_instance.execution_date.isoformat() return params
[ "def", "context_to_airflow_vars", "(", "context", ")", ":", "params", "=", "dict", "(", ")", "dag", "=", "context", ".", "get", "(", "'dag'", ")", "if", "(", "dag", "and", "dag", ".", "dag_id", ")", ":", "params", "[", "'airflow.ctx.dag.dag_id'", "]", "=", "dag", ".", "dag_id", "dag_run", "=", "context", ".", "get", "(", "'dag_run'", ")", "if", "(", "dag_run", "and", "dag_run", ".", "execution_date", ")", ":", "params", "[", "'airflow.ctx.dag_run.execution_date'", "]", "=", "dag_run", ".", "execution_date", ".", "isoformat", "(", ")", "task", "=", "context", ".", "get", "(", "'task'", ")", "if", "(", "task", "and", "task", ".", "task_id", ")", ":", "params", "[", "'airflow.ctx.task.task_id'", "]", "=", "task", ".", "task_id", "task_instance", "=", "context", ".", "get", "(", "'task_instance'", ")", "if", "(", "task_instance", "and", "task_instance", ".", "execution_date", ")", ":", "params", "[", "'airflow.ctx.task_instance.execution_date'", "]", "=", "task_instance", ".", "execution_date", ".", "isoformat", "(", ")", "return", "params" ]
given a context .
train
false
8,707
def combine_range(lines, start, end): ((srow, scol), (erow, ecol)) = (start, end) if (srow == erow): return (lines[(srow - 1)][scol:ecol], end) rows = (([lines[(srow - 1)][scol:]] + lines[srow:(erow - 1)]) + [lines[(erow - 1)][:ecol]]) return (''.join(rows), end)
[ "def", "combine_range", "(", "lines", ",", "start", ",", "end", ")", ":", "(", "(", "srow", ",", "scol", ")", ",", "(", "erow", ",", "ecol", ")", ")", "=", "(", "start", ",", "end", ")", "if", "(", "srow", "==", "erow", ")", ":", "return", "(", "lines", "[", "(", "srow", "-", "1", ")", "]", "[", "scol", ":", "ecol", "]", ",", "end", ")", "rows", "=", "(", "(", "[", "lines", "[", "(", "srow", "-", "1", ")", "]", "[", "scol", ":", "]", "]", "+", "lines", "[", "srow", ":", "(", "erow", "-", "1", ")", "]", ")", "+", "[", "lines", "[", "(", "erow", "-", "1", ")", "]", "[", ":", "ecol", "]", "]", ")", "return", "(", "''", ".", "join", "(", "rows", ")", ",", "end", ")" ]
join content from a range of lines between start and end .
train
false
8,708
def attach_pyinstrument_profiler(): profiler = Profiler() profiler.start() def handle_signal(signum, frame): print profiler.output_text(color=True) delattr(profiler, '_root_frame') signal.signal(signal.SIGTRAP, handle_signal)
[ "def", "attach_pyinstrument_profiler", "(", ")", ":", "profiler", "=", "Profiler", "(", ")", "profiler", ".", "start", "(", ")", "def", "handle_signal", "(", "signum", ",", "frame", ")", ":", "print", "profiler", ".", "output_text", "(", "color", "=", "True", ")", "delattr", "(", "profiler", ",", "'_root_frame'", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTRAP", ",", "handle_signal", ")" ]
run the pyinstrument profiler in the background and dump its output to stdout when the process receives sigtrap .
train
false
8,709
def env_fallback(*args, **kwargs): for arg in args: if (arg in os.environ): return os.environ[arg] else: raise AnsibleFallbackNotFound
[ "def", "env_fallback", "(", "*", "args", ",", "**", "kwargs", ")", ":", "for", "arg", "in", "args", ":", "if", "(", "arg", "in", "os", ".", "environ", ")", ":", "return", "os", ".", "environ", "[", "arg", "]", "else", ":", "raise", "AnsibleFallbackNotFound" ]
load value from environment .
train
false
8,710
def test_randomise_corrmat_seed(): a = rs.randn(3, 20) (_, dist1) = algo.randomize_corrmat(a, random_seed=0, return_dist=True) (_, dist2) = algo.randomize_corrmat(a, random_seed=0, return_dist=True) assert_array_equal(dist1, dist2)
[ "def", "test_randomise_corrmat_seed", "(", ")", ":", "a", "=", "rs", ".", "randn", "(", "3", ",", "20", ")", "(", "_", ",", "dist1", ")", "=", "algo", ".", "randomize_corrmat", "(", "a", ",", "random_seed", "=", "0", ",", "return_dist", "=", "True", ")", "(", "_", ",", "dist2", ")", "=", "algo", ".", "randomize_corrmat", "(", "a", ",", "random_seed", "=", "0", ",", "return_dist", "=", "True", ")", "assert_array_equal", "(", "dist1", ",", "dist2", ")" ]
test that we can seed the corrmat randomization .
train
false
8,711
def create_stream(client, stream_name, number_of_shards=1, retention_period=None, tags=None, wait=False, wait_timeout=300, check_mode=False): success = False changed = False err_msg = '' results = dict() (stream_found, stream_msg, current_stream) = find_stream(client, stream_name, check_mode=check_mode) if (stream_found and (not check_mode)): if (current_stream['ShardsCount'] != number_of_shards): err_msg = 'Can not change the number of shards in a Kinesis Stream' return (success, changed, err_msg, results) if (stream_found and (current_stream['StreamStatus'] == 'DELETING') and wait): (wait_success, wait_msg, current_stream) = wait_for_status(client, stream_name, 'ACTIVE', wait_timeout, check_mode=check_mode) if (stream_found and (current_stream['StreamStatus'] != 'DELETING')): (success, changed, err_msg) = update(client, current_stream, stream_name, retention_period, tags, wait, wait_timeout, check_mode=check_mode) else: (create_success, create_msg) = stream_action(client, stream_name, number_of_shards, action='create', check_mode=check_mode) if create_success: changed = True if wait: (wait_success, wait_msg, results) = wait_for_status(client, stream_name, 'ACTIVE', wait_timeout, check_mode=check_mode) err_msg = 'Kinesis Stream {0} is in the process of being created'.format(stream_name) if (not wait_success): return (wait_success, True, wait_msg, results) else: err_msg = 'Kinesis Stream {0} created successfully'.format(stream_name) if tags: (changed, err_msg) = tags_action(client, stream_name, tags, action='create', check_mode=check_mode) if changed: success = True if (not success): return (success, changed, err_msg, results) (stream_found, stream_msg, current_stream) = find_stream(client, stream_name, check_mode=check_mode) if (retention_period and (current_stream['StreamStatus'] == 'ACTIVE')): (changed, err_msg) = retention_action(client, stream_name, retention_period, action='increase', check_mode=check_mode) if changed: success = True if (not success): return (success, changed, err_msg, results) else: err_msg = 'StreamStatus has to be ACTIVE in order to modify the retention period. Current status is {0}'.format(current_stream['StreamStatus']) success = create_success changed = True if success: (_, _, results) = find_stream(client, stream_name, check_mode=check_mode) (_, _, current_tags) = get_tags(client, stream_name, check_mode=check_mode) if (current_tags and (not check_mode)): current_tags = make_tags_in_proper_format(current_tags) results['Tags'] = current_tags elif (check_mode and tags): results['Tags'] = tags else: results['Tags'] = dict() results = convert_to_lower(results) return (success, changed, err_msg, results)
[ "def", "create_stream", "(", "client", ",", "stream_name", ",", "number_of_shards", "=", "1", ",", "retention_period", "=", "None", ",", "tags", "=", "None", ",", "wait", "=", "False", ",", "wait_timeout", "=", "300", ",", "check_mode", "=", "False", ")", ":", "success", "=", "False", "changed", "=", "False", "err_msg", "=", "''", "results", "=", "dict", "(", ")", "(", "stream_found", ",", "stream_msg", ",", "current_stream", ")", "=", "find_stream", "(", "client", ",", "stream_name", ",", "check_mode", "=", "check_mode", ")", "if", "(", "stream_found", "and", "(", "not", "check_mode", ")", ")", ":", "if", "(", "current_stream", "[", "'ShardsCount'", "]", "!=", "number_of_shards", ")", ":", "err_msg", "=", "'Can not change the number of shards in a Kinesis Stream'", "return", "(", "success", ",", "changed", ",", "err_msg", ",", "results", ")", "if", "(", "stream_found", "and", "(", "current_stream", "[", "'StreamStatus'", "]", "==", "'DELETING'", ")", "and", "wait", ")", ":", "(", "wait_success", ",", "wait_msg", ",", "current_stream", ")", "=", "wait_for_status", "(", "client", ",", "stream_name", ",", "'ACTIVE'", ",", "wait_timeout", ",", "check_mode", "=", "check_mode", ")", "if", "(", "stream_found", "and", "(", "current_stream", "[", "'StreamStatus'", "]", "!=", "'DELETING'", ")", ")", ":", "(", "success", ",", "changed", ",", "err_msg", ")", "=", "update", "(", "client", ",", "current_stream", ",", "stream_name", ",", "retention_period", ",", "tags", ",", "wait", ",", "wait_timeout", ",", "check_mode", "=", "check_mode", ")", "else", ":", "(", "create_success", ",", "create_msg", ")", "=", "stream_action", "(", "client", ",", "stream_name", ",", "number_of_shards", ",", "action", "=", "'create'", ",", "check_mode", "=", "check_mode", ")", "if", "create_success", ":", "changed", "=", "True", "if", "wait", ":", "(", "wait_success", ",", "wait_msg", ",", "results", ")", "=", "wait_for_status", "(", "client", ",", "stream_name", ",", "'ACTIVE'", ",", "wait_timeout", ",", "check_mode", "=", "check_mode", ")", "err_msg", "=", "'Kinesis Stream {0} is in the process of being created'", ".", "format", "(", "stream_name", ")", "if", "(", "not", "wait_success", ")", ":", "return", "(", "wait_success", ",", "True", ",", "wait_msg", ",", "results", ")", "else", ":", "err_msg", "=", "'Kinesis Stream {0} created successfully'", ".", "format", "(", "stream_name", ")", "if", "tags", ":", "(", "changed", ",", "err_msg", ")", "=", "tags_action", "(", "client", ",", "stream_name", ",", "tags", ",", "action", "=", "'create'", ",", "check_mode", "=", "check_mode", ")", "if", "changed", ":", "success", "=", "True", "if", "(", "not", "success", ")", ":", "return", "(", "success", ",", "changed", ",", "err_msg", ",", "results", ")", "(", "stream_found", ",", "stream_msg", ",", "current_stream", ")", "=", "find_stream", "(", "client", ",", "stream_name", ",", "check_mode", "=", "check_mode", ")", "if", "(", "retention_period", "and", "(", "current_stream", "[", "'StreamStatus'", "]", "==", "'ACTIVE'", ")", ")", ":", "(", "changed", ",", "err_msg", ")", "=", "retention_action", "(", "client", ",", "stream_name", ",", "retention_period", ",", "action", "=", "'increase'", ",", "check_mode", "=", "check_mode", ")", "if", "changed", ":", "success", "=", "True", "if", "(", "not", "success", ")", ":", "return", "(", "success", ",", "changed", ",", "err_msg", ",", "results", ")", "else", ":", "err_msg", "=", "'StreamStatus has to be ACTIVE in order to modify the retention period. Current status is {0}'", ".", "format", "(", "current_stream", "[", "'StreamStatus'", "]", ")", "success", "=", "create_success", "changed", "=", "True", "if", "success", ":", "(", "_", ",", "_", ",", "results", ")", "=", "find_stream", "(", "client", ",", "stream_name", ",", "check_mode", "=", "check_mode", ")", "(", "_", ",", "_", ",", "current_tags", ")", "=", "get_tags", "(", "client", ",", "stream_name", ",", "check_mode", "=", "check_mode", ")", "if", "(", "current_tags", "and", "(", "not", "check_mode", ")", ")", ":", "current_tags", "=", "make_tags_in_proper_format", "(", "current_tags", ")", "results", "[", "'Tags'", "]", "=", "current_tags", "elif", "(", "check_mode", "and", "tags", ")", ":", "results", "[", "'Tags'", "]", "=", "tags", "else", ":", "results", "[", "'Tags'", "]", "=", "dict", "(", ")", "results", "=", "convert_to_lower", "(", "results", ")", "return", "(", "success", ",", "changed", ",", "err_msg", ",", "results", ")" ]
create a stream with name stream_name and initial number of shards num_shards .
train
false
8,712
def default_palette(): return create_palette(QColor(NAMED_COLORS['light-yellow']), QColor(NAMED_COLORS['yellow']))
[ "def", "default_palette", "(", ")", ":", "return", "create_palette", "(", "QColor", "(", "NAMED_COLORS", "[", "'light-yellow'", "]", ")", ",", "QColor", "(", "NAMED_COLORS", "[", "'yellow'", "]", ")", ")" ]
create and return a default palette for a node .
train
false
8,713
def can_become_premium(f): @functools.wraps(f) def wrapper(request, addon_id, addon, *args, **kw): if (not addon.can_become_premium()): log.info(('Cannot become premium: %d' % addon.pk)) raise PermissionDenied return f(request, addon_id, addon, *args, **kw) return wrapper
[ "def", "can_become_premium", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "addon_id", ",", "addon", ",", "*", "args", ",", "**", "kw", ")", ":", "if", "(", "not", "addon", ".", "can_become_premium", "(", ")", ")", ":", "log", ".", "info", "(", "(", "'Cannot become premium: %d'", "%", "addon", ".", "pk", ")", ")", "raise", "PermissionDenied", "return", "f", "(", "request", ",", "addon_id", ",", "addon", ",", "*", "args", ",", "**", "kw", ")", "return", "wrapper" ]
check that the addon can become premium .
train
false
8,714
def test_has_version(): assert_equals(lettuce.version, '0.2.23')
[ "def", "test_has_version", "(", ")", ":", "assert_equals", "(", "lettuce", ".", "version", ",", "'0.2.23'", ")" ]
a nice python module is supposed to have a version .
train
false
8,715
def list_downloadable_sources(target_dir): return [os.path.join(target_dir, fname) for fname in os.listdir(target_dir) if fname.endswith('.py')]
[ "def", "list_downloadable_sources", "(", "target_dir", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "target_dir", ",", "fname", ")", "for", "fname", "in", "os", ".", "listdir", "(", "target_dir", ")", "if", "fname", ".", "endswith", "(", "'.py'", ")", "]" ]
returns a list of python source files is target_dir parameters target_dir : string path to the directory where python source file are returns list list of paths to all python source files in target_dir .
train
true
8,716
def xform_name(name, sep='_', _xform_cache=_xform_cache, partial_renames=_partial_renames): if (sep in name): return name key = (name, sep) if (key not in _xform_cache): if (_special_case_transform.search(name) is not None): is_special = _special_case_transform.search(name) matched = is_special.group() name = ((name[:(- len(matched))] + sep) + matched.lower()) s1 = _first_cap_regex.sub((('\\1' + sep) + '\\2'), name) s2 = _number_cap_regex.sub((('\\1' + sep) + '\\2'), s1) transformed = _end_cap_regex.sub((('\\1' + sep) + '\\2'), s2).lower() for (old, new) in partial_renames.items(): if (old in transformed): transformed = transformed.replace(old, new) _xform_cache[key] = transformed return _xform_cache[key]
[ "def", "xform_name", "(", "name", ",", "sep", "=", "'_'", ",", "_xform_cache", "=", "_xform_cache", ",", "partial_renames", "=", "_partial_renames", ")", ":", "if", "(", "sep", "in", "name", ")", ":", "return", "name", "key", "=", "(", "name", ",", "sep", ")", "if", "(", "key", "not", "in", "_xform_cache", ")", ":", "if", "(", "_special_case_transform", ".", "search", "(", "name", ")", "is", "not", "None", ")", ":", "is_special", "=", "_special_case_transform", ".", "search", "(", "name", ")", "matched", "=", "is_special", ".", "group", "(", ")", "name", "=", "(", "(", "name", "[", ":", "(", "-", "len", "(", "matched", ")", ")", "]", "+", "sep", ")", "+", "matched", ".", "lower", "(", ")", ")", "s1", "=", "_first_cap_regex", ".", "sub", "(", "(", "(", "'\\\\1'", "+", "sep", ")", "+", "'\\\\2'", ")", ",", "name", ")", "s2", "=", "_number_cap_regex", ".", "sub", "(", "(", "(", "'\\\\1'", "+", "sep", ")", "+", "'\\\\2'", ")", ",", "s1", ")", "transformed", "=", "_end_cap_regex", ".", "sub", "(", "(", "(", "'\\\\1'", "+", "sep", ")", "+", "'\\\\2'", ")", ",", "s2", ")", ".", "lower", "(", ")", "for", "(", "old", ",", "new", ")", "in", "partial_renames", ".", "items", "(", ")", ":", "if", "(", "old", "in", "transformed", ")", ":", "transformed", "=", "transformed", ".", "replace", "(", "old", ",", "new", ")", "_xform_cache", "[", "key", "]", "=", "transformed", "return", "_xform_cache", "[", "key", "]" ]
convert camel case to a "pythonic" name .
train
false
8,717
def send_msg(recipient, message, jid=None, password=None, profile=None): if profile: creds = __salt__['config.option'](profile) jid = creds.get('xmpp.jid') password = creds.get('xmpp.password') xmpp = SendMsgBot(jid, password, recipient, message) xmpp.register_plugin('xep_0030') xmpp.register_plugin('xep_0199') if xmpp.connect(): xmpp.process(block=True) return True return False
[ "def", "send_msg", "(", "recipient", ",", "message", ",", "jid", "=", "None", ",", "password", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "profile", ":", "creds", "=", "__salt__", "[", "'config.option'", "]", "(", "profile", ")", "jid", "=", "creds", ".", "get", "(", "'xmpp.jid'", ")", "password", "=", "creds", ".", "get", "(", "'xmpp.password'", ")", "xmpp", "=", "SendMsgBot", "(", "jid", ",", "password", ",", "recipient", ",", "message", ")", "xmpp", ".", "register_plugin", "(", "'xep_0030'", ")", "xmpp", ".", "register_plugin", "(", "'xep_0199'", ")", "if", "xmpp", ".", "connect", "(", ")", ":", "xmpp", ".", "process", "(", "block", "=", "True", ")", "return", "True", "return", "False" ]
send an openflow message and wait for reply messages .
train
true
8,718
@register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_no_params_from_template(): return {'result': 'inclusion_no_params_from_template - Expected result'}
[ "@", "register", ".", "inclusion_tag", "(", "engine", ".", "get_template", "(", "'inclusion.html'", ")", ")", "def", "inclusion_no_params_from_template", "(", ")", ":", "return", "{", "'result'", ":", "'inclusion_no_params_from_template - Expected result'", "}" ]
expected inclusion_no_params_from_template __doc__ .
train
false
8,719
def update_ca_bundle(target=None, source=None, merge_files=None): return salt.utils.http.update_ca_bundle(target, source, __opts__, merge_files)
[ "def", "update_ca_bundle", "(", "target", "=", "None", ",", "source", "=", "None", ",", "merge_files", "=", "None", ")", ":", "return", "salt", ".", "utils", ".", "http", ".", "update_ca_bundle", "(", "target", ",", "source", ",", "__opts__", ",", "merge_files", ")" ]
update the local ca bundle file from a url .
train
true
8,720
def sentence_position(i, size): normalized = ((i * 1.0) / size) if (normalized > 1.0): return 0 elif (normalized > 0.9): return 0.15 elif (normalized > 0.8): return 0.04 elif (normalized > 0.7): return 0.04 elif (normalized > 0.6): return 0.06 elif (normalized > 0.5): return 0.04 elif (normalized > 0.4): return 0.05 elif (normalized > 0.3): return 0.08 elif (normalized > 0.2): return 0.14 elif (normalized > 0.1): return 0.23 elif (normalized > 0): return 0.17 else: return 0
[ "def", "sentence_position", "(", "i", ",", "size", ")", ":", "normalized", "=", "(", "(", "i", "*", "1.0", ")", "/", "size", ")", "if", "(", "normalized", ">", "1.0", ")", ":", "return", "0", "elif", "(", "normalized", ">", "0.9", ")", ":", "return", "0.15", "elif", "(", "normalized", ">", "0.8", ")", ":", "return", "0.04", "elif", "(", "normalized", ">", "0.7", ")", ":", "return", "0.04", "elif", "(", "normalized", ">", "0.6", ")", ":", "return", "0.06", "elif", "(", "normalized", ">", "0.5", ")", ":", "return", "0.04", "elif", "(", "normalized", ">", "0.4", ")", ":", "return", "0.05", "elif", "(", "normalized", ">", "0.3", ")", ":", "return", "0.08", "elif", "(", "normalized", ">", "0.2", ")", ":", "return", "0.14", "elif", "(", "normalized", ">", "0.1", ")", ":", "return", "0.23", "elif", "(", "normalized", ">", "0", ")", ":", "return", "0.17", "else", ":", "return", "0" ]
different sentence positions indicate different probability of being an important sentence .
train
true
8,721
@library.filter def label_with_help(f): label = u'<label for="%s" title="%s">%s</label>' return jinja2.Markup((label % (f.auto_id, f.help_text, f.label)))
[ "@", "library", ".", "filter", "def", "label_with_help", "(", "f", ")", ":", "label", "=", "u'<label for=\"%s\" title=\"%s\">%s</label>'", "return", "jinja2", ".", "Markup", "(", "(", "label", "%", "(", "f", ".", "auto_id", ",", "f", ".", "help_text", ",", "f", ".", "label", ")", ")", ")" ]
print the label tag for a form field .
train
false
8,724
def get_bootstrap_setting(setting, default=None): return BOOTSTRAP3.get(setting, default)
[ "def", "get_bootstrap_setting", "(", "setting", ",", "default", "=", "None", ")", ":", "return", "BOOTSTRAP3", ".", "get", "(", "setting", ",", "default", ")" ]
read a setting .
train
false
8,725
def block_device_mappings(vm_): return config.get_cloud_config_value('block_device_mappings', vm_, __opts__, search_global=True)
[ "def", "block_device_mappings", "(", "vm_", ")", ":", "return", "config", ".", "get_cloud_config_value", "(", "'block_device_mappings'", ",", "vm_", ",", "__opts__", ",", "search_global", "=", "True", ")" ]
return the block device mapping: [{devicename: /dev/sdb .
train
false
8,726
def _paths_from_assignment(evaluator, expr_stmt): for (assignee, operator) in zip(expr_stmt.children[::2], expr_stmt.children[1::2]): try: assert (operator in ['=', '+=']) assert (tree.is_node(assignee, 'power', 'atom_expr') and (len(assignee.children) > 1)) c = assignee.children assert ((c[0].type == 'name') and (c[0].value == 'sys')) trailer = c[1] assert ((trailer.children[0] == '.') and (trailer.children[1].value == 'path')) "\n execution = c[2]\n assert execution.children[0] == '['\n subscript = execution.children[1]\n assert subscript.type == 'subscript'\n assert ':' in subscript.children\n " except AssertionError: continue from jedi.evaluate.iterable import py__iter__ from jedi.evaluate.precedence import is_string types = evaluator.eval_element(expr_stmt) for types in py__iter__(evaluator, types, expr_stmt): for typ in types: if is_string(typ): (yield typ.obj)
[ "def", "_paths_from_assignment", "(", "evaluator", ",", "expr_stmt", ")", ":", "for", "(", "assignee", ",", "operator", ")", "in", "zip", "(", "expr_stmt", ".", "children", "[", ":", ":", "2", "]", ",", "expr_stmt", ".", "children", "[", "1", ":", ":", "2", "]", ")", ":", "try", ":", "assert", "(", "operator", "in", "[", "'='", ",", "'+='", "]", ")", "assert", "(", "tree", ".", "is_node", "(", "assignee", ",", "'power'", ",", "'atom_expr'", ")", "and", "(", "len", "(", "assignee", ".", "children", ")", ">", "1", ")", ")", "c", "=", "assignee", ".", "children", "assert", "(", "(", "c", "[", "0", "]", ".", "type", "==", "'name'", ")", "and", "(", "c", "[", "0", "]", ".", "value", "==", "'sys'", ")", ")", "trailer", "=", "c", "[", "1", "]", "assert", "(", "(", "trailer", ".", "children", "[", "0", "]", "==", "'.'", ")", "and", "(", "trailer", ".", "children", "[", "1", "]", ".", "value", "==", "'path'", ")", ")", "except", "AssertionError", ":", "continue", "from", "jedi", ".", "evaluate", ".", "iterable", "import", "py__iter__", "from", "jedi", ".", "evaluate", ".", "precedence", "import", "is_string", "types", "=", "evaluator", ".", "eval_element", "(", "expr_stmt", ")", "for", "types", "in", "py__iter__", "(", "evaluator", ",", "types", ",", "expr_stmt", ")", ":", "for", "typ", "in", "types", ":", "if", "is_string", "(", "typ", ")", ":", "(", "yield", "typ", ".", "obj", ")" ]
extracts the assigned strings from an assignment that looks as follows:: .
train
false
8,727
def parse_val(v): if isinstance(v, (datetime.date, datetime.datetime)): v = unicode(v) elif isinstance(v, datetime.timedelta): v = u':'.join(unicode(v).split(u':')[:2]) elif isinstance(v, long): v = int(v) return v
[ "def", "parse_val", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "(", "datetime", ".", "date", ",", "datetime", ".", "datetime", ")", ")", ":", "v", "=", "unicode", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "datetime", ".", "timedelta", ")", ":", "v", "=", "u':'", ".", "join", "(", "unicode", "(", "v", ")", ".", "split", "(", "u':'", ")", "[", ":", "2", "]", ")", "elif", "isinstance", "(", "v", ",", "long", ")", ":", "v", "=", "int", "(", "v", ")", "return", "v" ]
converts to simple datatypes from sql query results .
train
false
8,728
def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '): h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws) for (s, charset) in decoded_seq: if ((charset is not None) and (not isinstance(charset, Charset))): charset = Charset(charset) h.append(s, charset) return h
[ "def", "make_header", "(", "decoded_seq", ",", "maxlinelen", "=", "None", ",", "header_name", "=", "None", ",", "continuation_ws", "=", "' '", ")", ":", "h", "=", "Header", "(", "maxlinelen", "=", "maxlinelen", ",", "header_name", "=", "header_name", ",", "continuation_ws", "=", "continuation_ws", ")", "for", "(", "s", ",", "charset", ")", "in", "decoded_seq", ":", "if", "(", "(", "charset", "is", "not", "None", ")", "and", "(", "not", "isinstance", "(", "charset", ",", "Charset", ")", ")", ")", ":", "charset", "=", "Charset", "(", "charset", ")", "h", ".", "append", "(", "s", ",", "charset", ")", "return", "h" ]
create a header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format where charset is the string name of the character set .
train
true
8,729
def sync_keys(dsk1, dsk2): return _sync_keys(dsk1, dsk2, toposort(dsk2))
[ "def", "sync_keys", "(", "dsk1", ",", "dsk2", ")", ":", "return", "_sync_keys", "(", "dsk1", ",", "dsk2", ",", "toposort", "(", "dsk2", ")", ")" ]
return a dict matching keys in dsk2 to equivalent keys in dsk1 .
train
false
8,731
def import_item(name): parts = name.rsplit('.', 1) if (len(parts) == 2): (package, obj) = parts module = __import__(package, fromlist=[obj]) try: pak = getattr(module, obj) except AttributeError: raise ImportError(('No module named %s' % obj)) return pak else: return __import__(parts[0])
[ "def", "import_item", "(", "name", ")", ":", "parts", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "if", "(", "len", "(", "parts", ")", "==", "2", ")", ":", "(", "package", ",", "obj", ")", "=", "parts", "module", "=", "__import__", "(", "package", ",", "fromlist", "=", "[", "obj", "]", ")", "try", ":", "pak", "=", "getattr", "(", "module", ",", "obj", ")", "except", "AttributeError", ":", "raise", "ImportError", "(", "(", "'No module named %s'", "%", "obj", ")", ")", "return", "pak", "else", ":", "return", "__import__", "(", "parts", "[", "0", "]", ")" ]
import and return bar given the string foo .
train
false
8,732
def _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'): if isinstance(tyinp, types.ArrayCompatible): ary = ctxt.make_array(tyinp)(ctxt, bld, inp) shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim) strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim) return _ArrayHelper(ctxt, bld, shape, strides, ary.data, tyinp.layout, tyinp.dtype, tyinp.ndim, inp) elif (tyinp in (types.number_domain | set([types.boolean]))): return _ScalarHelper(ctxt, bld, inp, tyinp) else: raise NotImplementedError('unsupported type for {0}: {1}'.format(where, str(tyinp)))
[ "def", "_prepare_argument", "(", "ctxt", ",", "bld", ",", "inp", ",", "tyinp", ",", "where", "=", "'input operand'", ")", ":", "if", "isinstance", "(", "tyinp", ",", "types", ".", "ArrayCompatible", ")", ":", "ary", "=", "ctxt", ".", "make_array", "(", "tyinp", ")", "(", "ctxt", ",", "bld", ",", "inp", ")", "shape", "=", "cgutils", ".", "unpack_tuple", "(", "bld", ",", "ary", ".", "shape", ",", "tyinp", ".", "ndim", ")", "strides", "=", "cgutils", ".", "unpack_tuple", "(", "bld", ",", "ary", ".", "strides", ",", "tyinp", ".", "ndim", ")", "return", "_ArrayHelper", "(", "ctxt", ",", "bld", ",", "shape", ",", "strides", ",", "ary", ".", "data", ",", "tyinp", ".", "layout", ",", "tyinp", ".", "dtype", ",", "tyinp", ".", "ndim", ",", "inp", ")", "elif", "(", "tyinp", "in", "(", "types", ".", "number_domain", "|", "set", "(", "[", "types", ".", "boolean", "]", ")", ")", ")", ":", "return", "_ScalarHelper", "(", "ctxt", ",", "bld", ",", "inp", ",", "tyinp", ")", "else", ":", "raise", "NotImplementedError", "(", "'unsupported type for {0}: {1}'", ".", "format", "(", "where", ",", "str", "(", "tyinp", ")", ")", ")" ]
returns an instance of the appropriate helper class to handle the argument .
train
false
8,733
def test_set_guess_kwarg(): data = ascii.read('t/space_delim_no_header.dat', delimiter=',', guess=True) assert (data.dtype.names == ('1 3.4 hello',)) assert (len(data) == 1)
[ "def", "test_set_guess_kwarg", "(", ")", ":", "data", "=", "ascii", ".", "read", "(", "'t/space_delim_no_header.dat'", ",", "delimiter", "=", "','", ",", "guess", "=", "True", ")", "assert", "(", "data", ".", "dtype", ".", "names", "==", "(", "'1 3.4 hello'", ",", ")", ")", "assert", "(", "len", "(", "data", ")", "==", "1", ")" ]
read a file using guess with one of the typical guess_kwargs explicitly set .
train
false
8,735
def list_configs(): try: configs = snapper.ListConfigs() return dict(((config[0], config[2]) for config in configs)) except dbus.DBusException as exc: raise CommandExecutionError('Error encountered while listing configurations: {0}'.format(_dbus_exception_to_reason(exc, locals())))
[ "def", "list_configs", "(", ")", ":", "try", ":", "configs", "=", "snapper", ".", "ListConfigs", "(", ")", "return", "dict", "(", "(", "(", "config", "[", "0", "]", ",", "config", "[", "2", "]", ")", "for", "config", "in", "configs", ")", ")", "except", "dbus", ".", "DBusException", "as", "exc", ":", "raise", "CommandExecutionError", "(", "'Error encountered while listing configurations: {0}'", ".", "format", "(", "_dbus_exception_to_reason", "(", "exc", ",", "locals", "(", ")", ")", ")", ")" ]
list all available configs cli example: .
train
true
8,736
@contextmanager def set_flask_request(wsgi_environ): environ = {} environ.update(wsgi_environ) wsgiref.util.setup_testing_defaults(environ) r = werkzeug.wrappers.Request(environ) with mock.patch.dict(extract_params.__globals__, {'request': r}): (yield)
[ "@", "contextmanager", "def", "set_flask_request", "(", "wsgi_environ", ")", ":", "environ", "=", "{", "}", "environ", ".", "update", "(", "wsgi_environ", ")", "wsgiref", ".", "util", ".", "setup_testing_defaults", "(", "environ", ")", "r", "=", "werkzeug", ".", "wrappers", ".", "Request", "(", "environ", ")", "with", "mock", ".", "patch", ".", "dict", "(", "extract_params", ".", "__globals__", ",", "{", "'request'", ":", "r", "}", ")", ":", "(", "yield", ")" ]
test helper context manager that mocks the flask request global i didnt need the whole request context just to test the functions in helpers and i wanted to be able to set the raw wsgi environment .
train
false
8,737
def get_ipython_module_path(module_str): if (module_str == 'IPython'): return os.path.join(get_ipython_package_dir(), '__init__.py') mod = import_item(module_str) the_path = mod.__file__.replace('.pyc', '.py') the_path = the_path.replace('.pyo', '.py') return py3compat.cast_unicode(the_path, fs_encoding)
[ "def", "get_ipython_module_path", "(", "module_str", ")", ":", "if", "(", "module_str", "==", "'IPython'", ")", ":", "return", "os", ".", "path", ".", "join", "(", "get_ipython_package_dir", "(", ")", ",", "'__init__.py'", ")", "mod", "=", "import_item", "(", "module_str", ")", "the_path", "=", "mod", ".", "__file__", ".", "replace", "(", "'.pyc'", ",", "'.py'", ")", "the_path", "=", "the_path", ".", "replace", "(", "'.pyo'", ",", "'.py'", ")", "return", "py3compat", ".", "cast_unicode", "(", "the_path", ",", "fs_encoding", ")" ]
find the path to an ipython module in this version of ipython .
train
true
8,738
@pytest.fixture def quickmarks(quickmark_manager_stub): quickmark_manager_stub.marks = collections.OrderedDict([('aw', 'https://wiki.archlinux.org'), ('ddg', 'https://duckduckgo.com'), ('wiki', 'https://wikipedia.org')]) return quickmark_manager_stub
[ "@", "pytest", ".", "fixture", "def", "quickmarks", "(", "quickmark_manager_stub", ")", ":", "quickmark_manager_stub", ".", "marks", "=", "collections", ".", "OrderedDict", "(", "[", "(", "'aw'", ",", "'https://wiki.archlinux.org'", ")", ",", "(", "'ddg'", ",", "'https://duckduckgo.com'", ")", ",", "(", "'wiki'", ",", "'https://wikipedia.org'", ")", "]", ")", "return", "quickmark_manager_stub" ]
pre-populate the quickmark-manager stub with some quickmarks .
train
false
8,739
def _dumps(obj): return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '), cls=_ActionEncoder)
[ "def", "_dumps", "(", "obj", ")", ":", "return", "json", ".", "dumps", "(", "obj", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ",", "cls", "=", "_ActionEncoder", ")" ]
json encode an object using some visually pleasing formatting .
train
false
8,740
def chvatal_graph(create_using=None): description = ['adjacencylist', 'Chvatal Graph', 12, [[2, 5, 7, 10], [3, 6, 8], [4, 7, 9], [5, 8, 10], [6, 9], [11, 12], [11, 12], [9, 12], [11], [11, 12], [], []]] G = make_small_undirected_graph(description, create_using) return G
[ "def", "chvatal_graph", "(", "create_using", "=", "None", ")", ":", "description", "=", "[", "'adjacencylist'", ",", "'Chvatal Graph'", ",", "12", ",", "[", "[", "2", ",", "5", ",", "7", ",", "10", "]", ",", "[", "3", ",", "6", ",", "8", "]", ",", "[", "4", ",", "7", ",", "9", "]", ",", "[", "5", ",", "8", ",", "10", "]", ",", "[", "6", ",", "9", "]", ",", "[", "11", ",", "12", "]", ",", "[", "11", ",", "12", "]", ",", "[", "9", ",", "12", "]", ",", "[", "11", "]", ",", "[", "11", ",", "12", "]", ",", "[", "]", ",", "[", "]", "]", "]", "G", "=", "make_small_undirected_graph", "(", "description", ",", "create_using", ")", "return", "G" ]
return the chvátal graph .
train
false
8,741
def encoded_path(root, identifiers, extension='.enc', depth=3, digest_filenames=True): ident = '_'.join(identifiers) global sha1 if (sha1 is None): from beaker.crypto import sha1 if digest_filenames: if py3k: ident = sha1(ident.encode('utf-8')).hexdigest() else: ident = sha1(ident).hexdigest() ident = os.path.basename(ident) tokens = [] for d in range(1, depth): tokens.append(ident[0:d]) dir = os.path.join(root, *tokens) verify_directory(dir) return os.path.join(dir, (ident + extension))
[ "def", "encoded_path", "(", "root", ",", "identifiers", ",", "extension", "=", "'.enc'", ",", "depth", "=", "3", ",", "digest_filenames", "=", "True", ")", ":", "ident", "=", "'_'", ".", "join", "(", "identifiers", ")", "global", "sha1", "if", "(", "sha1", "is", "None", ")", ":", "from", "beaker", ".", "crypto", "import", "sha1", "if", "digest_filenames", ":", "if", "py3k", ":", "ident", "=", "sha1", "(", "ident", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "else", ":", "ident", "=", "sha1", "(", "ident", ")", ".", "hexdigest", "(", ")", "ident", "=", "os", ".", "path", ".", "basename", "(", "ident", ")", "tokens", "=", "[", "]", "for", "d", "in", "range", "(", "1", ",", "depth", ")", ":", "tokens", ".", "append", "(", "ident", "[", "0", ":", "d", "]", ")", "dir", "=", "os", ".", "path", ".", "join", "(", "root", ",", "*", "tokens", ")", "verify_directory", "(", "dir", ")", "return", "os", ".", "path", ".", "join", "(", "dir", ",", "(", "ident", "+", "extension", ")", ")" ]
generate a unique file-accessible path from the given list of identifiers starting at the given root directory .
train
false
8,743
def goto_position_target_global_int(aLocation): msg = vehicle.message_factory.set_position_target_global_int_encode(0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, 4088, (aLocation.lat * 10000000.0), (aLocation.lon * 10000000.0), aLocation.alt, 0, 0, 0, 0, 0, 0, 0, 0) vehicle.send_mavlink(msg)
[ "def", "goto_position_target_global_int", "(", "aLocation", ")", ":", "msg", "=", "vehicle", ".", "message_factory", ".", "set_position_target_global_int_encode", "(", "0", ",", "0", ",", "0", ",", "mavutil", ".", "mavlink", ".", "MAV_FRAME_GLOBAL_RELATIVE_ALT_INT", ",", "4088", ",", "(", "aLocation", ".", "lat", "*", "10000000.0", ")", ",", "(", "aLocation", ".", "lon", "*", "10000000.0", ")", ",", "aLocation", ".", "alt", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ")", "vehicle", ".", "send_mavlink", "(", "msg", ")" ]
send set_position_target_global_int command to request the vehicle fly to a specified locationglobal .
train
true
8,745
def _p_to_cp(p): ret = _porttree().dbapi.xmatch('match-all', p) if ret: return portage.cpv_getkey(ret[0]) return None
[ "def", "_p_to_cp", "(", "p", ")", ":", "ret", "=", "_porttree", "(", ")", ".", "dbapi", ".", "xmatch", "(", "'match-all'", ",", "p", ")", "if", "ret", ":", "return", "portage", ".", "cpv_getkey", "(", "ret", "[", "0", "]", ")", "return", "None" ]
convert a package name or a depend atom to category/package format .
train
false
8,746
@csrf_exempt @require_POST @social_utils.strategy('social:complete') def login_oauth_token(request, backend): warnings.warn('Please use AccessTokenExchangeView instead.', DeprecationWarning) backend = request.backend if (isinstance(backend, social_oauth.BaseOAuth1) or isinstance(backend, social_oauth.BaseOAuth2)): if ('access_token' in request.POST): request.session[pipeline.AUTH_ENTRY_KEY] = pipeline.AUTH_ENTRY_LOGIN_API user = None try: user = backend.do_auth(request.POST['access_token']) except (HTTPError, AuthException): pass if (user and isinstance(user, User)): login(request, user) return JsonResponse(status=204) else: request.social_strategy.clean_partial_pipeline() return JsonResponse({'error': 'invalid_token'}, status=401) else: return JsonResponse({'error': 'invalid_request'}, status=400) raise Http404
[ "@", "csrf_exempt", "@", "require_POST", "@", "social_utils", ".", "strategy", "(", "'social:complete'", ")", "def", "login_oauth_token", "(", "request", ",", "backend", ")", ":", "warnings", ".", "warn", "(", "'Please use AccessTokenExchangeView instead.'", ",", "DeprecationWarning", ")", "backend", "=", "request", ".", "backend", "if", "(", "isinstance", "(", "backend", ",", "social_oauth", ".", "BaseOAuth1", ")", "or", "isinstance", "(", "backend", ",", "social_oauth", ".", "BaseOAuth2", ")", ")", ":", "if", "(", "'access_token'", "in", "request", ".", "POST", ")", ":", "request", ".", "session", "[", "pipeline", ".", "AUTH_ENTRY_KEY", "]", "=", "pipeline", ".", "AUTH_ENTRY_LOGIN_API", "user", "=", "None", "try", ":", "user", "=", "backend", ".", "do_auth", "(", "request", ".", "POST", "[", "'access_token'", "]", ")", "except", "(", "HTTPError", ",", "AuthException", ")", ":", "pass", "if", "(", "user", "and", "isinstance", "(", "user", ",", "User", ")", ")", ":", "login", "(", "request", ",", "user", ")", "return", "JsonResponse", "(", "status", "=", "204", ")", "else", ":", "request", ".", "social_strategy", ".", "clean_partial_pipeline", "(", ")", "return", "JsonResponse", "(", "{", "'error'", ":", "'invalid_token'", "}", ",", "status", "=", "401", ")", "else", ":", "return", "JsonResponse", "(", "{", "'error'", ":", "'invalid_request'", "}", ",", "status", "=", "400", ")", "raise", "Http404" ]
authenticate the client using an oauth access token by using the token to retrieve information from a third party and matching that information to an existing user .
train
false
8,747
def ISO8601ToUTCTimestamp(day, hour=0, minute=0, second=0): (y, m, d) = day.split('-') return calendar.timegm(datetime(int(y), int(m), int(d), hour, minute, second).timetuple())
[ "def", "ISO8601ToUTCTimestamp", "(", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ")", ":", "(", "y", ",", "m", ",", "d", ")", "=", "day", ".", "split", "(", "'-'", ")", "return", "calendar", ".", "timegm", "(", "datetime", "(", "int", "(", "y", ")", ",", "int", "(", "m", ")", ",", "int", "(", "d", ")", ",", "hour", ",", "minute", ",", "second", ")", ".", "timetuple", "(", ")", ")" ]
convert the day in iso 8601 format to timestamp .
train
false
8,748
@register_vcs_handler('git', 'get_keywords') def git_get_keywords(versionfile_abs): keywords = {} try: f = open(versionfile_abs, 'r') for line in f.readlines(): if line.strip().startswith('git_refnames ='): mo = re.search('=\\s*"(.*)"', line) if mo: keywords['refnames'] = mo.group(1) if line.strip().startswith('git_full ='): mo = re.search('=\\s*"(.*)"', line) if mo: keywords['full'] = mo.group(1) f.close() except EnvironmentError: pass return keywords
[ "@", "register_vcs_handler", "(", "'git'", ",", "'get_keywords'", ")", "def", "git_get_keywords", "(", "versionfile_abs", ")", ":", "keywords", "=", "{", "}", "try", ":", "f", "=", "open", "(", "versionfile_abs", ",", "'r'", ")", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "if", "line", ".", "strip", "(", ")", ".", "startswith", "(", "'git_refnames ='", ")", ":", "mo", "=", "re", ".", "search", "(", "'=\\\\s*\"(.*)\"'", ",", "line", ")", "if", "mo", ":", "keywords", "[", "'refnames'", "]", "=", "mo", ".", "group", "(", "1", ")", "if", "line", ".", "strip", "(", ")", ".", "startswith", "(", "'git_full ='", ")", ":", "mo", "=", "re", ".", "search", "(", "'=\\\\s*\"(.*)\"'", ",", "line", ")", "if", "mo", ":", "keywords", "[", "'full'", "]", "=", "mo", ".", "group", "(", "1", ")", "f", ".", "close", "(", ")", "except", "EnvironmentError", ":", "pass", "return", "keywords" ]
extract version information from the given file .
train
true
8,749
def convert_line(line, comments): for (pattern, repl) in comments['replace'].items(): line = re.sub(pattern, repl, line) pkgname = line.split('=')[0] if (pkgname in comments['ignore']): line = ('# ' + line) try: line += (' # ' + comments['comment'][pkgname]) except KeyError: pass try: line += ' # rq.filter: {}'.format(comments['filter'][pkgname]) except KeyError: pass return line
[ "def", "convert_line", "(", "line", ",", "comments", ")", ":", "for", "(", "pattern", ",", "repl", ")", "in", "comments", "[", "'replace'", "]", ".", "items", "(", ")", ":", "line", "=", "re", ".", "sub", "(", "pattern", ",", "repl", ",", "line", ")", "pkgname", "=", "line", ".", "split", "(", "'='", ")", "[", "0", "]", "if", "(", "pkgname", "in", "comments", "[", "'ignore'", "]", ")", ":", "line", "=", "(", "'# '", "+", "line", ")", "try", ":", "line", "+=", "(", "' # '", "+", "comments", "[", "'comment'", "]", "[", "pkgname", "]", ")", "except", "KeyError", ":", "pass", "try", ":", "line", "+=", "' # rq.filter: {}'", ".", "format", "(", "comments", "[", "'filter'", "]", "[", "pkgname", "]", ")", "except", "KeyError", ":", "pass", "return", "line" ]
convert the given requirement line to place into the output .
train
false
8,750
def setTopOverBottomByRadius(derivation, endZ, radius, startZ): angleDegrees = evaluate.getEvaluatedFloat(None, derivation.elementNode, 'angle') if (angleDegrees != None): derivation.topOverBottom = cylinder.getTopOverBottom(math.radians(angleDegrees), endZ, complex(radius, radius), startZ)
[ "def", "setTopOverBottomByRadius", "(", "derivation", ",", "endZ", ",", "radius", ",", "startZ", ")", ":", "angleDegrees", "=", "evaluate", ".", "getEvaluatedFloat", "(", "None", ",", "derivation", ".", "elementNode", ",", "'angle'", ")", "if", "(", "angleDegrees", "!=", "None", ")", ":", "derivation", ".", "topOverBottom", "=", "cylinder", ".", "getTopOverBottom", "(", "math", ".", "radians", "(", "angleDegrees", ")", ",", "endZ", ",", "complex", "(", "radius", ",", "radius", ")", ",", "startZ", ")" ]
set the derivation topoverbottom by the angle of the elementnode .
train
false
8,751
def _random_state(state=None): if types.is_integer(state): return np.random.RandomState(state) elif isinstance(state, np.random.RandomState): return state elif (state is None): return np.random else: raise ValueError('random_state must be an integer, a numpy RandomState, or None')
[ "def", "_random_state", "(", "state", "=", "None", ")", ":", "if", "types", ".", "is_integer", "(", "state", ")", ":", "return", "np", ".", "random", ".", "RandomState", "(", "state", ")", "elif", "isinstance", "(", "state", ",", "np", ".", "random", ".", "RandomState", ")", ":", "return", "state", "elif", "(", "state", "is", "None", ")", ":", "return", "np", ".", "random", "else", ":", "raise", "ValueError", "(", "'random_state must be an integer, a numpy RandomState, or None'", ")" ]
helper function for processing random_state arguments .
train
false
8,752
def database_conf(db_path, prefix='GALAXY'): database_auto_migrate = False dburi_var = ('%s_TEST_DBURI' % prefix) if (dburi_var in os.environ): database_connection = os.environ[dburi_var] else: default_db_filename = ('%s.sqlite' % prefix.lower()) template_var = ('%s_TEST_DB_TEMPLATE' % prefix) db_path = os.path.join(db_path, default_db_filename) if (template_var in os.environ): copy_database_template(os.environ[template_var], db_path) database_auto_migrate = True database_connection = ('sqlite:///%s' % db_path) config = {'database_connection': database_connection, 'database_auto_migrate': database_auto_migrate} if (not database_connection.startswith('sqlite://')): config['database_engine_option_max_overflow'] = '20' config['database_engine_option_pool_size'] = '10' return config
[ "def", "database_conf", "(", "db_path", ",", "prefix", "=", "'GALAXY'", ")", ":", "database_auto_migrate", "=", "False", "dburi_var", "=", "(", "'%s_TEST_DBURI'", "%", "prefix", ")", "if", "(", "dburi_var", "in", "os", ".", "environ", ")", ":", "database_connection", "=", "os", ".", "environ", "[", "dburi_var", "]", "else", ":", "default_db_filename", "=", "(", "'%s.sqlite'", "%", "prefix", ".", "lower", "(", ")", ")", "template_var", "=", "(", "'%s_TEST_DB_TEMPLATE'", "%", "prefix", ")", "db_path", "=", "os", ".", "path", ".", "join", "(", "db_path", ",", "default_db_filename", ")", "if", "(", "template_var", "in", "os", ".", "environ", ")", ":", "copy_database_template", "(", "os", ".", "environ", "[", "template_var", "]", ",", "db_path", ")", "database_auto_migrate", "=", "True", "database_connection", "=", "(", "'sqlite:///%s'", "%", "db_path", ")", "config", "=", "{", "'database_connection'", ":", "database_connection", ",", "'database_auto_migrate'", ":", "database_auto_migrate", "}", "if", "(", "not", "database_connection", ".", "startswith", "(", "'sqlite://'", ")", ")", ":", "config", "[", "'database_engine_option_max_overflow'", "]", "=", "'20'", "config", "[", "'database_engine_option_pool_size'", "]", "=", "'10'", "return", "config" ]
find galaxy database connection .
train
false
8,753
def leapdays(y1, y2): y1 -= 1 y2 -= 1 return ((((y2 // 4) - (y1 // 4)) - ((y2 // 100) - (y1 // 100))) + ((y2 // 400) - (y1 // 400)))
[ "def", "leapdays", "(", "y1", ",", "y2", ")", ":", "y1", "-=", "1", "y2", "-=", "1", "return", "(", "(", "(", "(", "y2", "//", "4", ")", "-", "(", "y1", "//", "4", ")", ")", "-", "(", "(", "y2", "//", "100", ")", "-", "(", "y1", "//", "100", ")", ")", ")", "+", "(", "(", "y2", "//", "400", ")", "-", "(", "y1", "//", "400", ")", ")", ")" ]
return number of leap years in range [y1 .
train
false
8,755
def get_first_profile_id(service): accounts = service.management().accounts().list().execute() if accounts.get('items'): firstAccountId = accounts.get('items')[0].get('id') webproperties = service.management().webproperties().list(accountId=firstAccountId).execute() if webproperties.get('items'): firstWebpropertyId = webproperties.get('items')[0].get('id') profiles = service.management().profiles().list(accountId=firstAccountId, webPropertyId=firstWebpropertyId).execute() if profiles.get('items'): return profiles.get('items')[0].get('id') return None
[ "def", "get_first_profile_id", "(", "service", ")", ":", "accounts", "=", "service", ".", "management", "(", ")", ".", "accounts", "(", ")", ".", "list", "(", ")", ".", "execute", "(", ")", "if", "accounts", ".", "get", "(", "'items'", ")", ":", "firstAccountId", "=", "accounts", ".", "get", "(", "'items'", ")", "[", "0", "]", ".", "get", "(", "'id'", ")", "webproperties", "=", "service", ".", "management", "(", ")", ".", "webproperties", "(", ")", ".", "list", "(", "accountId", "=", "firstAccountId", ")", ".", "execute", "(", ")", "if", "webproperties", ".", "get", "(", "'items'", ")", ":", "firstWebpropertyId", "=", "webproperties", ".", "get", "(", "'items'", ")", "[", "0", "]", ".", "get", "(", "'id'", ")", "profiles", "=", "service", ".", "management", "(", ")", ".", "profiles", "(", ")", ".", "list", "(", "accountId", "=", "firstAccountId", ",", "webPropertyId", "=", "firstWebpropertyId", ")", ".", "execute", "(", ")", "if", "profiles", ".", "get", "(", "'items'", ")", ":", "return", "profiles", ".", "get", "(", "'items'", ")", "[", "0", "]", ".", "get", "(", "'id'", ")", "return", "None" ]
traverses management api to return the first profile id .
train
false
8,756
def idle_showwarning_subproc(message, category, filename, lineno, file=None, line=None): if (file is None): file = sys.stderr try: file.write(PyShell.idle_formatwarning(message, category, filename, lineno, line)) except IOError: pass
[ "def", "idle_showwarning_subproc", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "file", "=", "None", ",", "line", "=", "None", ")", ":", "if", "(", "file", "is", "None", ")", ":", "file", "=", "sys", ".", "stderr", "try", ":", "file", ".", "write", "(", "PyShell", ".", "idle_formatwarning", "(", "message", ",", "category", ",", "filename", ",", "lineno", ",", "line", ")", ")", "except", "IOError", ":", "pass" ]
show idle-format warning after replacing warnings .
train
false
8,757
@pytest.fixture def webframe(webpage): return webpage.mainFrame()
[ "@", "pytest", ".", "fixture", "def", "webframe", "(", "webpage", ")", ":", "return", "webpage", ".", "mainFrame", "(", ")" ]
convenience fixture to get a mainframe of a qwebpage .
train
false
8,758
@require_POST @login_required @permitted def vote_for_comment(request, course_id, comment_id, value): comment = cc.Comment.find(comment_id) result = _vote_or_unvote(request, course_id, comment, value) comment_voted.send(sender=None, user=request.user, post=comment) return result
[ "@", "require_POST", "@", "login_required", "@", "permitted", "def", "vote_for_comment", "(", "request", ",", "course_id", ",", "comment_id", ",", "value", ")", ":", "comment", "=", "cc", ".", "Comment", ".", "find", "(", "comment_id", ")", "result", "=", "_vote_or_unvote", "(", "request", ",", "course_id", ",", "comment", ",", "value", ")", "comment_voted", ".", "send", "(", "sender", "=", "None", ",", "user", "=", "request", ".", "user", ",", "post", "=", "comment", ")", "return", "result" ]
given a course_id and comment_id .
train
false
8,760
def destroy_database(): if (DBDRIVER in ['sqlite3']): if os.path.exists(TESTDB): os.remove(TESTDB)
[ "def", "destroy_database", "(", ")", ":", "if", "(", "DBDRIVER", "in", "[", "'sqlite3'", "]", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "TESTDB", ")", ":", "os", ".", "remove", "(", "TESTDB", ")" ]
delete any temporary biosql sqlite3 database files .
train
false
8,761
def logfilesize(registry, xml_parent, data): lfswrapper = XML.SubElement(xml_parent, 'hudson.plugins.logfilesizechecker.LogfilesizecheckerWrapper') lfswrapper.set('plugin', 'logfilesizechecker') mapping = [('set-own', 'setOwn', False), ('size', 'maxLogSize', 128), ('fail', 'failBuild', False)] convert_mapping_to_xml(lfswrapper, data, mapping, fail_required=True)
[ "def", "logfilesize", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "lfswrapper", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.logfilesizechecker.LogfilesizecheckerWrapper'", ")", "lfswrapper", ".", "set", "(", "'plugin'", ",", "'logfilesizechecker'", ")", "mapping", "=", "[", "(", "'set-own'", ",", "'setOwn'", ",", "False", ")", ",", "(", "'size'", ",", "'maxLogSize'", ",", "128", ")", ",", "(", "'fail'", ",", "'failBuild'", ",", "False", ")", "]", "convert_mapping_to_xml", "(", "lfswrapper", ",", "data", ",", "mapping", ",", "fail_required", "=", "True", ")" ]
yaml: logfilesize abort the build if its logfile becomes too big .
train
false
8,762
def __qsympify_sequence_helper(seq): if (not is_sequence(seq)): if isinstance(seq, Matrix): return seq elif isinstance(seq, string_types): return Symbol(seq) else: return sympify(seq) if isinstance(seq, QExpr): return seq result = [__qsympify_sequence_helper(item) for item in seq] return Tuple(*result)
[ "def", "__qsympify_sequence_helper", "(", "seq", ")", ":", "if", "(", "not", "is_sequence", "(", "seq", ")", ")", ":", "if", "isinstance", "(", "seq", ",", "Matrix", ")", ":", "return", "seq", "elif", "isinstance", "(", "seq", ",", "string_types", ")", ":", "return", "Symbol", "(", "seq", ")", "else", ":", "return", "sympify", "(", "seq", ")", "if", "isinstance", "(", "seq", ",", "QExpr", ")", ":", "return", "seq", "result", "=", "[", "__qsympify_sequence_helper", "(", "item", ")", "for", "item", "in", "seq", "]", "return", "Tuple", "(", "*", "result", ")" ]
helper function for _qsympify_sequence this function does the actual work .
train
false