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
40,395
def list_runner_functions(*args, **kwargs): run_ = salt.runner.Runner(__opts__) if (not args): return sorted(run_.functions) names = set() for module in args: if (('*' in module) or ('.' in module)): for func in fnmatch.filter(run_.functions, module): names.add(func) else: moduledot = (module + '.') for func in run_.functions: if func.startswith(moduledot): names.add(func) return sorted(names)
[ "def", "list_runner_functions", "(", "*", "args", ",", "**", "kwargs", ")", ":", "run_", "=", "salt", ".", "runner", ".", "Runner", "(", "__opts__", ")", "if", "(", "not", "args", ")", ":", "return", "sorted", "(", "run_", ".", "functions", ")", "names", "=", "set", "(", ")", "for", "module", "in", "args", ":", "if", "(", "(", "'*'", "in", "module", ")", "or", "(", "'.'", "in", "module", ")", ")", ":", "for", "func", "in", "fnmatch", ".", "filter", "(", "run_", ".", "functions", ",", "module", ")", ":", "names", ".", "add", "(", "func", ")", "else", ":", "moduledot", "=", "(", "module", "+", "'.'", ")", "for", "func", "in", "run_", ".", "functions", ":", "if", "func", ".", "startswith", "(", "moduledot", ")", ":", "names", ".", "add", "(", "func", ")", "return", "sorted", "(", "names", ")" ]
list the functions for all runner modules .
train
true
40,396
def render_tag(tag, attrs=None, content=None, close=True): builder = u'<{tag}{attrs}>{content}' if (content or close): builder += u'</{tag}>' return format_html(builder, tag=tag, attrs=(mark_safe(flatatt(attrs)) if attrs else u''), content=text_value(content))
[ "def", "render_tag", "(", "tag", ",", "attrs", "=", "None", ",", "content", "=", "None", ",", "close", "=", "True", ")", ":", "builder", "=", "u'<{tag}{attrs}>{content}'", "if", "(", "content", "or", "close", ")", ":", "builder", "+=", "u'</{tag}>'", "return", "format_html", "(", "builder", ",", "tag", "=", "tag", ",", "attrs", "=", "(", "mark_safe", "(", "flatatt", "(", "attrs", ")", ")", "if", "attrs", "else", "u''", ")", ",", "content", "=", "text_value", "(", "content", ")", ")" ]
render a html tag .
train
false
40,398
def get_components_from_key(key): items = key.split(STRSEP) toolshed_base_url = items[0] repository_name = items[1] repository_owner = items[2] changeset_revision = items[3] if (len(items) == 5): prior_installation_required = items[4] return (toolshed_base_url, repository_name, repository_owner, changeset_revision, prior_installation_required) elif (len(items) == 6): prior_installation_required = items[4] only_if_compiling_contained_td = items[5] return (toolshed_base_url, repository_name, repository_owner, changeset_revision, prior_installation_required, only_if_compiling_contained_td) else: return (toolshed_base_url, repository_name, repository_owner, changeset_revision)
[ "def", "get_components_from_key", "(", "key", ")", ":", "items", "=", "key", ".", "split", "(", "STRSEP", ")", "toolshed_base_url", "=", "items", "[", "0", "]", "repository_name", "=", "items", "[", "1", "]", "repository_owner", "=", "items", "[", "2", "]", "changeset_revision", "=", "items", "[", "3", "]", "if", "(", "len", "(", "items", ")", "==", "5", ")", ":", "prior_installation_required", "=", "items", "[", "4", "]", "return", "(", "toolshed_base_url", ",", "repository_name", ",", "repository_owner", ",", "changeset_revision", ",", "prior_installation_required", ")", "elif", "(", "len", "(", "items", ")", "==", "6", ")", ":", "prior_installation_required", "=", "items", "[", "4", "]", "only_if_compiling_contained_td", "=", "items", "[", "5", "]", "return", "(", "toolshed_base_url", ",", "repository_name", ",", "repository_owner", ",", "changeset_revision", ",", "prior_installation_required", ",", "only_if_compiling_contained_td", ")", "else", ":", "return", "(", "toolshed_base_url", ",", "repository_name", ",", "repository_owner", ",", "changeset_revision", ")" ]
assumes tool shed is current tool shed since repository dependencies across tool sheds is not yet supported .
train
false
40,400
def _prequest(**headers): request = http.Request(DummyChannel(), None) for (k, v) in headers.iteritems(): request.requestHeaders.setRawHeaders(k, v) return request
[ "def", "_prequest", "(", "**", "headers", ")", ":", "request", "=", "http", ".", "Request", "(", "DummyChannel", "(", ")", ",", "None", ")", "for", "(", "k", ",", "v", ")", "in", "headers", ".", "iteritems", "(", ")", ":", "request", ".", "requestHeaders", ".", "setRawHeaders", "(", "k", ",", "v", ")", "return", "request" ]
make a request with the given request headers for the persistence tests .
train
false
40,402
def get_saml_provider(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: provider = conn.get_saml_provider(name) return provider['get_saml_provider_response']['get_saml_provider_result']['saml_metadata_document'] except boto.exception.BotoServerError as e: aws = __utils__['boto.get_error'](e) log.debug(aws) msg = 'Failed to get SAML provider document.' log.error(msg) return False
[ "def", "get_saml_provider", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "try", ":", "provider", "=", "conn", ".", "get_saml_provider", "(", "name", ")", "return", "provider", "[", "'get_saml_provider_response'", "]", "[", "'get_saml_provider_result'", "]", "[", "'saml_metadata_document'", "]", "except", "boto", ".", "exception", ".", "BotoServerError", "as", "e", ":", "aws", "=", "__utils__", "[", "'boto.get_error'", "]", "(", "e", ")", "log", ".", "debug", "(", "aws", ")", "msg", "=", "'Failed to get SAML provider document.'", "log", ".", "error", "(", "msg", ")", "return", "False" ]
get saml provider document .
train
true
40,403
def twitterlist(): t = Twitter(auth=authen()) try: g['list_action'] = g['stuff'].split()[0] except: show_lists(t) return action_ary = {'home': list_home, 'all_mem': list_members, 'all_sub': list_subscribers, 'add': list_add, 'rm': list_remove, 'sub': list_subscribe, 'unsub': list_unsubscribe, 'own': list_own, 'new': list_new, 'update': list_update, 'del': list_delete} try: return action_ary[g['list_action']](t) except: printNicely(red('Please try again.'))
[ "def", "twitterlist", "(", ")", ":", "t", "=", "Twitter", "(", "auth", "=", "authen", "(", ")", ")", "try", ":", "g", "[", "'list_action'", "]", "=", "g", "[", "'stuff'", "]", ".", "split", "(", ")", "[", "0", "]", "except", ":", "show_lists", "(", "t", ")", "return", "action_ary", "=", "{", "'home'", ":", "list_home", ",", "'all_mem'", ":", "list_members", ",", "'all_sub'", ":", "list_subscribers", ",", "'add'", ":", "list_add", ",", "'rm'", ":", "list_remove", ",", "'sub'", ":", "list_subscribe", ",", "'unsub'", ":", "list_unsubscribe", ",", "'own'", ":", "list_own", ",", "'new'", ":", "list_new", ",", "'update'", ":", "list_update", ",", "'del'", ":", "list_delete", "}", "try", ":", "return", "action_ary", "[", "g", "[", "'list_action'", "]", "]", "(", "t", ")", "except", ":", "printNicely", "(", "red", "(", "'Please try again.'", ")", ")" ]
twitters list .
train
false
40,404
def possibly_scored(usage_key): return (usage_key.block_type in _block_types_possibly_scored())
[ "def", "possibly_scored", "(", "usage_key", ")", ":", "return", "(", "usage_key", ".", "block_type", "in", "_block_types_possibly_scored", "(", ")", ")" ]
returns whether the given block could impact grading .
train
false
40,405
def req_item_in_shipment(shipment_item, shipment_type, req_items): shipment_item_table = ('inv_%s_item' % shipment_type) try: item_id = shipment_item[shipment_item_table].item_id except: item_id = shipment_item.inv_inv_item.item_id if (item_id in req_items): shipment_to_req_type = dict(recv='fulfil', send='transit') quantity_req_type = ('quantity_%s' % shipment_to_req_type[shipment_type]) req_item = req_items[item_id] req_item_id = req_item.id quantity = (req_item[quantity_req_type] + ((shipment_item[shipment_item_table].pack_quantity / req_item.pack_quantity) * shipment_item[shipment_item_table].quantity)) quantity = min(quantity, req_item.quantity) s3db.req_req_item[req_item_id] = {quantity_req_type: quantity} s3db[shipment_item_table][shipment_item[shipment_item_table].id] = dict(req_item_id=req_item_id) return (req_item.req_id, req_item.id) else: return (None, None)
[ "def", "req_item_in_shipment", "(", "shipment_item", ",", "shipment_type", ",", "req_items", ")", ":", "shipment_item_table", "=", "(", "'inv_%s_item'", "%", "shipment_type", ")", "try", ":", "item_id", "=", "shipment_item", "[", "shipment_item_table", "]", ".", "item_id", "except", ":", "item_id", "=", "shipment_item", ".", "inv_inv_item", ".", "item_id", "if", "(", "item_id", "in", "req_items", ")", ":", "shipment_to_req_type", "=", "dict", "(", "recv", "=", "'fulfil'", ",", "send", "=", "'transit'", ")", "quantity_req_type", "=", "(", "'quantity_%s'", "%", "shipment_to_req_type", "[", "shipment_type", "]", ")", "req_item", "=", "req_items", "[", "item_id", "]", "req_item_id", "=", "req_item", ".", "id", "quantity", "=", "(", "req_item", "[", "quantity_req_type", "]", "+", "(", "(", "shipment_item", "[", "shipment_item_table", "]", ".", "pack_quantity", "/", "req_item", ".", "pack_quantity", ")", "*", "shipment_item", "[", "shipment_item_table", "]", ".", "quantity", ")", ")", "quantity", "=", "min", "(", "quantity", ",", "req_item", ".", "quantity", ")", "s3db", ".", "req_req_item", "[", "req_item_id", "]", "=", "{", "quantity_req_type", ":", "quantity", "}", "s3db", "[", "shipment_item_table", "]", "[", "shipment_item", "[", "shipment_item_table", "]", ".", "id", "]", "=", "dict", "(", "req_item_id", "=", "req_item_id", ")", "return", "(", "req_item", ".", "req_id", ",", "req_item", ".", "id", ")", "else", ":", "return", "(", "None", ",", "None", ")" ]
checks if a shipment item is in a request and updates req_item and the shipment .
train
false
40,406
def urlencode_params(params): params = [(key, normalize_for_urlencode(val)) for (key, val) in params] return requests.utils.unquote_unreserved(urlencode(params))
[ "def", "urlencode_params", "(", "params", ")", ":", "params", "=", "[", "(", "key", ",", "normalize_for_urlencode", "(", "val", ")", ")", "for", "(", "key", ",", "val", ")", "in", "params", "]", "return", "requests", ".", "utils", ".", "unquote_unreserved", "(", "urlencode", "(", "params", ")", ")" ]
url encodes the parameters .
train
true
40,407
def _update(s, _lambda, P): k = min([j for j in range(s, len(_lambda)) if (_lambda[j] != 0)]) for r in range(len(_lambda)): if (r != k): P[r] = [(P[r][j] - ((P[k][j] * _lambda[r]) / _lambda[k])) for j in range(len(P[r]))] P[k] = [(P[k][j] / _lambda[k]) for j in range(len(P[k]))] (P[k], P[s]) = (P[s], P[k]) return P
[ "def", "_update", "(", "s", ",", "_lambda", ",", "P", ")", ":", "k", "=", "min", "(", "[", "j", "for", "j", "in", "range", "(", "s", ",", "len", "(", "_lambda", ")", ")", "if", "(", "_lambda", "[", "j", "]", "!=", "0", ")", "]", ")", "for", "r", "in", "range", "(", "len", "(", "_lambda", ")", ")", ":", "if", "(", "r", "!=", "k", ")", ":", "P", "[", "r", "]", "=", "[", "(", "P", "[", "r", "]", "[", "j", "]", "-", "(", "(", "P", "[", "k", "]", "[", "j", "]", "*", "_lambda", "[", "r", "]", ")", "/", "_lambda", "[", "k", "]", ")", ")", "for", "j", "in", "range", "(", "len", "(", "P", "[", "r", "]", ")", ")", "]", "P", "[", "k", "]", "=", "[", "(", "P", "[", "k", "]", "[", "j", "]", "/", "_lambda", "[", "k", "]", ")", "for", "j", "in", "range", "(", "len", "(", "P", "[", "k", "]", ")", ")", "]", "(", "P", "[", "k", "]", ",", "P", "[", "s", "]", ")", "=", "(", "P", "[", "s", "]", ",", "P", "[", "k", "]", ")", "return", "P" ]
update a specific dashboard .
train
false
40,408
def copy_file_to_dir_if_newer(sourcefile, destdir): destfile = os.path.join(destdir, os.path.basename(sourcefile)) try: desttime = modification_time(destfile) except OSError: safe_makedirs(destdir) else: if (not file_newer_than(sourcefile, desttime)): return shutil.copy2(sourcefile, destfile)
[ "def", "copy_file_to_dir_if_newer", "(", "sourcefile", ",", "destdir", ")", ":", "destfile", "=", "os", ".", "path", ".", "join", "(", "destdir", ",", "os", ".", "path", ".", "basename", "(", "sourcefile", ")", ")", "try", ":", "desttime", "=", "modification_time", "(", "destfile", ")", "except", "OSError", ":", "safe_makedirs", "(", "destdir", ")", "else", ":", "if", "(", "not", "file_newer_than", "(", "sourcefile", ",", "desttime", ")", ")", ":", "return", "shutil", ".", "copy2", "(", "sourcefile", ",", "destfile", ")" ]
copy file sourcefile to directory destdir .
train
false
40,410
def test_helmet(): base_dir = op.join(op.dirname(__file__), '..', 'io') fname_raw = op.join(base_dir, 'tests', 'data', 'test_raw.fif') fname_kit_raw = op.join(base_dir, 'kit', 'tests', 'data', 'test_bin_raw.fif') fname_bti_raw = op.join(base_dir, 'bti', 'tests', 'data', 'exported4D_linux_raw.fif') fname_ctf_raw = op.join(base_dir, 'tests', 'data', 'test_ctf_raw.fif') fname_trans = op.join(base_dir, 'tests', 'data', 'sample-audvis-raw-trans.txt') trans = _get_trans(fname_trans)[0] for fname in [fname_raw, fname_kit_raw, fname_bti_raw, fname_ctf_raw]: helmet = get_meg_helmet_surf(read_info(fname), trans) assert_equal(len(helmet['rr']), 304) assert_equal(len(helmet['rr']), len(helmet['nn']))
[ "def", "test_helmet", "(", ")", ":", "base_dir", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'io'", ")", "fname_raw", "=", "op", ".", "join", "(", "base_dir", ",", "'tests'", ",", "'data'", ",", "'test_raw.fif'", ")", "fname_kit_raw", "=", "op", ".", "join", "(", "base_dir", ",", "'kit'", ",", "'tests'", ",", "'data'", ",", "'test_bin_raw.fif'", ")", "fname_bti_raw", "=", "op", ".", "join", "(", "base_dir", ",", "'bti'", ",", "'tests'", ",", "'data'", ",", "'exported4D_linux_raw.fif'", ")", "fname_ctf_raw", "=", "op", ".", "join", "(", "base_dir", ",", "'tests'", ",", "'data'", ",", "'test_ctf_raw.fif'", ")", "fname_trans", "=", "op", ".", "join", "(", "base_dir", ",", "'tests'", ",", "'data'", ",", "'sample-audvis-raw-trans.txt'", ")", "trans", "=", "_get_trans", "(", "fname_trans", ")", "[", "0", "]", "for", "fname", "in", "[", "fname_raw", ",", "fname_kit_raw", ",", "fname_bti_raw", ",", "fname_ctf_raw", "]", ":", "helmet", "=", "get_meg_helmet_surf", "(", "read_info", "(", "fname", ")", ",", "trans", ")", "assert_equal", "(", "len", "(", "helmet", "[", "'rr'", "]", ")", ",", "304", ")", "assert_equal", "(", "len", "(", "helmet", "[", "'rr'", "]", ")", ",", "len", "(", "helmet", "[", "'nn'", "]", ")", ")" ]
test loading helmet surfaces .
train
false
40,412
def get_module_context(course, item): item_dict = {'location': unicode(item.location), 'display_name': item.display_name_with_default_escaped} if ((item.category == 'chapter') and item.get_parent()): course = item.get_parent() item_dict['index'] = get_index(item_dict['location'], course.children) elif (item.category == 'vertical'): section = item.get_parent() chapter = section.get_parent() position = (get_index(unicode(item.location), section.children) + 1) item_dict['url'] = reverse('courseware_position', kwargs={'course_id': unicode(course.id), 'chapter': chapter.url_name, 'section': section.url_name, 'position': position}) if (item.category in ('chapter', 'sequential')): item_dict['children'] = [unicode(child) for child in item.children] return item_dict
[ "def", "get_module_context", "(", "course", ",", "item", ")", ":", "item_dict", "=", "{", "'location'", ":", "unicode", "(", "item", ".", "location", ")", ",", "'display_name'", ":", "item", ".", "display_name_with_default_escaped", "}", "if", "(", "(", "item", ".", "category", "==", "'chapter'", ")", "and", "item", ".", "get_parent", "(", ")", ")", ":", "course", "=", "item", ".", "get_parent", "(", ")", "item_dict", "[", "'index'", "]", "=", "get_index", "(", "item_dict", "[", "'location'", "]", ",", "course", ".", "children", ")", "elif", "(", "item", ".", "category", "==", "'vertical'", ")", ":", "section", "=", "item", ".", "get_parent", "(", ")", "chapter", "=", "section", ".", "get_parent", "(", ")", "position", "=", "(", "get_index", "(", "unicode", "(", "item", ".", "location", ")", ",", "section", ".", "children", ")", "+", "1", ")", "item_dict", "[", "'url'", "]", "=", "reverse", "(", "'courseware_position'", ",", "kwargs", "=", "{", "'course_id'", ":", "unicode", "(", "course", ".", "id", ")", ",", "'chapter'", ":", "chapter", ".", "url_name", ",", "'section'", ":", "section", ".", "url_name", ",", "'position'", ":", "position", "}", ")", "if", "(", "item", ".", "category", "in", "(", "'chapter'", ",", "'sequential'", ")", ")", ":", "item_dict", "[", "'children'", "]", "=", "[", "unicode", "(", "child", ")", "for", "child", "in", "item", ".", "children", "]", "return", "item_dict" ]
returns dispay_name and url for the parent module .
train
false
40,415
def invalidate_certificate(request, generated_certificate, certificate_invalidation_data): if (len(CertificateInvalidation.get_certificate_invalidations(generated_certificate.course_id, generated_certificate.user)) > 0): raise ValueError(_('Certificate of {user} has already been invalidated. Please check your spelling and retry.').format(user=generated_certificate.user.username)) if (not generated_certificate.is_valid()): raise ValueError(_('Certificate for student {user} is already invalid, kindly verify that certificate was generated for this student and then proceed.').format(user=generated_certificate.user.username)) (certificate_invalidation, __) = CertificateInvalidation.objects.update_or_create(generated_certificate=generated_certificate, defaults={'invalidated_by': request.user, 'notes': certificate_invalidation_data.get('notes', ''), 'active': True}) generated_certificate.invalidate() return {'id': certificate_invalidation.id, 'user': certificate_invalidation.generated_certificate.user.username, 'invalidated_by': certificate_invalidation.invalidated_by.username, 'created': certificate_invalidation.created.strftime('%B %d, %Y'), 'notes': certificate_invalidation.notes}
[ "def", "invalidate_certificate", "(", "request", ",", "generated_certificate", ",", "certificate_invalidation_data", ")", ":", "if", "(", "len", "(", "CertificateInvalidation", ".", "get_certificate_invalidations", "(", "generated_certificate", ".", "course_id", ",", "generated_certificate", ".", "user", ")", ")", ">", "0", ")", ":", "raise", "ValueError", "(", "_", "(", "'Certificate of {user} has already been invalidated. Please check your spelling and retry.'", ")", ".", "format", "(", "user", "=", "generated_certificate", ".", "user", ".", "username", ")", ")", "if", "(", "not", "generated_certificate", ".", "is_valid", "(", ")", ")", ":", "raise", "ValueError", "(", "_", "(", "'Certificate for student {user} is already invalid, kindly verify that certificate was generated for this student and then proceed.'", ")", ".", "format", "(", "user", "=", "generated_certificate", ".", "user", ".", "username", ")", ")", "(", "certificate_invalidation", ",", "__", ")", "=", "CertificateInvalidation", ".", "objects", ".", "update_or_create", "(", "generated_certificate", "=", "generated_certificate", ",", "defaults", "=", "{", "'invalidated_by'", ":", "request", ".", "user", ",", "'notes'", ":", "certificate_invalidation_data", ".", "get", "(", "'notes'", ",", "''", ")", ",", "'active'", ":", "True", "}", ")", "generated_certificate", ".", "invalidate", "(", ")", "return", "{", "'id'", ":", "certificate_invalidation", ".", "id", ",", "'user'", ":", "certificate_invalidation", ".", "generated_certificate", ".", "user", ".", "username", ",", "'invalidated_by'", ":", "certificate_invalidation", ".", "invalidated_by", ".", "username", ",", "'created'", ":", "certificate_invalidation", ".", "created", ".", "strftime", "(", "'%B %d, %Y'", ")", ",", "'notes'", ":", "certificate_invalidation", ".", "notes", "}" ]
invalidate given generatedcertificate and add certificateinvalidation record for future reference or re-validation .
train
false
40,416
def test_settings_clean_revert(): env.modified = 'outer' env.notmodified = 'outer' with settings(modified='inner', notmodified='inner', inner_only='only', clean_revert=True): eq_(env.modified, 'inner') eq_(env.notmodified, 'inner') eq_(env.inner_only, 'only') env.modified = 'modified internally' eq_(env.modified, 'modified internally') ok_(('inner_only' not in env))
[ "def", "test_settings_clean_revert", "(", ")", ":", "env", ".", "modified", "=", "'outer'", "env", ".", "notmodified", "=", "'outer'", "with", "settings", "(", "modified", "=", "'inner'", ",", "notmodified", "=", "'inner'", ",", "inner_only", "=", "'only'", ",", "clean_revert", "=", "True", ")", ":", "eq_", "(", "env", ".", "modified", ",", "'inner'", ")", "eq_", "(", "env", ".", "notmodified", ",", "'inner'", ")", "eq_", "(", "env", ".", "inner_only", ",", "'only'", ")", "env", ".", "modified", "=", "'modified internally'", "eq_", "(", "env", ".", "modified", ",", "'modified internally'", ")", "ok_", "(", "(", "'inner_only'", "not", "in", "env", ")", ")" ]
settings should only revert values matching input values .
train
false
40,417
def int_to_Integer(s): from tokenize import generate_tokens, untokenize, NUMBER, NAME, OP from sympy.core.compatibility import StringIO def _is_int(num): '\n Returns true if string value num (with token NUMBER) represents an integer.\n ' if (('.' in num) or ('j' in num.lower()) or ('e' in num.lower())): return False return True result = [] g = generate_tokens(StringIO(s).readline) for (toknum, tokval, _, _, _) in g: if ((toknum == NUMBER) and _is_int(tokval)): result.extend([(NAME, 'Integer'), (OP, '('), (NUMBER, tokval), (OP, ')')]) else: result.append((toknum, tokval)) return untokenize(result)
[ "def", "int_to_Integer", "(", "s", ")", ":", "from", "tokenize", "import", "generate_tokens", ",", "untokenize", ",", "NUMBER", ",", "NAME", ",", "OP", "from", "sympy", ".", "core", ".", "compatibility", "import", "StringIO", "def", "_is_int", "(", "num", ")", ":", "if", "(", "(", "'.'", "in", "num", ")", "or", "(", "'j'", "in", "num", ".", "lower", "(", ")", ")", "or", "(", "'e'", "in", "num", ".", "lower", "(", ")", ")", ")", ":", "return", "False", "return", "True", "result", "=", "[", "]", "g", "=", "generate_tokens", "(", "StringIO", "(", "s", ")", ".", "readline", ")", "for", "(", "toknum", ",", "tokval", ",", "_", ",", "_", ",", "_", ")", "in", "g", ":", "if", "(", "(", "toknum", "==", "NUMBER", ")", "and", "_is_int", "(", "tokval", ")", ")", ":", "result", ".", "extend", "(", "[", "(", "NAME", ",", "'Integer'", ")", ",", "(", "OP", ",", "'('", ")", ",", "(", "NUMBER", ",", "tokval", ")", ",", "(", "OP", ",", "')'", ")", "]", ")", "else", ":", "result", ".", "append", "(", "(", "toknum", ",", "tokval", ")", ")", "return", "untokenize", "(", "result", ")" ]
wrap integer literals with integer .
train
false
40,418
def delete_pid_file_if_exists(program_name, pid_files_dir=None): pidfile_path = get_pid_path(program_name, pid_files_dir) try: os.remove(pidfile_path) except OSError: if (not os.path.exists(pidfile_path)): return raise
[ "def", "delete_pid_file_if_exists", "(", "program_name", ",", "pid_files_dir", "=", "None", ")", ":", "pidfile_path", "=", "get_pid_path", "(", "program_name", ",", "pid_files_dir", ")", "try", ":", "os", ".", "remove", "(", "pidfile_path", ")", "except", "OSError", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "pidfile_path", ")", ")", ":", "return", "raise" ]
tries to remove <program_name> .
train
false
40,420
def monitor_except_format_assert(logical_line): if logical_line.startswith('self.assertRaises(Exception'): (yield (1, 'ENERGY N202: assertRaises Exception too broad'))
[ "def", "monitor_except_format_assert", "(", "logical_line", ")", ":", "if", "logical_line", ".", "startswith", "(", "'self.assertRaises(Exception'", ")", ":", "(", "yield", "(", "1", ",", "'ENERGY N202: assertRaises Exception too broad'", ")", ")" ]
check for assertraises(exception .
train
false
40,421
def _create_file(content=''): sjson_file = tempfile.NamedTemporaryFile(prefix='subs_', suffix='.srt.sjson') sjson_file.content_type = 'application/json' sjson_file.write(textwrap.dedent(content)) sjson_file.seek(0) return sjson_file
[ "def", "_create_file", "(", "content", "=", "''", ")", ":", "sjson_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "prefix", "=", "'subs_'", ",", "suffix", "=", "'.srt.sjson'", ")", "sjson_file", ".", "content_type", "=", "'application/json'", "sjson_file", ".", "write", "(", "textwrap", ".", "dedent", "(", "content", ")", ")", "sjson_file", ".", "seek", "(", "0", ")", "return", "sjson_file" ]
create temporary subs_somevalue .
train
false
40,422
def insert_meta_param_description(*args, **kwargs): if (not args): return (lambda f: insert_meta_param_description(f, **kwargs)) f = args[0] if f.__doc__: indent = (' ' * kwargs.get('pad', 8)) body = textwrap.wrap(_META_DESCRIPTION, initial_indent=indent, subsequent_indent=indent, width=78) descr = '{0}\n{1}'.format(_META_TYPES, '\n'.join(body)) f.__doc__ = f.__doc__.replace('$META', descr) return f
[ "def", "insert_meta_param_description", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "not", "args", ")", ":", "return", "(", "lambda", "f", ":", "insert_meta_param_description", "(", "f", ",", "**", "kwargs", ")", ")", "f", "=", "args", "[", "0", "]", "if", "f", ".", "__doc__", ":", "indent", "=", "(", "' '", "*", "kwargs", ".", "get", "(", "'pad'", ",", "8", ")", ")", "body", "=", "textwrap", ".", "wrap", "(", "_META_DESCRIPTION", ",", "initial_indent", "=", "indent", ",", "subsequent_indent", "=", "indent", ",", "width", "=", "78", ")", "descr", "=", "'{0}\\n{1}'", ".", "format", "(", "_META_TYPES", ",", "'\\n'", ".", "join", "(", "body", ")", ")", "f", ".", "__doc__", "=", "f", ".", "__doc__", ".", "replace", "(", "'$META'", ",", "descr", ")", "return", "f" ]
replace $meta in docstring with param description .
train
false
40,423
def generate_model(root_class=ROOT_CLASS): classes_result = {} result = {u'root': fqpn(root_class), u'classes': classes_result} classes = {root_class} while classes: klass = classes.pop() klass_name = fqpn(klass) if (klass_name in classes_result): continue if issubclass(klass, (PRecord, PClass)): to_model = _precord_model elif issubclass(klass, CheckedPMap): to_model = _pmap_model elif issubclass(klass, (CheckedPSet, CheckedPVector)): to_model = _psequence_model else: to_model = _default_model (record, further_classes) = to_model(klass) classes_result[klass_name] = record classes |= further_classes return result
[ "def", "generate_model", "(", "root_class", "=", "ROOT_CLASS", ")", ":", "classes_result", "=", "{", "}", "result", "=", "{", "u'root'", ":", "fqpn", "(", "root_class", ")", ",", "u'classes'", ":", "classes_result", "}", "classes", "=", "{", "root_class", "}", "while", "classes", ":", "klass", "=", "classes", ".", "pop", "(", ")", "klass_name", "=", "fqpn", "(", "klass", ")", "if", "(", "klass_name", "in", "classes_result", ")", ":", "continue", "if", "issubclass", "(", "klass", ",", "(", "PRecord", ",", "PClass", ")", ")", ":", "to_model", "=", "_precord_model", "elif", "issubclass", "(", "klass", ",", "CheckedPMap", ")", ":", "to_model", "=", "_pmap_model", "elif", "issubclass", "(", "klass", ",", "(", "CheckedPSet", ",", "CheckedPVector", ")", ")", ":", "to_model", "=", "_psequence_model", "else", ":", "to_model", "=", "_default_model", "(", "record", ",", "further_classes", ")", "=", "to_model", "(", "klass", ")", "classes_result", "[", "klass_name", "]", "=", "record", "classes", "|=", "further_classes", "return", "result" ]
generate a data-structure that represents the current configuration model .
train
false
40,424
def ExpandWindowsUserEnvironmentVariables(data_string, knowledge_base, sid=None, username=None): win_environ_regex = re.compile('%([^%]+?)%') components = [] offset = 0 for match in win_environ_regex.finditer(data_string): components.append(data_string[offset:match.start()]) kb_user = knowledge_base.GetUser(sid=sid, username=username) kb_value = None if kb_user: kb_value = getattr(kb_user, match.group(1).lower(), None) if (isinstance(kb_value, basestring) and kb_value): components.append(kb_value) else: components.append(('%%%s%%' % match.group(1))) offset = match.end() components.append(data_string[offset:]) return ''.join(components)
[ "def", "ExpandWindowsUserEnvironmentVariables", "(", "data_string", ",", "knowledge_base", ",", "sid", "=", "None", ",", "username", "=", "None", ")", ":", "win_environ_regex", "=", "re", ".", "compile", "(", "'%([^%]+?)%'", ")", "components", "=", "[", "]", "offset", "=", "0", "for", "match", "in", "win_environ_regex", ".", "finditer", "(", "data_string", ")", ":", "components", ".", "append", "(", "data_string", "[", "offset", ":", "match", ".", "start", "(", ")", "]", ")", "kb_user", "=", "knowledge_base", ".", "GetUser", "(", "sid", "=", "sid", ",", "username", "=", "username", ")", "kb_value", "=", "None", "if", "kb_user", ":", "kb_value", "=", "getattr", "(", "kb_user", ",", "match", ".", "group", "(", "1", ")", ".", "lower", "(", ")", ",", "None", ")", "if", "(", "isinstance", "(", "kb_value", ",", "basestring", ")", "and", "kb_value", ")", ":", "components", ".", "append", "(", "kb_value", ")", "else", ":", "components", ".", "append", "(", "(", "'%%%s%%'", "%", "match", ".", "group", "(", "1", ")", ")", ")", "offset", "=", "match", ".", "end", "(", ")", "components", ".", "append", "(", "data_string", "[", "offset", ":", "]", ")", "return", "''", ".", "join", "(", "components", ")" ]
take a string and expand windows user environment variables based .
train
true
40,425
def fixup_ins_del_tags(html): doc = parse_html(html, cleanup=False) _fixup_ins_del_tags(doc) html = serialize_html_fragment(doc, skip_outer=True) return html
[ "def", "fixup_ins_del_tags", "(", "html", ")", ":", "doc", "=", "parse_html", "(", "html", ",", "cleanup", "=", "False", ")", "_fixup_ins_del_tags", "(", "doc", ")", "html", "=", "serialize_html_fragment", "(", "doc", ",", "skip_outer", "=", "True", ")", "return", "html" ]
given an html string .
train
true
40,426
def post_account(url, token, headers, http_conn=None, response_dict=None, service_token=None, query_string=None, data=None): if http_conn: (parsed, conn) = http_conn else: (parsed, conn) = http_connection(url) method = 'POST' path = parsed.path if query_string: path += ('?' + query_string) headers['X-Auth-Token'] = token if service_token: headers['X-Service-Token'] = service_token conn.request(method, path, data, headers) resp = conn.getresponse() body = resp.read() http_log((url, method), {'headers': headers}, resp, body) store_response(resp, response_dict) if ((resp.status < 200) or (resp.status >= 300)): raise ClientException.from_response(resp, 'Account POST failed', body) resp_headers = {} for (header, value) in resp.getheaders(): resp_headers[header.lower()] = value return (resp_headers, body)
[ "def", "post_account", "(", "url", ",", "token", ",", "headers", ",", "http_conn", "=", "None", ",", "response_dict", "=", "None", ",", "service_token", "=", "None", ",", "query_string", "=", "None", ",", "data", "=", "None", ")", ":", "if", "http_conn", ":", "(", "parsed", ",", "conn", ")", "=", "http_conn", "else", ":", "(", "parsed", ",", "conn", ")", "=", "http_connection", "(", "url", ")", "method", "=", "'POST'", "path", "=", "parsed", ".", "path", "if", "query_string", ":", "path", "+=", "(", "'?'", "+", "query_string", ")", "headers", "[", "'X-Auth-Token'", "]", "=", "token", "if", "service_token", ":", "headers", "[", "'X-Service-Token'", "]", "=", "service_token", "conn", ".", "request", "(", "method", ",", "path", ",", "data", ",", "headers", ")", "resp", "=", "conn", ".", "getresponse", "(", ")", "body", "=", "resp", ".", "read", "(", ")", "http_log", "(", "(", "url", ",", "method", ")", ",", "{", "'headers'", ":", "headers", "}", ",", "resp", ",", "body", ")", "store_response", "(", "resp", ",", "response_dict", ")", "if", "(", "(", "resp", ".", "status", "<", "200", ")", "or", "(", "resp", ".", "status", ">=", "300", ")", ")", ":", "raise", "ClientException", ".", "from_response", "(", "resp", ",", "'Account POST failed'", ",", "body", ")", "resp_headers", "=", "{", "}", "for", "(", "header", ",", "value", ")", "in", "resp", ".", "getheaders", "(", ")", ":", "resp_headers", "[", "header", ".", "lower", "(", ")", "]", "=", "value", "return", "(", "resp_headers", ",", "body", ")" ]
update an accounts metadata .
train
false
40,428
def service_cgconfig_control(action): actions = ['start', 'stop', 'restart', 'condrestart'] if (action in actions): try: utils.run(('service cgconfig %s' % action)) logging.debug('%s cgconfig successfully', action) return True except error.CmdError as detail: logging.error('Failed to %s cgconfig:\n%s', action, detail) return False elif ((action == 'status') or (action == 'exists')): cmd_result = utils.run('service cgconfig status', ignore_status=True) if (action == 'exists'): if cmd_result.exit_status: return False else: return True if (((not cmd_result.exit_status) and cmd_result.stdout.strip()) == 'Running'): logging.info('Cgconfig service is running') return True else: return False else: raise error.TestError(('Unknown action: %s' % action))
[ "def", "service_cgconfig_control", "(", "action", ")", ":", "actions", "=", "[", "'start'", ",", "'stop'", ",", "'restart'", ",", "'condrestart'", "]", "if", "(", "action", "in", "actions", ")", ":", "try", ":", "utils", ".", "run", "(", "(", "'service cgconfig %s'", "%", "action", ")", ")", "logging", ".", "debug", "(", "'%s cgconfig successfully'", ",", "action", ")", "return", "True", "except", "error", ".", "CmdError", "as", "detail", ":", "logging", ".", "error", "(", "'Failed to %s cgconfig:\\n%s'", ",", "action", ",", "detail", ")", "return", "False", "elif", "(", "(", "action", "==", "'status'", ")", "or", "(", "action", "==", "'exists'", ")", ")", ":", "cmd_result", "=", "utils", ".", "run", "(", "'service cgconfig status'", ",", "ignore_status", "=", "True", ")", "if", "(", "action", "==", "'exists'", ")", ":", "if", "cmd_result", ".", "exit_status", ":", "return", "False", "else", ":", "return", "True", "if", "(", "(", "(", "not", "cmd_result", ".", "exit_status", ")", "and", "cmd_result", ".", "stdout", ".", "strip", "(", ")", ")", "==", "'Running'", ")", ":", "logging", ".", "info", "(", "'Cgconfig service is running'", ")", "return", "True", "else", ":", "return", "False", "else", ":", "raise", "error", ".", "TestError", "(", "(", "'Unknown action: %s'", "%", "action", ")", ")" ]
cgconfig control by action .
train
false
40,429
@lru_cache() def physical_memory(): (start_time, parameter) = (time.time(), 'system physical memory') mem_total_line = _get_line('/proc/meminfo', 'MemTotal:', parameter) try: result = (int(mem_total_line.split()[1]) * 1024) _log_runtime(parameter, '/proc/meminfo[MemTotal]', start_time) return result except: exc = IOError(('unable to parse the /proc/meminfo MemTotal entry: %s' % mem_total_line)) _log_failure(parameter, exc) raise exc
[ "@", "lru_cache", "(", ")", "def", "physical_memory", "(", ")", ":", "(", "start_time", ",", "parameter", ")", "=", "(", "time", ".", "time", "(", ")", ",", "'system physical memory'", ")", "mem_total_line", "=", "_get_line", "(", "'/proc/meminfo'", ",", "'MemTotal:'", ",", "parameter", ")", "try", ":", "result", "=", "(", "int", "(", "mem_total_line", ".", "split", "(", ")", "[", "1", "]", ")", "*", "1024", ")", "_log_runtime", "(", "parameter", ",", "'/proc/meminfo[MemTotal]'", ",", "start_time", ")", "return", "result", "except", ":", "exc", "=", "IOError", "(", "(", "'unable to parse the /proc/meminfo MemTotal entry: %s'", "%", "mem_total_line", ")", ")", "_log_failure", "(", "parameter", ",", "exc", ")", "raise", "exc" ]
provides the total physical memory on the system in bytes .
train
false
40,430
def floor(x): return Floor()(x)
[ "def", "floor", "(", "x", ")", ":", "return", "Floor", "(", ")", "(", "x", ")" ]
evaluates the floor of an interval .
train
false
40,431
def get_selected_option_text(select_browser_query): def get_option(query): ' Get the first select element that matches the query and return its value. ' try: select = Select(query.first.results[0]) return (True, select.first_selected_option.text) except StaleElementReferenceException: return (False, None) text = Promise((lambda : get_option(select_browser_query)), 'Retrieved selected option text').fulfill() return text
[ "def", "get_selected_option_text", "(", "select_browser_query", ")", ":", "def", "get_option", "(", "query", ")", ":", "try", ":", "select", "=", "Select", "(", "query", ".", "first", ".", "results", "[", "0", "]", ")", "return", "(", "True", ",", "select", ".", "first_selected_option", ".", "text", ")", "except", "StaleElementReferenceException", ":", "return", "(", "False", ",", "None", ")", "text", "=", "Promise", "(", "(", "lambda", ":", "get_option", "(", "select_browser_query", ")", ")", ",", "'Retrieved selected option text'", ")", ".", "fulfill", "(", ")", "return", "text" ]
returns the text value for the first selected option within a select .
train
false
40,432
def make_matrix(): raise NotImplementedError('TODO: implement this function.')
[ "def", "make_matrix", "(", ")", ":", "raise", "NotImplementedError", "(", "'TODO: implement this function.'", ")" ]
returns a new theano matrix .
train
false
40,433
@cli.command('paste') @click.option('-l', '--left', default=0, help='Offset from left.') @click.option('-r', '--right', default=0, help='Offset from right.') @processor def paste_cmd(images, left, right): imageiter = iter(images) image = next(imageiter, None) to_paste = next(imageiter, None) if (to_paste is None): if (image is not None): (yield image) return click.echo(('Paste "%s" on "%s"' % (to_paste.filename, image.filename))) mask = None if ((to_paste.mode == 'RGBA') or ('transparency' in to_paste.info)): mask = to_paste image.paste(to_paste, (left, right), mask) image.filename += ('+' + to_paste.filename) (yield image) for image in imageiter: (yield image)
[ "@", "cli", ".", "command", "(", "'paste'", ")", "@", "click", ".", "option", "(", "'-l'", ",", "'--left'", ",", "default", "=", "0", ",", "help", "=", "'Offset from left.'", ")", "@", "click", ".", "option", "(", "'-r'", ",", "'--right'", ",", "default", "=", "0", ",", "help", "=", "'Offset from right.'", ")", "@", "processor", "def", "paste_cmd", "(", "images", ",", "left", ",", "right", ")", ":", "imageiter", "=", "iter", "(", "images", ")", "image", "=", "next", "(", "imageiter", ",", "None", ")", "to_paste", "=", "next", "(", "imageiter", ",", "None", ")", "if", "(", "to_paste", "is", "None", ")", ":", "if", "(", "image", "is", "not", "None", ")", ":", "(", "yield", "image", ")", "return", "click", ".", "echo", "(", "(", "'Paste \"%s\" on \"%s\"'", "%", "(", "to_paste", ".", "filename", ",", "image", ".", "filename", ")", ")", ")", "mask", "=", "None", "if", "(", "(", "to_paste", ".", "mode", "==", "'RGBA'", ")", "or", "(", "'transparency'", "in", "to_paste", ".", "info", ")", ")", ":", "mask", "=", "to_paste", "image", ".", "paste", "(", "to_paste", ",", "(", "left", ",", "right", ")", ",", "mask", ")", "image", ".", "filename", "+=", "(", "'+'", "+", "to_paste", ".", "filename", ")", "(", "yield", "image", ")", "for", "image", "in", "imageiter", ":", "(", "yield", "image", ")" ]
pastes the second image on the first image and leaves the rest unchanged .
train
false
40,436
def _convert_codecs(template, byte_order): codecs = {} postfix = (((byte_order == '<') and '_le') or '_be') for (k, v) in template.items(): codec = v['codec'] try: ' '.encode(codec) except LookupError: codecs[k] = None continue if (v['width'] > 1): codec += postfix codecs[k] = codec return codecs.copy()
[ "def", "_convert_codecs", "(", "template", ",", "byte_order", ")", ":", "codecs", "=", "{", "}", "postfix", "=", "(", "(", "(", "byte_order", "==", "'<'", ")", "and", "'_le'", ")", "or", "'_be'", ")", "for", "(", "k", ",", "v", ")", "in", "template", ".", "items", "(", ")", ":", "codec", "=", "v", "[", "'codec'", "]", "try", ":", ".", "encode", "(", "codec", ")", "except", "LookupError", ":", "codecs", "[", "k", "]", "=", "None", "continue", "if", "(", "v", "[", "'width'", "]", ">", "1", ")", ":", "codec", "+=", "postfix", "codecs", "[", "k", "]", "=", "codec", "return", "codecs", ".", "copy", "(", ")" ]
convert codec template mapping to byte order set codecs not on this system to none parameters template : mapping key .
train
false
40,437
def _get_client(timeout=None): if ('docker.client' not in __context__): client_kwargs = {} for (key, val) in (('base_url', 'docker.url'), ('version', 'docker.version')): param = __salt__['config.get'](val, NOTSET) if (param is not NOTSET): client_kwargs[key] = param if (('base_url' not in client_kwargs) and ('DOCKER_HOST' in os.environ)): client_kwargs['base_url'] = os.environ.get('DOCKER_HOST') if ('version' not in client_kwargs): client_kwargs['version'] = 'auto' docker_machine = __salt__['config.get']('docker.machine', NOTSET) if (docker_machine is not NOTSET): docker_machine_json = __salt__['cmd.run'](('docker-machine inspect ' + docker_machine)) try: docker_machine_json = json.loads(docker_machine_json) docker_machine_tls = docker_machine_json['HostOptions']['AuthOptions'] docker_machine_ip = docker_machine_json['Driver']['IPAddress'] client_kwargs['base_url'] = (('https://' + docker_machine_ip) + ':2376') client_kwargs['tls'] = docker.tls.TLSConfig(client_cert=(docker_machine_tls['ClientCertPath'], docker_machine_tls['ClientKeyPath']), ca_cert=docker_machine_tls['CaCertPath'], assert_hostname=False, verify=True) except Exception as exc: raise CommandExecutionError('Docker machine {0} failed: {1}'.format(docker_machine, exc)) try: __context__['docker.client'] = docker.Client(**client_kwargs) except docker.errors.DockerException: log.error('Could not initialize Docker client') return False if ((timeout is not None) and (__context__['docker.client'].timeout != timeout)): __context__['docker.client'].timeout = timeout
[ "def", "_get_client", "(", "timeout", "=", "None", ")", ":", "if", "(", "'docker.client'", "not", "in", "__context__", ")", ":", "client_kwargs", "=", "{", "}", "for", "(", "key", ",", "val", ")", "in", "(", "(", "'base_url'", ",", "'docker.url'", ")", ",", "(", "'version'", ",", "'docker.version'", ")", ")", ":", "param", "=", "__salt__", "[", "'config.get'", "]", "(", "val", ",", "NOTSET", ")", "if", "(", "param", "is", "not", "NOTSET", ")", ":", "client_kwargs", "[", "key", "]", "=", "param", "if", "(", "(", "'base_url'", "not", "in", "client_kwargs", ")", "and", "(", "'DOCKER_HOST'", "in", "os", ".", "environ", ")", ")", ":", "client_kwargs", "[", "'base_url'", "]", "=", "os", ".", "environ", ".", "get", "(", "'DOCKER_HOST'", ")", "if", "(", "'version'", "not", "in", "client_kwargs", ")", ":", "client_kwargs", "[", "'version'", "]", "=", "'auto'", "docker_machine", "=", "__salt__", "[", "'config.get'", "]", "(", "'docker.machine'", ",", "NOTSET", ")", "if", "(", "docker_machine", "is", "not", "NOTSET", ")", ":", "docker_machine_json", "=", "__salt__", "[", "'cmd.run'", "]", "(", "(", "'docker-machine inspect '", "+", "docker_machine", ")", ")", "try", ":", "docker_machine_json", "=", "json", ".", "loads", "(", "docker_machine_json", ")", "docker_machine_tls", "=", "docker_machine_json", "[", "'HostOptions'", "]", "[", "'AuthOptions'", "]", "docker_machine_ip", "=", "docker_machine_json", "[", "'Driver'", "]", "[", "'IPAddress'", "]", "client_kwargs", "[", "'base_url'", "]", "=", "(", "(", "'https://'", "+", "docker_machine_ip", ")", "+", "':2376'", ")", "client_kwargs", "[", "'tls'", "]", "=", "docker", ".", "tls", ".", "TLSConfig", "(", "client_cert", "=", "(", "docker_machine_tls", "[", "'ClientCertPath'", "]", ",", "docker_machine_tls", "[", "'ClientKeyPath'", "]", ")", ",", "ca_cert", "=", "docker_machine_tls", "[", "'CaCertPath'", "]", ",", "assert_hostname", "=", "False", ",", "verify", "=", "True", ")", "except", "Exception", "as", "exc", ":", "raise", "CommandExecutionError", "(", "'Docker machine {0} failed: {1}'", ".", "format", "(", "docker_machine", ",", "exc", ")", ")", "try", ":", "__context__", "[", "'docker.client'", "]", "=", "docker", ".", "Client", "(", "**", "client_kwargs", ")", "except", "docker", ".", "errors", ".", "DockerException", ":", "log", ".", "error", "(", "'Could not initialize Docker client'", ")", "return", "False", "if", "(", "(", "timeout", "is", "not", "None", ")", "and", "(", "__context__", "[", "'docker.client'", "]", ".", "timeout", "!=", "timeout", ")", ")", ":", "__context__", "[", "'docker.client'", "]", ".", "timeout", "=", "timeout" ]
get a boto connection to data pipeline .
train
false
40,438
def libvlc_media_get_type(p_md): f = (_Cfunctions.get('libvlc_media_get_type', None) or _Cfunction('libvlc_media_get_type', ((1,),), None, MediaType, Media)) return f(p_md)
[ "def", "libvlc_media_get_type", "(", "p_md", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_get_type'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_get_type'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None", ",", "MediaType", ",", "Media", ")", ")", "return", "f", "(", "p_md", ")" ]
get the media type of the media descriptor object .
train
true
40,439
def dependency_check(): if (not pysftp): raise plugin.DependencyError(issued_by=u'sftp', missing=u'pysftp', message=u'sftp plugin requires the pysftp Python module.')
[ "def", "dependency_check", "(", ")", ":", "if", "(", "not", "pysftp", ")", ":", "raise", "plugin", ".", "DependencyError", "(", "issued_by", "=", "u'sftp'", ",", "missing", "=", "u'pysftp'", ",", "message", "=", "u'sftp plugin requires the pysftp Python module.'", ")" ]
this dependency check function uses the information stored in the platforms module to call the function in core .
train
false
40,441
def format_unit_match(unit, quality): return (unit.get_target_plurals()[0], quality, (u'Weblate (%s)' % force_text(unit.translation.subproject)), unit.get_source_plurals()[0])
[ "def", "format_unit_match", "(", "unit", ",", "quality", ")", ":", "return", "(", "unit", ".", "get_target_plurals", "(", ")", "[", "0", "]", ",", "quality", ",", "(", "u'Weblate (%s)'", "%", "force_text", "(", "unit", ".", "translation", ".", "subproject", ")", ")", ",", "unit", ".", "get_source_plurals", "(", ")", "[", "0", "]", ")" ]
formats unit to translation service result .
train
false
40,443
def create_user_contributions(user_id, created_exploration_ids, edited_exploration_ids): user_contributions = get_user_contributions(user_id, strict=False) if user_contributions: raise Exception(('User contributions model for user %s already exists.' % user_id)) else: user_contributions = UserContributions(user_id, created_exploration_ids, edited_exploration_ids) _save_user_contributions(user_contributions) return user_contributions
[ "def", "create_user_contributions", "(", "user_id", ",", "created_exploration_ids", ",", "edited_exploration_ids", ")", ":", "user_contributions", "=", "get_user_contributions", "(", "user_id", ",", "strict", "=", "False", ")", "if", "user_contributions", ":", "raise", "Exception", "(", "(", "'User contributions model for user %s already exists.'", "%", "user_id", ")", ")", "else", ":", "user_contributions", "=", "UserContributions", "(", "user_id", ",", "created_exploration_ids", ",", "edited_exploration_ids", ")", "_save_user_contributions", "(", "user_contributions", ")", "return", "user_contributions" ]
creates a new usercontributionsmodel and returns the domain object .
train
false
40,444
@depends(HAS_ESX_CLI) def enable_firewall_ruleset(host, username, password, ruleset_enable, ruleset_name, protocol=None, port=None, esxi_hosts=None): cmd = 'network firewall ruleset set --enabled {0} --ruleset-id={1}'.format(ruleset_enable, ruleset_name) ret = {} if esxi_hosts: if (not isinstance(esxi_hosts, list)): raise CommandExecutionError("'esxi_hosts' must be a list.") for esxi_host in esxi_hosts: response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port, esxi_host=esxi_host) ret.update({esxi_host: response}) else: response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port) ret.update({host: response}) return ret
[ "@", "depends", "(", "HAS_ESX_CLI", ")", "def", "enable_firewall_ruleset", "(", "host", ",", "username", ",", "password", ",", "ruleset_enable", ",", "ruleset_name", ",", "protocol", "=", "None", ",", "port", "=", "None", ",", "esxi_hosts", "=", "None", ")", ":", "cmd", "=", "'network firewall ruleset set --enabled {0} --ruleset-id={1}'", ".", "format", "(", "ruleset_enable", ",", "ruleset_name", ")", "ret", "=", "{", "}", "if", "esxi_hosts", ":", "if", "(", "not", "isinstance", "(", "esxi_hosts", ",", "list", ")", ")", ":", "raise", "CommandExecutionError", "(", "\"'esxi_hosts' must be a list.\"", ")", "for", "esxi_host", "in", "esxi_hosts", ":", "response", "=", "salt", ".", "utils", ".", "vmware", ".", "esxcli", "(", "host", ",", "username", ",", "password", ",", "cmd", ",", "protocol", "=", "protocol", ",", "port", "=", "port", ",", "esxi_host", "=", "esxi_host", ")", "ret", ".", "update", "(", "{", "esxi_host", ":", "response", "}", ")", "else", ":", "response", "=", "salt", ".", "utils", ".", "vmware", ".", "esxcli", "(", "host", ",", "username", ",", "password", ",", "cmd", ",", "protocol", "=", "protocol", ",", "port", "=", "port", ")", "ret", ".", "update", "(", "{", "host", ":", "response", "}", ")", "return", "ret" ]
enable or disable an esxi firewall rule set .
train
true
40,445
def postorder(graph, root): visited = set() order = [] def dfs_walk(node): visited.add(node) for succ in graph.successors(node): if (not (succ in visited)): dfs_walk(succ) order.append(node) dfs_walk(root) return order
[ "def", "postorder", "(", "graph", ",", "root", ")", ":", "visited", "=", "set", "(", ")", "order", "=", "[", "]", "def", "dfs_walk", "(", "node", ")", ":", "visited", ".", "add", "(", "node", ")", "for", "succ", "in", "graph", ".", "successors", "(", "node", ")", ":", "if", "(", "not", "(", "succ", "in", "visited", ")", ")", ":", "dfs_walk", "(", "succ", ")", "order", ".", "append", "(", "node", ")", "dfs_walk", "(", "root", ")", "return", "order" ]
return a post-order ordering of nodes in the graph .
train
false
40,447
def run_unittest(testclass, debug=0): suite = unittest.makeSuite(testclass) if debug: suite.debug() else: run_suite(suite, testclass)
[ "def", "run_unittest", "(", "testclass", ",", "debug", "=", "0", ")", ":", "suite", "=", "unittest", ".", "makeSuite", "(", "testclass", ")", "if", "debug", ":", "suite", ".", "debug", "(", ")", "else", ":", "run_suite", "(", "suite", ",", "testclass", ")" ]
run tests from a unittest .
train
false
40,449
def load_interface_driver(conf): try: loaded_class = neutron_utils.load_class_by_alias_or_classname(INTERFACE_NAMESPACE, conf.interface_driver) return loaded_class(conf) except ImportError: LOG.error(_LE("Error loading interface driver '%s'"), conf.interface_driver) raise SystemExit(1)
[ "def", "load_interface_driver", "(", "conf", ")", ":", "try", ":", "loaded_class", "=", "neutron_utils", ".", "load_class_by_alias_or_classname", "(", "INTERFACE_NAMESPACE", ",", "conf", ".", "interface_driver", ")", "return", "loaded_class", "(", "conf", ")", "except", "ImportError", ":", "LOG", ".", "error", "(", "_LE", "(", "\"Error loading interface driver '%s'\"", ")", ",", "conf", ".", "interface_driver", ")", "raise", "SystemExit", "(", "1", ")" ]
load interface driver for agents like dhcp or l3 agent .
train
false
40,452
def test_cons_replacing(): cons = HyCons('foo', 'bar') cons[0] = 'car' assert (cons == HyCons('car', 'bar')) cons[1:] = 'cdr' assert (cons == HyCons('car', 'cdr')) try: cons[:] = 'foo' assert (True is False) except IndexError: pass
[ "def", "test_cons_replacing", "(", ")", ":", "cons", "=", "HyCons", "(", "'foo'", ",", "'bar'", ")", "cons", "[", "0", "]", "=", "'car'", "assert", "(", "cons", "==", "HyCons", "(", "'car'", ",", "'bar'", ")", ")", "cons", "[", "1", ":", "]", "=", "'cdr'", "assert", "(", "cons", "==", "HyCons", "(", "'car'", ",", "'cdr'", ")", ")", "try", ":", "cons", "[", ":", "]", "=", "'foo'", "assert", "(", "True", "is", "False", ")", "except", "IndexError", ":", "pass" ]
check that assigning to a cons works as expected .
train
false
40,453
def lcim(numbers): result = None if all((num.is_irrational for num in numbers)): factorized_nums = list(map((lambda num: num.factor()), numbers)) factors_num = list(map((lambda num: num.as_coeff_Mul()), factorized_nums)) term = factors_num[0][1] if all(((factor == term) for (coeff, factor) in factors_num)): common_term = term coeffs = [coeff for (coeff, factor) in factors_num] result = (lcm_list(coeffs) * common_term) elif all((num.is_rational for num in numbers)): result = lcm_list(numbers) else: pass return result
[ "def", "lcim", "(", "numbers", ")", ":", "result", "=", "None", "if", "all", "(", "(", "num", ".", "is_irrational", "for", "num", "in", "numbers", ")", ")", ":", "factorized_nums", "=", "list", "(", "map", "(", "(", "lambda", "num", ":", "num", ".", "factor", "(", ")", ")", ",", "numbers", ")", ")", "factors_num", "=", "list", "(", "map", "(", "(", "lambda", "num", ":", "num", ".", "as_coeff_Mul", "(", ")", ")", ",", "factorized_nums", ")", ")", "term", "=", "factors_num", "[", "0", "]", "[", "1", "]", "if", "all", "(", "(", "(", "factor", "==", "term", ")", "for", "(", "coeff", ",", "factor", ")", "in", "factors_num", ")", ")", ":", "common_term", "=", "term", "coeffs", "=", "[", "coeff", "for", "(", "coeff", ",", "factor", ")", "in", "factors_num", "]", "result", "=", "(", "lcm_list", "(", "coeffs", ")", "*", "common_term", ")", "elif", "all", "(", "(", "num", ".", "is_rational", "for", "num", "in", "numbers", ")", ")", ":", "result", "=", "lcm_list", "(", "numbers", ")", "else", ":", "pass", "return", "result" ]
returns the least common integral multiple of a list of numbers .
train
false
40,454
def check_purchase(paykey): with statsd.timer('paypal.payment.details'): try: response = _call((settings.PAYPAL_PAY_URL + 'PaymentDetails'), {'payKey': paykey}) except PaypalError: paypal_log.error('Payment details error', exc_info=True) return False return response['status']
[ "def", "check_purchase", "(", "paykey", ")", ":", "with", "statsd", ".", "timer", "(", "'paypal.payment.details'", ")", ":", "try", ":", "response", "=", "_call", "(", "(", "settings", ".", "PAYPAL_PAY_URL", "+", "'PaymentDetails'", ")", ",", "{", "'payKey'", ":", "paykey", "}", ")", "except", "PaypalError", ":", "paypal_log", ".", "error", "(", "'Payment details error'", ",", "exc_info", "=", "True", ")", "return", "False", "return", "response", "[", "'status'", "]" ]
when a purchase is complete checks paypal that the purchase has gone through .
train
false
40,457
def get_bom(fn, compression=None): boms = set((codecs.BOM_UTF16, codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)) with open(fn, mode='rb', compression=compression) as f: f.seek(0) bom = f.read(2) f.seek(0) if (bom in boms): return bom else: return ''
[ "def", "get_bom", "(", "fn", ",", "compression", "=", "None", ")", ":", "boms", "=", "set", "(", "(", "codecs", ".", "BOM_UTF16", ",", "codecs", ".", "BOM_UTF16_BE", ",", "codecs", ".", "BOM_UTF16_LE", ")", ")", "with", "open", "(", "fn", ",", "mode", "=", "'rb'", ",", "compression", "=", "compression", ")", "as", "f", ":", "f", ".", "seek", "(", "0", ")", "bom", "=", "f", ".", "read", "(", "2", ")", "f", ".", "seek", "(", "0", ")", "if", "(", "bom", "in", "boms", ")", ":", "return", "bom", "else", ":", "return", "''" ]
get the byte order mark if it exists .
train
false
40,458
def map_view(request, mapid, snapshot=None, template='maps/map_view.html'): map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) if ('access_token' in request.session): access_token = request.session['access_token'] else: access_token = None if (snapshot is None): config = map_obj.viewer_json(request.user, access_token) else: config = snapshot_config(snapshot, map_obj, request.user, access_token) return render_to_response(template, RequestContext(request, {'config': json.dumps(config), 'map': map_obj, 'preview': getattr(settings, 'LAYER_PREVIEW_LIBRARY', '')}))
[ "def", "map_view", "(", "request", ",", "mapid", ",", "snapshot", "=", "None", ",", "template", "=", "'maps/map_view.html'", ")", ":", "map_obj", "=", "_resolve_map", "(", "request", ",", "mapid", ",", "'base.view_resourcebase'", ",", "_PERMISSION_MSG_VIEW", ")", "if", "(", "'access_token'", "in", "request", ".", "session", ")", ":", "access_token", "=", "request", ".", "session", "[", "'access_token'", "]", "else", ":", "access_token", "=", "None", "if", "(", "snapshot", "is", "None", ")", ":", "config", "=", "map_obj", ".", "viewer_json", "(", "request", ".", "user", ",", "access_token", ")", "else", ":", "config", "=", "snapshot_config", "(", "snapshot", ",", "map_obj", ",", "request", ".", "user", ",", "access_token", ")", "return", "render_to_response", "(", "template", ",", "RequestContext", "(", "request", ",", "{", "'config'", ":", "json", ".", "dumps", "(", "config", ")", ",", "'map'", ":", "map_obj", ",", "'preview'", ":", "getattr", "(", "settings", ",", "'LAYER_PREVIEW_LIBRARY'", ",", "''", ")", "}", ")", ")" ]
the view that returns the map composer opened to the map with the given map id .
train
false
40,459
def get_ctx_rev(app, tool_shed_url, name, owner, changeset_revision): tool_shed_url = common_util.get_tool_shed_url_from_tool_shed_registry(app, tool_shed_url) params = dict(name=name, owner=owner, changeset_revision=changeset_revision) pathspec = ['repository', 'get_ctx_rev'] ctx_rev = util.url_get(tool_shed_url, password_mgr=app.tool_shed_registry.url_auth(tool_shed_url), pathspec=pathspec, params=params) return ctx_rev
[ "def", "get_ctx_rev", "(", "app", ",", "tool_shed_url", ",", "name", ",", "owner", ",", "changeset_revision", ")", ":", "tool_shed_url", "=", "common_util", ".", "get_tool_shed_url_from_tool_shed_registry", "(", "app", ",", "tool_shed_url", ")", "params", "=", "dict", "(", "name", "=", "name", ",", "owner", "=", "owner", ",", "changeset_revision", "=", "changeset_revision", ")", "pathspec", "=", "[", "'repository'", ",", "'get_ctx_rev'", "]", "ctx_rev", "=", "util", ".", "url_get", "(", "tool_shed_url", ",", "password_mgr", "=", "app", ".", "tool_shed_registry", ".", "url_auth", "(", "tool_shed_url", ")", ",", "pathspec", "=", "pathspec", ",", "params", "=", "params", ")", "return", "ctx_rev" ]
send a request to the tool shed to retrieve the ctx_rev for a repository defined by the combination of a name .
train
false
40,460
@treeio_login_required @handle_response_format def currency_add(request, response_format='html'): if (not request.user.profile.is_admin('treeio.finance')): return user_denied(request, message="You don't have administrator access to the Finance module") if request.POST: if ('cancel' not in request.POST): currency = Currency() form = CurrencyForm(request.user.profile, request.POST, instance=currency) if form.is_valid(): currency = form.save(commit=False) cname = dict_currencies[currency.code] currency.name = cname[(cname.index(' ') + 2):] currency.save() currency.set_user_from_request(request) return HttpResponseRedirect(reverse('finance_currency_view', args=[currency.id])) else: return HttpResponseRedirect(reverse('finance_settings_view')) else: form = CurrencyForm(request.user.profile) return render_to_response('finance/currency_add', {'form': form}, context_instance=RequestContext(request), response_format=response_format)
[ "@", "treeio_login_required", "@", "handle_response_format", "def", "currency_add", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "if", "(", "not", "request", ".", "user", ".", "profile", ".", "is_admin", "(", "'treeio.finance'", ")", ")", ":", "return", "user_denied", "(", "request", ",", "message", "=", "\"You don't have administrator access to the Finance module\"", ")", "if", "request", ".", "POST", ":", "if", "(", "'cancel'", "not", "in", "request", ".", "POST", ")", ":", "currency", "=", "Currency", "(", ")", "form", "=", "CurrencyForm", "(", "request", ".", "user", ".", "profile", ",", "request", ".", "POST", ",", "instance", "=", "currency", ")", "if", "form", ".", "is_valid", "(", ")", ":", "currency", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "cname", "=", "dict_currencies", "[", "currency", ".", "code", "]", "currency", ".", "name", "=", "cname", "[", "(", "cname", ".", "index", "(", "' '", ")", "+", "2", ")", ":", "]", "currency", ".", "save", "(", ")", "currency", ".", "set_user_from_request", "(", "request", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'finance_currency_view'", ",", "args", "=", "[", "currency", ".", "id", "]", ")", ")", "else", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'finance_settings_view'", ")", ")", "else", ":", "form", "=", "CurrencyForm", "(", "request", ".", "user", ".", "profile", ")", "return", "render_to_response", "(", "'finance/currency_add'", ",", "{", "'form'", ":", "form", "}", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ",", "response_format", "=", "response_format", ")" ]
currency add .
train
false
40,461
def list_downloads(): outfiles = [] for (root, subFolder, files) in os.walk('/Library/Updates'): for f in files: outfiles.append(os.path.join(root, f)) dist_files = [] for f in outfiles: if f.endswith('.dist'): dist_files.append(f) ret = [] for update in _get_available(): for f in dist_files: with salt.utils.fopen(f) as fhr: if (update.rsplit('-', 1)[0] in fhr.read()): ret.append(update) return ret
[ "def", "list_downloads", "(", ")", ":", "outfiles", "=", "[", "]", "for", "(", "root", ",", "subFolder", ",", "files", ")", "in", "os", ".", "walk", "(", "'/Library/Updates'", ")", ":", "for", "f", "in", "files", ":", "outfiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", ")", "dist_files", "=", "[", "]", "for", "f", "in", "outfiles", ":", "if", "f", ".", "endswith", "(", "'.dist'", ")", ":", "dist_files", ".", "append", "(", "f", ")", "ret", "=", "[", "]", "for", "update", "in", "_get_available", "(", ")", ":", "for", "f", "in", "dist_files", ":", "with", "salt", ".", "utils", ".", "fopen", "(", "f", ")", "as", "fhr", ":", "if", "(", "update", ".", "rsplit", "(", "'-'", ",", "1", ")", "[", "0", "]", "in", "fhr", ".", "read", "(", ")", ")", ":", "ret", ".", "append", "(", "update", ")", "return", "ret" ]
return a list of all updates that have been downloaded locally .
train
true
40,463
@utils.arg('host', metavar='<hostname>', help=_('Name of host.')) @utils.arg('binary', metavar='<binary>', help=_('Service binary.')) @utils.arg('--reason', metavar='<reason>', help=_('Reason for disabling service.')) def do_service_disable(cs, args): if args.reason: result = cs.services.disable_log_reason(args.host, args.binary, args.reason) utils.print_list([result], ['Host', 'Binary', 'Status', 'Disabled Reason']) else: result = cs.services.disable(args.host, args.binary) utils.print_list([result], ['Host', 'Binary', 'Status'])
[ "@", "utils", ".", "arg", "(", "'host'", ",", "metavar", "=", "'<hostname>'", ",", "help", "=", "_", "(", "'Name of host.'", ")", ")", "@", "utils", ".", "arg", "(", "'binary'", ",", "metavar", "=", "'<binary>'", ",", "help", "=", "_", "(", "'Service binary.'", ")", ")", "@", "utils", ".", "arg", "(", "'--reason'", ",", "metavar", "=", "'<reason>'", ",", "help", "=", "_", "(", "'Reason for disabling service.'", ")", ")", "def", "do_service_disable", "(", "cs", ",", "args", ")", ":", "if", "args", ".", "reason", ":", "result", "=", "cs", ".", "services", ".", "disable_log_reason", "(", "args", ".", "host", ",", "args", ".", "binary", ",", "args", ".", "reason", ")", "utils", ".", "print_list", "(", "[", "result", "]", ",", "[", "'Host'", ",", "'Binary'", ",", "'Status'", ",", "'Disabled Reason'", "]", ")", "else", ":", "result", "=", "cs", ".", "services", ".", "disable", "(", "args", ".", "host", ",", "args", ".", "binary", ")", "utils", ".", "print_list", "(", "[", "result", "]", ",", "[", "'Host'", ",", "'Binary'", ",", "'Status'", "]", ")" ]
disable the service .
train
false
40,464
def test_Gaussian2D(): model = models.Gaussian2D(4.2, 1.7, 3.1, x_stddev=5.1, y_stddev=3.3, theta=(np.pi / 6.0)) (y, x) = np.mgrid[0:5, 0:5] g = model(x, y) g_ref = [[3.01907812, 2.99051889, 2.81271552, 2.5119566, 2.13012709], [3.55982239, 3.6086023, 3.4734158, 3.17454575, 2.75494838], [3.88059142, 4.0257528, 3.96554926, 3.70908389, 3.29410187], [3.91095768, 4.15212857, 4.18567526, 4.00652015, 3.64146544], [3.6440466, 3.95922417, 4.08454159, 4.00113878, 3.72161094]] assert_allclose(g, g_ref, rtol=0, atol=1e-06)
[ "def", "test_Gaussian2D", "(", ")", ":", "model", "=", "models", ".", "Gaussian2D", "(", "4.2", ",", "1.7", ",", "3.1", ",", "x_stddev", "=", "5.1", ",", "y_stddev", "=", "3.3", ",", "theta", "=", "(", "np", ".", "pi", "/", "6.0", ")", ")", "(", "y", ",", "x", ")", "=", "np", ".", "mgrid", "[", "0", ":", "5", ",", "0", ":", "5", "]", "g", "=", "model", "(", "x", ",", "y", ")", "g_ref", "=", "[", "[", "3.01907812", ",", "2.99051889", ",", "2.81271552", ",", "2.5119566", ",", "2.13012709", "]", ",", "[", "3.55982239", ",", "3.6086023", ",", "3.4734158", ",", "3.17454575", ",", "2.75494838", "]", ",", "[", "3.88059142", ",", "4.0257528", ",", "3.96554926", ",", "3.70908389", ",", "3.29410187", "]", ",", "[", "3.91095768", ",", "4.15212857", ",", "4.18567526", ",", "4.00652015", ",", "3.64146544", "]", ",", "[", "3.6440466", ",", "3.95922417", ",", "4.08454159", ",", "4.00113878", ",", "3.72161094", "]", "]", "assert_allclose", "(", "g", ",", "g_ref", ",", "rtol", "=", "0", ",", "atol", "=", "1e-06", ")" ]
test rotated elliptical gaussian2d model .
train
false
40,465
def is_graph_input(variable): return ((not variable.owner) and (not isinstance(variable, SharedVariable)) and (not isinstance(variable, Constant)))
[ "def", "is_graph_input", "(", "variable", ")", ":", "return", "(", "(", "not", "variable", ".", "owner", ")", "and", "(", "not", "isinstance", "(", "variable", ",", "SharedVariable", ")", ")", "and", "(", "not", "isinstance", "(", "variable", ",", "Constant", ")", ")", ")" ]
check if variable is a user-provided graph input .
train
false
40,466
def _listdir(root): res = [] root = os.path.expanduser(root) try: for name in os.listdir(root): path = os.path.join(root, name) if os.path.isdir(path): name += os.sep res.append(name) except: pass return res
[ "def", "_listdir", "(", "root", ")", ":", "res", "=", "[", "]", "root", "=", "os", ".", "path", ".", "expanduser", "(", "root", ")", "try", ":", "for", "name", "in", "os", ".", "listdir", "(", "root", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "name", "+=", "os", ".", "sep", "res", ".", "append", "(", "name", ")", "except", ":", "pass", "return", "res" ]
list directory root appending the path separator to subdirs .
train
true
40,468
def authenticated(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): if (not self.current_user): if (self.request.method in ('GET', 'HEAD')): url = self.get_login_url() if ('?' not in url): if urlparse.urlsplit(url).scheme: next_url = self.request.full_url() else: next_url = self.request.uri url += ('?' + urlencode(dict(next=next_url))) self.redirect(url) return raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
[ "def", "authenticated", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "not", "self", ".", "current_user", ")", ":", "if", "(", "self", ".", "request", ".", "method", "in", "(", "'GET'", ",", "'HEAD'", ")", ")", ":", "url", "=", "self", ".", "get_login_url", "(", ")", "if", "(", "'?'", "not", "in", "url", ")", ":", "if", "urlparse", ".", "urlsplit", "(", "url", ")", ".", "scheme", ":", "next_url", "=", "self", ".", "request", ".", "full_url", "(", ")", "else", ":", "next_url", "=", "self", ".", "request", ".", "uri", "url", "+=", "(", "'?'", "+", "urlencode", "(", "dict", "(", "next", "=", "next_url", ")", ")", ")", "self", ".", "redirect", "(", "url", ")", "return", "raise", "HTTPError", "(", "403", ")", "return", "method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper" ]
wrap request handler methods with this decorator to require that the user be logged in .
train
false
40,469
def fuzzy_or(args): return fuzzy_not(fuzzy_and((fuzzy_not(i) for i in args)))
[ "def", "fuzzy_or", "(", "args", ")", ":", "return", "fuzzy_not", "(", "fuzzy_and", "(", "(", "fuzzy_not", "(", "i", ")", "for", "i", "in", "args", ")", ")", ")" ]
or in fuzzy logic .
train
false
40,471
def _create_scaling_policies(conn, as_name, scaling_policies): if scaling_policies: for policy in scaling_policies: policy = autoscale.policy.ScalingPolicy(name=policy['name'], as_name=as_name, adjustment_type=policy['adjustment_type'], scaling_adjustment=policy['scaling_adjustment'], min_adjustment_step=policy.get('min_adjustment_step', None), cooldown=policy['cooldown']) conn.create_scaling_policy(policy)
[ "def", "_create_scaling_policies", "(", "conn", ",", "as_name", ",", "scaling_policies", ")", ":", "if", "scaling_policies", ":", "for", "policy", "in", "scaling_policies", ":", "policy", "=", "autoscale", ".", "policy", ".", "ScalingPolicy", "(", "name", "=", "policy", "[", "'name'", "]", ",", "as_name", "=", "as_name", ",", "adjustment_type", "=", "policy", "[", "'adjustment_type'", "]", ",", "scaling_adjustment", "=", "policy", "[", "'scaling_adjustment'", "]", ",", "min_adjustment_step", "=", "policy", ".", "get", "(", "'min_adjustment_step'", ",", "None", ")", ",", "cooldown", "=", "policy", "[", "'cooldown'", "]", ")", "conn", ".", "create_scaling_policy", "(", "policy", ")" ]
helper function to create scaling policies .
train
true
40,472
def sha_encode(t): s = hashlib.sha1(t) return s.hexdigest()
[ "def", "sha_encode", "(", "t", ")", ":", "s", "=", "hashlib", ".", "sha1", "(", "t", ")", "return", "s", ".", "hexdigest", "(", ")" ]
encoder using sha1 .
train
false
40,474
def test_key_dependency(): schema = vol.Schema(cv.key_dependency('beer', 'soda')) options = {'beer': None} for value in options: with pytest.raises(vol.MultipleInvalid): schema(value) options = ({'beer': None, 'soda': None}, {'soda': None}, {}) for value in options: schema(value)
[ "def", "test_key_dependency", "(", ")", ":", "schema", "=", "vol", ".", "Schema", "(", "cv", ".", "key_dependency", "(", "'beer'", ",", "'soda'", ")", ")", "options", "=", "{", "'beer'", ":", "None", "}", "for", "value", "in", "options", ":", "with", "pytest", ".", "raises", "(", "vol", ".", "MultipleInvalid", ")", ":", "schema", "(", "value", ")", "options", "=", "(", "{", "'beer'", ":", "None", ",", "'soda'", ":", "None", "}", ",", "{", "'soda'", ":", "None", "}", ",", "{", "}", ")", "for", "value", "in", "options", ":", "schema", "(", "value", ")" ]
test key_dependency validator .
train
false
40,476
def multinomial_logpmf_vec(x, n, p): if (len(x.shape) == 1): return multinomial_logpmf(x, n, p) else: size = x.shape[0] return np.array([multinomial_logpmf(x[i, :], n, p) for i in range(size)])
[ "def", "multinomial_logpmf_vec", "(", "x", ",", "n", ",", "p", ")", ":", "if", "(", "len", "(", "x", ".", "shape", ")", "==", "1", ")", ":", "return", "multinomial_logpmf", "(", "x", ",", "n", ",", "p", ")", "else", ":", "size", "=", "x", ".", "shape", "[", "0", "]", "return", "np", ".", "array", "(", "[", "multinomial_logpmf", "(", "x", "[", "i", ",", ":", "]", ",", "n", ",", "p", ")", "for", "i", "in", "range", "(", "size", ")", "]", ")" ]
vectorized version of multinomial_logpmf .
train
false
40,478
def test_fault_join(): pool = make_pool(1, 1) tpart = FakeTarPartition(1, explosive=Explosion('Boom')) pool.put(tpart) with pytest.raises(Explosion): pool.join()
[ "def", "test_fault_join", "(", ")", ":", "pool", "=", "make_pool", "(", "1", ",", "1", ")", "tpart", "=", "FakeTarPartition", "(", "1", ",", "explosive", "=", "Explosion", "(", "'Boom'", ")", ")", "pool", ".", "put", "(", "tpart", ")", "with", "pytest", ".", "raises", "(", "Explosion", ")", ":", "pool", ".", "join", "(", ")" ]
test if a fault is detected when .
train
false
40,481
@register.tag def minifyspace(parser, token): nodelist = parser.parse(('endminifyspace',)) parser.delete_first_token() return MinifiedNode(nodelist)
[ "@", "register", ".", "tag", "def", "minifyspace", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endminifyspace'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "MinifiedNode", "(", "nodelist", ")" ]
removes whitespace including tab and newline characters .
train
false
40,482
def bumper_metadata(video, sources): transcripts = video.get_transcripts_info(is_bumper=True) (unused_track_url, bumper_transcript_language, bumper_languages) = video.get_transcripts_for_student(transcripts) metadata = OrderedDict({'saveStateUrl': (video.system.ajax_url + '/save_user_state'), 'showCaptions': json.dumps(video.show_captions), 'sources': sources, 'streams': '', 'transcriptLanguage': bumper_transcript_language, 'transcriptLanguages': bumper_languages, 'transcriptTranslationUrl': set_query_parameter(video.runtime.handler_url(video, 'transcript', 'translation/__lang__').rstrip('/?'), 'is_bumper', 1), 'transcriptAvailableTranslationsUrl': set_query_parameter(video.runtime.handler_url(video, 'transcript', 'available_translations').rstrip('/?'), 'is_bumper', 1)}) return metadata
[ "def", "bumper_metadata", "(", "video", ",", "sources", ")", ":", "transcripts", "=", "video", ".", "get_transcripts_info", "(", "is_bumper", "=", "True", ")", "(", "unused_track_url", ",", "bumper_transcript_language", ",", "bumper_languages", ")", "=", "video", ".", "get_transcripts_for_student", "(", "transcripts", ")", "metadata", "=", "OrderedDict", "(", "{", "'saveStateUrl'", ":", "(", "video", ".", "system", ".", "ajax_url", "+", "'/save_user_state'", ")", ",", "'showCaptions'", ":", "json", ".", "dumps", "(", "video", ".", "show_captions", ")", ",", "'sources'", ":", "sources", ",", "'streams'", ":", "''", ",", "'transcriptLanguage'", ":", "bumper_transcript_language", ",", "'transcriptLanguages'", ":", "bumper_languages", ",", "'transcriptTranslationUrl'", ":", "set_query_parameter", "(", "video", ".", "runtime", ".", "handler_url", "(", "video", ",", "'transcript'", ",", "'translation/__lang__'", ")", ".", "rstrip", "(", "'/?'", ")", ",", "'is_bumper'", ",", "1", ")", ",", "'transcriptAvailableTranslationsUrl'", ":", "set_query_parameter", "(", "video", ".", "runtime", ".", "handler_url", "(", "video", ",", "'transcript'", ",", "'available_translations'", ")", ".", "rstrip", "(", "'/?'", ")", ",", "'is_bumper'", ",", "1", ")", "}", ")", "return", "metadata" ]
generate bumper metadata .
train
false
40,484
def _module_versions(): lines = [] modules = collections.OrderedDict([('sip', ['SIP_VERSION_STR']), ('colorama', ['VERSION', '__version__']), ('pypeg2', ['__version__']), ('jinja2', ['__version__']), ('pygments', ['__version__']), ('yaml', ['__version__']), ('cssutils', ['__version__']), ('typing', []), ('PyQt5.QtWebEngineWidgets', [])]) for (name, attributes) in modules.items(): try: module = importlib.import_module(name) except ImportError: text = '{}: no'.format(name) else: for attr in attributes: try: text = '{}: {}'.format(name, getattr(module, attr)) except AttributeError: pass else: break else: text = '{}: yes'.format(name) lines.append(text) return lines
[ "def", "_module_versions", "(", ")", ":", "lines", "=", "[", "]", "modules", "=", "collections", ".", "OrderedDict", "(", "[", "(", "'sip'", ",", "[", "'SIP_VERSION_STR'", "]", ")", ",", "(", "'colorama'", ",", "[", "'VERSION'", ",", "'__version__'", "]", ")", ",", "(", "'pypeg2'", ",", "[", "'__version__'", "]", ")", ",", "(", "'jinja2'", ",", "[", "'__version__'", "]", ")", ",", "(", "'pygments'", ",", "[", "'__version__'", "]", ")", ",", "(", "'yaml'", ",", "[", "'__version__'", "]", ")", ",", "(", "'cssutils'", ",", "[", "'__version__'", "]", ")", ",", "(", "'typing'", ",", "[", "]", ")", ",", "(", "'PyQt5.QtWebEngineWidgets'", ",", "[", "]", ")", "]", ")", "for", "(", "name", ",", "attributes", ")", "in", "modules", ".", "items", "(", ")", ":", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "name", ")", "except", "ImportError", ":", "text", "=", "'{}: no'", ".", "format", "(", "name", ")", "else", ":", "for", "attr", "in", "attributes", ":", "try", ":", "text", "=", "'{}: {}'", ".", "format", "(", "name", ",", "getattr", "(", "module", ",", "attr", ")", ")", "except", "AttributeError", ":", "pass", "else", ":", "break", "else", ":", "text", "=", "'{}: yes'", ".", "format", "(", "name", ")", "lines", ".", "append", "(", "text", ")", "return", "lines" ]
get versions of optional modules .
train
false
40,485
def dt_logout(request, next_page=None): username = request.user.get_username() request.audit = {'username': username, 'operation': 'USER_LOGOUT', 'operationText': ('Logged out user: %s' % username)} backends = get_backends() if backends: for backend in backends: if hasattr(backend, 'logout'): try: response = backend.logout(request, next_page) if response: return response except Exception as e: LOG.warn(('Potential error on logout for user: %s with exception: %s' % (username, e))) if (len(filter((lambda backend: hasattr(backend, 'logout')), backends)) == len(backends)): LOG.warn(('Failed to log out from all backends for user: %s' % username)) return django.contrib.auth.views.logout(request, next_page)
[ "def", "dt_logout", "(", "request", ",", "next_page", "=", "None", ")", ":", "username", "=", "request", ".", "user", ".", "get_username", "(", ")", "request", ".", "audit", "=", "{", "'username'", ":", "username", ",", "'operation'", ":", "'USER_LOGOUT'", ",", "'operationText'", ":", "(", "'Logged out user: %s'", "%", "username", ")", "}", "backends", "=", "get_backends", "(", ")", "if", "backends", ":", "for", "backend", "in", "backends", ":", "if", "hasattr", "(", "backend", ",", "'logout'", ")", ":", "try", ":", "response", "=", "backend", ".", "logout", "(", "request", ",", "next_page", ")", "if", "response", ":", "return", "response", "except", "Exception", "as", "e", ":", "LOG", ".", "warn", "(", "(", "'Potential error on logout for user: %s with exception: %s'", "%", "(", "username", ",", "e", ")", ")", ")", "if", "(", "len", "(", "filter", "(", "(", "lambda", "backend", ":", "hasattr", "(", "backend", ",", "'logout'", ")", ")", ",", "backends", ")", ")", "==", "len", "(", "backends", ")", ")", ":", "LOG", ".", "warn", "(", "(", "'Failed to log out from all backends for user: %s'", "%", "username", ")", ")", "return", "django", ".", "contrib", ".", "auth", ".", "views", ".", "logout", "(", "request", ",", "next_page", ")" ]
log out the user .
train
false
40,487
def gen_batches(n, batch_size): start = 0 for _ in range(int((n // batch_size))): end = (start + batch_size) (yield slice(start, end)) start = end if (start < n): (yield slice(start, n))
[ "def", "gen_batches", "(", "n", ",", "batch_size", ")", ":", "start", "=", "0", "for", "_", "in", "range", "(", "int", "(", "(", "n", "//", "batch_size", ")", ")", ")", ":", "end", "=", "(", "start", "+", "batch_size", ")", "(", "yield", "slice", "(", "start", ",", "end", ")", ")", "start", "=", "end", "if", "(", "start", "<", "n", ")", ":", "(", "yield", "slice", "(", "start", ",", "n", ")", ")" ]
generator to create slices containing batch_size elements .
train
false
40,488
def clear_old_snapshots(): logging.info('Removing old Cassandra snapshots...') try: subprocess.check_call([NODE_TOOL, 'clearsnapshot']) except CalledProcessError as error: logging.error('Error while deleting old Cassandra snapshots. Error: {0}'.format(str(error)))
[ "def", "clear_old_snapshots", "(", ")", ":", "logging", ".", "info", "(", "'Removing old Cassandra snapshots...'", ")", "try", ":", "subprocess", ".", "check_call", "(", "[", "NODE_TOOL", ",", "'clearsnapshot'", "]", ")", "except", "CalledProcessError", "as", "error", ":", "logging", ".", "error", "(", "'Error while deleting old Cassandra snapshots. Error: {0}'", ".", "format", "(", "str", "(", "error", ")", ")", ")" ]
remove any old snapshots to minimize disk space usage locally .
train
false
40,490
def circular_ladder_graph(n, create_using=None): G = ladder_graph(n, create_using) G.name = ('circular_ladder_graph(%d)' % n) G.add_edge(0, (n - 1)) G.add_edge(n, ((2 * n) - 1)) return G
[ "def", "circular_ladder_graph", "(", "n", ",", "create_using", "=", "None", ")", ":", "G", "=", "ladder_graph", "(", "n", ",", "create_using", ")", "G", ".", "name", "=", "(", "'circular_ladder_graph(%d)'", "%", "n", ")", "G", ".", "add_edge", "(", "0", ",", "(", "n", "-", "1", ")", ")", "G", ".", "add_edge", "(", "n", ",", "(", "(", "2", "*", "n", ")", "-", "1", ")", ")", "return", "G" ]
return the circular ladder graph cl_n of length n .
train
false
40,491
def get_repo_info(repo_name, profile='github', ignore_cache=False): org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:{1}:repo_info'.format(_get_config_value(profile, 'org_name'), repo_name.lower()) if ((key not in __context__) or ignore_cache): client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if (not repo): return {} ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError("The '{0}' repository under the '{1}' organization could not be found.".format(repo_name, org_name)) return __context__[key]
[ "def", "get_repo_info", "(", "repo_name", ",", "profile", "=", "'github'", ",", "ignore_cache", "=", "False", ")", ":", "org_name", "=", "_get_config_value", "(", "profile", ",", "'org_name'", ")", "key", "=", "'github.{0}:{1}:repo_info'", ".", "format", "(", "_get_config_value", "(", "profile", ",", "'org_name'", ")", ",", "repo_name", ".", "lower", "(", ")", ")", "if", "(", "(", "key", "not", "in", "__context__", ")", "or", "ignore_cache", ")", ":", "client", "=", "_get_client", "(", "profile", ")", "try", ":", "repo", "=", "client", ".", "get_repo", "(", "'/'", ".", "join", "(", "[", "org_name", ",", "repo_name", "]", ")", ")", "if", "(", "not", "repo", ")", ":", "return", "{", "}", "ret", "=", "_repo_to_dict", "(", "repo", ")", "__context__", "[", "key", "]", "=", "ret", "except", "github", ".", "UnknownObjectException", ":", "raise", "CommandExecutionError", "(", "\"The '{0}' repository under the '{1}' organization could not be found.\"", ".", "format", "(", "repo_name", ",", "org_name", ")", ")", "return", "__context__", "[", "key", "]" ]
return information for a given repo .
train
true
40,492
def _render_file(file, request): file.restat(False) if (file.type is None): (file.type, file.encoding) = getTypeAndEncoding(file.basename(), file.contentTypes, file.contentEncodings, file.defaultType) if (not file.exists()): return file.childNotFound.render(request) if file.isdir(): return file.redirect(request) request.setHeader('accept-ranges', 'bytes') try: fileForReading = file.openForReading() except IOError as e: import errno if (e[0] == errno.EACCES): return ForbiddenResource().render(request) else: raise producer = file.makeProducer(request, fileForReading) if (request.method == 'HEAD'): return '' producer.start() return NOT_DONE_YET
[ "def", "_render_file", "(", "file", ",", "request", ")", ":", "file", ".", "restat", "(", "False", ")", "if", "(", "file", ".", "type", "is", "None", ")", ":", "(", "file", ".", "type", ",", "file", ".", "encoding", ")", "=", "getTypeAndEncoding", "(", "file", ".", "basename", "(", ")", ",", "file", ".", "contentTypes", ",", "file", ".", "contentEncodings", ",", "file", ".", "defaultType", ")", "if", "(", "not", "file", ".", "exists", "(", ")", ")", ":", "return", "file", ".", "childNotFound", ".", "render", "(", "request", ")", "if", "file", ".", "isdir", "(", ")", ":", "return", "file", ".", "redirect", "(", "request", ")", "request", ".", "setHeader", "(", "'accept-ranges'", ",", "'bytes'", ")", "try", ":", "fileForReading", "=", "file", ".", "openForReading", "(", ")", "except", "IOError", "as", "e", ":", "import", "errno", "if", "(", "e", "[", "0", "]", "==", "errno", ".", "EACCES", ")", ":", "return", "ForbiddenResource", "(", ")", ".", "render", "(", "request", ")", "else", ":", "raise", "producer", "=", "file", ".", "makeProducer", "(", "request", ",", "fileForReading", ")", "if", "(", "request", ".", "method", "==", "'HEAD'", ")", ":", "return", "''", "producer", ".", "start", "(", ")", "return", "NOT_DONE_YET" ]
begin sending the contents of this l{file} to the given request .
train
false
40,493
def RedirectToRemoteHelp(path): allowed_chars = set(((string.ascii_letters + string.digits) + '._')) if (not (set(path) <= allowed_chars)): raise RuntimeError(('Unusual chars in path %r - possible exploit attempt.' % path)) target_path = os.path.join(config_lib.CONFIG['AdminUI.github_docs_location'], path.replace('.html', '.adoc')) response = http.HttpResponse() response.write(("\n<script>\nvar friendly_hash = window.location.hash.replace('#_', '#').replace(/_/g, '-');\nwindow.location = '%s' + friendly_hash;\n</script>\n" % target_path)) return response
[ "def", "RedirectToRemoteHelp", "(", "path", ")", ":", "allowed_chars", "=", "set", "(", "(", "(", "string", ".", "ascii_letters", "+", "string", ".", "digits", ")", "+", "'._'", ")", ")", "if", "(", "not", "(", "set", "(", "path", ")", "<=", "allowed_chars", ")", ")", ":", "raise", "RuntimeError", "(", "(", "'Unusual chars in path %r - possible exploit attempt.'", "%", "path", ")", ")", "target_path", "=", "os", ".", "path", ".", "join", "(", "config_lib", ".", "CONFIG", "[", "'AdminUI.github_docs_location'", "]", ",", "path", ".", "replace", "(", "'.html'", ",", "'.adoc'", ")", ")", "response", "=", "http", ".", "HttpResponse", "(", ")", "response", ".", "write", "(", "(", "\"\\n<script>\\nvar friendly_hash = window.location.hash.replace('#_', '#').replace(/_/g, '-');\\nwindow.location = '%s' + friendly_hash;\\n</script>\\n\"", "%", "target_path", ")", ")", "return", "response" ]
redirect to github-hosted documentation .
train
false
40,494
def _update_rospack_cache(env=None): if (env is None): env = os.environ cache = _pkg_dir_cache if cache: return True ros_root = env[ROS_ROOT] ros_package_path = env.get(ROS_PACKAGE_PATH, '') return _read_rospack_cache(cache, ros_root, ros_package_path)
[ "def", "_update_rospack_cache", "(", "env", "=", "None", ")", ":", "if", "(", "env", "is", "None", ")", ":", "env", "=", "os", ".", "environ", "cache", "=", "_pkg_dir_cache", "if", "cache", ":", "return", "True", "ros_root", "=", "env", "[", "ROS_ROOT", "]", "ros_package_path", "=", "env", ".", "get", "(", "ROS_PACKAGE_PATH", ",", "''", ")", "return", "_read_rospack_cache", "(", "cache", ",", "ros_root", ",", "ros_package_path", ")" ]
internal routine to update global package directory cache @return: true if cache is valid @rtype: bool .
train
false
40,495
def apply_extra_context(extra_context, context): for (key, value) in extra_context.iteritems(): if callable(value): context[key] = value() else: context[key] = value
[ "def", "apply_extra_context", "(", "extra_context", ",", "context", ")", ":", "for", "(", "key", ",", "value", ")", "in", "extra_context", ".", "iteritems", "(", ")", ":", "if", "callable", "(", "value", ")", ":", "context", "[", "key", "]", "=", "value", "(", ")", "else", ":", "context", "[", "key", "]", "=", "value" ]
adds items from extra_context dict to context .
train
true
40,496
def multi_params(schema): return {'type': 'array', 'items': schema}
[ "def", "multi_params", "(", "schema", ")", ":", "return", "{", "'type'", ":", "'array'", ",", "'items'", ":", "schema", "}" ]
macro function for use in jsonschema to support query parameters that may have multiple values .
train
false
40,497
def anchor_map(html): ans = {} for match in re.finditer(u'(?:id|name)\\s*=\\s*[\'"]([^\'"]+)[\'"]', html): anchor = match.group(1) ans[anchor] = ans.get(anchor, match.start()) return ans
[ "def", "anchor_map", "(", "html", ")", ":", "ans", "=", "{", "}", "for", "match", "in", "re", ".", "finditer", "(", "u'(?:id|name)\\\\s*=\\\\s*[\\'\"]([^\\'\"]+)[\\'\"]'", ",", "html", ")", ":", "anchor", "=", "match", ".", "group", "(", "1", ")", "ans", "[", "anchor", "]", "=", "ans", ".", "get", "(", "anchor", ",", "match", ".", "start", "(", ")", ")", "return", "ans" ]
return map of all anchor names to their offsets in the html .
train
false
40,499
def invert_real(f_x, y, x, domain=S.Reals): return _invert(f_x, y, x, domain)
[ "def", "invert_real", "(", "f_x", ",", "y", ",", "x", ",", "domain", "=", "S", ".", "Reals", ")", ":", "return", "_invert", "(", "f_x", ",", "y", ",", "x", ",", "domain", ")" ]
inverts a real-valued function .
train
false
40,500
def _one_step(mu, u): if (np.abs(mu).max() > 1.0): return 1.0 _compose_linear_fitting_data(mu, u) (u['uu'], u['sing'], u['vv']) = linalg.svd(u['M']) u['resi'][:] = u['y'][:] for p in range((u['nfit'] - 1)): dot = np.dot(u['uu'][p], u['y']) for k in range((u['nterms'] - 1)): u['resi'][k] = (u['resi'][k] - (u['uu'][(p, k)] * dot)) return np.dot(u['resi'], u['resi'])
[ "def", "_one_step", "(", "mu", ",", "u", ")", ":", "if", "(", "np", ".", "abs", "(", "mu", ")", ".", "max", "(", ")", ">", "1.0", ")", ":", "return", "1.0", "_compose_linear_fitting_data", "(", "mu", ",", "u", ")", "(", "u", "[", "'uu'", "]", ",", "u", "[", "'sing'", "]", ",", "u", "[", "'vv'", "]", ")", "=", "linalg", ".", "svd", "(", "u", "[", "'M'", "]", ")", "u", "[", "'resi'", "]", "[", ":", "]", "=", "u", "[", "'y'", "]", "[", ":", "]", "for", "p", "in", "range", "(", "(", "u", "[", "'nfit'", "]", "-", "1", ")", ")", ":", "dot", "=", "np", ".", "dot", "(", "u", "[", "'uu'", "]", "[", "p", "]", ",", "u", "[", "'y'", "]", ")", "for", "k", "in", "range", "(", "(", "u", "[", "'nterms'", "]", "-", "1", ")", ")", ":", "u", "[", "'resi'", "]", "[", "k", "]", "=", "(", "u", "[", "'resi'", "]", "[", "k", "]", "-", "(", "u", "[", "'uu'", "]", "[", "(", "p", ",", "k", ")", "]", "*", "dot", ")", ")", "return", "np", ".", "dot", "(", "u", "[", "'resi'", "]", ",", "u", "[", "'resi'", "]", ")" ]
evaluate the residual sum of squares fit for one set of mu values .
train
false
40,501
def admin_url_params(request, params=None): params = (params or {}) if popup_status(request): params[IS_POPUP_VAR] = u'1' pick_type = popup_pick_type(request) if pick_type: params[u'_pick'] = pick_type return params
[ "def", "admin_url_params", "(", "request", ",", "params", "=", "None", ")", ":", "params", "=", "(", "params", "or", "{", "}", ")", "if", "popup_status", "(", "request", ")", ":", "params", "[", "IS_POPUP_VAR", "]", "=", "u'1'", "pick_type", "=", "popup_pick_type", "(", "request", ")", "if", "pick_type", ":", "params", "[", "u'_pick'", "]", "=", "pick_type", "return", "params" ]
given a request .
train
false
40,502
def process_tag_pattern(pattern, variables=None): if (variables is None): variables = {} if isinstance(pattern, str): pattern = bre.compile_search((pattern % variables), (bre.I | bre.M)) return pattern
[ "def", "process_tag_pattern", "(", "pattern", ",", "variables", "=", "None", ")", ":", "if", "(", "variables", "is", "None", ")", ":", "variables", "=", "{", "}", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "pattern", "=", "bre", ".", "compile_search", "(", "(", "pattern", "%", "variables", ")", ",", "(", "bre", ".", "I", "|", "bre", ".", "M", ")", ")", "return", "pattern" ]
process the tag pattern .
train
false
40,504
def system_info(): data = show_ver() info = {'software': _parse_software(data), 'hardware': _parse_hardware(data), 'plugins': _parse_plugins(data)} return info
[ "def", "system_info", "(", ")", ":", "data", "=", "show_ver", "(", ")", "info", "=", "{", "'software'", ":", "_parse_software", "(", "data", ")", ",", "'hardware'", ":", "_parse_hardware", "(", "data", ")", ",", "'plugins'", ":", "_parse_plugins", "(", "data", ")", "}", "return", "info" ]
return system information for grains of the nx os proxy minion .
train
true
40,506
def group_rheader(r, tabs=[]): if (r.representation == 'html'): if (r.record is None): return None tabs = [(T('Basic Details'), None), (T('Problems'), 'problem')] group = r.record duser = s3db.delphi_DelphiUser(group.id) if duser.authorised: tabs.append((T('Membership'), 'membership')) rheader_tabs = s3_rheader_tabs(r, tabs) rheader = DIV(TABLE(TR(TH(('%s: ' % T('Group'))), group.name), TR(TH(('%s: ' % T('Description'))), group.description), TR(TH(('%s: ' % T('Active'))), group.active)), rheader_tabs) return rheader
[ "def", "group_rheader", "(", "r", ",", "tabs", "=", "[", "]", ")", ":", "if", "(", "r", ".", "representation", "==", "'html'", ")", ":", "if", "(", "r", ".", "record", "is", "None", ")", ":", "return", "None", "tabs", "=", "[", "(", "T", "(", "'Basic Details'", ")", ",", "None", ")", ",", "(", "T", "(", "'Problems'", ")", ",", "'problem'", ")", "]", "group", "=", "r", ".", "record", "duser", "=", "s3db", ".", "delphi_DelphiUser", "(", "group", ".", "id", ")", "if", "duser", ".", "authorised", ":", "tabs", ".", "append", "(", "(", "T", "(", "'Membership'", ")", ",", "'membership'", ")", ")", "rheader_tabs", "=", "s3_rheader_tabs", "(", "r", ",", "tabs", ")", "rheader", "=", "DIV", "(", "TABLE", "(", "TR", "(", "TH", "(", "(", "'%s: '", "%", "T", "(", "'Group'", ")", ")", ")", ",", "group", ".", "name", ")", ",", "TR", "(", "TH", "(", "(", "'%s: '", "%", "T", "(", "'Description'", ")", ")", ")", ",", "group", ".", "description", ")", ",", "TR", "(", "TH", "(", "(", "'%s: '", "%", "T", "(", "'Active'", ")", ")", ")", ",", "group", ".", "active", ")", ")", ",", "rheader_tabs", ")", "return", "rheader" ]
group rheader .
train
false
40,507
def delete_servers(*servers, **options): test = options.pop('test', False) commit = options.pop('commit', True) return __salt__['net.load_template']('delete_ntp_servers', servers=servers, test=test, commit=commit)
[ "def", "delete_servers", "(", "*", "servers", ",", "**", "options", ")", ":", "test", "=", "options", ".", "pop", "(", "'test'", ",", "False", ")", "commit", "=", "options", ".", "pop", "(", "'commit'", ",", "True", ")", "return", "__salt__", "[", "'net.load_template'", "]", "(", "'delete_ntp_servers'", ",", "servers", "=", "servers", ",", "test", "=", "test", ",", "commit", "=", "commit", ")" ]
removes ntp servers configured on the device .
train
true
40,508
def _ListAllHelpFilesInRoot(root): import regutil retList = [] try: key = win32api.RegOpenKey(root, (regutil.BuildDefaultPythonKey() + '\\Help'), 0, win32con.KEY_READ) except win32api.error as exc: import winerror if (exc.winerror != winerror.ERROR_FILE_NOT_FOUND): raise return retList try: keyNo = 0 while 1: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) retList.append((helpDesc, helpFile)) keyNo = (keyNo + 1) except win32api.error as exc: import winerror if (exc.winerror != winerror.ERROR_NO_MORE_ITEMS): raise break finally: win32api.RegCloseKey(key) return retList
[ "def", "_ListAllHelpFilesInRoot", "(", "root", ")", ":", "import", "regutil", "retList", "=", "[", "]", "try", ":", "key", "=", "win32api", ".", "RegOpenKey", "(", "root", ",", "(", "regutil", ".", "BuildDefaultPythonKey", "(", ")", "+", "'\\\\Help'", ")", ",", "0", ",", "win32con", ".", "KEY_READ", ")", "except", "win32api", ".", "error", "as", "exc", ":", "import", "winerror", "if", "(", "exc", ".", "winerror", "!=", "winerror", ".", "ERROR_FILE_NOT_FOUND", ")", ":", "raise", "return", "retList", "try", ":", "keyNo", "=", "0", "while", "1", ":", "try", ":", "helpDesc", "=", "win32api", ".", "RegEnumKey", "(", "key", ",", "keyNo", ")", "helpFile", "=", "win32api", ".", "RegQueryValue", "(", "key", ",", "helpDesc", ")", "retList", ".", "append", "(", "(", "helpDesc", ",", "helpFile", ")", ")", "keyNo", "=", "(", "keyNo", "+", "1", ")", "except", "win32api", ".", "error", "as", "exc", ":", "import", "winerror", "if", "(", "exc", ".", "winerror", "!=", "winerror", ".", "ERROR_NO_MORE_ITEMS", ")", ":", "raise", "break", "finally", ":", "win32api", ".", "RegCloseKey", "(", "key", ")", "return", "retList" ]
returns a list of for all registered help files .
train
false
40,510
def get_account_currency(account): if (not account): return def generator(): (account_currency, company) = frappe.db.get_value(u'Account', account, [u'account_currency', u'company']) if (not account_currency): account_currency = frappe.db.get_value(u'Company', company, u'default_currency') return account_currency return frappe.local_cache(u'account_currency', account, generator)
[ "def", "get_account_currency", "(", "account", ")", ":", "if", "(", "not", "account", ")", ":", "return", "def", "generator", "(", ")", ":", "(", "account_currency", ",", "company", ")", "=", "frappe", ".", "db", ".", "get_value", "(", "u'Account'", ",", "account", ",", "[", "u'account_currency'", ",", "u'company'", "]", ")", "if", "(", "not", "account_currency", ")", ":", "account_currency", "=", "frappe", ".", "db", ".", "get_value", "(", "u'Company'", ",", "company", ",", "u'default_currency'", ")", "return", "account_currency", "return", "frappe", ".", "local_cache", "(", "u'account_currency'", ",", "account", ",", "generator", ")" ]
helper function to get account currency .
train
false
40,511
def alarms(): if _TRAFFICCTL: cmd = _traffic_ctl('alarm', 'list') else: cmd = _traffic_line('--alarms') log.debug('Running: %s', cmd) return _subprocess(cmd)
[ "def", "alarms", "(", ")", ":", "if", "_TRAFFICCTL", ":", "cmd", "=", "_traffic_ctl", "(", "'alarm'", ",", "'list'", ")", "else", ":", "cmd", "=", "_traffic_line", "(", "'--alarms'", ")", "log", ".", "debug", "(", "'Running: %s'", ",", "cmd", ")", "return", "_subprocess", "(", "cmd", ")" ]
list all alarm events that have not been acknowledged .
train
false
40,513
def _collapse_wspace(text): if (text is not None): return ' '.join(text.split())
[ "def", "_collapse_wspace", "(", "text", ")", ":", "if", "(", "text", "is", "not", "None", ")", ":", "return", "' '", ".", "join", "(", "text", ".", "split", "(", ")", ")" ]
replace all spans of whitespace with a single space character .
train
false
40,516
def create_channels(): logger.log_info('Creating default channels ...') goduser = get_god_player() for channeldict in settings.DEFAULT_CHANNELS: channel = create.create_channel(**channeldict) channel.connect(goduser)
[ "def", "create_channels", "(", ")", ":", "logger", ".", "log_info", "(", "'Creating default channels ...'", ")", "goduser", "=", "get_god_player", "(", ")", "for", "channeldict", "in", "settings", ".", "DEFAULT_CHANNELS", ":", "channel", "=", "create", ".", "create_channel", "(", "**", "channeldict", ")", "channel", ".", "connect", "(", "goduser", ")" ]
creates some sensible default channels .
train
false
40,517
def parsedocx(path, *args, **kwargs): return DOCX(path, *args, **kwargs).content
[ "def", "parsedocx", "(", "path", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "DOCX", "(", "path", ",", "*", "args", ",", "**", "kwargs", ")", ".", "content" ]
returns the content as a unicode string from the given .
train
false
40,518
@task def test_sympy(): with cd('/home/vagrant/repos/sympy'): run('./setup.py test')
[ "@", "task", "def", "test_sympy", "(", ")", ":", "with", "cd", "(", "'/home/vagrant/repos/sympy'", ")", ":", "run", "(", "'./setup.py test'", ")" ]
run the sympy test suite .
train
false
40,520
def cmServiceAbort(): a = TpPd(pd=5) b = MessageType(mesType=35) packet = (a / b) return packet
[ "def", "cmServiceAbort", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "5", ")", "b", "=", "MessageType", "(", "mesType", "=", "35", ")", "packet", "=", "(", "a", "/", "b", ")", "return", "packet" ]
cm service abort section 9 .
train
true
40,521
def _calculate_navigation(offset, length, size): if (offset == 0): (first, prev) = (((-1), None, _('First Block')), ((-1), None, _('Previous Block'))) else: (first, prev) = ((0, length, _('First Block')), (max(0, (offset - length)), length, _('Previous Block'))) if ((offset + length) >= size): (next, last) = (((-1), None, _('Next Block')), ((-1), None, _('Last Block'))) else: (next, last) = (((offset + length), length, _('Next Block')), (max(0, (size - length)), length, _('Last Block'))) return (first, prev, next, last)
[ "def", "_calculate_navigation", "(", "offset", ",", "length", ",", "size", ")", ":", "if", "(", "offset", "==", "0", ")", ":", "(", "first", ",", "prev", ")", "=", "(", "(", "(", "-", "1", ")", ",", "None", ",", "_", "(", "'First Block'", ")", ")", ",", "(", "(", "-", "1", ")", ",", "None", ",", "_", "(", "'Previous Block'", ")", ")", ")", "else", ":", "(", "first", ",", "prev", ")", "=", "(", "(", "0", ",", "length", ",", "_", "(", "'First Block'", ")", ")", ",", "(", "max", "(", "0", ",", "(", "offset", "-", "length", ")", ")", ",", "length", ",", "_", "(", "'Previous Block'", ")", ")", ")", "if", "(", "(", "offset", "+", "length", ")", ">=", "size", ")", ":", "(", "next", ",", "last", ")", "=", "(", "(", "(", "-", "1", ")", ",", "None", ",", "_", "(", "'Next Block'", ")", ")", ",", "(", "(", "-", "1", ")", ",", "None", ",", "_", "(", "'Last Block'", ")", ")", ")", "else", ":", "(", "next", ",", "last", ")", "=", "(", "(", "(", "offset", "+", "length", ")", ",", "length", ",", "_", "(", "'Next Block'", ")", ")", ",", "(", "max", "(", "0", ",", "(", "size", "-", "length", ")", ")", ",", "length", ",", "_", "(", "'Last Block'", ")", ")", ")", "return", "(", "first", ",", "prev", ",", "next", ",", "last", ")" ]
list of tuples for suggested navigation through the file .
train
false
40,522
def test_LogNorm(): ln = mcolors.LogNorm(clip=True, vmax=5) assert_array_equal(ln([1, 6]), [0, 1.0])
[ "def", "test_LogNorm", "(", ")", ":", "ln", "=", "mcolors", ".", "LogNorm", "(", "clip", "=", "True", ",", "vmax", "=", "5", ")", "assert_array_equal", "(", "ln", "(", "[", "1", ",", "6", "]", ")", ",", "[", "0", ",", "1.0", "]", ")" ]
lognorm ignored clip .
train
false
40,524
def generate_addon_preview(addon): color = random.choice(ImageColor.colormap.keys()) im = Image.new('RGB', (320, 480), color) p = Preview.objects.create(addon=addon, caption='Screenshot 1', position=1) f = tempfile.NamedTemporaryFile() im.save(f, 'png') resize_preview(f.name, p)
[ "def", "generate_addon_preview", "(", "addon", ")", ":", "color", "=", "random", ".", "choice", "(", "ImageColor", ".", "colormap", ".", "keys", "(", ")", ")", "im", "=", "Image", ".", "new", "(", "'RGB'", ",", "(", "320", ",", "480", ")", ",", "color", ")", "p", "=", "Preview", ".", "objects", ".", "create", "(", "addon", "=", "addon", ",", "caption", "=", "'Screenshot 1'", ",", "position", "=", "1", ")", "f", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "im", ".", "save", "(", "f", ",", "'png'", ")", "resize_preview", "(", "f", ".", "name", ",", "p", ")" ]
generate a screenshot for the given addon .
train
false
40,525
def parse_schema_file(file_name, files={}, repr_=Thier_repr(with_ns=False), skip_errors=False): elt = etree.fromstring(open(file_name, 'rb').read(), parser=PARSER) wd = abspath(dirname(file_name)) return XmlSchemaParser(files, wd, repr_=repr_, skip_errors=skip_errors).parse_schema(elt)
[ "def", "parse_schema_file", "(", "file_name", ",", "files", "=", "{", "}", ",", "repr_", "=", "Thier_repr", "(", "with_ns", "=", "False", ")", ",", "skip_errors", "=", "False", ")", ":", "elt", "=", "etree", ".", "fromstring", "(", "open", "(", "file_name", ",", "'rb'", ")", ".", "read", "(", ")", ",", "parser", "=", "PARSER", ")", "wd", "=", "abspath", "(", "dirname", "(", "file_name", ")", ")", "return", "XmlSchemaParser", "(", "files", ",", "wd", ",", "repr_", "=", "repr_", ",", "skip_errors", "=", "skip_errors", ")", ".", "parse_schema", "(", "elt", ")" ]
parses a schema file and returns a _schema object .
train
false
40,526
@app.route('/account/<subscription_id>/resourcegroups/<resource_group_name>') @auth.require_login def resourcegroup_view(subscription_id, resource_group_name): creds = _get_credentials() model = models.get_resource_group_details(subscription_id, creds, resource_group_name) return render_template('resourcegroup.html', title=resource_group_name, year=datetime.now().year, subscription_id=subscription_id, resource_group_name=resource_group_name, model=model)
[ "@", "app", ".", "route", "(", "'/account/<subscription_id>/resourcegroups/<resource_group_name>'", ")", "@", "auth", ".", "require_login", "def", "resourcegroup_view", "(", "subscription_id", ",", "resource_group_name", ")", ":", "creds", "=", "_get_credentials", "(", ")", "model", "=", "models", ".", "get_resource_group_details", "(", "subscription_id", ",", "creds", ",", "resource_group_name", ")", "return", "render_template", "(", "'resourcegroup.html'", ",", "title", "=", "resource_group_name", ",", "year", "=", "datetime", ".", "now", "(", ")", ".", "year", ",", "subscription_id", "=", "subscription_id", ",", "resource_group_name", "=", "resource_group_name", ",", "model", "=", "model", ")" ]
renders the resource group details .
train
false
40,527
def read_installed_packages_list(): def read_from_file(config_filename): '\n Reads an installed.lst file from a given location\n\n :param config_filename: the configuration file to read\n ' global installed_packages_list try: installed_list_file = open(config_filename) except IOError: pass else: for line in installed_list_file: l = line.rstrip().split(' ') if l: installed_packages_list[l[0]] = this_package = package_info(config_filename, l[0], l[1], l[2], urllib.unquote(l[3]), urllib.unquote(l[4])) else: pass if super_powers: read_from_file(os.path.join(dataset_conf_path, 'installed.lst')) else: paths = [os.path.join(root_conf_path, 'installed.lst'), os.path.join(user_conf_path, 'installed.lst')] try: paths += [os.path.join(x, 'installed.lst') for x in re.split(':|;', os.environ['PYLEARN2_DATA_PATH'])] except Exception: pass for path in paths: read_from_file(path) if (len(installed_packages_list) == 0): logger.warning('[cf] no install.lst found (will be created on install/upgrade)')
[ "def", "read_installed_packages_list", "(", ")", ":", "def", "read_from_file", "(", "config_filename", ")", ":", "global", "installed_packages_list", "try", ":", "installed_list_file", "=", "open", "(", "config_filename", ")", "except", "IOError", ":", "pass", "else", ":", "for", "line", "in", "installed_list_file", ":", "l", "=", "line", ".", "rstrip", "(", ")", ".", "split", "(", "' '", ")", "if", "l", ":", "installed_packages_list", "[", "l", "[", "0", "]", "]", "=", "this_package", "=", "package_info", "(", "config_filename", ",", "l", "[", "0", "]", ",", "l", "[", "1", "]", ",", "l", "[", "2", "]", ",", "urllib", ".", "unquote", "(", "l", "[", "3", "]", ")", ",", "urllib", ".", "unquote", "(", "l", "[", "4", "]", ")", ")", "else", ":", "pass", "if", "super_powers", ":", "read_from_file", "(", "os", ".", "path", ".", "join", "(", "dataset_conf_path", ",", "'installed.lst'", ")", ")", "else", ":", "paths", "=", "[", "os", ".", "path", ".", "join", "(", "root_conf_path", ",", "'installed.lst'", ")", ",", "os", ".", "path", ".", "join", "(", "user_conf_path", ",", "'installed.lst'", ")", "]", "try", ":", "paths", "+=", "[", "os", ".", "path", ".", "join", "(", "x", ",", "'installed.lst'", ")", "for", "x", "in", "re", ".", "split", "(", "':|;'", ",", "os", ".", "environ", "[", "'PYLEARN2_DATA_PATH'", "]", ")", "]", "except", "Exception", ":", "pass", "for", "path", "in", "paths", ":", "read_from_file", "(", "path", ")", "if", "(", "len", "(", "installed_packages_list", ")", "==", "0", ")", ":", "logger", ".", "warning", "(", "'[cf] no install.lst found (will be created on install/upgrade)'", ")" ]
reads the various installed .
train
false
40,528
def _changeVersionInFile(old, new, filename): replaceInFile(filename, {old.base(): new.base()})
[ "def", "_changeVersionInFile", "(", "old", ",", "new", ",", "filename", ")", ":", "replaceInFile", "(", "filename", ",", "{", "old", ".", "base", "(", ")", ":", "new", ".", "base", "(", ")", "}", ")" ]
replace the c{old} version number with the c{new} one in the given c{filename} .
train
false
40,530
def assess_multi_type_represent(ids, opts): if (not ids): return current.messages['NONE'] ids = ([ids] if (type(ids) is not list) else ids) strings = [str(opts.get(id)) for id in ids] return ', '.join(strings)
[ "def", "assess_multi_type_represent", "(", "ids", ",", "opts", ")", ":", "if", "(", "not", "ids", ")", ":", "return", "current", ".", "messages", "[", "'NONE'", "]", "ids", "=", "(", "[", "ids", "]", "if", "(", "type", "(", "ids", ")", "is", "not", "list", ")", "else", "ids", ")", "strings", "=", "[", "str", "(", "opts", ".", "get", "(", "id", ")", ")", "for", "id", "in", "ids", "]", "return", "', '", ".", "join", "(", "strings", ")" ]
represent multiple types .
train
false
40,532
def show_most_popular_groups(): value = config.get('ckan.example_theme.show_most_popular_groups', False) value = toolkit.asbool(value) return value
[ "def", "show_most_popular_groups", "(", ")", ":", "value", "=", "config", ".", "get", "(", "'ckan.example_theme.show_most_popular_groups'", ",", "False", ")", "value", "=", "toolkit", ".", "asbool", "(", "value", ")", "return", "value" ]
return the value of the most_popular_groups config setting .
train
false
40,533
def cry(): tmap = {} main_thread = None for t in threading.enumerate(): if getattr(t, 'ident', None): tmap[t.ident] = t else: main_thread = t out = StringIO() sep = (('=' * 49) + '\n') for (tid, frame) in sys._current_frames().iteritems(): thread = tmap.get(tid, main_thread) if (not thread): continue out.write(('%s\n' % (thread.getName(),))) out.write(sep) traceback.print_stack(frame, file=out) out.write(sep) out.write('LOCAL VARIABLES\n') out.write(sep) pprint(frame.f_locals, stream=out) out.write('\n\n') return out.getvalue()
[ "def", "cry", "(", ")", ":", "tmap", "=", "{", "}", "main_thread", "=", "None", "for", "t", "in", "threading", ".", "enumerate", "(", ")", ":", "if", "getattr", "(", "t", ",", "'ident'", ",", "None", ")", ":", "tmap", "[", "t", ".", "ident", "]", "=", "t", "else", ":", "main_thread", "=", "t", "out", "=", "StringIO", "(", ")", "sep", "=", "(", "(", "'='", "*", "49", ")", "+", "'\\n'", ")", "for", "(", "tid", ",", "frame", ")", "in", "sys", ".", "_current_frames", "(", ")", ".", "iteritems", "(", ")", ":", "thread", "=", "tmap", ".", "get", "(", "tid", ",", "main_thread", ")", "if", "(", "not", "thread", ")", ":", "continue", "out", ".", "write", "(", "(", "'%s\\n'", "%", "(", "thread", ".", "getName", "(", ")", ",", ")", ")", ")", "out", ".", "write", "(", "sep", ")", "traceback", ".", "print_stack", "(", "frame", ",", "file", "=", "out", ")", "out", ".", "write", "(", "sep", ")", "out", ".", "write", "(", "'LOCAL VARIABLES\\n'", ")", "out", ".", "write", "(", "sep", ")", "pprint", "(", "frame", ".", "f_locals", ",", "stream", "=", "out", ")", "out", ".", "write", "(", "'\\n\\n'", ")", "return", "out", ".", "getvalue", "(", ")" ]
return stacktrace of all active threads .
train
true
40,534
def get_pre_release(version): if (not is_pre_release(version)): raise NotAPreRelease(version) parsed_version = parse_version(version) return int(parsed_version.pre_release)
[ "def", "get_pre_release", "(", "version", ")", ":", "if", "(", "not", "is_pre_release", "(", "version", ")", ")", ":", "raise", "NotAPreRelease", "(", "version", ")", "parsed_version", "=", "parse_version", "(", "version", ")", "return", "int", "(", "parsed_version", ".", "pre_release", ")" ]
return the number of a pre-release .
train
false
40,535
def iter_sample(draws, step, start=None, trace=None, chain=0, tune=None, model=None, random_seed=(-1)): sampling = _iter_sample(draws, step, start, trace, chain, tune, model, random_seed) for (i, strace) in enumerate(sampling): (yield MultiTrace([strace[:(i + 1)]]))
[ "def", "iter_sample", "(", "draws", ",", "step", ",", "start", "=", "None", ",", "trace", "=", "None", ",", "chain", "=", "0", ",", "tune", "=", "None", ",", "model", "=", "None", ",", "random_seed", "=", "(", "-", "1", ")", ")", ":", "sampling", "=", "_iter_sample", "(", "draws", ",", "step", ",", "start", ",", "trace", ",", "chain", ",", "tune", ",", "model", ",", "random_seed", ")", "for", "(", "i", ",", "strace", ")", "in", "enumerate", "(", "sampling", ")", ":", "(", "yield", "MultiTrace", "(", "[", "strace", "[", ":", "(", "i", "+", "1", ")", "]", "]", ")", ")" ]
generator that returns a trace on each iteration using the given step method .
train
false