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
43,209
def current_umask(): mask = os.umask(0) os.umask(mask) return mask
[ "def", "current_umask", "(", ")", ":", "mask", "=", "os", ".", "umask", "(", "0", ")", "os", ".", "umask", "(", "mask", ")", "return", "mask" ]
get the current umask which involves having to set it temporarily .
train
false
43,210
def get_pack_ref_from_metadata(metadata, pack_directory_name=None): pack_ref = None if metadata.get('ref', None): pack_ref = metadata['ref'] elif (pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name)): pack_ref = pack_directory_name elif re.match(PACK_REF_WHITELIST_REGEX, metadata['na...
[ "def", "get_pack_ref_from_metadata", "(", "metadata", ",", "pack_directory_name", "=", "None", ")", ":", "pack_ref", "=", "None", "if", "metadata", ".", "get", "(", "'ref'", ",", "None", ")", ":", "pack_ref", "=", "metadata", "[", "'ref'", "]", "elif", "("...
utility function which retrieves pack "ref" attribute from the pack metadata file .
train
false
43,211
def re_map_foreign_keys(data, table, field_name, related_table, verbose=False): lookup_table = id_maps[related_table] for item in data[table]: old_id = item[field_name] if (old_id in lookup_table): new_id = lookup_table[old_id] if verbose: logging.info(('Remapping %s%s from %s to %s' % (table, (field_na...
[ "def", "re_map_foreign_keys", "(", "data", ",", "table", ",", "field_name", ",", "related_table", ",", "verbose", "=", "False", ")", ":", "lookup_table", "=", "id_maps", "[", "related_table", "]", "for", "item", "in", "data", "[", "table", "]", ":", "old_i...
we occasionally need to assign new ids to rows during the import/export process .
train
false
43,212
def test_fast_wait(): gevent.sleep(300)
[ "def", "test_fast_wait", "(", ")", ":", "gevent", ".", "sleep", "(", "300", ")" ]
annoy someone who causes fast-sleep test patching to regress .
train
false
43,213
def _render_blog_supernav(entry): return render_to_string('blogs/supernav.html', {'entry': entry})
[ "def", "_render_blog_supernav", "(", "entry", ")", ":", "return", "render_to_string", "(", "'blogs/supernav.html'", ",", "{", "'entry'", ":", "entry", "}", ")" ]
utility to make testing update_blogs management command easier .
train
false
43,217
def calculate_avail_vmem(mems): free = mems['MemFree:'] fallback = (free + mems.get('Cached:', 0)) try: lru_active_file = mems['Active(file):'] lru_inactive_file = mems['Inactive(file):'] slab_reclaimable = mems['SReclaimable:'] except KeyError: return fallback try: f = open_binary(('%s/zoneinfo' % get_p...
[ "def", "calculate_avail_vmem", "(", "mems", ")", ":", "free", "=", "mems", "[", "'MemFree:'", "]", "fallback", "=", "(", "free", "+", "mems", ".", "get", "(", "'Cached:'", ",", "0", ")", ")", "try", ":", "lru_active_file", "=", "mems", "[", "'Active(fi...
fallback for kernels < 3 .
train
false
43,218
def allocate_address(ec2, domain, reuse_existing_ip_allowed): if reuse_existing_ip_allowed: domain_filter = {'domain': (domain or 'standard')} all_addresses = ec2.get_all_addresses(filters=domain_filter) if (domain == 'vpc'): unassociated_addresses = [a for a in all_addresses if (not a.association_id)] else...
[ "def", "allocate_address", "(", "ec2", ",", "domain", ",", "reuse_existing_ip_allowed", ")", ":", "if", "reuse_existing_ip_allowed", ":", "domain_filter", "=", "{", "'domain'", ":", "(", "domain", "or", "'standard'", ")", "}", "all_addresses", "=", "ec2", ".", ...
allocate a new elastic ip address and return it .
train
false
43,219
def test_config_file_override_stack(script, virtualenv): (fd, config_file) = tempfile.mkstemp('-pip.cfg', 'test-') try: _test_config_file_override_stack(script, virtualenv, config_file) finally: os.close(fd) os.remove(config_file)
[ "def", "test_config_file_override_stack", "(", "script", ",", "virtualenv", ")", ":", "(", "fd", ",", "config_file", ")", "=", "tempfile", ".", "mkstemp", "(", "'-pip.cfg'", ",", "'test-'", ")", "try", ":", "_test_config_file_override_stack", "(", "script", ",",...
test config files .
train
false
43,224
def gen_random_state(): M1 = 2147483647 M2 = 2147462579 return (np.random.randint(0, M1, 3).tolist() + np.random.randint(0, M2, 3).tolist())
[ "def", "gen_random_state", "(", ")", ":", "M1", "=", "2147483647", "M2", "=", "2147462579", "return", "(", "np", ".", "random", ".", "randint", "(", "0", ",", "M1", ",", "3", ")", ".", "tolist", "(", ")", "+", "np", ".", "random", ".", "randint", ...
helper to generate a random state for mrg_randomstreams .
train
false
43,226
def descriptor_global_handler_url(block, handler_name, suffix='', query='', thirdparty=False): raise NotImplementedError('Applications must monkey-patch this function before using handler_url for studio_view')
[ "def", "descriptor_global_handler_url", "(", "block", ",", "handler_name", ",", "suffix", "=", "''", ",", "query", "=", "''", ",", "thirdparty", "=", "False", ")", ":", "raise", "NotImplementedError", "(", "'Applications must monkey-patch this function before using hand...
see :meth:xblock .
train
false
43,227
def filter_preconditions(classes, logger=None): filtered = [] for cls in classes: (status, message) = cls.check_precondition() if status: filtered.append(cls) elif (logger is not None): logger.warning('Disabling handler %s because preconditions not met: %s.', cls.name, message) return filtered
[ "def", "filter_preconditions", "(", "classes", ",", "logger", "=", "None", ")", ":", "filtered", "=", "[", "]", "for", "cls", "in", "classes", ":", "(", "status", ",", "message", ")", "=", "cls", ".", "check_precondition", "(", ")", "if", "status", ":"...
filter handlers whose preconditions are not met classes: list of nogotofail handler classes to filter logger: logging .
train
false
43,228
def cookie_decode(data, key, digestmod=None): depr(0, 13, 'cookie_decode() will be removed soon.', 'Do not use this API directly.') data = tob(data) if cookie_is_encoded(data): (sig, msg) = data.split(tob('?'), 1) digestmod = (digestmod or hashlib.sha256) hashed = hmac.new(tob(key), msg, digestmod=digestmod).d...
[ "def", "cookie_decode", "(", "data", ",", "key", ",", "digestmod", "=", "None", ")", ":", "depr", "(", "0", ",", "13", ",", "'cookie_decode() will be removed soon.'", ",", "'Do not use this API directly.'", ")", "data", "=", "tob", "(", "data", ")", "if", "c...
verify and decode an encoded string .
train
true
43,229
@_api_version(1.21) @_client_version('1.5.0') def disconnect_container_from_network(container, network_id): response = _client_wrapper('disconnect_container_from_network', container, network_id) _clear_context() return response
[ "@", "_api_version", "(", "1.21", ")", "@", "_client_version", "(", "'1.5.0'", ")", "def", "disconnect_container_from_network", "(", "container", ",", "network_id", ")", ":", "response", "=", "_client_wrapper", "(", "'disconnect_container_from_network'", ",", "contain...
disconnect container from network .
train
false
43,230
def setup_testing_defaults(environ): environ.setdefault('SERVER_NAME', '127.0.0.1') environ.setdefault('SERVER_PROTOCOL', 'HTTP/1.0') environ.setdefault('HTTP_HOST', environ['SERVER_NAME']) environ.setdefault('REQUEST_METHOD', 'GET') if (('SCRIPT_NAME' not in environ) and ('PATH_INFO' not in environ)): environ.s...
[ "def", "setup_testing_defaults", "(", "environ", ")", ":", "environ", ".", "setdefault", "(", "'SERVER_NAME'", ",", "'127.0.0.1'", ")", "environ", ".", "setdefault", "(", "'SERVER_PROTOCOL'", ",", "'HTTP/1.0'", ")", "environ", ".", "setdefault", "(", "'HTTP_HOST'"...
update environ with trivial defaults for testing purposes this adds various parameters required for wsgi .
train
false
43,231
def get_variables(scope=None, suffix=None): candidates = tf.get_collection(MODEL_VARIABLES, scope)[:] if (suffix is not None): candidates = [var for var in candidates if var.op.name.endswith(suffix)] return candidates
[ "def", "get_variables", "(", "scope", "=", "None", ",", "suffix", "=", "None", ")", ":", "candidates", "=", "tf", ".", "get_collection", "(", "MODEL_VARIABLES", ",", "scope", ")", "[", ":", "]", "if", "(", "suffix", "is", "not", "None", ")", ":", "ca...
gets the list of variables .
train
true
43,232
def _get_user_model(): custom_model = getattr(settings, setting_name('USER_MODEL'), None) if custom_model: return module_member(custom_model) try: from mongoengine.django.mongo_auth.models import get_user_document return get_user_document() except ImportError: return module_member('mongoengine.django.auth.U...
[ "def", "_get_user_model", "(", ")", ":", "custom_model", "=", "getattr", "(", "settings", ",", "setting_name", "(", "'USER_MODEL'", ")", ",", "None", ")", "if", "custom_model", ":", "return", "module_member", "(", "custom_model", ")", "try", ":", "from", "mo...
get the user document class user for mongoengine authentication .
train
false
43,233
def _find_monitor(cs, monitor): return utils.find_resource(cs.monitors, monitor)
[ "def", "_find_monitor", "(", "cs", ",", "monitor", ")", ":", "return", "utils", ".", "find_resource", "(", "cs", ".", "monitors", ",", "monitor", ")" ]
get a monitor by id .
train
false
43,235
def stack_partitions(dfs, divisions, join='outer'): meta = methods.concat([df._meta for df in dfs], join=join) empty = strip_unknown_categories(meta) name = 'concat-{0}'.format(tokenize(*dfs)) dsk = {} i = 0 for df in dfs: dsk.update(df.dask) try: (df._meta == meta) match = True except (ValueError, Ty...
[ "def", "stack_partitions", "(", "dfs", ",", "divisions", ",", "join", "=", "'outer'", ")", ":", "meta", "=", "methods", ".", "concat", "(", "[", "df", ".", "_meta", "for", "df", "in", "dfs", "]", ",", "join", "=", "join", ")", "empty", "=", "strip_...
concatenate partitions on axis=0 by doing a simple stack .
train
false
43,236
def show_pillar(item=None): if item: return __salt__['pillar.get'](('oracle:' + item)) else: return __salt__['pillar.get']('oracle')
[ "def", "show_pillar", "(", "item", "=", "None", ")", ":", "if", "item", ":", "return", "__salt__", "[", "'pillar.get'", "]", "(", "(", "'oracle:'", "+", "item", ")", ")", "else", ":", "return", "__salt__", "[", "'pillar.get'", "]", "(", "'oracle'", ")"...
show pillar segment oracle .
train
false
43,238
def is_array_scalar(x): return (np.size(x) == 1)
[ "def", "is_array_scalar", "(", "x", ")", ":", "return", "(", "np", ".", "size", "(", "x", ")", "==", "1", ")" ]
test whether x is either a scalar or an array scalar .
train
false
43,240
def export_pipeline(exported_pipeline): pipeline_tree = expr_to_tree(exported_pipeline) pipeline_text = generate_import_code(exported_pipeline) pipeline_text += pipeline_code_wrapper(generate_pipeline_code(pipeline_tree)) return pipeline_text
[ "def", "export_pipeline", "(", "exported_pipeline", ")", ":", "pipeline_tree", "=", "expr_to_tree", "(", "exported_pipeline", ")", "pipeline_text", "=", "generate_import_code", "(", "exported_pipeline", ")", "pipeline_text", "+=", "pipeline_code_wrapper", "(", "generate_p...
generates the source code of a tpot pipeline parameters exported_pipeline: deap .
train
false
43,241
def list_members_without_mfa(profile='github', ignore_cache=False): key = 'github.{0}:non_mfa_users'.format(_get_config_value(profile, 'org_name')) if ((key not in __context__) or ignore_cache): client = _get_client(profile) organization = client.get_organization(_get_config_value(profile, 'org_name')) filter_k...
[ "def", "list_members_without_mfa", "(", "profile", "=", "'github'", ",", "ignore_cache", "=", "False", ")", ":", "key", "=", "'github.{0}:non_mfa_users'", ".", "format", "(", "_get_config_value", "(", "profile", ",", "'org_name'", ")", ")", "if", "(", "(", "ke...
list all members without mfa turned on .
train
true
43,242
def wordwrap(value, arg): from django.utils.text import wrap return wrap(value, int(arg))
[ "def", "wordwrap", "(", "value", ",", "arg", ")", ":", "from", "django", ".", "utils", ".", "text", "import", "wrap", "return", "wrap", "(", "value", ",", "int", "(", "arg", ")", ")" ]
wraps words at specified line length argument: number of characters to wrap the text at .
train
false
43,245
@task @set_modified_on def resize_icon(src, dst, locally=False, **kw): log.info(('[1@None] Resizing icon: %s' % dst)) try: resize_image(src, dst, (32, 32), locally=locally) return True except Exception as e: log.error(('Error saving collection icon: %s' % e))
[ "@", "task", "@", "set_modified_on", "def", "resize_icon", "(", "src", ",", "dst", ",", "locally", "=", "False", ",", "**", "kw", ")", ":", "log", ".", "info", "(", "(", "'[1@None] Resizing icon: %s'", "%", "dst", ")", ")", "try", ":", "resize_image", ...
resizes collection icons to 32x32 .
train
false
43,246
def authenticationReject(): a = TpPd(pd=5) b = MessageType(mesType=17) packet = (a / b) return packet
[ "def", "authenticationReject", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "5", ")", "b", "=", "MessageType", "(", "mesType", "=", "17", ")", "packet", "=", "(", "a", "/", "b", ")", "return", "packet" ]
authentication reject section 9 .
train
true
43,247
@if_conch def generate_ssh_key(key_file): check_call(['ssh-keygen', '-f', key_file.path, '-N', '', '-q']) return Key.fromFile(key_file.path)
[ "@", "if_conch", "def", "generate_ssh_key", "(", "key_file", ")", ":", "check_call", "(", "[", "'ssh-keygen'", ",", "'-f'", ",", "key_file", ".", "path", ",", "'-N'", ",", "''", ",", "'-q'", "]", ")", "return", "Key", ".", "fromFile", "(", "key_file", ...
generate a ssh key .
train
false
43,249
@keep_lazy_text def normalize_newlines(text): text = force_text(text) return re_newlines.sub('\n', text)
[ "@", "keep_lazy_text", "def", "normalize_newlines", "(", "text", ")", ":", "text", "=", "force_text", "(", "text", ")", "return", "re_newlines", ".", "sub", "(", "'\\n'", ",", "text", ")" ]
normalizes crlf and cr newlines to just lf .
train
false
43,251
def test_compound_custom_inverse(): poly = Polynomial1D(1, c0=1, c1=2) scale = Scale(1) shift = Shift(1) model1 = (poly | scale) model1.inverse = poly model2 = (shift | model1) assert_allclose(model2.inverse(1), (poly | shift.inverse)(1)) with pytest.raises(NotImplementedError): (shift + model1).inverse with...
[ "def", "test_compound_custom_inverse", "(", ")", ":", "poly", "=", "Polynomial1D", "(", "1", ",", "c0", "=", "1", ",", "c1", "=", "2", ")", "scale", "=", "Scale", "(", "1", ")", "shift", "=", "Shift", "(", "1", ")", "model1", "=", "(", "poly", "|...
test that a compound model with a custom inverse has that inverse applied when the inverse of another model .
train
false
43,252
def _parse_file(document_file, validate, entry_class, entry_keyword='r', start_position=None, end_position=None, section_end_keywords=(), extra_args=()): if start_position: document_file.seek(start_position) else: start_position = document_file.tell() if section_end_keywords: first_keyword = None line_match ...
[ "def", "_parse_file", "(", "document_file", ",", "validate", ",", "entry_class", ",", "entry_keyword", "=", "'r'", ",", "start_position", "=", "None", ",", "end_position", "=", "None", ",", "section_end_keywords", "=", "(", ")", ",", "extra_args", "=", "(", ...
iterates over a tordnsel file .
train
false
43,253
def _api_queue_priority(output, value, kwargs): value2 = kwargs.get('value2') if (value and value2): try: try: priority = int(value2) except: return report(output, _MSG_INT_VALUE) pos = set_priority(value, priority) return report(output, keyword='position', data=pos) except: return report(o...
[ "def", "_api_queue_priority", "(", "output", ",", "value", ",", "kwargs", ")", ":", "value2", "=", "kwargs", ".", "get", "(", "'value2'", ")", "if", "(", "value", "and", "value2", ")", ":", "try", ":", "try", ":", "priority", "=", "int", "(", "value2...
api: accepts output .
train
false
43,254
def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if (not conn): return {'exists': bool(conn)} rds = conn.describe_db_subnet_groups(DBSubnetGroupName=name) return {'exists': bool(rds)} excep...
[ "def", "subnet_group_exists", "(", "name", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "r...
check to see if an rds subnet group exists .
train
false
43,256
def pwd_from_uid(uid): global _uid_to_pwd_cache, _name_to_pwd_cache (entry, cached) = _cache_key_value(pwd.getpwuid, uid, _uid_to_pwd_cache) if (entry and (not cached)): _name_to_pwd_cache[entry.pw_name] = entry return entry
[ "def", "pwd_from_uid", "(", "uid", ")", ":", "global", "_uid_to_pwd_cache", ",", "_name_to_pwd_cache", "(", "entry", ",", "cached", ")", "=", "_cache_key_value", "(", "pwd", ".", "getpwuid", ",", "uid", ",", "_uid_to_pwd_cache", ")", "if", "(", "entry", "and...
return password database entry for uid .
train
false
43,258
def must_have_addon(addon_name, model): def wrapper(func): @functools.wraps(func) @collect_auth def wrapped(*args, **kwargs): if (model == 'node'): _inject_nodes(kwargs) owner = kwargs['node'] elif (model == 'user'): auth = kwargs.get('auth') owner = (auth.user if auth else None) if (ow...
[ "def", "must_have_addon", "(", "addon_name", ",", "model", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "@", "collect_auth", "def", "wrapped", "(", "*", "args", ",", "**", "kwargs", ")", ":", "i...
decorator factory that ensures that a given addon has been added to the target node .
train
false
43,259
def skip_if_disabled(func): @functools.wraps(func) def wrapped(*a, **kwargs): func.__test__ = False test_obj = a[0] message = getattr(test_obj, 'disabled_message', 'Test disabled') if getattr(test_obj, 'disabled', False): test_obj.skipTest(message) func(*a, **kwargs) return wrapped
[ "def", "skip_if_disabled", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "a", ",", "**", "kwargs", ")", ":", "func", ".", "__test__", "=", "False", "test_obj", "=", "a", "[", "0", "]", "message...
decorator that skips a test if test case is disabled .
train
false
43,260
@register.inclusion_tag(u'includes/pagination.html', takes_context=True) def pagination_for(context, current_page, page_var=u'page', exclude_vars=u''): querystring = context[u'request'].GET.copy() exclude_vars = ([v for v in exclude_vars.split(u',') if v] + [page_var]) for exclude_var in exclude_vars: if (exclude_...
[ "@", "register", ".", "inclusion_tag", "(", "u'includes/pagination.html'", ",", "takes_context", "=", "True", ")", "def", "pagination_for", "(", "context", ",", "current_page", ",", "page_var", "=", "u'page'", ",", "exclude_vars", "=", "u''", ")", ":", "querystr...
include the pagination template and data for persisting querystring in pagination links .
train
false
43,261
def get_stack_at_position(grammar, code_lines, module, pos): class EndMarkerReached(Exception, ): pass def tokenize_without_endmarker(code): tokens = tokenize.source_tokens(code, use_exact_op_types=True) for token_ in tokens: if (token_.string == safeword): raise EndMarkerReached() else: (yield to...
[ "def", "get_stack_at_position", "(", "grammar", ",", "code_lines", ",", "module", ",", "pos", ")", ":", "class", "EndMarkerReached", "(", "Exception", ",", ")", ":", "pass", "def", "tokenize_without_endmarker", "(", "code", ")", ":", "tokens", "=", "tokenize",...
returns the possible node names .
train
false
43,262
def _create_diff(diff, fun, key, prev, curr): if (not fun(prev)): _create_diff_action(diff, 'added', key, curr) elif (fun(prev) and (not fun(curr))): _create_diff_action(diff, 'removed', key, prev) elif (not fun(curr)): _create_diff_action(diff, 'updated', key, curr)
[ "def", "_create_diff", "(", "diff", ",", "fun", ",", "key", ",", "prev", ",", "curr", ")", ":", "if", "(", "not", "fun", "(", "prev", ")", ")", ":", "_create_diff_action", "(", "diff", ",", "'added'", ",", "key", ",", "curr", ")", "elif", "(", "f...
builds the diff dictionary .
train
true
43,263
def is_exe(filepath): return (os.path.exists(filepath) and os.access(filepath, os.X_OK))
[ "def", "is_exe", "(", "filepath", ")", ":", "return", "(", "os", ".", "path", ".", "exists", "(", "filepath", ")", "and", "os", ".", "access", "(", "filepath", ",", "os", ".", "X_OK", ")", ")" ]
test if a file is an executable .
train
false
43,264
def set_mako(mako, key=_registry_key, app=None): app = (app or webapp2.get_app()) app.registry[key] = mako
[ "def", "set_mako", "(", "mako", ",", "key", "=", "_registry_key", ",", "app", "=", "None", ")", ":", "app", "=", "(", "app", "or", "webapp2", ".", "get_app", "(", ")", ")", "app", ".", "registry", "[", "key", "]", "=", "mako" ]
sets an instance of :class:mako in the app registry .
train
false
43,265
def capacity_assessment_data(): return s3_rest_controller()
[ "def", "capacity_assessment_data", "(", ")", ":", "return", "s3_rest_controller", "(", ")" ]
restful crud controller - just used for the custom_report method .
train
false
43,268
@must_have_permission(ADMIN) @must_be_branched_from_node def draft_before_register_page(auth, node, draft, *args, **kwargs): ret = serialize_node(node, auth, primary=True) ret['draft'] = serialize_draft_registration(draft, auth) return ret
[ "@", "must_have_permission", "(", "ADMIN", ")", "@", "must_be_branched_from_node", "def", "draft_before_register_page", "(", "auth", ",", "node", ",", "draft", ",", "*", "args", ",", "**", "kwargs", ")", ":", "ret", "=", "serialize_node", "(", "node", ",", "...
allow the user to select an embargo period and confirm registration :return: serialized node + draftregistration :rtype: dict .
train
false
43,269
def getAnalyzePluginsDirectoryPath(subName=''): return getJoinedPath(getSkeinforgePluginsPath('analyze_plugins'), subName)
[ "def", "getAnalyzePluginsDirectoryPath", "(", "subName", "=", "''", ")", ":", "return", "getJoinedPath", "(", "getSkeinforgePluginsPath", "(", "'analyze_plugins'", ")", ",", "subName", ")" ]
get the analyze plugins directory path .
train
false
43,270
def _ns(tag, namespace=NAMESPACES['phy']): return ('{%s}%s' % (namespace, tag))
[ "def", "_ns", "(", "tag", ",", "namespace", "=", "NAMESPACES", "[", "'phy'", "]", ")", ":", "return", "(", "'{%s}%s'", "%", "(", "namespace", ",", "tag", ")", ")" ]
format an xml tag with the given namespace .
train
false
43,271
def decode_missing(line): result = {} parts = line.split() result['object_hash'] = urllib.parse.unquote(parts[0]) t_data = urllib.parse.unquote(parts[1]) result['ts_data'] = Timestamp(t_data) result['ts_meta'] = result['ts_ctype'] = result['ts_data'] if (len(parts) > 2): subparts = urllib.parse.unquote(parts[2...
[ "def", "decode_missing", "(", "line", ")", ":", "result", "=", "{", "}", "parts", "=", "line", ".", "split", "(", ")", "result", "[", "'object_hash'", "]", "=", "urllib", ".", "parse", ".", "unquote", "(", "parts", "[", "0", "]", ")", "t_data", "="...
parse a string of the form generated by :py:func:~swift .
train
false
43,272
def EnumKey(key, index): regenumkeyex = advapi32['RegEnumKeyExW'] regenumkeyex.restype = ctypes.c_long regenumkeyex.argtypes = [ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.c_wchar_p, LPDWORD, LPDWORD, ctypes.c_wchar_p, LPDWORD, ctypes.POINTER(FileTime)] buf = ctypes.create_unicode_buffer(257) length = ctypes.wi...
[ "def", "EnumKey", "(", "key", ",", "index", ")", ":", "regenumkeyex", "=", "advapi32", "[", "'RegEnumKeyExW'", "]", "regenumkeyex", ".", "restype", "=", "ctypes", ".", "c_long", "regenumkeyex", ".", "argtypes", "=", "[", "ctypes", ".", "c_void_p", ",", "ct...
this calls the windows regenumkeyex function in a unicode safe way .
train
true
43,273
def get_acl_usr(msg): if hasattr(msg.frm, 'aclattr'): return msg.frm.aclattr return msg.frm.person
[ "def", "get_acl_usr", "(", "msg", ")", ":", "if", "hasattr", "(", "msg", ".", "frm", ",", "'aclattr'", ")", ":", "return", "msg", ".", "frm", ".", "aclattr", "return", "msg", ".", "frm", ".", "person" ]
return the acl attribute of the sender of the given message .
train
false
43,274
def get_device_count(verbose=False): try: import pycuda import pycuda.driver as drv except ImportError: if verbose: neon_logger.display('PyCUDA module not found') return 0 try: drv.init() except pycuda._driver.RuntimeError as e: neon_logger.display('PyCUDA Runtime error: {0}'.format(str(e))) return...
[ "def", "get_device_count", "(", "verbose", "=", "False", ")", ":", "try", ":", "import", "pycuda", "import", "pycuda", ".", "driver", "as", "drv", "except", "ImportError", ":", "if", "verbose", ":", "neon_logger", ".", "display", "(", "'PyCUDA module not found...
query device count through pycuda .
train
false
43,275
def benchmark_influence(conf): prediction_times = [] prediction_powers = [] complexities = [] for param_value in conf['changing_param_values']: conf['tuned_params'][conf['changing_param']] = param_value estimator = conf['estimator'](**conf['tuned_params']) print ('Benchmarking %s' % estimator) estimator.fit...
[ "def", "benchmark_influence", "(", "conf", ")", ":", "prediction_times", "=", "[", "]", "prediction_powers", "=", "[", "]", "complexities", "=", "[", "]", "for", "param_value", "in", "conf", "[", "'changing_param_values'", "]", ":", "conf", "[", "'tuned_params...
benchmark influence of :changing_param: on both mse and latency .
train
false
43,276
def eligible_for_deletion(conf, namespace, force=False): if conf.agent_type: prefixes = NS_PREFIXES.get(conf.agent_type) else: prefixes = itertools.chain(*NS_PREFIXES.values()) ns_mangling_pattern = ('(%s%s)' % ('|'.join(prefixes), constants.UUID_PATTERN)) if (not re.match(ns_mangling_pattern, namespace)): re...
[ "def", "eligible_for_deletion", "(", "conf", ",", "namespace", ",", "force", "=", "False", ")", ":", "if", "conf", ".", "agent_type", ":", "prefixes", "=", "NS_PREFIXES", ".", "get", "(", "conf", ".", "agent_type", ")", "else", ":", "prefixes", "=", "ite...
determine whether a namespace is eligible for deletion .
train
false
43,277
def ll_op(left, right): if (len(left) > 0): ll_gate = left[0] ll_gate_is_unitary = is_scalar_matrix((Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True) if ((len(left) > 0) and ll_gate_is_unitary): new_left = left[1:len(left)] new_right = ((Dagger(ll_gate),) + right) return (new_left, new_right) ret...
[ "def", "ll_op", "(", "left", ",", "right", ")", ":", "if", "(", "len", "(", "left", ")", ">", "0", ")", ":", "ll_gate", "=", "left", "[", "0", "]", "ll_gate_is_unitary", "=", "is_scalar_matrix", "(", "(", "Dagger", "(", "ll_gate", ")", ",", "ll_gat...
perform a ll operation .
train
false
43,278
def example1(): l_in = lasagne.layers.InputLayer((100, 20)) l_hidden1 = lasagne.layers.DenseLayer(l_in, num_units=20) l_hidden1_dropout = lasagne.layers.DropoutLayer(l_hidden1) l_hidden2 = lasagne.layers.DenseLayer(l_hidden1_dropout, num_units=20) l_hidden2_dropout = lasagne.layers.DropoutLayer(l_hidden2) l_out =...
[ "def", "example1", "(", ")", ":", "l_in", "=", "lasagne", ".", "layers", ".", "InputLayer", "(", "(", "100", ",", "20", ")", ")", "l_hidden1", "=", "lasagne", ".", "layers", ".", "DenseLayer", "(", "l_in", ",", "num_units", "=", "20", ")", "l_hidden1...
sequential network .
train
false
43,279
def keys(name, basepath='/etc/pki'): ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} pillar = __salt__['pillar.ext']({'libvirt': '_'}) paths = {'serverkey': os.path.join(basepath, 'libvirt', 'private', 'serverkey.pem'), 'servercert': os.path.join(basepath, 'libvirt', 'servercert.pem'), 'clientkey'...
[ "def", "keys", "(", "name", ",", "basepath", "=", "'/etc/pki'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "pillar", "=", "__salt__", "[", "'pil...
a context manager that sets up the correct keyczar environment for a test .
train
false
43,280
def varcorrection_unequal(var_all, nobs_all, df_all): var_all = np.asarray(var_all) var_over_n = ((var_all * 1.0) / nobs_all) varjoint = var_over_n.sum() dfjoint = ((varjoint ** 2) / ((var_over_n ** 2) * df_all).sum()) return (varjoint, dfjoint)
[ "def", "varcorrection_unequal", "(", "var_all", ",", "nobs_all", ",", "df_all", ")", ":", "var_all", "=", "np", ".", "asarray", "(", "var_all", ")", "var_over_n", "=", "(", "(", "var_all", "*", "1.0", ")", "/", "nobs_all", ")", "varjoint", "=", "var_over...
return joint variance from samples with unequal variances and unequal sample sizes something is wrong parameters var_all : array_like the variance for each sample nobs_all : array_like the number of observations for each sample df_all : array_like degrees of freedom for each sample returns varjoint : float joint varian...
train
false
43,282
def get_manual_interface_attributes(interface, module): if (get_interface_type(interface) == 'svi'): command = ('show interface ' + interface) try: body = execute_modified_show_for_cli_text(command, module)[0] except (IndexError, ShellError): return None command_list = body.split('\n') desc = None ad...
[ "def", "get_manual_interface_attributes", "(", "interface", ",", "module", ")", ":", "if", "(", "get_interface_type", "(", "interface", ")", "==", "'svi'", ")", ":", "command", "=", "(", "'show interface '", "+", "interface", ")", "try", ":", "body", "=", "e...
gets admin state and description of a svi interface .
train
false
43,284
def get_nodes(node, klass): for child in node.children: if isinstance(child, klass): (yield child) for grandchild in get_nodes(child, klass): (yield grandchild)
[ "def", "get_nodes", "(", "node", ",", "klass", ")", ":", "for", "child", "in", "node", ".", "children", ":", "if", "isinstance", "(", "child", ",", "klass", ")", ":", "(", "yield", "child", ")", "for", "grandchild", "in", "get_nodes", "(", "child", "...
return an iterator on all children node of the given klass .
train
false
43,286
@handle_response_format @treeio_login_required @_process_mass_form def index_assigned(request, response_format='html'): context = _get_default_context(request) agent = context['agent'] if agent: query = Q(assigned=agent) if request.GET: if (('status' in request.GET) and request.GET['status']): query = (qu...
[ "@", "handle_response_format", "@", "treeio_login_required", "@", "_process_mass_form", "def", "index_assigned", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "context", "=", "_get_default_context", "(", "request", ")", "agent", "=", "context", "[...
tickets assigned to current user .
train
false
43,287
def parse_host_list(list_of_hosts): p = set((m.group(1) for m in re.finditer('\\s*([^,\\s]+)\\s*,?\\s*', list_of_hosts))) return p
[ "def", "parse_host_list", "(", "list_of_hosts", ")", ":", "p", "=", "set", "(", "(", "m", ".", "group", "(", "1", ")", "for", "m", "in", "re", ".", "finditer", "(", "'\\\\s*([^,\\\\s]+)\\\\s*,?\\\\s*'", ",", "list_of_hosts", ")", ")", ")", "return", "p" ...
parse the comma separated list of hosts .
train
false
43,292
def getScalarMetricWithTimeOfDayAnomalyParams(metricData, minVal=None, maxVal=None, minResolution=None, tmImplementation='cpp'): if (minResolution is None): minResolution = 0.001 if ((minVal is None) or (maxVal is None)): (compMinVal, compMaxVal) = _rangeGen(metricData) if (minVal is None): minVal = compMinV...
[ "def", "getScalarMetricWithTimeOfDayAnomalyParams", "(", "metricData", ",", "minVal", "=", "None", ",", "maxVal", "=", "None", ",", "minResolution", "=", "None", ",", "tmImplementation", "=", "'cpp'", ")", ":", "if", "(", "minResolution", "is", "None", ")", ":...
return a dict that can be used to create an anomaly model via opfs modelfactory .
train
true
43,293
def parse_response(resp, content, strict=False, content_type=None): if (not content_type): content_type = resp.headers.get('content-type', 'application/json') (ct, options) = parse_options_header(content_type) if (ct in ('application/json', 'text/javascript')): if (not content): return {} return json.loads(...
[ "def", "parse_response", "(", "resp", ",", "content", ",", "strict", "=", "False", ",", "content_type", "=", "None", ")", ":", "if", "(", "not", "content_type", ")", ":", "content_type", "=", "resp", ".", "headers", ".", "get", "(", "'content-type'", ","...
try and parse response as an http response .
train
true
43,294
def getKeyIsInPixelTableAddValue(key, pathIndexTable, pixelTable): if (key in pixelTable): value = pixelTable[key] if (value != None): pathIndexTable[value] = None return True return False
[ "def", "getKeyIsInPixelTableAddValue", "(", "key", ",", "pathIndexTable", ",", "pixelTable", ")", ":", "if", "(", "key", "in", "pixelTable", ")", ":", "value", "=", "pixelTable", "[", "key", "]", "if", "(", "value", "!=", "None", ")", ":", "pathIndexTable"...
determine if the key is in the pixel table .
train
false
43,295
def failureFromJSON(failureDict): newFailure = getattr(Failure, '__new__', None) if (newFailure is None): f = types.InstanceType(Failure) else: f = newFailure(Failure) if (not _PY3): failureDict = asBytes(failureDict) typeInfo = failureDict['type'] failureDict['type'] = type(typeInfo['__name__'], (), typeIn...
[ "def", "failureFromJSON", "(", "failureDict", ")", ":", "newFailure", "=", "getattr", "(", "Failure", ",", "'__new__'", ",", "None", ")", "if", "(", "newFailure", "is", "None", ")", ":", "f", "=", "types", ".", "InstanceType", "(", "Failure", ")", "else"...
load a l{failure} from a dictionary deserialized from json .
train
false
43,296
def ld_cifar10(test_only=False): file_urls = ['https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'] local_urls = maybe_download(file_urls, FLAGS.data_dir) dataset = extract_cifar10(local_urls[0], FLAGS.data_dir) (train_data, train_labels, test_data, test_labels) = dataset train_data = image_whitening(train_da...
[ "def", "ld_cifar10", "(", "test_only", "=", "False", ")", ":", "file_urls", "=", "[", "'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'", "]", "local_urls", "=", "maybe_download", "(", "file_urls", ",", "FLAGS", ".", "data_dir", ")", "dataset", "=", "extrac...
load the original cifar10 data .
train
false
43,297
def CredibleInterval(pmf, percentage=90): cdf = pmf.MakeCdf() prob = ((1 - (percentage / 100.0)) / 2) interval = (cdf.Value(prob), cdf.Value((1 - prob))) return interval
[ "def", "CredibleInterval", "(", "pmf", ",", "percentage", "=", "90", ")", ":", "cdf", "=", "pmf", ".", "MakeCdf", "(", ")", "prob", "=", "(", "(", "1", "-", "(", "percentage", "/", "100.0", ")", ")", "/", "2", ")", "interval", "=", "(", "cdf", ...
computes a credible interval for a given distribution .
train
true
43,301
def webattack_vector(attack_vector): return {'1': 'java', '2': 'browser', '3': 'harvester', '4': 'tabnapping', '5': 'webjacking', '6': 'multiattack', '7': 'fsattack'}.get(attack_vector, 'ERROR')
[ "def", "webattack_vector", "(", "attack_vector", ")", ":", "return", "{", "'1'", ":", "'java'", ",", "'2'", ":", "'browser'", ",", "'3'", ":", "'harvester'", ",", "'4'", ":", "'tabnapping'", ",", "'5'", ":", "'webjacking'", ",", "'6'", ":", "'multiattack'"...
receives the input given by the user from set .
train
false
43,302
def transform_column_source_data(data): data_copy = {} for key in iterkeys(data): if (pd and isinstance(data[key], (pd.Series, pd.Index))): data_copy[key] = transform_series(data[key]) elif isinstance(data[key], np.ndarray): data_copy[key] = transform_array(data[key]) else: data_copy[key] = traverse_da...
[ "def", "transform_column_source_data", "(", "data", ")", ":", "data_copy", "=", "{", "}", "for", "key", "in", "iterkeys", "(", "data", ")", ":", "if", "(", "pd", "and", "isinstance", "(", "data", "[", "key", "]", ",", "(", "pd", ".", "Series", ",", ...
transform columnsourcedata data to a serialized format args: data : the mapping of names to data columns to transform returns: json compatible dict .
train
false
43,303
def patch_signal(): patch_module('signal')
[ "def", "patch_signal", "(", ")", ":", "patch_module", "(", "'signal'", ")" ]
make the signal .
train
false
43,309
def ConvertToNumber(value): try: return int(value) except: return float(value)
[ "def", "ConvertToNumber", "(", "value", ")", ":", "try", ":", "return", "int", "(", "value", ")", "except", ":", "return", "float", "(", "value", ")" ]
converts value .
train
false
43,310
def set_proxy(proxy, user=None, password=''): from nltk import compat if (proxy is None): try: proxy = getproxies()['http'] except KeyError: raise ValueError('Could not detect default proxy settings') proxy_handler = ProxyHandler({'http': proxy}) opener = build_opener(proxy_handler) if (user is not None)...
[ "def", "set_proxy", "(", "proxy", ",", "user", "=", "None", ",", "password", "=", "''", ")", ":", "from", "nltk", "import", "compat", "if", "(", "proxy", "is", "None", ")", ":", "try", ":", "proxy", "=", "getproxies", "(", ")", "[", "'http'", "]", ...
set the http proxy for python to download through .
train
false
43,311
def yaml_encode(data): yrepr = yaml.representer.SafeRepresenter() ynode = yrepr.represent_data(data) if (not isinstance(ynode, yaml.ScalarNode)): raise TypeError('yaml_encode() only works with YAML scalar data; failed for {0}'.format(type(data))) tag = ynode.tag.rsplit(':', 1)[(-1)] ret = ynode.value if (tag ==...
[ "def", "yaml_encode", "(", "data", ")", ":", "yrepr", "=", "yaml", ".", "representer", ".", "SafeRepresenter", "(", ")", "ynode", "=", "yrepr", ".", "represent_data", "(", "data", ")", "if", "(", "not", "isinstance", "(", "ynode", ",", "yaml", ".", "Sc...
a simple yaml encode that can take a single-element datatype and return a string representation .
train
true
43,312
def ClientIdToHostname(client_id, token=None): client = OpenClient(client_id, token=token)[0] if (client and client.Get('Host')): return client.Get('Host').Summary()
[ "def", "ClientIdToHostname", "(", "client_id", ",", "token", "=", "None", ")", ":", "client", "=", "OpenClient", "(", "client_id", ",", "token", "=", "token", ")", "[", "0", "]", "if", "(", "client", "and", "client", ".", "Get", "(", "'Host'", ")", "...
quick helper for scripts to get a hostname from a client id .
train
false
43,313
def _arg_combine(data, axis, argfunc, keepdims=False): axis = (None if ((len(axis) == data.ndim) or (data.ndim == 1)) else axis[0]) vals = data['vals'] arg = data['arg'] if (axis is None): local_args = argfunc(vals, axis=axis, keepdims=keepdims) vals = vals.ravel()[local_args] arg = arg.ravel()[local_args] e...
[ "def", "_arg_combine", "(", "data", ",", "axis", ",", "argfunc", ",", "keepdims", "=", "False", ")", ":", "axis", "=", "(", "None", "if", "(", "(", "len", "(", "axis", ")", "==", "data", ".", "ndim", ")", "or", "(", "data", ".", "ndim", "==", "...
merge intermediate results from arg_* functions .
train
false
43,315
def info_installed(*names): ret = dict() for (pkg_name, pkg_nfo) in __salt__['lowpkg.info'](*names).items(): t_nfo = dict() for (key, value) in pkg_nfo.items(): if (key == 'source_rpm'): t_nfo['source'] = value else: t_nfo[key] = value ret[pkg_name] = t_nfo return ret
[ "def", "info_installed", "(", "*", "names", ")", ":", "ret", "=", "dict", "(", ")", "for", "(", "pkg_name", ",", "pkg_nfo", ")", "in", "__salt__", "[", "'lowpkg.info'", "]", "(", "*", "names", ")", ".", "items", "(", ")", ":", "t_nfo", "=", "dict",...
return the information of the named package(s) .
train
false
43,316
def copy_virtual_disk(session, dc_ref, source, dest): LOG.debug('Copying Virtual Disk %(source)s to %(dest)s', {'source': source, 'dest': dest}) vim = session.vim vmdk_copy_task = session._call_method(vim, 'CopyVirtualDisk_Task', vim.service_content.virtualDiskManager, sourceName=source, sourceDatacenter=dc_ref, des...
[ "def", "copy_virtual_disk", "(", "session", ",", "dc_ref", ",", "source", ",", "dest", ")", ":", "LOG", ".", "debug", "(", "'Copying Virtual Disk %(source)s to %(dest)s'", ",", "{", "'source'", ":", "source", ",", "'dest'", ":", "dest", "}", ")", "vim", "=",...
copy a sparse virtual disk to a thin virtual disk .
train
false
43,317
def reset_indent(TokenClass): def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = (-1) context.next_indent = 0 context.block_scalar_indent = None (yield (match.start(), TokenClass, text)) context.pos = match.end() return callback
[ "def", "reset_indent", "(", "TokenClass", ")", ":", "def", "callback", "(", "lexer", ",", "match", ",", "context", ")", ":", "text", "=", "match", ".", "group", "(", ")", "context", ".", "indent_stack", "=", "[", "]", "context", ".", "indent", "=", "...
reset the indentation levels .
train
true
43,318
def get_request_ip(request): return (request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR') or request.META.get('HTTP_X_REAL_IP'))
[ "def", "get_request_ip", "(", "request", ")", ":", "return", "(", "request", ".", "META", ".", "get", "(", "'HTTP_X_FORWARDED_FOR'", ")", "or", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ")", "or", "request", ".", "META", ".", "get", "(", ...
return the ip address from a http request object .
train
false
43,319
def parse_set_header(value, on_update=None): if (not value): return HeaderSet(None, on_update) return HeaderSet(parse_list_header(value), on_update)
[ "def", "parse_set_header", "(", "value", ",", "on_update", "=", "None", ")", ":", "if", "(", "not", "value", ")", ":", "return", "HeaderSet", "(", "None", ",", "on_update", ")", "return", "HeaderSet", "(", "parse_list_header", "(", "value", ")", ",", "on...
parse a set-like header and return a :class:~werkzeug .
train
true
43,320
def rm_host(ip, alias): if (not has_pair(ip, alias)): return True hfn = _get_or_create_hostfile() with salt.utils.fopen(hfn) as fp_: lines = fp_.readlines() for ind in range(len(lines)): tmpline = lines[ind].strip() if (not tmpline): continue if tmpline.startswith('#'): continue comps = tmpline.sp...
[ "def", "rm_host", "(", "ip", ",", "alias", ")", ":", "if", "(", "not", "has_pair", "(", "ip", ",", "alias", ")", ")", ":", "return", "True", "hfn", "=", "_get_or_create_hostfile", "(", ")", "with", "salt", ".", "utils", ".", "fopen", "(", "hfn", ")...
remove a host entry from the hosts file cli example: .
train
false
43,321
@cronjobs.register def update_l10n_metric(): if settings.STAGE: return top_60_docs = _get_top_docs(60) end = (date.today() - timedelta(days=1)) start = (end - timedelta(days=30)) locale_visits = googleanalytics.visitors_by_locale(start, end) total_visits = sum(locale_visits.itervalues()) coverage = 0 for (loc...
[ "@", "cronjobs", ".", "register", "def", "update_l10n_metric", "(", ")", ":", "if", "settings", ".", "STAGE", ":", "return", "top_60_docs", "=", "_get_top_docs", "(", "60", ")", "end", "=", "(", "date", ".", "today", "(", ")", "-", "timedelta", "(", "d...
calculate new l10n coverage numbers and save .
train
false
43,322
def create_event(name='TestEvent', creator_email=None, **kwargs): event = Event(name=name, start_time=datetime(2016, 4, 8, 12, 30, 45), end_time=datetime(2016, 4, 9, 12, 30, 45), **kwargs) if creator_email: event.creator = User.query.filter_by(email=creator_email).first() save_to_db(event, 'Event saved') copyrigh...
[ "def", "create_event", "(", "name", "=", "'TestEvent'", ",", "creator_email", "=", "None", ",", "**", "kwargs", ")", ":", "event", "=", "Event", "(", "name", "=", "name", ",", "start_time", "=", "datetime", "(", "2016", ",", "4", ",", "8", ",", "12",...
create an event on the victorops service .
train
false
43,323
def get_human_readable_disk_usage(d): if (platform.system() in ['Linux', 'FreeBSD']): try: return subprocess.Popen(['du', '-sh', d], stdout=subprocess.PIPE).communicate()[0].split()[0] except: raise CleanupException('rosclean is not supported on this platform') else: raise CleanupException('rosclean is no...
[ "def", "get_human_readable_disk_usage", "(", "d", ")", ":", "if", "(", "platform", ".", "system", "(", ")", "in", "[", "'Linux'", ",", "'FreeBSD'", "]", ")", ":", "try", ":", "return", "subprocess", ".", "Popen", "(", "[", "'du'", ",", "'-sh'", ",", ...
get human-readable disk usage for directory .
train
false
43,324
def make_runserver(app_factory, hostname='localhost', port=5000, use_reloader=False, use_debugger=False, use_evalex=True, threaded=False, processes=1, static_files=None, extra_files=None, ssl_context=None): _deprecated() def action(hostname=('h', hostname), port=('p', port), reloader=use_reloader, debugger=use_debugg...
[ "def", "make_runserver", "(", "app_factory", ",", "hostname", "=", "'localhost'", ",", "port", "=", "5000", ",", "use_reloader", "=", "False", ",", "use_debugger", "=", "False", ",", "use_evalex", "=", "True", ",", "threaded", "=", "False", ",", "processes",...
returns an action callback that spawns a new development server .
train
true
43,326
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
create a new git repository .
train
false
43,327
def user_deletemedia(mediaids, **connection_args): conn_args = _login(**connection_args) try: if conn_args: method = 'user.deletemedia' if (not isinstance(mediaids, list)): mediaids = [mediaids] params = mediaids ret = _query(method, params, conn_args['url'], conn_args['auth']) return ret['result...
[ "def", "user_deletemedia", "(", "mediaids", ",", "**", "connection_args", ")", ":", "conn_args", "=", "_login", "(", "**", "connection_args", ")", "try", ":", "if", "conn_args", ":", "method", "=", "'user.deletemedia'", "if", "(", "not", "isinstance", "(", "...
delete media by id .
train
true
43,328
def _format_return_data(retcode, stdout=None, stderr=None): ret = {'retcode': retcode} if (stdout is not None): ret['stdout'] = stdout if (stderr is not None): ret['stderr'] = stderr return ret
[ "def", "_format_return_data", "(", "retcode", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "ret", "=", "{", "'retcode'", ":", "retcode", "}", "if", "(", "stdout", "is", "not", "None", ")", ":", "ret", "[", "'stdout'", "]", "=", ...
creates a dictionary from the parameters .
train
true
43,329
def MakeDestinationKey(directory, filename): return utils.SmartStr(utils.JoinPath(directory, filename)).lstrip('/')
[ "def", "MakeDestinationKey", "(", "directory", ",", "filename", ")", ":", "return", "utils", ".", "SmartStr", "(", "utils", ".", "JoinPath", "(", "directory", ",", "filename", ")", ")", ".", "lstrip", "(", "'/'", ")" ]
creates a name that identifies a database file .
train
true
43,330
def _servicegroup_get_servers(sg_name, **connection_args): nitro = _connect(**connection_args) if (nitro is None): return None sg = NSServiceGroup() sg.set_servicegroupname(sg_name) try: sg = NSServiceGroup.get_servers(nitro, sg) except NSNitroError as error: log.debug('netscaler module error - NSServiceGro...
[ "def", "_servicegroup_get_servers", "(", "sg_name", ",", "**", "connection_args", ")", ":", "nitro", "=", "_connect", "(", "**", "connection_args", ")", "if", "(", "nitro", "is", "None", ")", ":", "return", "None", "sg", "=", "NSServiceGroup", "(", ")", "s...
returns a list of members of a servicegroup or none .
train
true
43,331
def solow_steady_state(g, n, s, alpha, delta): k_star = ((s / ((n + g) + delta)) ** (1 / (1 - alpha))) return k_star
[ "def", "solow_steady_state", "(", "g", ",", "n", ",", "s", ",", "alpha", ",", "delta", ")", ":", "k_star", "=", "(", "(", "s", "/", "(", "(", "n", "+", "g", ")", "+", "delta", ")", ")", "**", "(", "1", "/", "(", "1", "-", "alpha", ")", ")...
steady-state level of capital stock .
train
false
43,332
def memoized(maxsize=1024): cache = SimpleCache(maxsize=maxsize) def decorator(obj): @wraps(obj) def new_callable(*a, **kw): def create_new(): return obj(*a, **kw) key = (a, tuple(kw.items())) return cache.get(key, create_new) return new_callable return decorator
[ "def", "memoized", "(", "maxsize", "=", "1024", ")", ":", "cache", "=", "SimpleCache", "(", "maxsize", "=", "maxsize", ")", "def", "decorator", "(", "obj", ")", ":", "@", "wraps", "(", "obj", ")", "def", "new_callable", "(", "*", "a", ",", "**", "k...
decorator that caches function calls .
train
true
43,334
def wasLastResponseDelayed(): deviation = stdev(kb.responseTimes.get(kb.responseTimeMode, [])) threadData = getCurrentThreadData() if (deviation and (not conf.direct)): if (len(kb.responseTimes[kb.responseTimeMode]) < MIN_TIME_RESPONSES): warnMsg = 'time-based standard deviation method used on a model ' warn...
[ "def", "wasLastResponseDelayed", "(", ")", ":", "deviation", "=", "stdev", "(", "kb", ".", "responseTimes", ".", "get", "(", "kb", ".", "responseTimeMode", ",", "[", "]", ")", ")", "threadData", "=", "getCurrentThreadData", "(", ")", "if", "(", "deviation"...
returns true if the last web request resulted in a time-delay .
train
false
43,335
def im_feeling_lucky_async(image_data, output_encoding=PNG, quality=None, correct_orientation=UNCHANGED_ORIENTATION, rpc=None, transparent_substitution_rgb=None): image = Image(image_data) image.im_feeling_lucky() image.set_correct_orientation(correct_orientation) return image.execute_transforms_async(output_encodi...
[ "def", "im_feeling_lucky_async", "(", "image_data", ",", "output_encoding", "=", "PNG", ",", "quality", "=", "None", ",", "correct_orientation", "=", "UNCHANGED_ORIENTATION", ",", "rpc", "=", "None", ",", "transparent_substitution_rgb", "=", "None", ")", ":", "ima...
automatically adjust image levels - async version .
train
false
43,336
def enough_disk_space(service): available_space = get_available_disk_space() logging.debug('Available space: {0}'.format(available_space)) backup_size = get_backup_size(service) logging.debug('Backup size: {0}'.format(backup_size)) if (backup_size > (available_space * PADDING_PERCENTAGE)): logging.warning('Not e...
[ "def", "enough_disk_space", "(", "service", ")", ":", "available_space", "=", "get_available_disk_space", "(", ")", "logging", ".", "debug", "(", "'Available space: {0}'", ".", "format", "(", "available_space", ")", ")", "backup_size", "=", "get_backup_size", "(", ...
checks if theres enough available disk space for a new backup .
train
false
43,340
def is_proj_plane_distorted(wcs, maxerr=1e-05): cwcs = wcs.celestial return ((not _is_cd_orthogonal(cwcs.pixel_scale_matrix, maxerr)) or _has_distortion(cwcs))
[ "def", "is_proj_plane_distorted", "(", "wcs", ",", "maxerr", "=", "1e-05", ")", ":", "cwcs", "=", "wcs", ".", "celestial", "return", "(", "(", "not", "_is_cd_orthogonal", "(", "cwcs", ".", "pixel_scale_matrix", ",", "maxerr", ")", ")", "or", "_has_distortion...
for a wcs returns false if square image pixels stay square when projected onto the "plane of intermediate world coordinates" as defined in greisen & calabretta 2002 .
train
false
43,343
@check_dataset_access_permission @check_dataset_edition_permission() def edit_coordinator_dataset(request, dataset): response = {'status': (-1), 'data': 'None'} if (request.method == 'POST'): dataset_form = DatasetForm(request.POST, instance=dataset, prefix='edit') if dataset_form.is_valid(): dataset = dataset...
[ "@", "check_dataset_access_permission", "@", "check_dataset_edition_permission", "(", ")", "def", "edit_coordinator_dataset", "(", "request", ",", "dataset", ")", ":", "response", "=", "{", "'status'", ":", "(", "-", "1", ")", ",", "'data'", ":", "'None'", "}", ...
returns html for modal to edit datasets .
train
false
43,346
def texinfo_visit_inheritance_diagram(self, node): graph = node['graph'] graph_hash = get_graph_hash(node) name = ('inheritance%s' % graph_hash) dotcode = graph.generate_dot(name, env=self.builder.env, graph_attrs={'size': '"6.0,6.0"'}) render_dot_texinfo(self, node, dotcode, {}, 'inheritance') raise nodes.SkipNo...
[ "def", "texinfo_visit_inheritance_diagram", "(", "self", ",", "node", ")", ":", "graph", "=", "node", "[", "'graph'", "]", "graph_hash", "=", "get_graph_hash", "(", "node", ")", "name", "=", "(", "'inheritance%s'", "%", "graph_hash", ")", "dotcode", "=", "gr...
output the graph for texinfo .
train
true
43,347
def modifiers_dict(modifiers): return {mod[4:].lower(): ((modifiers & getattr(sys.modules[__name__], mod)) > 0) for mod in ['MOD_SHIFT', 'MOD_CTRL', 'MOD_ALT', 'MOD_CAPSLOCK', 'MOD_NUMLOCK', 'MOD_WINDOWS', 'MOD_COMMAND', 'MOD_OPTION', 'MOD_SCROLLLOCK']}
[ "def", "modifiers_dict", "(", "modifiers", ")", ":", "return", "{", "mod", "[", "4", ":", "]", ".", "lower", "(", ")", ":", "(", "(", "modifiers", "&", "getattr", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "mod", ")", ")", ">", "0", ...
return dict where the key is a keyboard modifier flag and the value is the boolean state of that flag .
train
false
43,348
def RegisterRealUrlHandler(func): _realurl_handlers.append(func)
[ "def", "RegisterRealUrlHandler", "(", "func", ")", ":", "_realurl_handlers", ".", "append", "(", "func", ")" ]
handle函数接受一个参数url,返回真实下载地址字符串, 如果需要返回真实文件名,可以返回一个tuple 如果返回空则调用下个handle函数, .
train
false
43,349
def _replace(reps): if (not reps): return (lambda x: x) D = (lambda match: reps[match.group(0)]) pattern = _re.compile('|'.join([_re.escape(k) for (k, v) in reps.items()]), _re.M) return (lambda string: pattern.sub(D, string))
[ "def", "_replace", "(", "reps", ")", ":", "if", "(", "not", "reps", ")", ":", "return", "(", "lambda", "x", ":", "x", ")", "D", "=", "(", "lambda", "match", ":", "reps", "[", "match", ".", "group", "(", "0", ")", "]", ")", "pattern", "=", "_r...
return a function that can make the replacements .
train
false
43,350
def _url(path=''): return (HTTP_BASE_URL + path)
[ "def", "_url", "(", "path", "=", "''", ")", ":", "return", "(", "HTTP_BASE_URL", "+", "path", ")" ]
helper method to generate urls .
train
false
43,351
def unquote_plus(string, encoding='utf-8', errors='replace'): string = string.replace('+', ' ') return unquote(string, encoding, errors)
[ "def", "unquote_plus", "(", "string", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "string", "=", "string", ".", "replace", "(", "'+'", ",", "' '", ")", "return", "unquote", "(", "string", ",", "encoding", ",", "errors", ...
like unquote() .
train
true
43,352
def setup_test_episode_file(): if (not os.path.exists(FILE_DIR)): os.makedirs(FILE_DIR) try: with open(FILE_PATH, 'wb') as ep_file: ep_file.write('foo bar') ep_file.flush() except Exception: print 'Unable to set up test episode' raise
[ "def", "setup_test_episode_file", "(", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "FILE_DIR", ")", ")", ":", "os", ".", "makedirs", "(", "FILE_DIR", ")", "try", ":", "with", "open", "(", "FILE_PATH", ",", "'wb'", ")", "as", ...
create a test episode directory with a test episode in it .
train
false