id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
17,790
def search_users(query, sort=None, order=None, per_page=None, text_match=False, number=(-1), etag=None): return gh.search_users(query, sort, order, per_page, text_match, number, etag)
[ "def", "search_users", "(", "query", ",", "sort", "=", "None", ",", "order", "=", "None", ",", "per_page", "=", "None", ",", "text_match", "=", "False", ",", "number", "=", "(", "-", "1", ")", ",", "etag", "=", "None", ")", ":", "return", "gh", ".", "search_users", "(", "query", ",", "sort", ",", "order", ",", "per_page", ",", "text_match", ",", "number", ",", "etag", ")" ]
find users via the search api .
train
true
17,792
def test_scenario_outlines_within_feature(): feature = Feature.from_string(OUTLINED_FEATURE) scenario = feature.scenarios[0] assert_equals(len(scenario.solved_steps), 12) expected_sentences = ['Given I have entered 20 into the calculator', 'And I have entered 30 into the calculator', 'When I press add', 'Then the result should be 50 on the screen', 'Given I have entered 2 into the calculator', 'And I have entered 5 into the calculator', 'When I press add', 'Then the result should be 7 on the screen', 'Given I have entered 0 into the calculator', 'And I have entered 40 into the calculator', 'When I press add', 'Then the result should be 40 on the screen'] for (step, expected_sentence) in zip(scenario.solved_steps, expected_sentences): assert_equals(type(step), Step) assert_equals(step.sentence, expected_sentence)
[ "def", "test_scenario_outlines_within_feature", "(", ")", ":", "feature", "=", "Feature", ".", "from_string", "(", "OUTLINED_FEATURE", ")", "scenario", "=", "feature", ".", "scenarios", "[", "0", "]", "assert_equals", "(", "len", "(", "scenario", ".", "solved_steps", ")", ",", "12", ")", "expected_sentences", "=", "[", "'Given I have entered 20 into the calculator'", ",", "'And I have entered 30 into the calculator'", ",", "'When I press add'", ",", "'Then the result should be 50 on the screen'", ",", "'Given I have entered 2 into the calculator'", ",", "'And I have entered 5 into the calculator'", ",", "'When I press add'", ",", "'Then the result should be 7 on the screen'", ",", "'Given I have entered 0 into the calculator'", ",", "'And I have entered 40 into the calculator'", ",", "'When I press add'", ",", "'Then the result should be 40 on the screen'", "]", "for", "(", "step", ",", "expected_sentence", ")", "in", "zip", "(", "scenario", ".", "solved_steps", ",", "expected_sentences", ")", ":", "assert_equals", "(", "type", "(", "step", ")", ",", "Step", ")", "assert_equals", "(", "step", ".", "sentence", ",", "expected_sentence", ")" ]
solving scenario outlines within a feature .
train
false
17,793
def Bastion(object, filter=(lambda name: (name[:1] != '_')), name=None, bastionclass=BastionClass): raise RuntimeError, 'This code is not secure in Python 2.2 and later' def get1(name, object=object, filter=filter): 'Internal function for Bastion(). See source comments.' if filter(name): attribute = getattr(object, name) if (type(attribute) == MethodType): return attribute raise AttributeError, name def get2(name, get1=get1): 'Internal function for Bastion(). See source comments.' return get1(name) if (name is None): name = repr(object) return bastionclass(get2, name)
[ "def", "Bastion", "(", "object", ",", "filter", "=", "(", "lambda", "name", ":", "(", "name", "[", ":", "1", "]", "!=", "'_'", ")", ")", ",", "name", "=", "None", ",", "bastionclass", "=", "BastionClass", ")", ":", "raise", "RuntimeError", ",", "'This code is not secure in Python 2.2 and later'", "def", "get1", "(", "name", ",", "object", "=", "object", ",", "filter", "=", "filter", ")", ":", "if", "filter", "(", "name", ")", ":", "attribute", "=", "getattr", "(", "object", ",", "name", ")", "if", "(", "type", "(", "attribute", ")", "==", "MethodType", ")", ":", "return", "attribute", "raise", "AttributeError", ",", "name", "def", "get2", "(", "name", ",", "get1", "=", "get1", ")", ":", "return", "get1", "(", "name", ")", "if", "(", "name", "is", "None", ")", ":", "name", "=", "repr", "(", "object", ")", "return", "bastionclass", "(", "get2", ",", "name", ")" ]
create a bastion for an object .
train
false
17,794
def calculate_multiplier(max_commits): m = (max_commits / 4.0) if (m == 0): return 1 m = math.ceil(m) m = int(m) return m
[ "def", "calculate_multiplier", "(", "max_commits", ")", ":", "m", "=", "(", "max_commits", "/", "4.0", ")", "if", "(", "m", "==", "0", ")", ":", "return", "1", "m", "=", "math", ".", "ceil", "(", "m", ")", "m", "=", "int", "(", "m", ")", "return", "m" ]
calculates a multiplier to scale github colors to commit history .
train
false
17,797
def ProgressDatabase(db_filename, signature): return _ProgressDatabase(db_filename, 'INTEGER', int, signature)
[ "def", "ProgressDatabase", "(", "db_filename", ",", "signature", ")", ":", "return", "_ProgressDatabase", "(", "db_filename", ",", "'INTEGER'", ",", "int", ",", "signature", ")" ]
returns a database to store upload progress information .
train
false
17,798
def _generic_factor(expr, gens, args, method): options.allowed_flags(args, []) opt = options.build_options(gens, args) return _symbolic_factor(sympify(expr), opt, method)
[ "def", "_generic_factor", "(", "expr", ",", "gens", ",", "args", ",", "method", ")", ":", "options", ".", "allowed_flags", "(", "args", ",", "[", "]", ")", "opt", "=", "options", ".", "build_options", "(", "gens", ",", "args", ")", "return", "_symbolic_factor", "(", "sympify", "(", "expr", ")", ",", "opt", ",", "method", ")" ]
helper function for :func:sqf and :func:factor .
train
false
17,800
def center_of_mass(input, labels=None, index=None): normalizer = sum(input, labels, index) grids = numpy.ogrid[[slice(0, i) for i in input.shape]] results = [(sum((input * grids[dir].astype(float)), labels, index) / normalizer) for dir in range(input.ndim)] if numpy.isscalar(results[0]): return tuple(results) return [tuple(v) for v in numpy.array(results).T]
[ "def", "center_of_mass", "(", "input", ",", "labels", "=", "None", ",", "index", "=", "None", ")", ":", "normalizer", "=", "sum", "(", "input", ",", "labels", ",", "index", ")", "grids", "=", "numpy", ".", "ogrid", "[", "[", "slice", "(", "0", ",", "i", ")", "for", "i", "in", "input", ".", "shape", "]", "]", "results", "=", "[", "(", "sum", "(", "(", "input", "*", "grids", "[", "dir", "]", ".", "astype", "(", "float", ")", ")", ",", "labels", ",", "index", ")", "/", "normalizer", ")", "for", "dir", "in", "range", "(", "input", ".", "ndim", ")", "]", "if", "numpy", ".", "isscalar", "(", "results", "[", "0", "]", ")", ":", "return", "tuple", "(", "results", ")", "return", "[", "tuple", "(", "v", ")", "for", "v", "in", "numpy", ".", "array", "(", "results", ")", ".", "T", "]" ]
calculate the center of mass of the values of an array at labels .
train
false
17,801
def user_detail(request, username): detail_user = get_object_or_404(User, username=username) if (detail_user.active_ban and (not request.user.has_perm('users.add_userban'))): return render(request, '403.html', {'reason': 'bannedprofile'}, status=403) context = {'detail_user': detail_user} return render(request, 'users/user_detail.html', context)
[ "def", "user_detail", "(", "request", ",", "username", ")", ":", "detail_user", "=", "get_object_or_404", "(", "User", ",", "username", "=", "username", ")", "if", "(", "detail_user", ".", "active_ban", "and", "(", "not", "request", ".", "user", ".", "has_perm", "(", "'users.add_userban'", ")", ")", ")", ":", "return", "render", "(", "request", ",", "'403.html'", ",", "{", "'reason'", ":", "'bannedprofile'", "}", ",", "status", "=", "403", ")", "context", "=", "{", "'detail_user'", ":", "detail_user", "}", "return", "render", "(", "request", ",", "'users/user_detail.html'", ",", "context", ")" ]
the main user view that only collects a bunch of user specific data to populate the template context .
train
false
17,803
def split_cell_and_item(cell_and_item): result = cell_and_item.rsplit(_CELL_ITEM_SEP, 1) if (len(result) == 1): return (None, cell_and_item) else: return result
[ "def", "split_cell_and_item", "(", "cell_and_item", ")", ":", "result", "=", "cell_and_item", ".", "rsplit", "(", "_CELL_ITEM_SEP", ",", "1", ")", "if", "(", "len", "(", "result", ")", "==", "1", ")", ":", "return", "(", "None", ",", "cell_and_item", ")", "else", ":", "return", "result" ]
split a combined cell@item and return them .
train
false
17,804
def _valid_locales(locales, normalize): if normalize: normalizer = (lambda x: locale.normalize(x.strip())) else: normalizer = (lambda x: x.strip()) return list(filter(_can_set_locale, map(normalizer, locales)))
[ "def", "_valid_locales", "(", "locales", ",", "normalize", ")", ":", "if", "normalize", ":", "normalizer", "=", "(", "lambda", "x", ":", "locale", ".", "normalize", "(", "x", ".", "strip", "(", ")", ")", ")", "else", ":", "normalizer", "=", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ")", "return", "list", "(", "filter", "(", "_can_set_locale", ",", "map", "(", "normalizer", ",", "locales", ")", ")", ")" ]
return a list of normalized locales that do not throw an exception when set .
train
true
17,805
def message_critical(text, title=None, informative_text=None, details=None, buttons=None, default_button=None, exc_info=False, parent=None): if (not text): text = 'An unexpected error occurred.' if (title is None): title = 'Error' return message(QMessageBox.Critical, text, title, informative_text, details, buttons, default_button, exc_info, parent)
[ "def", "message_critical", "(", "text", ",", "title", "=", "None", ",", "informative_text", "=", "None", ",", "details", "=", "None", ",", "buttons", "=", "None", ",", "default_button", "=", "None", ",", "exc_info", "=", "False", ",", "parent", "=", "None", ")", ":", "if", "(", "not", "text", ")", ":", "text", "=", "'An unexpected error occurred.'", "if", "(", "title", "is", "None", ")", ":", "title", "=", "'Error'", "return", "message", "(", "QMessageBox", ".", "Critical", ",", "text", ",", "title", ",", "informative_text", ",", "details", ",", "buttons", ",", "default_button", ",", "exc_info", ",", "parent", ")" ]
show a critical message .
train
false
17,806
def getProfilesPath(subName=''): return getJoinedPath(getSettingsPath('profiles'), subName)
[ "def", "getProfilesPath", "(", "subName", "=", "''", ")", ":", "return", "getJoinedPath", "(", "getSettingsPath", "(", "'profiles'", ")", ",", "subName", ")" ]
get the profiles directory path .
train
false
17,807
def pspace_independent(a, b): a_symbols = set(pspace(b).symbols) b_symbols = set(pspace(a).symbols) if (len(a_symbols.intersection(b_symbols)) == 0): return True return None
[ "def", "pspace_independent", "(", "a", ",", "b", ")", ":", "a_symbols", "=", "set", "(", "pspace", "(", "b", ")", ".", "symbols", ")", "b_symbols", "=", "set", "(", "pspace", "(", "a", ")", ".", "symbols", ")", "if", "(", "len", "(", "a_symbols", ".", "intersection", "(", "b_symbols", ")", ")", "==", "0", ")", ":", "return", "True", "return", "None" ]
tests for independence between a and b by checking if their pspaces have overlapping symbols .
train
false
17,809
def MakeCdfFromDict(d, label=None): return Cdf(d, label=label)
[ "def", "MakeCdfFromDict", "(", "d", ",", "label", "=", "None", ")", ":", "return", "Cdf", "(", "d", ",", "label", "=", "label", ")" ]
makes a cdf from a dictionary that maps values to frequencies .
train
false
17,811
def append_emerge_default_opts(value): return append_var('EMERGE_DEFAULT_OPTS', value)
[ "def", "append_emerge_default_opts", "(", "value", ")", ":", "return", "append_var", "(", "'EMERGE_DEFAULT_OPTS'", ",", "value", ")" ]
add to or create a new emerge_default_opts in the make .
train
false
17,812
@task def vagrant(): vc = get_vagrant_config() env.user = vc['User'] env.hosts = [('%s:%s' % (vc['HostName'], vc['Port']))] env.key_filename = vc['IdentityFile'].strip('"') env.forward_agent = (vc.get('ForwardAgent', 'no') == 'yes')
[ "@", "task", "def", "vagrant", "(", ")", ":", "vc", "=", "get_vagrant_config", "(", ")", "env", ".", "user", "=", "vc", "[", "'User'", "]", "env", ".", "hosts", "=", "[", "(", "'%s:%s'", "%", "(", "vc", "[", "'HostName'", "]", ",", "vc", "[", "'Port'", "]", ")", ")", "]", "env", ".", "key_filename", "=", "vc", "[", "'IdentityFile'", "]", ".", "strip", "(", "'\"'", ")", "env", ".", "forward_agent", "=", "(", "vc", ".", "get", "(", "'ForwardAgent'", ",", "'no'", ")", "==", "'yes'", ")" ]
run the following tasks on a vagrant box .
train
false
17,813
def get_registration_extension_form(*args, **kwargs): if (not settings.FEATURES.get('ENABLE_COMBINED_LOGIN_REGISTRATION')): return None if (not getattr(settings, 'REGISTRATION_EXTENSION_FORM', None)): return None (module, klass) = settings.REGISTRATION_EXTENSION_FORM.rsplit('.', 1) module = import_module(module) return getattr(module, klass)(*args, **kwargs)
[ "def", "get_registration_extension_form", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "not", "settings", ".", "FEATURES", ".", "get", "(", "'ENABLE_COMBINED_LOGIN_REGISTRATION'", ")", ")", ":", "return", "None", "if", "(", "not", "getattr", "(", "settings", ",", "'REGISTRATION_EXTENSION_FORM'", ",", "None", ")", ")", ":", "return", "None", "(", "module", ",", "klass", ")", "=", "settings", ".", "REGISTRATION_EXTENSION_FORM", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "import_module", "(", "module", ")", "return", "getattr", "(", "module", ",", "klass", ")", "(", "*", "args", ",", "**", "kwargs", ")" ]
convenience function for getting the custom form set in settings .
train
false
17,814
def p_direct_abstract_declarator_2(t): pass
[ "def", "p_direct_abstract_declarator_2", "(", "t", ")", ":", "pass" ]
direct_abstract_declarator : direct_abstract_declarator lbracket constant_expression_opt rbracket .
train
false
17,816
@pytest.fixture def en_tutorial_obsolete(english_tutorial): english_tutorial.directory.makeobsolete() return english_tutorial
[ "@", "pytest", ".", "fixture", "def", "en_tutorial_obsolete", "(", "english_tutorial", ")", ":", "english_tutorial", ".", "directory", ".", "makeobsolete", "(", ")", "return", "english_tutorial" ]
require arabic tutorial in obsolete state .
train
false
17,819
def timedelta_seconds(delta): return (((((delta.days * 24) * 60) * 60) + delta.seconds) + (delta.microseconds / 1000000.0))
[ "def", "timedelta_seconds", "(", "delta", ")", ":", "return", "(", "(", "(", "(", "(", "delta", ".", "days", "*", "24", ")", "*", "60", ")", "*", "60", ")", "+", "delta", ".", "seconds", ")", "+", "(", "delta", ".", "microseconds", "/", "1000000.0", ")", ")" ]
converts the given timedelta to seconds .
train
false
17,820
def fitnesse(registry, xml_parent, data): fitnesse = XML.SubElement(xml_parent, 'hudson.plugins.fitnesse.FitnesseResultsRecorder') results = data.get('results', '') XML.SubElement(fitnesse, 'fitnessePathToXmlResultsIn').text = results
[ "def", "fitnesse", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "fitnesse", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.fitnesse.FitnesseResultsRecorder'", ")", "results", "=", "data", ".", "get", "(", "'results'", ",", "''", ")", "XML", ".", "SubElement", "(", "fitnesse", ",", "'fitnessePathToXmlResultsIn'", ")", ".", "text", "=", "results" ]
yaml: fitnesse publish fitnesse test results requires the jenkins :jenkins-wiki:fitnesse plugin <fitnesse+plugin> .
train
false
17,822
def getYIntersectionIfExists(beginComplex, endComplex, x): if ((x > beginComplex.real) == (x > endComplex.real)): return None endMinusBeginComplex = (endComplex - beginComplex) return ((((x - beginComplex.real) / endMinusBeginComplex.real) * endMinusBeginComplex.imag) + beginComplex.imag)
[ "def", "getYIntersectionIfExists", "(", "beginComplex", ",", "endComplex", ",", "x", ")", ":", "if", "(", "(", "x", ">", "beginComplex", ".", "real", ")", "==", "(", "x", ">", "endComplex", ".", "real", ")", ")", ":", "return", "None", "endMinusBeginComplex", "=", "(", "endComplex", "-", "beginComplex", ")", "return", "(", "(", "(", "(", "x", "-", "beginComplex", ".", "real", ")", "/", "endMinusBeginComplex", ".", "real", ")", "*", "endMinusBeginComplex", ".", "imag", ")", "+", "beginComplex", ".", "imag", ")" ]
get the y intersection if it exists .
train
false
17,829
def keyword(name=None, tags=()): if callable(name): return keyword()(name) def _method_wrapper(func): func.robot_name = name func.robot_tags = tags return func return _method_wrapper
[ "def", "keyword", "(", "name", "=", "None", ",", "tags", "=", "(", ")", ")", ":", "if", "callable", "(", "name", ")", ":", "return", "keyword", "(", ")", "(", "name", ")", "def", "_method_wrapper", "(", "func", ")", ":", "func", ".", "robot_name", "=", "name", "func", ".", "robot_tags", "=", "tags", "return", "func", "return", "_method_wrapper" ]
rest controller .
train
false
17,830
def guess_lexer_for_filename(_fn, _text, **options): fn = basename(_fn) primary = None matching_lexers = set() for lexer in _iter_lexerclasses(): for filename in lexer.filenames: if fnmatch.fnmatch(fn, filename): matching_lexers.add(lexer) primary = lexer for filename in lexer.alias_filenames: if fnmatch.fnmatch(fn, filename): matching_lexers.add(lexer) if (not matching_lexers): raise ClassNotFound(('no lexer for filename %r found' % fn)) if (len(matching_lexers) == 1): return matching_lexers.pop()(**options) result = [] for lexer in matching_lexers: rv = lexer.analyse_text(_text) if (rv == 1.0): return lexer(**options) result.append((rv, lexer)) result.sort() if ((not result[(-1)][0]) and (primary is not None)): return primary(**options) return result[(-1)][1](**options)
[ "def", "guess_lexer_for_filename", "(", "_fn", ",", "_text", ",", "**", "options", ")", ":", "fn", "=", "basename", "(", "_fn", ")", "primary", "=", "None", "matching_lexers", "=", "set", "(", ")", "for", "lexer", "in", "_iter_lexerclasses", "(", ")", ":", "for", "filename", "in", "lexer", ".", "filenames", ":", "if", "fnmatch", ".", "fnmatch", "(", "fn", ",", "filename", ")", ":", "matching_lexers", ".", "add", "(", "lexer", ")", "primary", "=", "lexer", "for", "filename", "in", "lexer", ".", "alias_filenames", ":", "if", "fnmatch", ".", "fnmatch", "(", "fn", ",", "filename", ")", ":", "matching_lexers", ".", "add", "(", "lexer", ")", "if", "(", "not", "matching_lexers", ")", ":", "raise", "ClassNotFound", "(", "(", "'no lexer for filename %r found'", "%", "fn", ")", ")", "if", "(", "len", "(", "matching_lexers", ")", "==", "1", ")", ":", "return", "matching_lexers", ".", "pop", "(", ")", "(", "**", "options", ")", "result", "=", "[", "]", "for", "lexer", "in", "matching_lexers", ":", "rv", "=", "lexer", ".", "analyse_text", "(", "_text", ")", "if", "(", "rv", "==", "1.0", ")", ":", "return", "lexer", "(", "**", "options", ")", "result", ".", "append", "(", "(", "rv", ",", "lexer", ")", ")", "result", ".", "sort", "(", ")", "if", "(", "(", "not", "result", "[", "(", "-", "1", ")", "]", "[", "0", "]", ")", "and", "(", "primary", "is", "not", "None", ")", ")", ":", "return", "primary", "(", "**", "options", ")", "return", "result", "[", "(", "-", "1", ")", "]", "[", "1", "]", "(", "**", "options", ")" ]
lookup all lexers that handle those filenames primary or secondary .
train
false
17,832
def _iterate_second(first, second, bindings, used, skipped, finalize_method, debug): debug.line((u'unify(%s,%s) %s' % (first, second, bindings))) if ((not len(first)) or (not len(second))): return finalize_method(first, second, bindings, used, skipped, debug) else: newskipped = (skipped[0], (skipped[1] + [second[0]])) result = _iterate_second(first, second[1:], bindings, used, newskipped, finalize_method, (debug + 1)) try: (newbindings, newused, unused) = _unify_terms(first[0], second[0], bindings, used) newfirst = ((first[1:] + skipped[0]) + unused[0]) newsecond = ((second[1:] + skipped[1]) + unused[1]) result += _iterate_second(newfirst, newsecond, newbindings, newused, ([], []), finalize_method, (debug + 1)) except BindingException: pass return result
[ "def", "_iterate_second", "(", "first", ",", "second", ",", "bindings", ",", "used", ",", "skipped", ",", "finalize_method", ",", "debug", ")", ":", "debug", ".", "line", "(", "(", "u'unify(%s,%s) %s'", "%", "(", "first", ",", "second", ",", "bindings", ")", ")", ")", "if", "(", "(", "not", "len", "(", "first", ")", ")", "or", "(", "not", "len", "(", "second", ")", ")", ")", ":", "return", "finalize_method", "(", "first", ",", "second", ",", "bindings", ",", "used", ",", "skipped", ",", "debug", ")", "else", ":", "newskipped", "=", "(", "skipped", "[", "0", "]", ",", "(", "skipped", "[", "1", "]", "+", "[", "second", "[", "0", "]", "]", ")", ")", "result", "=", "_iterate_second", "(", "first", ",", "second", "[", "1", ":", "]", ",", "bindings", ",", "used", ",", "newskipped", ",", "finalize_method", ",", "(", "debug", "+", "1", ")", ")", "try", ":", "(", "newbindings", ",", "newused", ",", "unused", ")", "=", "_unify_terms", "(", "first", "[", "0", "]", ",", "second", "[", "0", "]", ",", "bindings", ",", "used", ")", "newfirst", "=", "(", "(", "first", "[", "1", ":", "]", "+", "skipped", "[", "0", "]", ")", "+", "unused", "[", "0", "]", ")", "newsecond", "=", "(", "(", "second", "[", "1", ":", "]", "+", "skipped", "[", "1", "]", ")", "+", "unused", "[", "1", "]", ")", "result", "+=", "_iterate_second", "(", "newfirst", ",", "newsecond", ",", "newbindings", ",", "newused", ",", "(", "[", "]", ",", "[", "]", ")", ",", "finalize_method", ",", "(", "debug", "+", "1", ")", ")", "except", "BindingException", ":", "pass", "return", "result" ]
this method facilitates movement through the terms of other .
train
false
17,834
def tagset_mapping(source, target): if ((source not in _MAPPINGS) or (target not in _MAPPINGS[source])): if (target == u'universal'): _load_universal_map(source) return _MAPPINGS[source][target]
[ "def", "tagset_mapping", "(", "source", ",", "target", ")", ":", "if", "(", "(", "source", "not", "in", "_MAPPINGS", ")", "or", "(", "target", "not", "in", "_MAPPINGS", "[", "source", "]", ")", ")", ":", "if", "(", "target", "==", "u'universal'", ")", ":", "_load_universal_map", "(", "source", ")", "return", "_MAPPINGS", "[", "source", "]", "[", "target", "]" ]
retrieve the mapping dictionary between tagsets .
train
false
17,835
def unicode_is_ascii(u_string): assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
[ "def", "unicode_is_ascii", "(", "u_string", ")", ":", "assert", "isinstance", "(", "u_string", ",", "str", ")", "try", ":", "u_string", ".", "encode", "(", "'ascii'", ")", "return", "True", "except", "UnicodeEncodeError", ":", "return", "False" ]
determine if unicode string only contains ascii characters .
train
true
17,836
@contextmanager def mask_modules(*modnames): realimport = builtins.__import__ def myimp(name, *args, **kwargs): if (name in modnames): raise ImportError(('No module named %s' % name)) else: return realimport(name, *args, **kwargs) builtins.__import__ = myimp (yield True) builtins.__import__ = realimport
[ "@", "contextmanager", "def", "mask_modules", "(", "*", "modnames", ")", ":", "realimport", "=", "builtins", ".", "__import__", "def", "myimp", "(", "name", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "name", "in", "modnames", ")", ":", "raise", "ImportError", "(", "(", "'No module named %s'", "%", "name", ")", ")", "else", ":", "return", "realimport", "(", "name", ",", "*", "args", ",", "**", "kwargs", ")", "builtins", ".", "__import__", "=", "myimp", "(", "yield", "True", ")", "builtins", ".", "__import__", "=", "realimport" ]
ban some modules from being importable inside the context for example: .
train
false
17,840
@removals.remove(message='keystoneclient auth plugins are deprecated. Use keystoneauth.', version='2.1.0', removal_version='3.0.0') def get_plugin_class(name): try: mgr = stevedore.DriverManager(namespace=PLUGIN_NAMESPACE, name=name, invoke_on_load=False) except RuntimeError: raise exceptions.NoMatchingPlugin(name) return mgr.driver
[ "@", "removals", ".", "remove", "(", "message", "=", "'keystoneclient auth plugins are deprecated. Use keystoneauth.'", ",", "version", "=", "'2.1.0'", ",", "removal_version", "=", "'3.0.0'", ")", "def", "get_plugin_class", "(", "name", ")", ":", "try", ":", "mgr", "=", "stevedore", ".", "DriverManager", "(", "namespace", "=", "PLUGIN_NAMESPACE", ",", "name", "=", "name", ",", "invoke_on_load", "=", "False", ")", "except", "RuntimeError", ":", "raise", "exceptions", ".", "NoMatchingPlugin", "(", "name", ")", "return", "mgr", ".", "driver" ]
retrieve a plugin class by its entrypoint name .
train
false
17,841
def remove_permission_grant_for_resource_db(role_db, resource_db, permission_types): permission_types = _validate_permission_types(resource_db=resource_db, permission_types=permission_types) resource_uid = resource_db.get_uid() resource_type = resource_db.get_resource_type() permission_grant_db = PermissionGrant.get(resource_uid=resource_uid, resource_type=resource_type, permission_types=permission_types) role_db.update(pull__permission_grants=str(permission_grant_db.id)) return permission_grant_db
[ "def", "remove_permission_grant_for_resource_db", "(", "role_db", ",", "resource_db", ",", "permission_types", ")", ":", "permission_types", "=", "_validate_permission_types", "(", "resource_db", "=", "resource_db", ",", "permission_types", "=", "permission_types", ")", "resource_uid", "=", "resource_db", ".", "get_uid", "(", ")", "resource_type", "=", "resource_db", ".", "get_resource_type", "(", ")", "permission_grant_db", "=", "PermissionGrant", ".", "get", "(", "resource_uid", "=", "resource_uid", ",", "resource_type", "=", "resource_type", ",", "permission_types", "=", "permission_types", ")", "role_db", ".", "update", "(", "pull__permission_grants", "=", "str", "(", "permission_grant_db", ".", "id", ")", ")", "return", "permission_grant_db" ]
remove a permission grant from a role .
train
false
17,842
def _get_plane_vectors(ez): assert (ez.shape == (3,)) ez_len = np.sqrt(np.sum((ez * ez))) if (ez_len == 0): raise RuntimeError('Zero length normal. Cannot proceed.') if (np.abs((ez_len - np.abs(ez[2]))) < 1e-05): ex = np.array([1.0, 0.0, 0.0]) else: ex = np.zeros(3) if (ez[1] < ez[2]): ex[(0 if (ez[0] < ez[1]) else 1)] = 1.0 else: ex[(0 if (ez[0] < ez[2]) else 2)] = 1.0 ez /= ez_len ex -= (np.dot(ez, ex) * ez) ex /= np.sqrt(np.sum((ex * ex))) ey = np.cross(ez, ex) return (ex, ey)
[ "def", "_get_plane_vectors", "(", "ez", ")", ":", "assert", "(", "ez", ".", "shape", "==", "(", "3", ",", ")", ")", "ez_len", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "ez", "*", "ez", ")", ")", ")", "if", "(", "ez_len", "==", "0", ")", ":", "raise", "RuntimeError", "(", "'Zero length normal. Cannot proceed.'", ")", "if", "(", "np", ".", "abs", "(", "(", "ez_len", "-", "np", ".", "abs", "(", "ez", "[", "2", "]", ")", ")", ")", "<", "1e-05", ")", ":", "ex", "=", "np", ".", "array", "(", "[", "1.0", ",", "0.0", ",", "0.0", "]", ")", "else", ":", "ex", "=", "np", ".", "zeros", "(", "3", ")", "if", "(", "ez", "[", "1", "]", "<", "ez", "[", "2", "]", ")", ":", "ex", "[", "(", "0", "if", "(", "ez", "[", "0", "]", "<", "ez", "[", "1", "]", ")", "else", "1", ")", "]", "=", "1.0", "else", ":", "ex", "[", "(", "0", "if", "(", "ez", "[", "0", "]", "<", "ez", "[", "2", "]", ")", "else", "2", ")", "]", "=", "1.0", "ez", "/=", "ez_len", "ex", "-=", "(", "np", ".", "dot", "(", "ez", ",", "ex", ")", "*", "ez", ")", "ex", "/=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "ex", "*", "ex", ")", ")", ")", "ey", "=", "np", ".", "cross", "(", "ez", ",", "ex", ")", "return", "(", "ex", ",", "ey", ")" ]
get two orthogonal vectors orthogonal to ez .
train
false
17,844
def frombytes(mode, size, data, decoder_name='raw', *args): _check_size(size) if ((len(args) == 1) and isinstance(args[0], tuple)): args = args[0] if ((decoder_name == 'raw') and (args == ())): args = mode im = new(mode, size) im.frombytes(data, decoder_name, args) return im
[ "def", "frombytes", "(", "mode", ",", "size", ",", "data", ",", "decoder_name", "=", "'raw'", ",", "*", "args", ")", ":", "_check_size", "(", "size", ")", "if", "(", "(", "len", "(", "args", ")", "==", "1", ")", "and", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ")", ":", "args", "=", "args", "[", "0", "]", "if", "(", "(", "decoder_name", "==", "'raw'", ")", "and", "(", "args", "==", "(", ")", ")", ")", ":", "args", "=", "mode", "im", "=", "new", "(", "mode", ",", "size", ")", "im", ".", "frombytes", "(", "data", ",", "decoder_name", ",", "args", ")", "return", "im" ]
creates a copy of an image memory from pixel data in a buffer .
train
false
17,845
@treeio_login_required @handle_response_format def location_edit(request, location_id, response_format='html'): location = get_object_or_404(Location, pk=location_id) if (not request.user.profile.has_permission(location, mode='w')): return user_denied(request, message="You don't have write access to this Location", response_format=response_format) if request.POST: if ('cancel' not in request.POST): form = LocationForm(request.user.profile, None, request.POST, instance=location) if form.is_valid(): location = form.save(request) return HttpResponseRedirect(reverse('identities_location_view', args=[location.id])) else: return HttpResponseRedirect(reverse('identities_location_view', args=[location.id])) else: form = LocationForm(request.user.profile, None, instance=location) context = _get_default_context(request) context.update({'location': location, 'form': form}) return render_to_response('identities/location_edit', context, context_instance=RequestContext(request), response_format=response_format)
[ "@", "treeio_login_required", "@", "handle_response_format", "def", "location_edit", "(", "request", ",", "location_id", ",", "response_format", "=", "'html'", ")", ":", "location", "=", "get_object_or_404", "(", "Location", ",", "pk", "=", "location_id", ")", "if", "(", "not", "request", ".", "user", ".", "profile", ".", "has_permission", "(", "location", ",", "mode", "=", "'w'", ")", ")", ":", "return", "user_denied", "(", "request", ",", "message", "=", "\"You don't have write access to this Location\"", ",", "response_format", "=", "response_format", ")", "if", "request", ".", "POST", ":", "if", "(", "'cancel'", "not", "in", "request", ".", "POST", ")", ":", "form", "=", "LocationForm", "(", "request", ".", "user", ".", "profile", ",", "None", ",", "request", ".", "POST", ",", "instance", "=", "location", ")", "if", "form", ".", "is_valid", "(", ")", ":", "location", "=", "form", ".", "save", "(", "request", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'identities_location_view'", ",", "args", "=", "[", "location", ".", "id", "]", ")", ")", "else", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'identities_location_view'", ",", "args", "=", "[", "location", ".", "id", "]", ")", ")", "else", ":", "form", "=", "LocationForm", "(", "request", ".", "user", ".", "profile", ",", "None", ",", "instance", "=", "location", ")", "context", "=", "_get_default_context", "(", "request", ")", "context", ".", "update", "(", "{", "'location'", ":", "location", ",", "'form'", ":", "form", "}", ")", "return", "render_to_response", "(", "'identities/location_edit'", ",", "context", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ",", "response_format", "=", "response_format", ")" ]
location edit page .
train
false
17,846
def delete_from_db(item, msg='Deleted from db'): try: logging.info(msg) db.session.delete(item) logging.info('removed from session') db.session.commit() return True except Exception as error: logging.error(('DB Exception! %s' % error)) db.session.rollback() return False
[ "def", "delete_from_db", "(", "item", ",", "msg", "=", "'Deleted from db'", ")", ":", "try", ":", "logging", ".", "info", "(", "msg", ")", "db", ".", "session", ".", "delete", "(", "item", ")", "logging", ".", "info", "(", "'removed from session'", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "True", "except", "Exception", "as", "error", ":", "logging", ".", "error", "(", "(", "'DB Exception! %s'", "%", "error", ")", ")", "db", ".", "session", ".", "rollback", "(", ")", "return", "False" ]
convenience function to wrap a proper db delete .
train
false
17,847
def envs(): metadata = _init() return list(metadata.keys())
[ "def", "envs", "(", ")", ":", "metadata", "=", "_init", "(", ")", "return", "list", "(", "metadata", ".", "keys", "(", ")", ")" ]
return a list of refs that can be used as environments .
train
false
17,849
def task_install_flocker(distribution=None, package_source=PackageSource()): return task_package_install('clusterhq-flocker-node', distribution, package_source)
[ "def", "task_install_flocker", "(", "distribution", "=", "None", ",", "package_source", "=", "PackageSource", "(", ")", ")", ":", "return", "task_package_install", "(", "'clusterhq-flocker-node'", ",", "distribution", ",", "package_source", ")" ]
install flocker cluster on a distribution .
train
false
17,852
def _item_to_sink(iterator, resource): return Sink.from_api_repr(resource, iterator.client)
[ "def", "_item_to_sink", "(", "iterator", ",", "resource", ")", ":", "return", "Sink", ".", "from_api_repr", "(", "resource", ",", "iterator", ".", "client", ")" ]
convert a sink protobuf to the native object .
train
false
17,854
def list2(L): return list(L)
[ "def", "list2", "(", "L", ")", ":", "return", "list", "(", "L", ")" ]
a call to list that wont get removed by lazify .
train
false
17,855
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get new repository .
train
false
17,856
def is_valid_circuit_id(entry): try: return bool(CIRC_ID_PATTERN.match(entry)) except TypeError: return False
[ "def", "is_valid_circuit_id", "(", "entry", ")", ":", "try", ":", "return", "bool", "(", "CIRC_ID_PATTERN", ".", "match", "(", "entry", ")", ")", "except", "TypeError", ":", "return", "False" ]
checks if a string is a valid format for being a circuit identifier .
train
false
17,858
def addTogetherList(functionList, togetherLists): sortedList = functionList[:] sortedList.sort(compareFunctionName) togetherList = None for functionIndex in xrange(len(functionList)): function = functionList[functionIndex] sorted = sortedList[functionIndex] if (function != sorted): together = (function, sorted) if (togetherList == None): togetherList = [] togetherLists.append(togetherList) togetherList.append(together)
[ "def", "addTogetherList", "(", "functionList", ",", "togetherLists", ")", ":", "sortedList", "=", "functionList", "[", ":", "]", "sortedList", ".", "sort", "(", "compareFunctionName", ")", "togetherList", "=", "None", "for", "functionIndex", "in", "xrange", "(", "len", "(", "functionList", ")", ")", ":", "function", "=", "functionList", "[", "functionIndex", "]", "sorted", "=", "sortedList", "[", "functionIndex", "]", "if", "(", "function", "!=", "sorted", ")", ":", "together", "=", "(", "function", ",", "sorted", ")", "if", "(", "togetherList", "==", "None", ")", ":", "togetherList", "=", "[", "]", "togetherLists", ".", "append", "(", "togetherList", ")", "togetherList", ".", "append", "(", "together", ")" ]
add the togetherlist to the togetherlists is the sorted is different .
train
false
17,859
def brightness_multi(x, gamma=1, gain=1, is_random=False): if is_random: gamma = np.random.uniform((1 - gamma), (1 + gamma)) results = [] for data in x: results.append(exposure.adjust_gamma(data, gamma, gain)) return np.asarray(results)
[ "def", "brightness_multi", "(", "x", ",", "gamma", "=", "1", ",", "gain", "=", "1", ",", "is_random", "=", "False", ")", ":", "if", "is_random", ":", "gamma", "=", "np", ".", "random", ".", "uniform", "(", "(", "1", "-", "gamma", ")", ",", "(", "1", "+", "gamma", ")", ")", "results", "=", "[", "]", "for", "data", "in", "x", ":", "results", ".", "append", "(", "exposure", ".", "adjust_gamma", "(", "data", ",", "gamma", ",", "gain", ")", ")", "return", "np", ".", "asarray", "(", "results", ")" ]
change the brightness of multiply images .
train
true
17,860
def print_tab_menu(needle, tab_entries, separator): for (i, entry) in enumerate(tab_entries): print_local(('%s%s%d%s%s' % (needle, separator, (i + 1), separator, entry.path)))
[ "def", "print_tab_menu", "(", "needle", ",", "tab_entries", ",", "separator", ")", ":", "for", "(", "i", ",", "entry", ")", "in", "enumerate", "(", "tab_entries", ")", ":", "print_local", "(", "(", "'%s%s%d%s%s'", "%", "(", "needle", ",", "separator", ",", "(", "i", "+", "1", ")", ",", "separator", ",", "entry", ".", "path", ")", ")", ")" ]
prints the tab completion menu according to the following format: [needle]__[index]__[possible_match] the needle and index are necessary to recreate the results on subsequent calls .
train
false
17,861
def MessageSetItemSizer(field_number): static_size = ((((_TagSize(1) * 2) + _TagSize(2)) + _VarintSize(field_number)) + _TagSize(3)) local_VarintSize = _VarintSize def FieldSize(value): l = value.ByteSize() return ((static_size + local_VarintSize(l)) + l) return FieldSize
[ "def", "MessageSetItemSizer", "(", "field_number", ")", ":", "static_size", "=", "(", "(", "(", "(", "_TagSize", "(", "1", ")", "*", "2", ")", "+", "_TagSize", "(", "2", ")", ")", "+", "_VarintSize", "(", "field_number", ")", ")", "+", "_TagSize", "(", "3", ")", ")", "local_VarintSize", "=", "_VarintSize", "def", "FieldSize", "(", "value", ")", ":", "l", "=", "value", ".", "ByteSize", "(", ")", "return", "(", "(", "static_size", "+", "local_VarintSize", "(", "l", ")", ")", "+", "l", ")", "return", "FieldSize" ]
returns a sizer for extensions of messageset .
train
true
17,862
def import_global_module(module, current_locals, current_globals, exceptions=None): try: objects = getattr(module, '__all__', dir(module)) for k in objects: if (k and (k[0] != '_')): current_globals[k] = getattr(module, k) except exceptions as e: return e finally: del current_globals, current_locals
[ "def", "import_global_module", "(", "module", ",", "current_locals", ",", "current_globals", ",", "exceptions", "=", "None", ")", ":", "try", ":", "objects", "=", "getattr", "(", "module", ",", "'__all__'", ",", "dir", "(", "module", ")", ")", "for", "k", "in", "objects", ":", "if", "(", "k", "and", "(", "k", "[", "0", "]", "!=", "'_'", ")", ")", ":", "current_globals", "[", "k", "]", "=", "getattr", "(", "module", ",", "k", ")", "except", "exceptions", "as", "e", ":", "return", "e", "finally", ":", "del", "current_globals", ",", "current_locals" ]
import the requested module into the global scope warning! this will import your module into the global scope **example**: from django .
train
false
17,863
def NewType(name, tp): def new_type(x): return x new_type.__name__ = str(name) new_type.__supertype__ = tp return new_type
[ "def", "NewType", "(", "name", ",", "tp", ")", ":", "def", "new_type", "(", "x", ")", ":", "return", "x", "new_type", ".", "__name__", "=", "str", "(", "name", ")", "new_type", ".", "__supertype__", "=", "tp", "return", "new_type" ]
newtype creates simple unique types with almost zero runtime overhead .
train
true
17,864
def _GetModuleOrNone(module_name): module = None if module_name: try: module = __import__(module_name) except ImportError: pass else: for name in module_name.split('.')[1:]: module = getattr(module, name) return module
[ "def", "_GetModuleOrNone", "(", "module_name", ")", ":", "module", "=", "None", "if", "module_name", ":", "try", ":", "module", "=", "__import__", "(", "module_name", ")", "except", "ImportError", ":", "pass", "else", ":", "for", "name", "in", "module_name", ".", "split", "(", "'.'", ")", "[", "1", ":", "]", ":", "module", "=", "getattr", "(", "module", ",", "name", ")", "return", "module" ]
returns a module if it exists or none .
train
false
17,865
def get_currency_symbol(currency, locale=LC_NUMERIC): return Locale.parse(locale).currency_symbols.get(currency, currency)
[ "def", "get_currency_symbol", "(", "currency", ",", "locale", "=", "LC_NUMERIC", ")", ":", "return", "Locale", ".", "parse", "(", "locale", ")", ".", "currency_symbols", ".", "get", "(", "currency", ",", "currency", ")" ]
return the symbol used by the locale for the specified currency .
train
false
17,866
def IS_LINE_JUNK(line, pat=re.compile('\\s*#?\\s*$').match): return (pat(line) is not None)
[ "def", "IS_LINE_JUNK", "(", "line", ",", "pat", "=", "re", ".", "compile", "(", "'\\\\s*#?\\\\s*$'", ")", ".", "match", ")", ":", "return", "(", "pat", "(", "line", ")", "is", "not", "None", ")" ]
return 1 for ignorable line: iff line is blank or contains a single # .
train
false
17,867
def _ca_path(temp_dir=None): ca_path = system_path() if (ca_path is None): if (temp_dir is None): temp_dir = tempfile.gettempdir() if (not os.path.isdir(temp_dir)): raise CACertsError(pretty_message(u'\n The temp dir specified, "%s", is not a directory\n ', temp_dir)) ca_path = os.path.join(temp_dir, u'oscrypto-ca-bundle.crt') return (ca_path, True) return (ca_path, False)
[ "def", "_ca_path", "(", "temp_dir", "=", "None", ")", ":", "ca_path", "=", "system_path", "(", ")", "if", "(", "ca_path", "is", "None", ")", ":", "if", "(", "temp_dir", "is", "None", ")", ":", "temp_dir", "=", "tempfile", ".", "gettempdir", "(", ")", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "temp_dir", ")", ")", ":", "raise", "CACertsError", "(", "pretty_message", "(", "u'\\n The temp dir specified, \"%s\", is not a directory\\n '", ",", "temp_dir", ")", ")", "ca_path", "=", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "u'oscrypto-ca-bundle.crt'", ")", "return", "(", "ca_path", ",", "True", ")", "return", "(", "ca_path", ",", "False", ")" ]
returns the file path to the ca certs file .
train
true
17,868
def verify_client_object(test): if ((str(type(test)) == "<class 'mock.Mock'>") or (str(type(test)) == "<class 'mock.mock.Mock'>")): pass elif (not isinstance(test, elasticsearch.Elasticsearch)): raise TypeError('Not a client object. Type: {0}'.format(type(test)))
[ "def", "verify_client_object", "(", "test", ")", ":", "if", "(", "(", "str", "(", "type", "(", "test", ")", ")", "==", "\"<class 'mock.Mock'>\"", ")", "or", "(", "str", "(", "type", "(", "test", ")", ")", "==", "\"<class 'mock.mock.Mock'>\"", ")", ")", ":", "pass", "elif", "(", "not", "isinstance", "(", "test", ",", "elasticsearch", ".", "Elasticsearch", ")", ")", ":", "raise", "TypeError", "(", "'Not a client object. Type: {0}'", ".", "format", "(", "type", "(", "test", ")", ")", ")" ]
test if test is a proper :class:elasticsearch .
train
false
17,869
def _map_roles_to_roles(graph, dirs, git_dir, key, type_1, type_2): Node = namedtuple('Node', ['name', 'type']) for d in dirs: d = pathlib2.Path(git_dir, d) for item in d.iterdir(): roles = {f for f in item.glob('meta/*.yml')} if roles: for role in roles: yaml_file = _open_yaml_file(role) if ((yaml_file is not None) and (key in yaml_file)): for dependent in yaml_file[key]: name = _get_role_name(dependent) node_1 = Node(item.name, type_1) node_2 = Node(name, type_2) graph.add_edge(node_2, node_1)
[ "def", "_map_roles_to_roles", "(", "graph", ",", "dirs", ",", "git_dir", ",", "key", ",", "type_1", ",", "type_2", ")", ":", "Node", "=", "namedtuple", "(", "'Node'", ",", "[", "'name'", ",", "'type'", "]", ")", "for", "d", "in", "dirs", ":", "d", "=", "pathlib2", ".", "Path", "(", "git_dir", ",", "d", ")", "for", "item", "in", "d", ".", "iterdir", "(", ")", ":", "roles", "=", "{", "f", "for", "f", "in", "item", ".", "glob", "(", "'meta/*.yml'", ")", "}", "if", "roles", ":", "for", "role", "in", "roles", ":", "yaml_file", "=", "_open_yaml_file", "(", "role", ")", "if", "(", "(", "yaml_file", "is", "not", "None", ")", "and", "(", "key", "in", "yaml_file", ")", ")", ":", "for", "dependent", "in", "yaml_file", "[", "key", "]", ":", "name", "=", "_get_role_name", "(", "dependent", ")", "node_1", "=", "Node", "(", "item", ".", "name", ",", "type_1", ")", "node_2", "=", "Node", "(", "name", ",", "type_2", ")", "graph", ".", "add_edge", "(", "node_2", ",", "node_1", ")" ]
maps roles to the roles that they depend on .
train
false
17,870
def editor(): editor = (os.environ.get('CHEAT_EDITOR') or os.environ.get('VISUAL') or os.environ.get('EDITOR') or False) if (editor == False): die('You must set a CHEAT_EDITOR, VISUAL, or EDITOR environment variable in order to create/edit a cheatsheet.') return editor
[ "def", "editor", "(", ")", ":", "editor", "=", "(", "os", ".", "environ", ".", "get", "(", "'CHEAT_EDITOR'", ")", "or", "os", ".", "environ", ".", "get", "(", "'VISUAL'", ")", "or", "os", ".", "environ", ".", "get", "(", "'EDITOR'", ")", "or", "False", ")", "if", "(", "editor", "==", "False", ")", ":", "die", "(", "'You must set a CHEAT_EDITOR, VISUAL, or EDITOR environment variable in order to create/edit a cheatsheet.'", ")", "return", "editor" ]
open the default editor at the given filename and linenumber .
train
false
17,871
def global_cleanup_assertions(): _assert_no_stray_pool_connections()
[ "def", "global_cleanup_assertions", "(", ")", ":", "_assert_no_stray_pool_connections", "(", ")" ]
check things that have to be finalized at the end of a test suite .
train
false
17,872
@utils.arg('aggregate', metavar='<aggregate>', help=_('Name or ID of aggregate.')) def do_aggregate_show(cs, args): aggregate = _find_aggregate(cs, args.aggregate) _print_aggregate_details(cs, aggregate)
[ "@", "utils", ".", "arg", "(", "'aggregate'", ",", "metavar", "=", "'<aggregate>'", ",", "help", "=", "_", "(", "'Name or ID of aggregate.'", ")", ")", "def", "do_aggregate_show", "(", "cs", ",", "args", ")", ":", "aggregate", "=", "_find_aggregate", "(", "cs", ",", "args", ".", "aggregate", ")", "_print_aggregate_details", "(", "cs", ",", "aggregate", ")" ]
show details of the specified aggregate .
train
false
17,874
def get_policy_version(policy_name, version_id, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_policy_version(_get_policy_arn(policy_name, region=region, key=key, keyid=keyid, profile=profile), version_id) retval = ret.get('get_policy_version_response', {}).get('get_policy_version_result', {}).get('policy_version', {}) retval['document'] = _unquote(retval.get('document')) return {'policy_version': retval} except boto.exception.BotoServerError: return None
[ "def", "get_policy_version", "(", "policy_name", ",", "version_id", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "try", ":", "ret", "=", "conn", ".", "get_policy_version", "(", "_get_policy_arn", "(", "policy_name", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", ",", "version_id", ")", "retval", "=", "ret", ".", "get", "(", "'get_policy_version_response'", ",", "{", "}", ")", ".", "get", "(", "'get_policy_version_result'", ",", "{", "}", ")", ".", "get", "(", "'policy_version'", ",", "{", "}", ")", "retval", "[", "'document'", "]", "=", "_unquote", "(", "retval", ".", "get", "(", "'document'", ")", ")", "return", "{", "'policy_version'", ":", "retval", "}", "except", "boto", ".", "exception", ".", "BotoServerError", ":", "return", "None" ]
check to see if policy exists .
train
true
17,876
def libvlc_toggle_fullscreen(p_mi): f = (_Cfunctions.get('libvlc_toggle_fullscreen', None) or _Cfunction('libvlc_toggle_fullscreen', ((1,),), None, None, MediaPlayer)) return f(p_mi)
[ "def", "libvlc_toggle_fullscreen", "(", "p_mi", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_toggle_fullscreen'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_toggle_fullscreen'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "MediaPlayer", ")", ")", "return", "f", "(", "p_mi", ")" ]
toggle fullscreen status on non-embedded video outputs .
train
false
17,877
def get_column_labels(command_name): cmd = cmd_reverse_lookup(command_name) if (cmd == 0): return {} labels = {} enum = mavutil.mavlink.enums['MAV_CMD'][cmd] for col in enum.param.keys(): labels[col] = make_column_label(command_name, enum.param[col], ('P%u' % col)) return labels
[ "def", "get_column_labels", "(", "command_name", ")", ":", "cmd", "=", "cmd_reverse_lookup", "(", "command_name", ")", "if", "(", "cmd", "==", "0", ")", ":", "return", "{", "}", "labels", "=", "{", "}", "enum", "=", "mavutil", ".", "mavlink", ".", "enums", "[", "'MAV_CMD'", "]", "[", "cmd", "]", "for", "col", "in", "enum", ".", "param", ".", "keys", "(", ")", ":", "labels", "[", "col", "]", "=", "make_column_label", "(", "command_name", ",", "enum", ".", "param", "[", "col", "]", ",", "(", "'P%u'", "%", "col", ")", ")", "return", "labels" ]
return dictionary of column labels if available .
train
true
17,878
def get_chunks(source, chunk_len): return (source[i:(i + chunk_len)] for i in range(0, len(source), chunk_len))
[ "def", "get_chunks", "(", "source", ",", "chunk_len", ")", ":", "return", "(", "source", "[", "i", ":", "(", "i", "+", "chunk_len", ")", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "source", ")", ",", "chunk_len", ")", ")" ]
returns an iterator over chunk_len chunks of source .
train
true
17,879
def otsu(image, selem, out=None, mask=None, shift_x=False, shift_y=False): return _apply_scalar_per_pixel(generic_cy._otsu, image, selem, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y)
[ "def", "otsu", "(", "image", ",", "selem", ",", "out", "=", "None", ",", "mask", "=", "None", ",", "shift_x", "=", "False", ",", "shift_y", "=", "False", ")", ":", "return", "_apply_scalar_per_pixel", "(", "generic_cy", ".", "_otsu", ",", "image", ",", "selem", ",", "out", "=", "out", ",", "mask", "=", "mask", ",", "shift_x", "=", "shift_x", ",", "shift_y", "=", "shift_y", ")" ]
local otsus threshold value for each pixel .
train
false
17,881
def _activites_from_users_followed_by_user_query(user_id, limit): import ckan.model as model follower_objects = model.UserFollowingUser.followee_list(user_id) if (not follower_objects): return model.Session.query(model.Activity).filter('0=1') return _activities_union_all(*[_user_activity_query(follower.object_id, limit) for follower in follower_objects])
[ "def", "_activites_from_users_followed_by_user_query", "(", "user_id", ",", "limit", ")", ":", "import", "ckan", ".", "model", "as", "model", "follower_objects", "=", "model", ".", "UserFollowingUser", ".", "followee_list", "(", "user_id", ")", "if", "(", "not", "follower_objects", ")", ":", "return", "model", ".", "Session", ".", "query", "(", "model", ".", "Activity", ")", ".", "filter", "(", "'0=1'", ")", "return", "_activities_union_all", "(", "*", "[", "_user_activity_query", "(", "follower", ".", "object_id", ",", "limit", ")", "for", "follower", "in", "follower_objects", "]", ")" ]
return a query for all activities from users that user_id follows .
train
false
17,882
def get_byURL(url, info=None, args=None, kwds=None): if (args is None): args = [] if (kwds is None): kwds = {} ia = IMDb(*args, **kwds) match = _re_imdbIDurl.search(url) if (not match): return None imdbtype = match.group(1) imdbID = match.group(2) if (imdbtype == 'tt'): return ia.get_movie(imdbID, info=info) elif (imdbtype == 'nm'): return ia.get_person(imdbID, info=info) elif (imdbtype == 'ch'): return ia.get_character(imdbID, info=info) elif (imdbtype == 'co'): return ia.get_company(imdbID, info=info) return None
[ "def", "get_byURL", "(", "url", ",", "info", "=", "None", ",", "args", "=", "None", ",", "kwds", "=", "None", ")", ":", "if", "(", "args", "is", "None", ")", ":", "args", "=", "[", "]", "if", "(", "kwds", "is", "None", ")", ":", "kwds", "=", "{", "}", "ia", "=", "IMDb", "(", "*", "args", ",", "**", "kwds", ")", "match", "=", "_re_imdbIDurl", ".", "search", "(", "url", ")", "if", "(", "not", "match", ")", ":", "return", "None", "imdbtype", "=", "match", ".", "group", "(", "1", ")", "imdbID", "=", "match", ".", "group", "(", "2", ")", "if", "(", "imdbtype", "==", "'tt'", ")", ":", "return", "ia", ".", "get_movie", "(", "imdbID", ",", "info", "=", "info", ")", "elif", "(", "imdbtype", "==", "'nm'", ")", ":", "return", "ia", ".", "get_person", "(", "imdbID", ",", "info", "=", "info", ")", "elif", "(", "imdbtype", "==", "'ch'", ")", ":", "return", "ia", ".", "get_character", "(", "imdbID", ",", "info", "=", "info", ")", "elif", "(", "imdbtype", "==", "'co'", ")", ":", "return", "ia", ".", "get_company", "(", "imdbID", ",", "info", "=", "info", ")", "return", "None" ]
return a movie .
train
false
17,884
def conjugate_transpose(matlist, K): return conjugate(transpose(matlist, K), K)
[ "def", "conjugate_transpose", "(", "matlist", ",", "K", ")", ":", "return", "conjugate", "(", "transpose", "(", "matlist", ",", "K", ")", ",", "K", ")" ]
returns the conjugate-transpose of a matrix examples .
train
false
17,887
def get_icloud_folder_location(): yosemite_icloud_path = '~/Library/Mobile Documents/com~apple~CloudDocs/' icloud_home = os.path.expanduser(yosemite_icloud_path) if (not os.path.isdir(icloud_home)): error('Unable to find your iCloud Drive =(') return unicode(icloud_home)
[ "def", "get_icloud_folder_location", "(", ")", ":", "yosemite_icloud_path", "=", "'~/Library/Mobile Documents/com~apple~CloudDocs/'", "icloud_home", "=", "os", ".", "path", ".", "expanduser", "(", "yosemite_icloud_path", ")", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "icloud_home", ")", ")", ":", "error", "(", "'Unable to find your iCloud Drive =('", ")", "return", "unicode", "(", "icloud_home", ")" ]
try to locate the icloud drive folder .
train
true
17,888
def log_remaining_rounds(ids, cluster_mapping, bail_out, log_fh=None): remaining_rounds = len([id for id in ids.keys() if (len(cluster_mapping[id]) >= bail_out)]) if log_fh: log_fh.write(('Rounds remaining in worst case: %d\n' % remaining_rounds)) return remaining_rounds
[ "def", "log_remaining_rounds", "(", "ids", ",", "cluster_mapping", ",", "bail_out", ",", "log_fh", "=", "None", ")", ":", "remaining_rounds", "=", "len", "(", "[", "id", "for", "id", "in", "ids", ".", "keys", "(", ")", "if", "(", "len", "(", "cluster_mapping", "[", "id", "]", ")", ">=", "bail_out", ")", "]", ")", "if", "log_fh", ":", "log_fh", ".", "write", "(", "(", "'Rounds remaining in worst case: %d\\n'", "%", "remaining_rounds", ")", ")", "return", "remaining_rounds" ]
estimate the worst case number of rounds remaining ids: dict of active ids cluster_mapping: cluster mapping as dict bail_out: minimally required cluster size log_fh: log file handle .
train
false
17,890
def make_src_pkg(dest_dir, spec, sources, env=None, template=None, saltenv='base'): _create_rpmmacros() tree_base = _mk_tree() spec_path = _get_spec(tree_base, spec, template, saltenv) if isinstance(sources, str): sources = sources.split(',') for src in sources: _get_src(tree_base, src, saltenv) cmd = 'rpmbuild --define "_topdir {0}" -bs --define "_source_filedigest_algorithm md5" --define "_binary_filedigest_algorithm md5" --define "dist .el5" {1}'.format(tree_base, spec_path) __salt__['cmd.run'](cmd) srpms = os.path.join(tree_base, 'SRPMS') ret = [] if (not os.path.isdir(dest_dir)): os.makedirs(dest_dir) for fn_ in os.listdir(srpms): full = os.path.join(srpms, fn_) tgt = os.path.join(dest_dir, fn_) shutil.copy(full, tgt) ret.append(tgt) return ret
[ "def", "make_src_pkg", "(", "dest_dir", ",", "spec", ",", "sources", ",", "env", "=", "None", ",", "template", "=", "None", ",", "saltenv", "=", "'base'", ")", ":", "_create_rpmmacros", "(", ")", "tree_base", "=", "_mk_tree", "(", ")", "spec_path", "=", "_get_spec", "(", "tree_base", ",", "spec", ",", "template", ",", "saltenv", ")", "if", "isinstance", "(", "sources", ",", "str", ")", ":", "sources", "=", "sources", ".", "split", "(", "','", ")", "for", "src", "in", "sources", ":", "_get_src", "(", "tree_base", ",", "src", ",", "saltenv", ")", "cmd", "=", "'rpmbuild --define \"_topdir {0}\" -bs --define \"_source_filedigest_algorithm md5\" --define \"_binary_filedigest_algorithm md5\" --define \"dist .el5\" {1}'", ".", "format", "(", "tree_base", ",", "spec_path", ")", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "srpms", "=", "os", ".", "path", ".", "join", "(", "tree_base", ",", "'SRPMS'", ")", "ret", "=", "[", "]", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "dest_dir", ")", ")", ":", "os", ".", "makedirs", "(", "dest_dir", ")", "for", "fn_", "in", "os", ".", "listdir", "(", "srpms", ")", ":", "full", "=", "os", ".", "path", ".", "join", "(", "srpms", ",", "fn_", ")", "tgt", "=", "os", ".", "path", ".", "join", "(", "dest_dir", ",", "fn_", ")", "shutil", ".", "copy", "(", "full", ",", "tgt", ")", "ret", ".", "append", "(", "tgt", ")", "return", "ret" ]
create a source rpm from the given spec file and sources cli example: .
train
false
17,892
def CreateResponseRewritersChain(): rewriters = [ParseStatusRewriter, dev_appserver_blobstore.DownloadRewriter, IgnoreHeadersRewriter, ValidHeadersRewriter, CacheRewriter, ContentLengthRewriter] return rewriters
[ "def", "CreateResponseRewritersChain", "(", ")", ":", "rewriters", "=", "[", "ParseStatusRewriter", ",", "dev_appserver_blobstore", ".", "DownloadRewriter", ",", "IgnoreHeadersRewriter", ",", "ValidHeadersRewriter", ",", "CacheRewriter", ",", "ContentLengthRewriter", "]", "return", "rewriters" ]
create the default response rewriter chain .
train
false
17,893
@facebook_required(scope=['user_status', 'friends_status']) def checkins(request, graph): checkins = graph.get('me/checkins') raise Exception(checkins)
[ "@", "facebook_required", "(", "scope", "=", "[", "'user_status'", ",", "'friends_status'", "]", ")", "def", "checkins", "(", "request", ",", "graph", ")", ":", "checkins", "=", "graph", ".", "get", "(", "'me/checkins'", ")", "raise", "Exception", "(", "checkins", ")" ]
see the facebook docs: URL URL todo: add a nice template to this .
train
false
17,894
def overridden_method(klass, name): try: parent = next(klass.local_attr_ancestors(name)) except (StopIteration, KeyError): return None try: meth_node = parent[name] except KeyError: return None if isinstance(meth_node, astroid.Function): return meth_node return None
[ "def", "overridden_method", "(", "klass", ",", "name", ")", ":", "try", ":", "parent", "=", "next", "(", "klass", ".", "local_attr_ancestors", "(", "name", ")", ")", "except", "(", "StopIteration", ",", "KeyError", ")", ":", "return", "None", "try", ":", "meth_node", "=", "parent", "[", "name", "]", "except", "KeyError", ":", "return", "None", "if", "isinstance", "(", "meth_node", ",", "astroid", ".", "Function", ")", ":", "return", "meth_node", "return", "None" ]
get overridden method if any .
train
true
17,895
def test_ur_literals(): def check(literal): io = StringIO(u(literal)) tokens = tokenize.generate_tokens(io.readline) token_list = list(tokens) (typ, result_literal, _, _) = token_list[0] assert (typ == STRING) assert (result_literal == literal) check('u""') check('ur""') check('Ur""') check('UR""') check('bR""') with pytest.raises(AssertionError): check('Rb""')
[ "def", "test_ur_literals", "(", ")", ":", "def", "check", "(", "literal", ")", ":", "io", "=", "StringIO", "(", "u", "(", "literal", ")", ")", "tokens", "=", "tokenize", ".", "generate_tokens", "(", "io", ".", "readline", ")", "token_list", "=", "list", "(", "tokens", ")", "(", "typ", ",", "result_literal", ",", "_", ",", "_", ")", "=", "token_list", "[", "0", "]", "assert", "(", "typ", "==", "STRING", ")", "assert", "(", "result_literal", "==", "literal", ")", "check", "(", "'u\"\"'", ")", "check", "(", "'ur\"\"'", ")", "check", "(", "'Ur\"\"'", ")", "check", "(", "'UR\"\"'", ")", "check", "(", "'bR\"\"'", ")", "with", "pytest", ".", "raises", "(", "AssertionError", ")", ":", "check", "(", "'Rb\"\"'", ")" ]
decided to parse u literals regardless of python version .
train
false
17,896
def _add_implied_task_id(d): if (d.get('attempt_id') and (not d.get('task_id'))): d['task_id'] = _attempt_id_to_task_id(d['attempt_id'])
[ "def", "_add_implied_task_id", "(", "d", ")", ":", "if", "(", "d", ".", "get", "(", "'attempt_id'", ")", "and", "(", "not", "d", ".", "get", "(", "'task_id'", ")", ")", ")", ":", "d", "[", "'task_id'", "]", "=", "_attempt_id_to_task_id", "(", "d", "[", "'attempt_id'", "]", ")" ]
if *d* has *attempt_id* but not *task_id* .
train
false
17,898
def getProjectionByName(name): if (name.lower() == 'spherical mercator'): return SphericalMercator() elif (name.lower() == 'wgs84'): return WGS84() else: try: return Core.loadClassPath(name) except Exception as e: raise Core.KnownUnknown(('Failed projection in configuration: "%s" - %s' % (name, e)))
[ "def", "getProjectionByName", "(", "name", ")", ":", "if", "(", "name", ".", "lower", "(", ")", "==", "'spherical mercator'", ")", ":", "return", "SphericalMercator", "(", ")", "elif", "(", "name", ".", "lower", "(", ")", "==", "'wgs84'", ")", ":", "return", "WGS84", "(", ")", "else", ":", "try", ":", "return", "Core", ".", "loadClassPath", "(", "name", ")", "except", "Exception", "as", "e", ":", "raise", "Core", ".", "KnownUnknown", "(", "(", "'Failed projection in configuration: \"%s\" - %s'", "%", "(", "name", ",", "e", ")", ")", ")" ]
retrieve a projection object by name .
train
false
17,899
def _get_or_add_proxy_child(parent_proxy, segment): child = parent_proxy._children.get(segment) if (child is not None): return child child = _get(parent_proxy._original, segment, _sentinel) if (child is _sentinel): raise KeyError("Attribute or key '{}' not found in {}".format(segment, parent_proxy._original)) proxy_for_child = _proxy_for_evolvable_object(child) parent_proxy._children[segment] = proxy_for_child return proxy_for_child
[ "def", "_get_or_add_proxy_child", "(", "parent_proxy", ",", "segment", ")", ":", "child", "=", "parent_proxy", ".", "_children", ".", "get", "(", "segment", ")", "if", "(", "child", "is", "not", "None", ")", ":", "return", "child", "child", "=", "_get", "(", "parent_proxy", ".", "_original", ",", "segment", ",", "_sentinel", ")", "if", "(", "child", "is", "_sentinel", ")", ":", "raise", "KeyError", "(", "\"Attribute or key '{}' not found in {}\"", ".", "format", "(", "segment", ",", "parent_proxy", ".", "_original", ")", ")", "proxy_for_child", "=", "_proxy_for_evolvable_object", "(", "child", ")", "parent_proxy", ".", "_children", "[", "segment", "]", "=", "proxy_for_child", "return", "proxy_for_child" ]
returns a proxy wrapper around the _ievolvable object corresponding to segment .
train
false
17,900
def get_variable_shape(x): return int_shape(x)
[ "def", "get_variable_shape", "(", "x", ")", ":", "return", "int_shape", "(", "x", ")" ]
returns shape of a variable .
train
false
17,901
def set_quota_volume(name, path, size, enable_quota=False): cmd = 'volume quota {0}'.format(name) if path: cmd += ' limit-usage {0}'.format(path) if size: cmd += ' {0}'.format(size) if enable_quota: if (not enable_quota_volume(name)): pass if (not _gluster(cmd)): return False return True
[ "def", "set_quota_volume", "(", "name", ",", "path", ",", "size", ",", "enable_quota", "=", "False", ")", ":", "cmd", "=", "'volume quota {0}'", ".", "format", "(", "name", ")", "if", "path", ":", "cmd", "+=", "' limit-usage {0}'", ".", "format", "(", "path", ")", "if", "size", ":", "cmd", "+=", "' {0}'", ".", "format", "(", "size", ")", "if", "enable_quota", ":", "if", "(", "not", "enable_quota_volume", "(", "name", ")", ")", ":", "pass", "if", "(", "not", "_gluster", "(", "cmd", ")", ")", ":", "return", "False", "return", "True" ]
set quota to glusterfs volume .
train
true
17,902
def option_dict(options): d = {} for option in options: d[option.name] = option return d
[ "def", "option_dict", "(", "options", ")", ":", "d", "=", "{", "}", "for", "option", "in", "options", ":", "d", "[", "option", ".", "name", "]", "=", "option", "return", "d" ]
return a dictionary mapping option names to option instances .
train
false
17,903
def remove_interface_suffix(interface): return interface.partition('@')[0]
[ "def", "remove_interface_suffix", "(", "interface", ")", ":", "return", "interface", ".", "partition", "(", "'@'", ")", "[", "0", "]" ]
remove a possible "<if>@<endpoint>" suffix from an interface name .
train
false
17,905
def next_history_or_next_completion(event): event.current_buffer.auto_down()
[ "def", "next_history_or_next_completion", "(", "event", ")", ":", "event", ".", "current_buffer", ".", "auto_down", "(", ")" ]
control-n in vi edit mode on readline is history previous .
train
false
17,906
def conn_has_method(conn, method_name): if (method_name in dir(conn)): return True log.error("Method '{0}' not yet supported!".format(method_name)) return False
[ "def", "conn_has_method", "(", "conn", ",", "method_name", ")", ":", "if", "(", "method_name", "in", "dir", "(", "conn", ")", ")", ":", "return", "True", "log", ".", "error", "(", "\"Method '{0}' not yet supported!\"", ".", "format", "(", "method_name", ")", ")", "return", "False" ]
find if the provided connection object has a specific method .
train
true
17,908
def json_safe(string, content_type='application/octet-stream'): try: string = string.decode('utf-8') json.dumps(string) return string except (ValueError, TypeError): return ''.join(['data:', content_type.encode('utf-8'), ';base64,', base64.b64encode(string)]).decode('utf-8')
[ "def", "json_safe", "(", "string", ",", "content_type", "=", "'application/octet-stream'", ")", ":", "try", ":", "string", "=", "string", ".", "decode", "(", "'utf-8'", ")", "json", ".", "dumps", "(", "string", ")", "return", "string", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "''", ".", "join", "(", "[", "'data:'", ",", "content_type", ".", "encode", "(", "'utf-8'", ")", ",", "';base64,'", ",", "base64", ".", "b64encode", "(", "string", ")", "]", ")", ".", "decode", "(", "'utf-8'", ")" ]
returns json-safe version of string .
train
true
17,909
def json_serial(obj): if isinstance(obj, datetime): return obj.isoformat() if isinstance(obj, timedelta): return obj.microseconds return (('<Object ' + type(obj).__name__) + '>')
[ "def", "json_serial", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ")", ":", "return", "obj", ".", "isoformat", "(", ")", "if", "isinstance", "(", "obj", ",", "timedelta", ")", ":", "return", "obj", ".", "microseconds", "return", "(", "(", "'<Object '", "+", "type", "(", "obj", ")", ".", "__name__", ")", "+", "'>'", ")" ]
json serializer for objects not serializable by default json code .
train
false
17,910
def check_negative_indices(*nodes): for node in nodes: if ((node is None) or ((not isinstance(node.constant_result, _py_int_types)) and (not isinstance(node.constant_result, float)))): continue if (node.constant_result < 0): warning(node.pos, "the result of using negative indices inside of code sections marked as 'wraparound=False' is undefined", level=1)
[ "def", "check_negative_indices", "(", "*", "nodes", ")", ":", "for", "node", "in", "nodes", ":", "if", "(", "(", "node", "is", "None", ")", "or", "(", "(", "not", "isinstance", "(", "node", ".", "constant_result", ",", "_py_int_types", ")", ")", "and", "(", "not", "isinstance", "(", "node", ".", "constant_result", ",", "float", ")", ")", ")", ")", ":", "continue", "if", "(", "node", ".", "constant_result", "<", "0", ")", ":", "warning", "(", "node", ".", "pos", ",", "\"the result of using negative indices inside of code sections marked as 'wraparound=False' is undefined\"", ",", "level", "=", "1", ")" ]
raise a warning on nodes that are known to have negative numeric values .
train
false
17,911
def trimAlphaNum(value): while (value and value[(-1)].isalnum()): value = value[:(-1)] while (value and value[0].isalnum()): value = value[1:] return value
[ "def", "trimAlphaNum", "(", "value", ")", ":", "while", "(", "value", "and", "value", "[", "(", "-", "1", ")", "]", ".", "isalnum", "(", ")", ")", ":", "value", "=", "value", "[", ":", "(", "-", "1", ")", "]", "while", "(", "value", "and", "value", "[", "0", "]", ".", "isalnum", "(", ")", ")", ":", "value", "=", "value", "[", "1", ":", "]", "return", "value" ]
trims alpha numeric characters from start and ending of a given value .
train
false
17,912
def build_instance(Model, data, db): obj = Model(**data) if ((obj.pk is None) and hasattr(Model, 'natural_key') and hasattr(Model._default_manager, 'get_by_natural_key')): natural_key = obj.natural_key() try: obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*natural_key).pk except Model.DoesNotExist: pass return obj
[ "def", "build_instance", "(", "Model", ",", "data", ",", "db", ")", ":", "obj", "=", "Model", "(", "**", "data", ")", "if", "(", "(", "obj", ".", "pk", "is", "None", ")", "and", "hasattr", "(", "Model", ",", "'natural_key'", ")", "and", "hasattr", "(", "Model", ".", "_default_manager", ",", "'get_by_natural_key'", ")", ")", ":", "natural_key", "=", "obj", ".", "natural_key", "(", ")", "try", ":", "obj", ".", "pk", "=", "Model", ".", "_default_manager", ".", "db_manager", "(", "db", ")", ".", "get_by_natural_key", "(", "*", "natural_key", ")", ".", "pk", "except", "Model", ".", "DoesNotExist", ":", "pass", "return", "obj" ]
build a model instance .
train
false
17,914
def c_moves_s(client): return 'south'
[ "def", "c_moves_s", "(", "client", ")", ":", "return", "'south'" ]
move through south exit if available .
train
false
17,918
def extract_regex(regex, text, encoding='utf-8'): if isinstance(regex, basestring): regex = re.compile(regex) try: strings = [regex.search(text).group('extract')] except: strings = regex.findall(text) strings = flatten(strings) if isinstance(text, unicode): return [remove_entities(s, keep=['lt', 'amp']) for s in strings] else: return [remove_entities(unicode(s, encoding), keep=['lt', 'amp']) for s in strings]
[ "def", "extract_regex", "(", "regex", ",", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "regex", ",", "basestring", ")", ":", "regex", "=", "re", ".", "compile", "(", "regex", ")", "try", ":", "strings", "=", "[", "regex", ".", "search", "(", "text", ")", ".", "group", "(", "'extract'", ")", "]", "except", ":", "strings", "=", "regex", ".", "findall", "(", "text", ")", "strings", "=", "flatten", "(", "strings", ")", "if", "isinstance", "(", "text", ",", "unicode", ")", ":", "return", "[", "remove_entities", "(", "s", ",", "keep", "=", "[", "'lt'", ",", "'amp'", "]", ")", "for", "s", "in", "strings", "]", "else", ":", "return", "[", "remove_entities", "(", "unicode", "(", "s", ",", "encoding", ")", ",", "keep", "=", "[", "'lt'", ",", "'amp'", "]", ")", "for", "s", "in", "strings", "]" ]
extract a list of unicode strings from the given text/encoding using the following policies: * if the regex contains a named group called "extract" that will be returned * if the regex contains multiple numbered groups .
train
false
17,919
def generate_encryption_key(): return as_base64(os.urandom((AES_KEY_SIZE + HMAC_SIG_SIZE)))
[ "def", "generate_encryption_key", "(", ")", ":", "return", "as_base64", "(", "os", ".", "urandom", "(", "(", "AES_KEY_SIZE", "+", "HMAC_SIG_SIZE", ")", ")", ")" ]
generates a 256 bit aes encryption key and prints the base64 representation .
train
false
17,921
def p_parameter_declaration_1(t): pass
[ "def", "p_parameter_declaration_1", "(", "t", ")", ":", "pass" ]
parameter_declaration : declaration_specifiers declarator .
train
false
17,923
def cache_id_func(service): return partial(cache_id, service)
[ "def", "cache_id_func", "(", "service", ")", ":", "return", "partial", "(", "cache_id", ",", "service", ")" ]
returns a partial cache_id function for the provided service .
train
false
17,924
def get_clipboard_text_and_convert(paste_list=False): txt = GetClipboardText() if txt: if (paste_list and (' DCTB ' in txt)): (array, flag) = make_list_of_list(txt) if flag: txt = repr(array) else: txt = ('array(%s)' % repr(array)) txt = ''.join([c for c in txt if (c not in ' DCTB \r\n')]) return txt
[ "def", "get_clipboard_text_and_convert", "(", "paste_list", "=", "False", ")", ":", "txt", "=", "GetClipboardText", "(", ")", "if", "txt", ":", "if", "(", "paste_list", "and", "(", "' DCTB '", "in", "txt", ")", ")", ":", "(", "array", ",", "flag", ")", "=", "make_list_of_list", "(", "txt", ")", "if", "flag", ":", "txt", "=", "repr", "(", "array", ")", "else", ":", "txt", "=", "(", "'array(%s)'", "%", "repr", "(", "array", ")", ")", "txt", "=", "''", ".", "join", "(", "[", "c", "for", "c", "in", "txt", "if", "(", "c", "not", "in", "' DCTB \\r\\n'", ")", "]", ")", "return", "txt" ]
get txt from clipboard .
train
false
17,925
def stacklists(arg): if isinstance(arg, (tuple, list)): return stack(list(map(stacklists, arg))) else: return arg
[ "def", "stacklists", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "stack", "(", "list", "(", "map", "(", "stacklists", ",", "arg", ")", ")", ")", "else", ":", "return", "arg" ]
recursively stack lists of tensors to maintain similar structure .
train
false
17,926
def s3_auth_user_represent(id, row=None): if row: return row.email elif (not id): return current.messages['NONE'] db = current.db table = db.auth_user user = db((table.id == id)).select(table.email, limitby=(0, 1), cache=current.s3db.cache).first() try: return user.email except: return current.messages.UNKNOWN_OPT
[ "def", "s3_auth_user_represent", "(", "id", ",", "row", "=", "None", ")", ":", "if", "row", ":", "return", "row", ".", "email", "elif", "(", "not", "id", ")", ":", "return", "current", ".", "messages", "[", "'NONE'", "]", "db", "=", "current", ".", "db", "table", "=", "db", ".", "auth_user", "user", "=", "db", "(", "(", "table", ".", "id", "==", "id", ")", ")", ".", "select", "(", "table", ".", "email", ",", "limitby", "=", "(", "0", ",", "1", ")", ",", "cache", "=", "current", ".", "s3db", ".", "cache", ")", ".", "first", "(", ")", "try", ":", "return", "user", ".", "email", "except", ":", "return", "current", ".", "messages", ".", "UNKNOWN_OPT" ]
represent a user as their email address .
train
false
17,927
def _take(iter, num): out = [] for val in iter: out.append(val) num -= 1 if (num <= 0): break return out
[ "def", "_take", "(", "iter", ",", "num", ")", ":", "out", "=", "[", "]", "for", "val", "in", "iter", ":", "out", ".", "append", "(", "val", ")", "num", "-=", "1", "if", "(", "num", "<=", "0", ")", ":", "break", "return", "out" ]
return a list containing the first num values in iter .
train
false
17,929
@pytest.mark.django_db def test_service_provider_base_manager(): obj = CustomCarrier.objects.language('en').create(name='Car') found = ServiceProvider.base_objects.language('en').get(pk=obj.pk) assert (found.pk == obj.pk) assert (type(found) == ServiceProvider)
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_service_provider_base_manager", "(", ")", ":", "obj", "=", "CustomCarrier", ".", "objects", ".", "language", "(", "'en'", ")", ".", "create", "(", "name", "=", "'Car'", ")", "found", "=", "ServiceProvider", ".", "base_objects", ".", "language", "(", "'en'", ")", ".", "get", "(", "pk", "=", "obj", ".", "pk", ")", "assert", "(", "found", ".", "pk", "==", "obj", ".", "pk", ")", "assert", "(", "type", "(", "found", ")", "==", "ServiceProvider", ")" ]
base manager of serviceprovider is translatable .
train
false
17,930
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
17,931
def overlap(a, b): _check_steps(a, b) return ((a.stop >= b.start) and (b.stop >= a.start))
[ "def", "overlap", "(", "a", ",", "b", ")", ":", "_check_steps", "(", "a", ",", "b", ")", "return", "(", "(", "a", ".", "stop", ">=", "b", ".", "start", ")", "and", "(", "b", ".", "stop", ">=", "a", ".", "start", ")", ")" ]
check if two ranges overlap .
train
true
17,932
def run_config(path, source=None, config_name=None, config_data=None, config_data_source=None, script_parameters=None, salt_env='base'): ret = compile_config(path=path, source=source, config_name=config_name, config_data=config_data, config_data_source=config_data_source, script_parameters=script_parameters, salt_env=salt_env) if ret.get('Exists'): config_path = os.path.dirname(ret['FullName']) return apply_config(config_path) else: return False
[ "def", "run_config", "(", "path", ",", "source", "=", "None", ",", "config_name", "=", "None", ",", "config_data", "=", "None", ",", "config_data_source", "=", "None", ",", "script_parameters", "=", "None", ",", "salt_env", "=", "'base'", ")", ":", "ret", "=", "compile_config", "(", "path", "=", "path", ",", "source", "=", "source", ",", "config_name", "=", "config_name", ",", "config_data", "=", "config_data", ",", "config_data_source", "=", "config_data_source", ",", "script_parameters", "=", "script_parameters", ",", "salt_env", "=", "salt_env", ")", "if", "ret", ".", "get", "(", "'Exists'", ")", ":", "config_path", "=", "os", ".", "path", ".", "dirname", "(", "ret", "[", "'FullName'", "]", ")", "return", "apply_config", "(", "config_path", ")", "else", ":", "return", "False" ]
compile a dsc configuration in the form of a powershell script and apply it .
train
true
17,933
def get_admin_app_list(parser, token): tokens = token.contents.split() if (len(tokens) < 3): raise template.TemplateSyntaxError, ("'%s' tag requires two arguments" % tokens[0]) if (tokens[1] != 'as'): raise template.TemplateSyntaxError, ("First argument to '%s' tag must be 'as'" % tokens[0]) return AdminApplistNode(tokens[2])
[ "def", "get_admin_app_list", "(", "parser", ",", "token", ")", ":", "tokens", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "(", "len", "(", "tokens", ")", "<", "3", ")", ":", "raise", "template", ".", "TemplateSyntaxError", ",", "(", "\"'%s' tag requires two arguments\"", "%", "tokens", "[", "0", "]", ")", "if", "(", "tokens", "[", "1", "]", "!=", "'as'", ")", ":", "raise", "template", ".", "TemplateSyntaxError", ",", "(", "\"First argument to '%s' tag must be 'as'\"", "%", "tokens", "[", "0", "]", ")", "return", "AdminApplistNode", "(", "tokens", "[", "2", "]", ")" ]
returns a list of installed applications and models for which the current user has at least one permission .
train
false
17,934
def ascii85Decode(stream): n = b = 0 decodedStream = '' try: for c in stream: if (('!' <= c) and (c <= 'u')): n += 1 b = ((b * 85) + (ord(c) - 33)) if (n == 5): decodedStream += struct.pack('>L', b) n = b = 0 elif (c == 'z'): assert (n == 0) decodedStream += '\x00\x00\x00\x00' elif (c == '~'): if n: for _ in range((5 - n)): b = ((b * 85) + 84) decodedStream += struct.pack('>L', b)[:(n - 1)] break except: return ((-1), 'Unspecified error') return (0, decodedStream)
[ "def", "ascii85Decode", "(", "stream", ")", ":", "n", "=", "b", "=", "0", "decodedStream", "=", "''", "try", ":", "for", "c", "in", "stream", ":", "if", "(", "(", "'!'", "<=", "c", ")", "and", "(", "c", "<=", "'u'", ")", ")", ":", "n", "+=", "1", "b", "=", "(", "(", "b", "*", "85", ")", "+", "(", "ord", "(", "c", ")", "-", "33", ")", ")", "if", "(", "n", "==", "5", ")", ":", "decodedStream", "+=", "struct", ".", "pack", "(", "'>L'", ",", "b", ")", "n", "=", "b", "=", "0", "elif", "(", "c", "==", "'z'", ")", ":", "assert", "(", "n", "==", "0", ")", "decodedStream", "+=", "'\\x00\\x00\\x00\\x00'", "elif", "(", "c", "==", "'~'", ")", ":", "if", "n", ":", "for", "_", "in", "range", "(", "(", "5", "-", "n", ")", ")", ":", "b", "=", "(", "(", "b", "*", "85", ")", "+", "84", ")", "decodedStream", "+=", "struct", ".", "pack", "(", "'>L'", ",", "b", ")", "[", ":", "(", "n", "-", "1", ")", "]", "break", "except", ":", "return", "(", "(", "-", "1", ")", ",", "'Unspecified error'", ")", "return", "(", "0", ",", "decodedStream", ")" ]
method to decode streams using ascii85 .
train
false
17,938
def _get_compute_api_class_name(): cell_type = nova.cells.opts.get_cell_type() return CELL_TYPE_TO_CLS_NAME[cell_type]
[ "def", "_get_compute_api_class_name", "(", ")", ":", "cell_type", "=", "nova", ".", "cells", ".", "opts", ".", "get_cell_type", "(", ")", "return", "CELL_TYPE_TO_CLS_NAME", "[", "cell_type", "]" ]
returns the name of compute api class .
train
false