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
47,343
def _import_keyDER(extern_key, passphrase): decodings = (_import_pkcs1_private, _import_pkcs1_public, _import_subjectPublicKeyInfo, _import_x509_cert, _import_pkcs8) for decoding in decodings: try: return decoding(extern_key, passphrase) except ValueError: pass raise ValueError('RSA key format is not supported')
[ "def", "_import_keyDER", "(", "extern_key", ",", "passphrase", ")", ":", "decodings", "=", "(", "_import_pkcs1_private", ",", "_import_pkcs1_public", ",", "_import_subjectPublicKeyInfo", ",", "_import_x509_cert", ",", "_import_pkcs8", ")", "for", "decoding", "in", "decodings", ":", "try", ":", "return", "decoding", "(", "extern_key", ",", "passphrase", ")", "except", "ValueError", ":", "pass", "raise", "ValueError", "(", "'RSA key format is not supported'", ")" ]
import an rsa key .
train
false
47,344
def results(): return __proxy__['napalm.call']('get_probes_results', **{})
[ "def", "results", "(", ")", ":", "return", "__proxy__", "[", "'napalm.call'", "]", "(", "'get_probes_results'", ",", "**", "{", "}", ")" ]
provides the results of the measurements of the rpm/sla probes .
train
false
47,346
def average(values): return ((sum(values) / len(values)) if values else None)
[ "def", "average", "(", "values", ")", ":", "return", "(", "(", "sum", "(", "values", ")", "/", "len", "(", "values", ")", ")", "if", "values", "else", "None", ")" ]
computes the arithmetic mean of a list of numbers .
train
false
47,348
def cstring(s, width=70): L = [] for l in s.split('\n'): if (len(l) < width): L.append(('"%s\\n"' % l)) return '\n'.join(L)
[ "def", "cstring", "(", "s", ",", "width", "=", "70", ")", ":", "L", "=", "[", "]", "for", "l", "in", "s", ".", "split", "(", "'\\n'", ")", ":", "if", "(", "len", "(", "l", ")", "<", "width", ")", ":", "L", ".", "append", "(", "(", "'\"%s\\\\n\"'", "%", "l", ")", ")", "return", "'\\n'", ".", "join", "(", "L", ")" ]
return c string representation of a python string .
train
false
47,350
def set_image_dim_ordering(dim_ordering): global _IMAGE_DIM_ORDERING if (dim_ordering not in {'tf', 'th'}): raise ValueError('Unknown dim_ordering:', dim_ordering) _IMAGE_DIM_ORDERING = str(dim_ordering)
[ "def", "set_image_dim_ordering", "(", "dim_ordering", ")", ":", "global", "_IMAGE_DIM_ORDERING", "if", "(", "dim_ordering", "not", "in", "{", "'tf'", ",", "'th'", "}", ")", ":", "raise", "ValueError", "(", "'Unknown dim_ordering:'", ",", "dim_ordering", ")", "_IMAGE_DIM_ORDERING", "=", "str", "(", "dim_ordering", ")" ]
sets the value of the image dimension ordering convention .
train
false
47,352
def _get_next_link(request, marker): params = request.params.copy() params['marker'] = marker return ('%s?%s' % (request.path_url, urlparse.urlencode(params)))
[ "def", "_get_next_link", "(", "request", ",", "marker", ")", ":", "params", "=", "request", ".", "params", ".", "copy", "(", ")", "params", "[", "'marker'", "]", "=", "marker", "return", "(", "'%s?%s'", "%", "(", "request", ".", "path_url", ",", "urlparse", ".", "urlencode", "(", "params", ")", ")", ")" ]
return href string with proper limit and marker params .
train
false
47,353
def _ssh_cat(ssh_bin, address, ec2_key_pair_file, path, keyfile=None, sudo=False): cmd_args = ['cat', path] if sudo: cmd_args = (['sudo'] + cmd_args) out = _check_output(*_ssh_run_with_recursion(ssh_bin, address, ec2_key_pair_file, keyfile, cmd_args)) return out
[ "def", "_ssh_cat", "(", "ssh_bin", ",", "address", ",", "ec2_key_pair_file", ",", "path", ",", "keyfile", "=", "None", ",", "sudo", "=", "False", ")", ":", "cmd_args", "=", "[", "'cat'", ",", "path", "]", "if", "sudo", ":", "cmd_args", "=", "(", "[", "'sudo'", "]", "+", "cmd_args", ")", "out", "=", "_check_output", "(", "*", "_ssh_run_with_recursion", "(", "ssh_bin", ",", "address", ",", "ec2_key_pair_file", ",", "keyfile", ",", "cmd_args", ")", ")", "return", "out" ]
return the file at path as a string .
train
false
47,354
def _reconstruct_ppa_name(owner_name, ppa_name): return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
[ "def", "_reconstruct_ppa_name", "(", "owner_name", ",", "ppa_name", ")", ":", "return", "'ppa:{0}/{1}'", ".", "format", "(", "owner_name", ",", "ppa_name", ")" ]
stringify ppa name from args .
train
false
47,355
def rand_name(name='', prefix=None): randbits = str(random.randint(1, 2147483647)) rand_name = randbits if name: rand_name = ((name + '-') + rand_name) if prefix: rand_name = ((prefix + '-') + rand_name) return rand_name
[ "def", "rand_name", "(", "name", "=", "''", ",", "prefix", "=", "None", ")", ":", "randbits", "=", "str", "(", "random", ".", "randint", "(", "1", ",", "2147483647", ")", ")", "rand_name", "=", "randbits", "if", "name", ":", "rand_name", "=", "(", "(", "name", "+", "'-'", ")", "+", "rand_name", ")", "if", "prefix", ":", "rand_name", "=", "(", "(", "prefix", "+", "'-'", ")", "+", "rand_name", ")", "return", "rand_name" ]
generate a random name that includes a random number .
train
false
47,356
def eff_request_host(request): erhn = req_host = request_host(request) if ((req_host.find('.') == (-1)) and (not IPV4_RE.search(req_host))): erhn = (req_host + '.local') return (req_host, erhn)
[ "def", "eff_request_host", "(", "request", ")", ":", "erhn", "=", "req_host", "=", "request_host", "(", "request", ")", "if", "(", "(", "req_host", ".", "find", "(", "'.'", ")", "==", "(", "-", "1", ")", ")", "and", "(", "not", "IPV4_RE", ".", "search", "(", "req_host", ")", ")", ")", ":", "erhn", "=", "(", "req_host", "+", "'.local'", ")", "return", "(", "req_host", ",", "erhn", ")" ]
return a tuple .
train
true
47,357
def _upper2lower(ub): lb = np.zeros(ub.shape, ub.dtype) (nrow, ncol) = ub.shape for i in range(ub.shape[0]): lb[i, 0:(ncol - i)] = ub[((nrow - 1) - i), i:ncol] lb[i, (ncol - i):] = ub[((nrow - 1) - i), 0:i] return lb
[ "def", "_upper2lower", "(", "ub", ")", ":", "lb", "=", "np", ".", "zeros", "(", "ub", ".", "shape", ",", "ub", ".", "dtype", ")", "(", "nrow", ",", "ncol", ")", "=", "ub", ".", "shape", "for", "i", "in", "range", "(", "ub", ".", "shape", "[", "0", "]", ")", ":", "lb", "[", "i", ",", "0", ":", "(", "ncol", "-", "i", ")", "]", "=", "ub", "[", "(", "(", "nrow", "-", "1", ")", "-", "i", ")", ",", "i", ":", "ncol", "]", "lb", "[", "i", ",", "(", "ncol", "-", "i", ")", ":", "]", "=", "ub", "[", "(", "(", "nrow", "-", "1", ")", "-", "i", ")", ",", "0", ":", "i", "]", "return", "lb" ]
convert upper triangular banded matrix to lower banded form .
train
false
47,358
def _match_css_class(str): return re.compile(('(^|.*\\s)%s($|\\s)' % str))
[ "def", "_match_css_class", "(", "str", ")", ":", "return", "re", ".", "compile", "(", "(", "'(^|.*\\\\s)%s($|\\\\s)'", "%", "str", ")", ")" ]
build a re to match the given css class .
train
false
47,359
def get_nics(vm_): with _get_xapi_session() as xapi: nic = {} vm_rec = _get_record_by_label(xapi, 'VM', vm_) if (vm_rec is False): return False for vif in vm_rec['VIFs']: vif_rec = _get_record(xapi, 'VIF', vif) nic[vif_rec['MAC']] = {'mac': vif_rec['MAC'], 'device': vif_rec['device'], 'mtu': vif_rec['MTU']} return nic
[ "def", "get_nics", "(", "vm_", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "nic", "=", "{", "}", "vm_rec", "=", "_get_record_by_label", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "(", "vm_rec", "is", "False", ")", ":", "return", "False", "for", "vif", "in", "vm_rec", "[", "'VIFs'", "]", ":", "vif_rec", "=", "_get_record", "(", "xapi", ",", "'VIF'", ",", "vif", ")", "nic", "[", "vif_rec", "[", "'MAC'", "]", "]", "=", "{", "'mac'", ":", "vif_rec", "[", "'MAC'", "]", ",", "'device'", ":", "vif_rec", "[", "'device'", "]", ",", "'mtu'", ":", "vif_rec", "[", "'MTU'", "]", "}", "return", "nic" ]
return info about the network interfaces of a named vm cli example: .
train
true
47,361
def ZMod(m): def ModM(coef): return Mod(coef, m) return ModM
[ "def", "ZMod", "(", "m", ")", ":", "def", "ModM", "(", "coef", ")", ":", "return", "Mod", "(", "coef", ",", "m", ")", "return", "ModM" ]
return a function that makes mod objects for a particular modulus m .
train
false
47,363
def argstoarray(*args): if ((len(args) == 1) and (not isinstance(args[0], ndarray))): output = ma.asarray(args[0]) if (output.ndim != 2): raise ValueError('The input should be 2D') else: n = len(args) m = max([len(k) for k in args]) output = ma.array(np.empty((n, m), dtype=float), mask=True) for (k, v) in enumerate(args): output[k, :len(v)] = v output[np.logical_not(np.isfinite(output._data))] = masked return output
[ "def", "argstoarray", "(", "*", "args", ")", ":", "if", "(", "(", "len", "(", "args", ")", "==", "1", ")", "and", "(", "not", "isinstance", "(", "args", "[", "0", "]", ",", "ndarray", ")", ")", ")", ":", "output", "=", "ma", ".", "asarray", "(", "args", "[", "0", "]", ")", "if", "(", "output", ".", "ndim", "!=", "2", ")", ":", "raise", "ValueError", "(", "'The input should be 2D'", ")", "else", ":", "n", "=", "len", "(", "args", ")", "m", "=", "max", "(", "[", "len", "(", "k", ")", "for", "k", "in", "args", "]", ")", "output", "=", "ma", ".", "array", "(", "np", ".", "empty", "(", "(", "n", ",", "m", ")", ",", "dtype", "=", "float", ")", ",", "mask", "=", "True", ")", "for", "(", "k", ",", "v", ")", "in", "enumerate", "(", "args", ")", ":", "output", "[", "k", ",", ":", "len", "(", "v", ")", "]", "=", "v", "output", "[", "np", ".", "logical_not", "(", "np", ".", "isfinite", "(", "output", ".", "_data", ")", ")", "]", "=", "masked", "return", "output" ]
constructs a 2d array from a group of sequences .
train
false
47,364
def get_annotated_content_info(course_id, content, user, user_info): voted = '' if (content['id'] in user_info['upvoted_ids']): voted = 'up' elif (content['id'] in user_info['downvoted_ids']): voted = 'down' return {'voted': voted, 'subscribed': (content['id'] in user_info['subscribed_thread_ids']), 'ability': get_ability(course_id, content, user)}
[ "def", "get_annotated_content_info", "(", "course_id", ",", "content", ",", "user", ",", "user_info", ")", ":", "voted", "=", "''", "if", "(", "content", "[", "'id'", "]", "in", "user_info", "[", "'upvoted_ids'", "]", ")", ":", "voted", "=", "'up'", "elif", "(", "content", "[", "'id'", "]", "in", "user_info", "[", "'downvoted_ids'", "]", ")", ":", "voted", "=", "'down'", "return", "{", "'voted'", ":", "voted", ",", "'subscribed'", ":", "(", "content", "[", "'id'", "]", "in", "user_info", "[", "'subscribed_thread_ids'", "]", ")", ",", "'ability'", ":", "get_ability", "(", "course_id", ",", "content", ",", "user", ")", "}" ]
get metadata for an individual content .
train
false
47,366
def disable_insecure_serializers(allowed=[u'json']): for name in registry._decoders: registry.disable(name) if (allowed is not None): for name in allowed: registry.enable(name)
[ "def", "disable_insecure_serializers", "(", "allowed", "=", "[", "u'json'", "]", ")", ":", "for", "name", "in", "registry", ".", "_decoders", ":", "registry", ".", "disable", "(", "name", ")", "if", "(", "allowed", "is", "not", "None", ")", ":", "for", "name", "in", "allowed", ":", "registry", ".", "enable", "(", "name", ")" ]
disable untrusted serializers .
train
false
47,368
def previous_workday(dt): dt -= timedelta(days=1) while (dt.weekday() > 4): dt -= timedelta(days=1) return dt
[ "def", "previous_workday", "(", "dt", ")", ":", "dt", "-=", "timedelta", "(", "days", "=", "1", ")", "while", "(", "dt", ".", "weekday", "(", ")", ">", "4", ")", ":", "dt", "-=", "timedelta", "(", "days", "=", "1", ")", "return", "dt" ]
returns previous weekday used for observances .
train
true
47,370
def get_standard_values(): return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx())
[ "def", "get_standard_values", "(", ")", ":", "return", "np", ".", "array", "(", "[", "[", "0", ",", "0.1", ",", "0.5", ",", "0.9", ",", "1.0", "]", "]", ",", "dtype", "=", "K", ".", "floatx", "(", ")", ")" ]
these are just a set of floats used for testing the activation functions .
train
false
47,371
def test_sphere(): md = create_sphere(rows=10, cols=20, radius=10, method='latitude') radii = np.sqrt((md.get_vertices() ** 2).sum(axis=1)) assert_allclose(radii, (np.ones_like(radii) * 10)) md = create_sphere(subdivisions=5, radius=10, method='ico') radii = np.sqrt((md.get_vertices() ** 2).sum(axis=1)) assert_allclose(radii, (np.ones_like(radii) * 10)) md = create_sphere(rows=20, cols=20, depth=20, radius=10, method='cube') radii = np.sqrt((md.get_vertices() ** 2).sum(axis=1)) assert_allclose(radii, (np.ones_like(radii) * 10))
[ "def", "test_sphere", "(", ")", ":", "md", "=", "create_sphere", "(", "rows", "=", "10", ",", "cols", "=", "20", ",", "radius", "=", "10", ",", "method", "=", "'latitude'", ")", "radii", "=", "np", ".", "sqrt", "(", "(", "md", ".", "get_vertices", "(", ")", "**", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", ")", "assert_allclose", "(", "radii", ",", "(", "np", ".", "ones_like", "(", "radii", ")", "*", "10", ")", ")", "md", "=", "create_sphere", "(", "subdivisions", "=", "5", ",", "radius", "=", "10", ",", "method", "=", "'ico'", ")", "radii", "=", "np", ".", "sqrt", "(", "(", "md", ".", "get_vertices", "(", ")", "**", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", ")", "assert_allclose", "(", "radii", ",", "(", "np", ".", "ones_like", "(", "radii", ")", "*", "10", ")", ")", "md", "=", "create_sphere", "(", "rows", "=", "20", ",", "cols", "=", "20", ",", "depth", "=", "20", ",", "radius", "=", "10", ",", "method", "=", "'cube'", ")", "radii", "=", "np", ".", "sqrt", "(", "(", "md", ".", "get_vertices", "(", ")", "**", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", ")", "assert_allclose", "(", "radii", ",", "(", "np", ".", "ones_like", "(", "radii", ")", "*", "10", ")", ")" ]
test sphere function .
train
false
47,372
def make_paths_absolute(pathdict, keys, base_path=None): if (base_path is None): base_path = os.getcwd() for key in keys: if pathdict.has_key(key): value = pathdict[key] if isinstance(value, types.ListType): value = [make_one_path_absolute(base_path, path) for path in value] elif value: value = make_one_path_absolute(base_path, value) pathdict[key] = value
[ "def", "make_paths_absolute", "(", "pathdict", ",", "keys", ",", "base_path", "=", "None", ")", ":", "if", "(", "base_path", "is", "None", ")", ":", "base_path", "=", "os", ".", "getcwd", "(", ")", "for", "key", "in", "keys", ":", "if", "pathdict", ".", "has_key", "(", "key", ")", ":", "value", "=", "pathdict", "[", "key", "]", "if", "isinstance", "(", "value", ",", "types", ".", "ListType", ")", ":", "value", "=", "[", "make_one_path_absolute", "(", "base_path", ",", "path", ")", "for", "path", "in", "value", "]", "elif", "value", ":", "value", "=", "make_one_path_absolute", "(", "base_path", ",", "value", ")", "pathdict", "[", "key", "]", "=", "value" ]
interpret filesystem path settings relative to the base_path given .
train
false
47,373
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): return a.trace(offset, axis1, axis2, dtype, out)
[ "def", "trace", "(", "a", ",", "offset", "=", "0", ",", "axis1", "=", "0", ",", "axis2", "=", "1", ",", "dtype", "=", "None", ",", "out", "=", "None", ")", ":", "return", "a", ".", "trace", "(", "offset", ",", "axis1", ",", "axis2", ",", "dtype", ",", "out", ")" ]
returns the trace of a matrix .
train
false
47,374
def at_server_start(): pass
[ "def", "at_server_start", "(", ")", ":", "pass" ]
this is called every time the server starts up .
train
false
47,375
def filter_type_for_hotswap_target(target, default=FilterType.disabled): if isinstance(target, Live.Device.Device): if (target.type == DeviceType.instrument): return FilterType.instrument_hotswap if (target.type == DeviceType.audio_effect): return FilterType.audio_effect_hotswap if (target.type == DeviceType.midi_effect): return FilterType.midi_effect_hotswap FilterType.disabled else: if isinstance(target, Live.DrumPad.DrumPad): return FilterType.drum_pad_hotswap if isinstance(target, Live.Chain.Chain): if target: return filter_type_for_hotswap_target(target.canonical_parent) return FilterType.disabled return default
[ "def", "filter_type_for_hotswap_target", "(", "target", ",", "default", "=", "FilterType", ".", "disabled", ")", ":", "if", "isinstance", "(", "target", ",", "Live", ".", "Device", ".", "Device", ")", ":", "if", "(", "target", ".", "type", "==", "DeviceType", ".", "instrument", ")", ":", "return", "FilterType", ".", "instrument_hotswap", "if", "(", "target", ".", "type", "==", "DeviceType", ".", "audio_effect", ")", ":", "return", "FilterType", ".", "audio_effect_hotswap", "if", "(", "target", ".", "type", "==", "DeviceType", ".", "midi_effect", ")", ":", "return", "FilterType", ".", "midi_effect_hotswap", "FilterType", ".", "disabled", "else", ":", "if", "isinstance", "(", "target", ",", "Live", ".", "DrumPad", ".", "DrumPad", ")", ":", "return", "FilterType", ".", "drum_pad_hotswap", "if", "isinstance", "(", "target", ",", "Live", ".", "Chain", ".", "Chain", ")", ":", "if", "target", ":", "return", "filter_type_for_hotswap_target", "(", "target", ".", "canonical_parent", ")", "return", "FilterType", ".", "disabled", "return", "default" ]
returns the appropriate browser filter type for a given hotswap target .
train
false
47,376
def _check_conversion(key, valid_dict): if ((key not in valid_dict) and (key not in valid_dict.values())): keys = [v for v in valid_dict.keys() if isinstance(v, string_types)] raise ValueError(('value must be one of %s, not %s' % (keys, key))) return (valid_dict[key] if (key in valid_dict) else key)
[ "def", "_check_conversion", "(", "key", ",", "valid_dict", ")", ":", "if", "(", "(", "key", "not", "in", "valid_dict", ")", "and", "(", "key", "not", "in", "valid_dict", ".", "values", "(", ")", ")", ")", ":", "keys", "=", "[", "v", "for", "v", "in", "valid_dict", ".", "keys", "(", ")", "if", "isinstance", "(", "v", ",", "string_types", ")", "]", "raise", "ValueError", "(", "(", "'value must be one of %s, not %s'", "%", "(", "keys", ",", "key", ")", ")", ")", "return", "(", "valid_dict", "[", "key", "]", "if", "(", "key", "in", "valid_dict", ")", "else", "key", ")" ]
check for existence of key in dict .
train
true
47,379
def set_http_wrapper(library=None, features=[]): global Http Http = get_http_wrapper(library, features) return Http
[ "def", "set_http_wrapper", "(", "library", "=", "None", ",", "features", "=", "[", "]", ")", ":", "global", "Http", "Http", "=", "get_http_wrapper", "(", "library", ",", "features", ")", "return", "Http" ]
set a suitable http connection wrapper .
train
false
47,380
def replace_topic_rule(ruleName, sql, actions, description, ruleDisabled=False, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.replace_topic_rule(ruleName=ruleName, topicRulePayload={'sql': sql, 'description': description, 'actions': actions, 'ruleDisabled': ruleDisabled}) return {'replaced': True} except ClientError as e: return {'replaced': False, 'error': salt.utils.boto3.get_error(e)}
[ "def", "replace_topic_rule", "(", "ruleName", ",", "sql", ",", "actions", ",", "description", ",", "ruleDisabled", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "conn", ".", "replace_topic_rule", "(", "ruleName", "=", "ruleName", ",", "topicRulePayload", "=", "{", "'sql'", ":", "sql", ",", "'description'", ":", "description", ",", "'actions'", ":", "actions", ",", "'ruleDisabled'", ":", "ruleDisabled", "}", ")", "return", "{", "'replaced'", ":", "True", "}", "except", "ClientError", "as", "e", ":", "return", "{", "'replaced'", ":", "False", ",", "'error'", ":", "salt", ".", "utils", ".", "boto3", ".", "get_error", "(", "e", ")", "}" ]
given a valid config .
train
false
47,381
def test_isfinite(): arr = np.random.random(100) assert isfinite(arr) arr[0] = np.nan assert (not isfinite(arr)) arr[0] = np.inf assert (not isfinite(arr)) arr[0] = (- np.inf) assert (not isfinite(arr))
[ "def", "test_isfinite", "(", ")", ":", "arr", "=", "np", ".", "random", ".", "random", "(", "100", ")", "assert", "isfinite", "(", "arr", ")", "arr", "[", "0", "]", "=", "np", ".", "nan", "assert", "(", "not", "isfinite", "(", "arr", ")", ")", "arr", "[", "0", "]", "=", "np", ".", "inf", "assert", "(", "not", "isfinite", "(", "arr", ")", ")", "arr", "[", "0", "]", "=", "(", "-", "np", ".", "inf", ")", "assert", "(", "not", "isfinite", "(", "arr", ")", ")" ]
tests that pylearn2 .
train
false
47,382
def DecodeAppIdNamespace(app_namespace_str): sep = app_namespace_str.find(_NAMESPACE_SEPARATOR) if (sep < 0): return (app_namespace_str, '') else: return (app_namespace_str[0:sep], app_namespace_str[(sep + 1):])
[ "def", "DecodeAppIdNamespace", "(", "app_namespace_str", ")", ":", "sep", "=", "app_namespace_str", ".", "find", "(", "_NAMESPACE_SEPARATOR", ")", "if", "(", "sep", "<", "0", ")", ":", "return", "(", "app_namespace_str", ",", "''", ")", "else", ":", "return", "(", "app_namespace_str", "[", "0", ":", "sep", "]", ",", "app_namespace_str", "[", "(", "sep", "+", "1", ")", ":", "]", ")" ]
decodes app_namespace_str into an pair .
train
false
47,383
def getMatrixSVG(elementNode): matrixSVG = MatrixSVG() if ('transform' not in elementNode.attributes): return matrixSVG transformWords = [] for transformWord in elementNode.attributes['transform'].replace(')', '(').split('('): transformWordStrip = transformWord.strip() if (transformWordStrip != ''): transformWords.append(transformWordStrip) global globalGetTricomplexDictionary getTricomplexDictionaryKeys = globalGetTricomplexDictionary.keys() for (transformWordIndex, transformWord) in enumerate(transformWords): if (transformWord in getTricomplexDictionaryKeys): transformString = transformWords[(transformWordIndex + 1)].replace(',', ' ') matrixSVG = matrixSVG.getSelfTimesOther(globalGetTricomplexDictionary[transformWord](transformString.split())) return matrixSVG
[ "def", "getMatrixSVG", "(", "elementNode", ")", ":", "matrixSVG", "=", "MatrixSVG", "(", ")", "if", "(", "'transform'", "not", "in", "elementNode", ".", "attributes", ")", ":", "return", "matrixSVG", "transformWords", "=", "[", "]", "for", "transformWord", "in", "elementNode", ".", "attributes", "[", "'transform'", "]", ".", "replace", "(", "')'", ",", "'('", ")", ".", "split", "(", "'('", ")", ":", "transformWordStrip", "=", "transformWord", ".", "strip", "(", ")", "if", "(", "transformWordStrip", "!=", "''", ")", ":", "transformWords", ".", "append", "(", "transformWordStrip", ")", "global", "globalGetTricomplexDictionary", "getTricomplexDictionaryKeys", "=", "globalGetTricomplexDictionary", ".", "keys", "(", ")", "for", "(", "transformWordIndex", ",", "transformWord", ")", "in", "enumerate", "(", "transformWords", ")", ":", "if", "(", "transformWord", "in", "getTricomplexDictionaryKeys", ")", ":", "transformString", "=", "transformWords", "[", "(", "transformWordIndex", "+", "1", ")", "]", ".", "replace", "(", "','", ",", "' '", ")", "matrixSVG", "=", "matrixSVG", ".", "getSelfTimesOther", "(", "globalGetTricomplexDictionary", "[", "transformWord", "]", "(", "transformString", ".", "split", "(", ")", ")", ")", "return", "matrixSVG" ]
get matrixsvg by svgelement .
train
false
47,384
def table_concat(tables): attributes = [] class_vars = [] metas = [] variables_seen = set() for table in tables: attributes.extend((v for v in table.domain.attributes if (v not in variables_seen))) variables_seen.update(table.domain.attributes) class_vars.extend((v for v in table.domain.class_vars if (v not in variables_seen))) variables_seen.update(table.domain.class_vars) metas.extend((v for v in table.domain.metas if (v not in variables_seen))) variables_seen.update(table.domain.metas) domain = Orange.data.Domain(attributes, class_vars, metas) new_table = Orange.data.Table(domain) for table in tables: new_table.extend(Orange.data.Table.from_table(domain, table)) new_table.attributes.update(table.attributes) return new_table
[ "def", "table_concat", "(", "tables", ")", ":", "attributes", "=", "[", "]", "class_vars", "=", "[", "]", "metas", "=", "[", "]", "variables_seen", "=", "set", "(", ")", "for", "table", "in", "tables", ":", "attributes", ".", "extend", "(", "(", "v", "for", "v", "in", "table", ".", "domain", ".", "attributes", "if", "(", "v", "not", "in", "variables_seen", ")", ")", ")", "variables_seen", ".", "update", "(", "table", ".", "domain", ".", "attributes", ")", "class_vars", ".", "extend", "(", "(", "v", "for", "v", "in", "table", ".", "domain", ".", "class_vars", "if", "(", "v", "not", "in", "variables_seen", ")", ")", ")", "variables_seen", ".", "update", "(", "table", ".", "domain", ".", "class_vars", ")", "metas", ".", "extend", "(", "(", "v", "for", "v", "in", "table", ".", "domain", ".", "metas", "if", "(", "v", "not", "in", "variables_seen", ")", ")", ")", "variables_seen", ".", "update", "(", "table", ".", "domain", ".", "metas", ")", "domain", "=", "Orange", ".", "data", ".", "Domain", "(", "attributes", ",", "class_vars", ",", "metas", ")", "new_table", "=", "Orange", ".", "data", ".", "Table", "(", "domain", ")", "for", "table", "in", "tables", ":", "new_table", ".", "extend", "(", "Orange", ".", "data", ".", "Table", ".", "from_table", "(", "domain", ",", "table", ")", ")", "new_table", ".", "attributes", ".", "update", "(", "table", ".", "attributes", ")", "return", "new_table" ]
concatenate a list of tables .
train
false
47,387
def _get_dataset_metadata(ldda): lds = ldda.library_dataset folder_info = _get_folder_info(lds.folder) lds_info = lds.get_info() if (lds_info and (not lds_info.startswith('upload'))): lds_info = lds_info.replace('no info', '') else: lds_info = '' return ('%s %s %s %s %s' % ((lds.name or ''), lds_info, ldda.metadata.dbkey, ldda.message, folder_info))
[ "def", "_get_dataset_metadata", "(", "ldda", ")", ":", "lds", "=", "ldda", ".", "library_dataset", "folder_info", "=", "_get_folder_info", "(", "lds", ".", "folder", ")", "lds_info", "=", "lds", ".", "get_info", "(", ")", "if", "(", "lds_info", "and", "(", "not", "lds_info", ".", "startswith", "(", "'upload'", ")", ")", ")", ":", "lds_info", "=", "lds_info", ".", "replace", "(", "'no info'", ",", "''", ")", "else", ":", "lds_info", "=", "''", "return", "(", "'%s %s %s %s %s'", "%", "(", "(", "lds", ".", "name", "or", "''", ")", ",", "lds_info", ",", "ldda", ".", "metadata", ".", "dbkey", ",", "ldda", ".", "message", ",", "folder_info", ")", ")" ]
retrieve descriptions and information associated with a dataset .
train
false
47,388
def cache_list(path=None, runas=None, env=None): env = (env or {}) if runas: uid = salt.utils.get_uid(runas) if uid: env.update({'SUDO_UID': '{0}'.format(uid), 'SUDO_USER': ''}) cmd = ['npm', 'cache', 'ls'] if path: cmd.append(path) cmd = ' '.join(cmd) result = __salt__['cmd.run_all'](cmd, cwd=None, runas=runas, env=env, python_shell=True, ignore_retcode=True) if ((result['retcode'] != 0) and result['stderr']): raise CommandExecutionError(result['stderr']) return result['stdout']
[ "def", "cache_list", "(", "path", "=", "None", ",", "runas", "=", "None", ",", "env", "=", "None", ")", ":", "env", "=", "(", "env", "or", "{", "}", ")", "if", "runas", ":", "uid", "=", "salt", ".", "utils", ".", "get_uid", "(", "runas", ")", "if", "uid", ":", "env", ".", "update", "(", "{", "'SUDO_UID'", ":", "'{0}'", ".", "format", "(", "uid", ")", ",", "'SUDO_USER'", ":", "''", "}", ")", "cmd", "=", "[", "'npm'", ",", "'cache'", ",", "'ls'", "]", "if", "path", ":", "cmd", ".", "append", "(", "path", ")", "cmd", "=", "' '", ".", "join", "(", "cmd", ")", "result", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "cwd", "=", "None", ",", "runas", "=", "runas", ",", "env", "=", "env", ",", "python_shell", "=", "True", ",", "ignore_retcode", "=", "True", ")", "if", "(", "(", "result", "[", "'retcode'", "]", "!=", "0", ")", "and", "result", "[", "'stderr'", "]", ")", ":", "raise", "CommandExecutionError", "(", "result", "[", "'stderr'", "]", ")", "return", "result", "[", "'stdout'", "]" ]
list npm cached packages .
train
true
47,389
@with_open_mode('wb+') @with_sizes('medium') def modify_seek_forward_blockwise(f, source): f.seek(0) for i in xrange(0, len(source), 2000): f.write(source[i:(i + 1000)]) f.seek((i + 2000))
[ "@", "with_open_mode", "(", "'wb+'", ")", "@", "with_sizes", "(", "'medium'", ")", "def", "modify_seek_forward_blockwise", "(", "f", ",", "source", ")", ":", "f", ".", "seek", "(", "0", ")", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "source", ")", ",", "2000", ")", ":", "f", ".", "write", "(", "source", "[", "i", ":", "(", "i", "+", "1000", ")", "]", ")", "f", ".", "seek", "(", "(", "i", "+", "2000", ")", ")" ]
alternate write & seek 1000 units .
train
false
47,390
def index_alt(): s3_redirect_default(URL(f='person'))
[ "def", "index_alt", "(", ")", ":", "s3_redirect_default", "(", "URL", "(", "f", "=", "'person'", ")", ")" ]
module homepage for non-admin users when no cms content found .
train
false
47,391
def GetRequestApiCpuUsage(): return _apphosting_runtime___python__apiproxy.get_request_api_cpu_usage()
[ "def", "GetRequestApiCpuUsage", "(", ")", ":", "return", "_apphosting_runtime___python__apiproxy", ".", "get_request_api_cpu_usage", "(", ")" ]
returns the number of megacycles used by api calls .
train
false
47,392
def byte_size(number): (quanta, mod) = divmod(bit_size(number), 8) if (mod or (number == 0)): quanta += 1 return quanta
[ "def", "byte_size", "(", "number", ")", ":", "(", "quanta", ",", "mod", ")", "=", "divmod", "(", "bit_size", "(", "number", ")", ",", "8", ")", "if", "(", "mod", "or", "(", "number", "==", "0", ")", ")", ":", "quanta", "+=", "1", "return", "quanta" ]
returns the number of bytes required to hold a specific long number .
train
false
47,394
def validate_greater_than(fieldname): def _validator(form, field): try: other = form[fieldname] except KeyError: raise validators.ValidationError((field.gettext(u"Invalid field name '%s'.") % fieldname)) if ((field.data != '') and (field.data < other.data)): message = field.gettext((u'Field must be greater than %s.' % fieldname)) raise validators.ValidationError(message) return _validator
[ "def", "validate_greater_than", "(", "fieldname", ")", ":", "def", "_validator", "(", "form", ",", "field", ")", ":", "try", ":", "other", "=", "form", "[", "fieldname", "]", "except", "KeyError", ":", "raise", "validators", ".", "ValidationError", "(", "(", "field", ".", "gettext", "(", "u\"Invalid field name '%s'.\"", ")", "%", "fieldname", ")", ")", "if", "(", "(", "field", ".", "data", "!=", "''", ")", "and", "(", "field", ".", "data", "<", "other", ".", "data", ")", ")", ":", "message", "=", "field", ".", "gettext", "(", "(", "u'Field must be greater than %s.'", "%", "fieldname", ")", ")", "raise", "validators", ".", "ValidationError", "(", "message", ")", "return", "_validator" ]
compares the value of two fields the value of self is to be greater than the supplied field .
train
false
47,396
def normalize_text(text, line_len=80, indent='', rest=False): if rest: normp = normalize_rest_paragraph else: normp = normalize_paragraph result = [] for text in _BLANKLINES_RGX.split(text): result.append(normp(text, line_len, indent)) return ('%s%s%s' % (linesep, indent, linesep)).join(result)
[ "def", "normalize_text", "(", "text", ",", "line_len", "=", "80", ",", "indent", "=", "''", ",", "rest", "=", "False", ")", ":", "if", "rest", ":", "normp", "=", "normalize_rest_paragraph", "else", ":", "normp", "=", "normalize_paragraph", "result", "=", "[", "]", "for", "text", "in", "_BLANKLINES_RGX", ".", "split", "(", "text", ")", ":", "result", ".", "append", "(", "normp", "(", "text", ",", "line_len", ",", "indent", ")", ")", "return", "(", "'%s%s%s'", "%", "(", "linesep", ",", "indent", ",", "linesep", ")", ")", ".", "join", "(", "result", ")" ]
normalize a text to display it with a maximum line size and optionally arbitrary indentation .
train
false
47,397
def divmod(x, y): return (floor_div(x, y), mod_check(x, y))
[ "def", "divmod", "(", "x", ",", "y", ")", ":", "return", "(", "floor_div", "(", "x", ",", "y", ")", ",", "mod_check", "(", "x", ",", "y", ")", ")" ]
elementvise divmod .
train
false
47,398
def safe_infer(node): try: inferit = node.infer() value = next(inferit) except astroid.InferenceError: return try: next(inferit) return except astroid.InferenceError: return except StopIteration: return value
[ "def", "safe_infer", "(", "node", ")", ":", "try", ":", "inferit", "=", "node", ".", "infer", "(", ")", "value", "=", "next", "(", "inferit", ")", "except", "astroid", ".", "InferenceError", ":", "return", "try", ":", "next", "(", "inferit", ")", "return", "except", "astroid", ".", "InferenceError", ":", "return", "except", "StopIteration", ":", "return", "value" ]
return the inferred value for the given node .
train
false
47,399
def update_zone(zone_id, domain, profile, type='master', ttl=None): conn = _get_driver(profile=profile) zone = conn.get_zone(zone_id) return conn.update_zone(zone=zone, domain=domain, type=type, ttl=ttl)
[ "def", "update_zone", "(", "zone_id", ",", "domain", ",", "profile", ",", "type", "=", "'master'", ",", "ttl", "=", "None", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "zone", "=", "conn", ".", "get_zone", "(", "zone_id", ")", "return", "conn", ".", "update_zone", "(", "zone", "=", "zone", ",", "domain", "=", "domain", ",", "type", "=", "type", ",", "ttl", "=", "ttl", ")" ]
update an existing zone .
train
true
47,402
def _create_diffs_for_mappings(current_path, mapping_a, mapping_b): resulting_diffs = pvector([]).evolver() a_keys = frozenset(mapping_a.keys()) b_keys = frozenset(mapping_b.keys()) for key in a_keys.intersection(b_keys): if (mapping_a[key] != mapping_b[key]): resulting_diffs.extend(_create_diffs_for(current_path.append(key), mapping_a[key], mapping_b[key])) for key in b_keys.difference(a_keys): resulting_diffs.append(_Set(path=current_path, key=key, value=mapping_b[key])) for key in a_keys.difference(b_keys): resulting_diffs.append(_Remove(path=current_path, item=key)) return resulting_diffs.persistent()
[ "def", "_create_diffs_for_mappings", "(", "current_path", ",", "mapping_a", ",", "mapping_b", ")", ":", "resulting_diffs", "=", "pvector", "(", "[", "]", ")", ".", "evolver", "(", ")", "a_keys", "=", "frozenset", "(", "mapping_a", ".", "keys", "(", ")", ")", "b_keys", "=", "frozenset", "(", "mapping_b", ".", "keys", "(", ")", ")", "for", "key", "in", "a_keys", ".", "intersection", "(", "b_keys", ")", ":", "if", "(", "mapping_a", "[", "key", "]", "!=", "mapping_b", "[", "key", "]", ")", ":", "resulting_diffs", ".", "extend", "(", "_create_diffs_for", "(", "current_path", ".", "append", "(", "key", ")", ",", "mapping_a", "[", "key", "]", ",", "mapping_b", "[", "key", "]", ")", ")", "for", "key", "in", "b_keys", ".", "difference", "(", "a_keys", ")", ":", "resulting_diffs", ".", "append", "(", "_Set", "(", "path", "=", "current_path", ",", "key", "=", "key", ",", "value", "=", "mapping_b", "[", "key", "]", ")", ")", "for", "key", "in", "a_keys", ".", "difference", "(", "b_keys", ")", ":", "resulting_diffs", ".", "append", "(", "_Remove", "(", "path", "=", "current_path", ",", "item", "=", "key", ")", ")", "return", "resulting_diffs", ".", "persistent", "(", ")" ]
computes a series of _idiffchange s to turn mapping_a into mapping_b assuming that these mappings are at current_path inside a nested pyrsistent object .
train
false
47,403
def datastore_wait_ready(popen): emulator_ready = False while (not emulator_ready): emulator_ready = (popen.stderr.readline() == _DS_READY_LINE)
[ "def", "datastore_wait_ready", "(", "popen", ")", ":", "emulator_ready", "=", "False", "while", "(", "not", "emulator_ready", ")", ":", "emulator_ready", "=", "(", "popen", ".", "stderr", ".", "readline", "(", ")", "==", "_DS_READY_LINE", ")" ]
wait until the datastore emulator is ready to use .
train
false
47,405
def dynamic_choice_param(registry, xml_parent, data): dynamic_param_common(registry, xml_parent, data, 'ChoiceParameterDefinition')
[ "def", "dynamic_choice_param", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "dynamic_param_common", "(", "registry", ",", "xml_parent", ",", "data", ",", "'ChoiceParameterDefinition'", ")" ]
yaml: dynamic-choice dynamic choice parameter requires the jenkins :jenkins-wiki:jenkins dynamic parameter plug-in <dynamic+parameter+plug-in> .
train
false
47,406
def assert_nav_help_link(test, page, href, signed_in=True): expected_link = {'href': href, 'text': 'Help'} actual_link = page.get_nav_help_element_and_click_help(signed_in) assert_link(test, expected_link, actual_link) assert_opened_help_link_is_correct(test, href)
[ "def", "assert_nav_help_link", "(", "test", ",", "page", ",", "href", ",", "signed_in", "=", "True", ")", ":", "expected_link", "=", "{", "'href'", ":", "href", ",", "'text'", ":", "'Help'", "}", "actual_link", "=", "page", ".", "get_nav_help_element_and_click_help", "(", "signed_in", ")", "assert_link", "(", "test", ",", "expected_link", ",", "actual_link", ")", "assert_opened_help_link_is_correct", "(", "test", ",", "href", ")" ]
asserts that help link in navigation bar is correct .
train
false
47,407
def unuse(): global cuda_enabled cuda_enabled = False handle_shared_float32(False) optdb.remove_tags('gpu_opt', 'fast_compile', 'fast_run') optdb.remove_tags('gpu_after_fusion', 'fast_run')
[ "def", "unuse", "(", ")", ":", "global", "cuda_enabled", "cuda_enabled", "=", "False", "handle_shared_float32", "(", "False", ")", "optdb", ".", "remove_tags", "(", "'gpu_opt'", ",", "'fast_compile'", ",", "'fast_run'", ")", "optdb", ".", "remove_tags", "(", "'gpu_after_fusion'", ",", "'fast_run'", ")" ]
this undo what was done by the call to .
train
false
47,409
def _create_cfb_cipher(factory, **kwargs): cipher_state = factory._create_base_cipher(kwargs) iv = kwargs.pop('IV', None) IV = kwargs.pop('iv', None) if ((None, None) == (iv, IV)): iv = get_random_bytes(factory.block_size) if (iv is not None): if (IV is not None): raise TypeError("You must either use 'iv' or 'IV', not both") else: iv = IV (segment_size_bytes, rem) = divmod(kwargs.pop('segment_size', 8), 8) if ((segment_size_bytes == 0) or (rem != 0)): raise ValueError("'segment_size' must be positive and multiple of 8 bits") if kwargs: raise TypeError(('Unknown parameters for CFB: %s' % str(kwargs))) return CfbMode(cipher_state, iv, segment_size_bytes)
[ "def", "_create_cfb_cipher", "(", "factory", ",", "**", "kwargs", ")", ":", "cipher_state", "=", "factory", ".", "_create_base_cipher", "(", "kwargs", ")", "iv", "=", "kwargs", ".", "pop", "(", "'IV'", ",", "None", ")", "IV", "=", "kwargs", ".", "pop", "(", "'iv'", ",", "None", ")", "if", "(", "(", "None", ",", "None", ")", "==", "(", "iv", ",", "IV", ")", ")", ":", "iv", "=", "get_random_bytes", "(", "factory", ".", "block_size", ")", "if", "(", "iv", "is", "not", "None", ")", ":", "if", "(", "IV", "is", "not", "None", ")", ":", "raise", "TypeError", "(", "\"You must either use 'iv' or 'IV', not both\"", ")", "else", ":", "iv", "=", "IV", "(", "segment_size_bytes", ",", "rem", ")", "=", "divmod", "(", "kwargs", ".", "pop", "(", "'segment_size'", ",", "8", ")", ",", "8", ")", "if", "(", "(", "segment_size_bytes", "==", "0", ")", "or", "(", "rem", "!=", "0", ")", ")", ":", "raise", "ValueError", "(", "\"'segment_size' must be positive and multiple of 8 bits\"", ")", "if", "kwargs", ":", "raise", "TypeError", "(", "(", "'Unknown parameters for CFB: %s'", "%", "str", "(", "kwargs", ")", ")", ")", "return", "CfbMode", "(", "cipher_state", ",", "iv", ",", "segment_size_bytes", ")" ]
instantiate a cipher object that performs cfb encryption/decryption .
train
false
47,410
def module_not_available(module): try: mod = import_module(module) mod_not_avail = False except ImportError: mod_not_avail = True return mod_not_avail
[ "def", "module_not_available", "(", "module", ")", ":", "try", ":", "mod", "=", "import_module", "(", "module", ")", "mod_not_avail", "=", "False", "except", "ImportError", ":", "mod_not_avail", "=", "True", "return", "mod_not_avail" ]
can module be imported? returns true if module does not import .
train
false
47,411
def find_package(dir): dir = os.path.abspath(dir) orig_dir = dir path = map(os.path.abspath, sys.path) packages = [] last_dir = None while 1: if (dir in path): return '.'.join(packages) packages.insert(0, os.path.basename(dir)) dir = os.path.dirname(dir) if (last_dir == dir): raise ValueError(('%s is not under any path found in sys.path' % orig_dir)) last_dir = dir
[ "def", "find_package", "(", "dir", ")", ":", "dir", "=", "os", ".", "path", ".", "abspath", "(", "dir", ")", "orig_dir", "=", "dir", "path", "=", "map", "(", "os", ".", "path", ".", "abspath", ",", "sys", ".", "path", ")", "packages", "=", "[", "]", "last_dir", "=", "None", "while", "1", ":", "if", "(", "dir", "in", "path", ")", ":", "return", "'.'", ".", "join", "(", "packages", ")", "packages", ".", "insert", "(", "0", ",", "os", ".", "path", ".", "basename", "(", "dir", ")", ")", "dir", "=", "os", ".", "path", ".", "dirname", "(", "dir", ")", "if", "(", "last_dir", "==", "dir", ")", ":", "raise", "ValueError", "(", "(", "'%s is not under any path found in sys.path'", "%", "orig_dir", ")", ")", "last_dir", "=", "dir" ]
given a directory .
train
false
47,412
def export_metadefs(): return get_backend().db_export_metadefs(engine=db_api.get_engine(), metadata_path=None)
[ "def", "export_metadefs", "(", ")", ":", "return", "get_backend", "(", ")", ".", "db_export_metadefs", "(", "engine", "=", "db_api", ".", "get_engine", "(", ")", ",", "metadata_path", "=", "None", ")" ]
export metadefinitions from database to files .
train
false
47,413
def clear(): cmd = '{0} -C'.format(__detect_os()) out = __salt__['cmd.run_all'](cmd, python_shell=False) if out['retcode']: ret = out['stderr'].strip() else: ret = True return ret
[ "def", "clear", "(", ")", ":", "cmd", "=", "'{0} -C'", ".", "format", "(", "__detect_os", "(", ")", ")", "out", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", "if", "out", "[", "'retcode'", "]", ":", "ret", "=", "out", "[", "'stderr'", "]", ".", "strip", "(", ")", "else", ":", "ret", "=", "True", "return", "ret" ]
clear the virtual server table cli example: .
train
true
47,415
def gdal_full_version(): return _version_info('')
[ "def", "gdal_full_version", "(", ")", ":", "return", "_version_info", "(", "''", ")" ]
returns the full gdal version information .
train
false
47,416
def byte_to_float(b, mantissabits=5, zeroexp=2): if (type(b) is not int): b = ord(b) if (b == 0): return 0.0 bits = ((b & 255) << (24 - mantissabits)) bits += ((63 - zeroexp) << 24) return unpack('f', pack('i', bits))[0]
[ "def", "byte_to_float", "(", "b", ",", "mantissabits", "=", "5", ",", "zeroexp", "=", "2", ")", ":", "if", "(", "type", "(", "b", ")", "is", "not", "int", ")", ":", "b", "=", "ord", "(", "b", ")", "if", "(", "b", "==", "0", ")", ":", "return", "0.0", "bits", "=", "(", "(", "b", "&", "255", ")", "<<", "(", "24", "-", "mantissabits", ")", ")", "bits", "+=", "(", "(", "63", "-", "zeroexp", ")", "<<", "24", ")", "return", "unpack", "(", "'f'", ",", "pack", "(", "'i'", ",", "bits", ")", ")", "[", "0", "]" ]
decodes a floating point number stored in a single byte .
train
false
47,419
def _sortKeywords(keyword, kwds): sm = SequenceMatcher() sm.set_seq1(keyword.lower()) ratios = [(ratcliff(keyword, k, sm), k) for k in kwds] checkContained = False if (len(keyword) > 4): checkContained = True for (idx, data) in enumerate(ratios): (ratio, key) = data if key.startswith(keyword): ratios[idx] = ((ratio + 0.5), key) elif (checkContained and (keyword in key)): ratios[idx] = ((ratio + 0.3), key) ratios.sort() ratios.reverse() return [r[1] for r in ratios]
[ "def", "_sortKeywords", "(", "keyword", ",", "kwds", ")", ":", "sm", "=", "SequenceMatcher", "(", ")", "sm", ".", "set_seq1", "(", "keyword", ".", "lower", "(", ")", ")", "ratios", "=", "[", "(", "ratcliff", "(", "keyword", ",", "k", ",", "sm", ")", ",", "k", ")", "for", "k", "in", "kwds", "]", "checkContained", "=", "False", "if", "(", "len", "(", "keyword", ")", ">", "4", ")", ":", "checkContained", "=", "True", "for", "(", "idx", ",", "data", ")", "in", "enumerate", "(", "ratios", ")", ":", "(", "ratio", ",", "key", ")", "=", "data", "if", "key", ".", "startswith", "(", "keyword", ")", ":", "ratios", "[", "idx", "]", "=", "(", "(", "ratio", "+", "0.5", ")", ",", "key", ")", "elif", "(", "checkContained", "and", "(", "keyword", "in", "key", ")", ")", ":", "ratios", "[", "idx", "]", "=", "(", "(", "ratio", "+", "0.3", ")", ",", "key", ")", "ratios", ".", "sort", "(", ")", "ratios", ".", "reverse", "(", ")", "return", "[", "r", "[", "1", "]", "for", "r", "in", "ratios", "]" ]
sort a list of keywords .
train
false
47,420
@pytest.fixture(autouse=True) def isolate(tmpdir): home_dir = os.path.join(str(tmpdir), 'home') os.makedirs(home_dir) fake_root = os.path.join(str(tmpdir), 'fake-root') os.makedirs(fake_root) os.environ['HOME'] = home_dir os.environ['XDG_DATA_HOME'] = os.path.join(home_dir, '.local', 'share') os.environ['XDG_CONFIG_HOME'] = os.path.join(home_dir, '.config') os.environ['XDG_CACHE_HOME'] = os.path.join(home_dir, '.cache') os.environ['XDG_RUNTIME_DIR'] = os.path.join(home_dir, '.runtime') os.environ['XDG_DATA_DIRS'] = ':'.join([os.path.join(fake_root, 'usr', 'local', 'share'), os.path.join(fake_root, 'usr', 'share')]) os.environ['XDG_CONFIG_DIRS'] = os.path.join(fake_root, 'etc', 'xdg') os.environ['GIT_CONFIG_NOSYSTEM'] = '1' os.environ['GIT_AUTHOR_NAME'] = 'pip' os.environ['GIT_AUTHOR_EMAIL'] = 'pypa-dev@googlegroups.com' os.environ['PIP_DISABLE_PIP_VERSION_CHECK'] = 'true' os.makedirs(os.path.join(home_dir, '.config', 'git')) with open(os.path.join(home_dir, '.config', 'git', 'config'), 'wb') as fp: fp.write('[user]\n DCTB name = pip\n DCTB email = pypa-dev@googlegroups.com\n')
[ "@", "pytest", ".", "fixture", "(", "autouse", "=", "True", ")", "def", "isolate", "(", "tmpdir", ")", ":", "home_dir", "=", "os", ".", "path", ".", "join", "(", "str", "(", "tmpdir", ")", ",", "'home'", ")", "os", ".", "makedirs", "(", "home_dir", ")", "fake_root", "=", "os", ".", "path", ".", "join", "(", "str", "(", "tmpdir", ")", ",", "'fake-root'", ")", "os", ".", "makedirs", "(", "fake_root", ")", "os", ".", "environ", "[", "'HOME'", "]", "=", "home_dir", "os", ".", "environ", "[", "'XDG_DATA_HOME'", "]", "=", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.local'", ",", "'share'", ")", "os", ".", "environ", "[", "'XDG_CONFIG_HOME'", "]", "=", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.config'", ")", "os", ".", "environ", "[", "'XDG_CACHE_HOME'", "]", "=", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.cache'", ")", "os", ".", "environ", "[", "'XDG_RUNTIME_DIR'", "]", "=", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.runtime'", ")", "os", ".", "environ", "[", "'XDG_DATA_DIRS'", "]", "=", "':'", ".", "join", "(", "[", "os", ".", "path", ".", "join", "(", "fake_root", ",", "'usr'", ",", "'local'", ",", "'share'", ")", ",", "os", ".", "path", ".", "join", "(", "fake_root", ",", "'usr'", ",", "'share'", ")", "]", ")", "os", ".", "environ", "[", "'XDG_CONFIG_DIRS'", "]", "=", "os", ".", "path", ".", "join", "(", "fake_root", ",", "'etc'", ",", "'xdg'", ")", "os", ".", "environ", "[", "'GIT_CONFIG_NOSYSTEM'", "]", "=", "'1'", "os", ".", "environ", "[", "'GIT_AUTHOR_NAME'", "]", "=", "'pip'", "os", ".", "environ", "[", "'GIT_AUTHOR_EMAIL'", "]", "=", "'pypa-dev@googlegroups.com'", "os", ".", "environ", "[", "'PIP_DISABLE_PIP_VERSION_CHECK'", "]", "=", "'true'", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.config'", ",", "'git'", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.config'", ",", "'git'", ",", "'config'", ")", ",", "'wb'", ")", "as", "fp", ":", "fp", ".", "write", "(", "'[user]\\n DCTB name = pip\\n DCTB email = pypa-dev@googlegroups.com\\n'", ")" ]
give a rational isolating interval for an algebraic number .
train
false
47,421
def _refsToReplace(value, modFunct, titlesRefs, namesRefs, charactersRefs): mRefs = [] for (refRe, refTemplate) in [(re_titleRef, u'_%s_ (qv)'), (re_nameRef, u"'%s' (qv)"), (re_characterRef, u'#%s# (qv)')]: theseRefs = [] for theRef in refRe.findall(value): goodValue = modFunct((refTemplate % theRef), titlesRefs, namesRefs, charactersRefs) if (('_' in goodValue) or (len(goodValue) > 128)): continue toReplace = escape4xml(goodValue) replaceWith = goodValue.replace(theRef, escape4xml(theRef)) theseRefs.append((toReplace, replaceWith)) mRefs.append(theseRefs) return mRefs
[ "def", "_refsToReplace", "(", "value", ",", "modFunct", ",", "titlesRefs", ",", "namesRefs", ",", "charactersRefs", ")", ":", "mRefs", "=", "[", "]", "for", "(", "refRe", ",", "refTemplate", ")", "in", "[", "(", "re_titleRef", ",", "u'_%s_ (qv)'", ")", ",", "(", "re_nameRef", ",", "u\"'%s' (qv)\"", ")", ",", "(", "re_characterRef", ",", "u'#%s# (qv)'", ")", "]", ":", "theseRefs", "=", "[", "]", "for", "theRef", "in", "refRe", ".", "findall", "(", "value", ")", ":", "goodValue", "=", "modFunct", "(", "(", "refTemplate", "%", "theRef", ")", ",", "titlesRefs", ",", "namesRefs", ",", "charactersRefs", ")", "if", "(", "(", "'_'", "in", "goodValue", ")", "or", "(", "len", "(", "goodValue", ")", ">", "128", ")", ")", ":", "continue", "toReplace", "=", "escape4xml", "(", "goodValue", ")", "replaceWith", "=", "goodValue", ".", "replace", "(", "theRef", ",", "escape4xml", "(", "theRef", ")", ")", "theseRefs", ".", "append", "(", "(", "toReplace", ",", "replaceWith", ")", ")", "mRefs", ".", "append", "(", "theseRefs", ")", "return", "mRefs" ]
return three lists - for movie titles .
train
false
47,423
def validate_email_unique(email, for_user=None): existing_accounts = get_user_model().objects.filter(email=email) existing_email = EmailAddress.objects.filter(email=email) if (for_user is not None): existing_accounts = existing_accounts.exclude(pk=for_user.pk) existing_email = existing_email.exclude(user=for_user) if (existing_accounts.exists() or existing_email.exists()): raise ValidationError('A user with that email address already exists')
[ "def", "validate_email_unique", "(", "email", ",", "for_user", "=", "None", ")", ":", "existing_accounts", "=", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "email", "=", "email", ")", "existing_email", "=", "EmailAddress", ".", "objects", ".", "filter", "(", "email", "=", "email", ")", "if", "(", "for_user", "is", "not", "None", ")", ":", "existing_accounts", "=", "existing_accounts", ".", "exclude", "(", "pk", "=", "for_user", ".", "pk", ")", "existing_email", "=", "existing_email", ".", "exclude", "(", "user", "=", "for_user", ")", "if", "(", "existing_accounts", ".", "exists", "(", ")", "or", "existing_email", ".", "exists", "(", ")", ")", ":", "raise", "ValidationError", "(", "'A user with that email address already exists'", ")" ]
validates an email to ensure it does not already exist in the system .
train
false
47,424
def get_tables(c): c.execute("select name from sqlite_master where type='table'") return c.fetchall()
[ "def", "get_tables", "(", "c", ")", ":", "c", ".", "execute", "(", "\"select name from sqlite_master where type='table'\"", ")", "return", "c", ".", "fetchall", "(", ")" ]
list table names in a given schema .
train
false
47,426
def private(fn): fn._private = True return fn
[ "def", "private", "(", "fn", ")", ":", "fn", ".", "_private", "=", "True", "return", "fn" ]
do not expose method in public api .
train
false
47,427
@click.command(u'mysql') @pass_context def mysql(context): site = get_site(context) frappe.init(site=site) msq = find_executable(u'mysql') os.execv(msq, [msq, u'-u', frappe.conf.db_name, (u'-p' + frappe.conf.db_password), frappe.conf.db_name, u'-h', (frappe.conf.db_host or u'localhost'), u'-A'])
[ "@", "click", ".", "command", "(", "u'mysql'", ")", "@", "pass_context", "def", "mysql", "(", "context", ")", ":", "site", "=", "get_site", "(", "context", ")", "frappe", ".", "init", "(", "site", "=", "site", ")", "msq", "=", "find_executable", "(", "u'mysql'", ")", "os", ".", "execv", "(", "msq", ",", "[", "msq", ",", "u'-u'", ",", "frappe", ".", "conf", ".", "db_name", ",", "(", "u'-p'", "+", "frappe", ".", "conf", ".", "db_password", ")", ",", "frappe", ".", "conf", ".", "db_name", ",", "u'-h'", ",", "(", "frappe", ".", "conf", ".", "db_host", "or", "u'localhost'", ")", ",", "u'-A'", "]", ")" ]
start mariadb console for a site .
train
false
47,428
def collection_reload(collection, **kwargs): _query('admin/collections?action=RELOAD&name={collection}&wt=json'.format(collection=collection), **kwargs)
[ "def", "collection_reload", "(", "collection", ",", "**", "kwargs", ")", ":", "_query", "(", "'admin/collections?action=RELOAD&name={collection}&wt=json'", ".", "format", "(", "collection", "=", "collection", ")", ",", "**", "kwargs", ")" ]
check if a collection exists additional parameters may be passed .
train
false
47,429
def _create_object(table, table_obj): _db_content[table][table_obj.obj] = table_obj
[ "def", "_create_object", "(", "table", ",", "table_obj", ")", ":", "_db_content", "[", "table", "]", "[", "table_obj", ".", "obj", "]", "=", "table_obj" ]
create an object in the db .
train
false
47,431
def new(rsa_key): return PKCS115_SigScheme(rsa_key)
[ "def", "new", "(", "rsa_key", ")", ":", "return", "PKCS115_SigScheme", "(", "rsa_key", ")" ]
create a new blowfish cipher .
train
false
47,433
def get_tree_changes(repo): with open_repo_closing(repo) as r: index = r.open_index() tracked_changes = {'add': [], 'delete': [], 'modify': []} try: tree_id = r['HEAD'].tree except KeyError: tree_id = None for change in index.changes_from_tree(r.object_store, tree_id): if (not change[0][0]): tracked_changes['add'].append(change[0][1]) elif (not change[0][1]): tracked_changes['delete'].append(change[0][0]) elif (change[0][0] == change[0][1]): tracked_changes['modify'].append(change[0][0]) else: raise AssertionError('git mv ops not yet supported') return tracked_changes
[ "def", "get_tree_changes", "(", "repo", ")", ":", "with", "open_repo_closing", "(", "repo", ")", "as", "r", ":", "index", "=", "r", ".", "open_index", "(", ")", "tracked_changes", "=", "{", "'add'", ":", "[", "]", ",", "'delete'", ":", "[", "]", ",", "'modify'", ":", "[", "]", "}", "try", ":", "tree_id", "=", "r", "[", "'HEAD'", "]", ".", "tree", "except", "KeyError", ":", "tree_id", "=", "None", "for", "change", "in", "index", ".", "changes_from_tree", "(", "r", ".", "object_store", ",", "tree_id", ")", ":", "if", "(", "not", "change", "[", "0", "]", "[", "0", "]", ")", ":", "tracked_changes", "[", "'add'", "]", ".", "append", "(", "change", "[", "0", "]", "[", "1", "]", ")", "elif", "(", "not", "change", "[", "0", "]", "[", "1", "]", ")", ":", "tracked_changes", "[", "'delete'", "]", ".", "append", "(", "change", "[", "0", "]", "[", "0", "]", ")", "elif", "(", "change", "[", "0", "]", "[", "0", "]", "==", "change", "[", "0", "]", "[", "1", "]", ")", ":", "tracked_changes", "[", "'modify'", "]", ".", "append", "(", "change", "[", "0", "]", "[", "0", "]", ")", "else", ":", "raise", "AssertionError", "(", "'git mv ops not yet supported'", ")", "return", "tracked_changes" ]
return add/delete/modify changes to tree by comparing index to head .
train
false
47,434
def str2fmt(s): regex = re.compile('(?P<bef>\\D*)(?P<fromyear>\\d+)(?P<sep>\\D*)(?P<toyear>\\d*)(?P<after>\\D*)') m = re.match(regex, s) res = {'fromnchars': len(m.group('fromyear')), 'tonchars': len(m.group('toyear'))} res['fmt'] = ('%s%%s%s%s%s' % (m.group('bef'), m.group('sep'), ('%s' if res['tonchars'] else ''), m.group('after'))) return res
[ "def", "str2fmt", "(", "s", ")", ":", "regex", "=", "re", ".", "compile", "(", "'(?P<bef>\\\\D*)(?P<fromyear>\\\\d+)(?P<sep>\\\\D*)(?P<toyear>\\\\d*)(?P<after>\\\\D*)'", ")", "m", "=", "re", ".", "match", "(", "regex", ",", "s", ")", "res", "=", "{", "'fromnchars'", ":", "len", "(", "m", ".", "group", "(", "'fromyear'", ")", ")", ",", "'tonchars'", ":", "len", "(", "m", ".", "group", "(", "'toyear'", ")", ")", "}", "res", "[", "'fmt'", "]", "=", "(", "'%s%%s%s%s%s'", "%", "(", "m", ".", "group", "(", "'bef'", ")", ",", "m", ".", "group", "(", "'sep'", ")", ",", "(", "'%s'", "if", "res", "[", "'tonchars'", "]", "else", "''", ")", ",", "m", ".", "group", "(", "'after'", ")", ")", ")", "return", "res" ]
deduces formatting syntax from a span string .
train
false
47,436
def make_exception(response, content, error_info=None, use_json=True): if isinstance(content, six.binary_type): content = content.decode('utf-8') if isinstance(content, six.string_types): payload = None if use_json: try: payload = json.loads(content) except ValueError: pass if (payload is None): payload = {'error': {'message': content}} else: payload = content message = payload.get('error', {}).get('message', '') errors = payload.get('error', {}).get('errors', ()) if (error_info is not None): message += (' (%s)' % (error_info,)) try: klass = _HTTP_CODE_TO_EXCEPTION[response.status] except KeyError: error = GoogleCloudError(message, errors) error.code = response.status else: error = klass(message, errors) return error
[ "def", "make_exception", "(", "response", ",", "content", ",", "error_info", "=", "None", ",", "use_json", "=", "True", ")", ":", "if", "isinstance", "(", "content", ",", "six", ".", "binary_type", ")", ":", "content", "=", "content", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "content", ",", "six", ".", "string_types", ")", ":", "payload", "=", "None", "if", "use_json", ":", "try", ":", "payload", "=", "json", ".", "loads", "(", "content", ")", "except", "ValueError", ":", "pass", "if", "(", "payload", "is", "None", ")", ":", "payload", "=", "{", "'error'", ":", "{", "'message'", ":", "content", "}", "}", "else", ":", "payload", "=", "content", "message", "=", "payload", ".", "get", "(", "'error'", ",", "{", "}", ")", ".", "get", "(", "'message'", ",", "''", ")", "errors", "=", "payload", ".", "get", "(", "'error'", ",", "{", "}", ")", ".", "get", "(", "'errors'", ",", "(", ")", ")", "if", "(", "error_info", "is", "not", "None", ")", ":", "message", "+=", "(", "' (%s)'", "%", "(", "error_info", ",", ")", ")", "try", ":", "klass", "=", "_HTTP_CODE_TO_EXCEPTION", "[", "response", ".", "status", "]", "except", "KeyError", ":", "error", "=", "GoogleCloudError", "(", "message", ",", "errors", ")", "error", ".", "code", "=", "response", ".", "status", "else", ":", "error", "=", "klass", "(", "message", ",", "errors", ")", "return", "error" ]
factory: create exception based on http response code .
train
false
47,437
def parseParam(line): if (line == ''): return (None, '') elif (line[0] != '"'): mode = 1 else: mode = 2 res = '' io = StringIO(line) if (mode == 2): io.read(1) while 1: a = io.read(1) if (a == '"'): if (mode == 2): io.read(1) return (res, io.read()) elif (a == '\\'): a = io.read(1) if (a == ''): return (None, line) elif (a == ''): if (mode == 1): return (res, io.read()) else: return (None, line) elif (a == ' '): if (mode == 1): return (res, io.read()) res += a
[ "def", "parseParam", "(", "line", ")", ":", "if", "(", "line", "==", "''", ")", ":", "return", "(", "None", ",", "''", ")", "elif", "(", "line", "[", "0", "]", "!=", "'\"'", ")", ":", "mode", "=", "1", "else", ":", "mode", "=", "2", "res", "=", "''", "io", "=", "StringIO", "(", "line", ")", "if", "(", "mode", "==", "2", ")", ":", "io", ".", "read", "(", "1", ")", "while", "1", ":", "a", "=", "io", ".", "read", "(", "1", ")", "if", "(", "a", "==", "'\"'", ")", ":", "if", "(", "mode", "==", "2", ")", ":", "io", ".", "read", "(", "1", ")", "return", "(", "res", ",", "io", ".", "read", "(", ")", ")", "elif", "(", "a", "==", "'\\\\'", ")", ":", "a", "=", "io", ".", "read", "(", "1", ")", "if", "(", "a", "==", "''", ")", ":", "return", "(", "None", ",", "line", ")", "elif", "(", "a", "==", "''", ")", ":", "if", "(", "mode", "==", "1", ")", ":", "return", "(", "res", ",", "io", ".", "read", "(", ")", ")", "else", ":", "return", "(", "None", ",", "line", ")", "elif", "(", "a", "==", "' '", ")", ":", "if", "(", "mode", "==", "1", ")", ":", "return", "(", "res", ",", "io", ".", "read", "(", ")", ")", "res", "+=", "a" ]
chew one dqstring or atom from beginning of line and return .
train
false
47,438
def oo_merge_dicts(first_dict, second_dict): if ((not isinstance(first_dict, dict)) or (not isinstance(second_dict, dict))): raise errors.AnsibleFilterError('|failed expects to merge two dicts') merged = first_dict.copy() merged.update(second_dict) return merged
[ "def", "oo_merge_dicts", "(", "first_dict", ",", "second_dict", ")", ":", "if", "(", "(", "not", "isinstance", "(", "first_dict", ",", "dict", ")", ")", "or", "(", "not", "isinstance", "(", "second_dict", ",", "dict", ")", ")", ")", ":", "raise", "errors", ".", "AnsibleFilterError", "(", "'|failed expects to merge two dicts'", ")", "merged", "=", "first_dict", ".", "copy", "(", ")", "merged", ".", "update", "(", "second_dict", ")", "return", "merged" ]
merge two dictionaries where second_dict values take precedence .
train
false
47,439
def write_rows(xf, worksheet): all_rows = get_rows_to_write(worksheet) dims = worksheet.row_dimensions max_column = worksheet.max_column with xf.element('sheetData'): for (row_idx, row) in all_rows: attrs = {'r': ('%d' % row_idx), 'spans': ('1:%d' % max_column)} if (row_idx in dims): row_dimension = dims[row_idx] attrs.update(dict(row_dimension)) with xf.element('row', attrs): for (col, cell) in sorted(row, key=itemgetter(0)): if ((cell.value is None) and (not cell.has_style)): continue el = write_cell(worksheet, cell, cell.has_style) xf.write(el)
[ "def", "write_rows", "(", "xf", ",", "worksheet", ")", ":", "all_rows", "=", "get_rows_to_write", "(", "worksheet", ")", "dims", "=", "worksheet", ".", "row_dimensions", "max_column", "=", "worksheet", ".", "max_column", "with", "xf", ".", "element", "(", "'sheetData'", ")", ":", "for", "(", "row_idx", ",", "row", ")", "in", "all_rows", ":", "attrs", "=", "{", "'r'", ":", "(", "'%d'", "%", "row_idx", ")", ",", "'spans'", ":", "(", "'1:%d'", "%", "max_column", ")", "}", "if", "(", "row_idx", "in", "dims", ")", ":", "row_dimension", "=", "dims", "[", "row_idx", "]", "attrs", ".", "update", "(", "dict", "(", "row_dimension", ")", ")", "with", "xf", ".", "element", "(", "'row'", ",", "attrs", ")", ":", "for", "(", "col", ",", "cell", ")", "in", "sorted", "(", "row", ",", "key", "=", "itemgetter", "(", "0", ")", ")", ":", "if", "(", "(", "cell", ".", "value", "is", "None", ")", "and", "(", "not", "cell", ".", "has_style", ")", ")", ":", "continue", "el", "=", "write_cell", "(", "worksheet", ",", "cell", ",", "cell", ".", "has_style", ")", "xf", ".", "write", "(", "el", ")" ]
write worksheet data to xml .
train
false
47,440
def url_is_from_any_domain(url, domains): host = parse_url(url).hostname if host: return any((((host == d) or host.endswith(('.%s' % d))) for d in domains)) else: return False
[ "def", "url_is_from_any_domain", "(", "url", ",", "domains", ")", ":", "host", "=", "parse_url", "(", "url", ")", ".", "hostname", "if", "host", ":", "return", "any", "(", "(", "(", "(", "host", "==", "d", ")", "or", "host", ".", "endswith", "(", "(", "'.%s'", "%", "d", ")", ")", ")", "for", "d", "in", "domains", ")", ")", "else", ":", "return", "False" ]
return true if the url belongs to any of the given domains .
train
false
47,442
@composite def tagged_union_strategy(draw, type_, attr_strategies): invariant = type_.__invariant__ tag = draw(sampled_from(invariant._allowed_tags)) attributes = {invariant.tag_attribute: tag} for (name, strategy) in attr_strategies.items(): if ((name in invariant.attributes_for_tag[tag]) or (name not in invariant._all_attributes)): attributes[name] = draw(strategy) return type_(**attributes)
[ "@", "composite", "def", "tagged_union_strategy", "(", "draw", ",", "type_", ",", "attr_strategies", ")", ":", "invariant", "=", "type_", ".", "__invariant__", "tag", "=", "draw", "(", "sampled_from", "(", "invariant", ".", "_allowed_tags", ")", ")", "attributes", "=", "{", "invariant", ".", "tag_attribute", ":", "tag", "}", "for", "(", "name", ",", "strategy", ")", "in", "attr_strategies", ".", "items", "(", ")", ":", "if", "(", "(", "name", "in", "invariant", ".", "attributes_for_tag", "[", "tag", "]", ")", "or", "(", "name", "not", "in", "invariant", ".", "_all_attributes", ")", ")", ":", "attributes", "[", "name", "]", "=", "draw", "(", "strategy", ")", "return", "type_", "(", "**", "attributes", ")" ]
create a strategy for building a type with a taggedunioninvariant .
train
false
47,443
def asymmetric_spatial_2d_padding(x, top_pad=1, bottom_pad=1, left_pad=1, right_pad=1, dim_ordering='default'): if (dim_ordering == 'default'): dim_ordering = image_dim_ordering() if (dim_ordering not in {'th', 'tf'}): raise ValueError(('Unknown dim_ordering ' + str(dim_ordering))) input_shape = x.shape if (dim_ordering == 'th'): output_shape = (input_shape[0], input_shape[1], ((input_shape[2] + top_pad) + bottom_pad), ((input_shape[3] + left_pad) + right_pad)) output = T.zeros(output_shape) indices = (slice(None), slice(None), slice(top_pad, (input_shape[2] + top_pad)), slice(left_pad, (input_shape[3] + left_pad))) elif (dim_ordering == 'tf'): output_shape = (input_shape[0], ((input_shape[1] + top_pad) + bottom_pad), ((input_shape[2] + left_pad) + right_pad), input_shape[3]) print output_shape output = T.zeros(output_shape) indices = (slice(None), slice(top_pad, (input_shape[1] + top_pad)), slice(left_pad, (input_shape[2] + left_pad)), slice(None)) else: raise ValueError('Invalid dim_ordering:', dim_ordering) return T.set_subtensor(output[indices], x)
[ "def", "asymmetric_spatial_2d_padding", "(", "x", ",", "top_pad", "=", "1", ",", "bottom_pad", "=", "1", ",", "left_pad", "=", "1", ",", "right_pad", "=", "1", ",", "dim_ordering", "=", "'default'", ")", ":", "if", "(", "dim_ordering", "==", "'default'", ")", ":", "dim_ordering", "=", "image_dim_ordering", "(", ")", "if", "(", "dim_ordering", "not", "in", "{", "'th'", ",", "'tf'", "}", ")", ":", "raise", "ValueError", "(", "(", "'Unknown dim_ordering '", "+", "str", "(", "dim_ordering", ")", ")", ")", "input_shape", "=", "x", ".", "shape", "if", "(", "dim_ordering", "==", "'th'", ")", ":", "output_shape", "=", "(", "input_shape", "[", "0", "]", ",", "input_shape", "[", "1", "]", ",", "(", "(", "input_shape", "[", "2", "]", "+", "top_pad", ")", "+", "bottom_pad", ")", ",", "(", "(", "input_shape", "[", "3", "]", "+", "left_pad", ")", "+", "right_pad", ")", ")", "output", "=", "T", ".", "zeros", "(", "output_shape", ")", "indices", "=", "(", "slice", "(", "None", ")", ",", "slice", "(", "None", ")", ",", "slice", "(", "top_pad", ",", "(", "input_shape", "[", "2", "]", "+", "top_pad", ")", ")", ",", "slice", "(", "left_pad", ",", "(", "input_shape", "[", "3", "]", "+", "left_pad", ")", ")", ")", "elif", "(", "dim_ordering", "==", "'tf'", ")", ":", "output_shape", "=", "(", "input_shape", "[", "0", "]", ",", "(", "(", "input_shape", "[", "1", "]", "+", "top_pad", ")", "+", "bottom_pad", ")", ",", "(", "(", "input_shape", "[", "2", "]", "+", "left_pad", ")", "+", "right_pad", ")", ",", "input_shape", "[", "3", "]", ")", "print", "output_shape", "output", "=", "T", ".", "zeros", "(", "output_shape", ")", "indices", "=", "(", "slice", "(", "None", ")", ",", "slice", "(", "top_pad", ",", "(", "input_shape", "[", "1", "]", "+", "top_pad", ")", ")", ",", "slice", "(", "left_pad", ",", "(", "input_shape", "[", "2", "]", "+", "left_pad", ")", ")", ",", "slice", "(", "None", ")", ")", "else", ":", "raise", "ValueError", "(", "'Invalid dim_ordering:'", ",", "dim_ordering", ")", "return", "T", ".", "set_subtensor", "(", "output", "[", "indices", "]", ",", "x", ")" ]
pad the rows and columns of a 4d tensor with "top_pad" .
train
false
47,445
def print_tokens(tokens, style=None, true_color=False, file=None): if (style is None): style = DEFAULT_STYLE assert isinstance(style, Style) output = create_output(true_color=true_color, stdout=file) renderer_print_tokens(output, tokens, style)
[ "def", "print_tokens", "(", "tokens", ",", "style", "=", "None", ",", "true_color", "=", "False", ",", "file", "=", "None", ")", ":", "if", "(", "style", "is", "None", ")", ":", "style", "=", "DEFAULT_STYLE", "assert", "isinstance", "(", "style", ",", "Style", ")", "output", "=", "create_output", "(", "true_color", "=", "true_color", ",", "stdout", "=", "file", ")", "renderer_print_tokens", "(", "output", ",", "tokens", ",", "style", ")" ]
print a list of tuples in the given style to the output .
train
true
47,446
def copy_to_slave(registry, xml_parent, data): p = 'com.michelin.cio.hudson.plugins.copytoslave.CopyToSlaveBuildWrapper' cs = XML.SubElement(xml_parent, p) XML.SubElement(cs, 'includes').text = ','.join(data.get('includes', [''])) XML.SubElement(cs, 'excludes').text = ','.join(data.get('excludes', [''])) XML.SubElement(cs, 'flatten').text = str(data.get('flatten', False)).lower() XML.SubElement(cs, 'includeAntExcludes').text = str(data.get('include-ant-excludes', False)).lower() rel = str(data.get('relative-to', 'userContent')) opt = ('home', 'somewhereElse', 'userContent', 'workspace') if (rel not in opt): raise ValueError(('relative-to must be one of %r' % opt)) XML.SubElement(cs, 'relativeTo').text = rel XML.SubElement(cs, 'hudsonHomeRelative').text = 'false'
[ "def", "copy_to_slave", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "p", "=", "'com.michelin.cio.hudson.plugins.copytoslave.CopyToSlaveBuildWrapper'", "cs", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "p", ")", "XML", ".", "SubElement", "(", "cs", ",", "'includes'", ")", ".", "text", "=", "','", ".", "join", "(", "data", ".", "get", "(", "'includes'", ",", "[", "''", "]", ")", ")", "XML", ".", "SubElement", "(", "cs", ",", "'excludes'", ")", ".", "text", "=", "','", ".", "join", "(", "data", ".", "get", "(", "'excludes'", ",", "[", "''", "]", ")", ")", "XML", ".", "SubElement", "(", "cs", ",", "'flatten'", ")", ".", "text", "=", "str", "(", "data", ".", "get", "(", "'flatten'", ",", "False", ")", ")", ".", "lower", "(", ")", "XML", ".", "SubElement", "(", "cs", ",", "'includeAntExcludes'", ")", ".", "text", "=", "str", "(", "data", ".", "get", "(", "'include-ant-excludes'", ",", "False", ")", ")", ".", "lower", "(", ")", "rel", "=", "str", "(", "data", ".", "get", "(", "'relative-to'", ",", "'userContent'", ")", ")", "opt", "=", "(", "'home'", ",", "'somewhereElse'", ",", "'userContent'", ",", "'workspace'", ")", "if", "(", "rel", "not", "in", "opt", ")", ":", "raise", "ValueError", "(", "(", "'relative-to must be one of %r'", "%", "opt", ")", ")", "XML", ".", "SubElement", "(", "cs", ",", "'relativeTo'", ")", ".", "text", "=", "rel", "XML", ".", "SubElement", "(", "cs", ",", "'hudsonHomeRelative'", ")", ".", "text", "=", "'false'" ]
yaml: copy-to-slave copy files to slave before build requires the jenkins :jenkins-wiki:copy to slave plugin <copy+to+slave+plugin> .
train
false
47,447
def drop_first_component(X, y): pipeline = make_pipeline(PCA(), FunctionTransformer(all_but_first_column)) (X_train, X_test, y_train, y_test) = train_test_split(X, y) pipeline.fit(X_train, y_train) return (pipeline.transform(X_test), y_test)
[ "def", "drop_first_component", "(", "X", ",", "y", ")", ":", "pipeline", "=", "make_pipeline", "(", "PCA", "(", ")", ",", "FunctionTransformer", "(", "all_but_first_column", ")", ")", "(", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", ")", "=", "train_test_split", "(", "X", ",", "y", ")", "pipeline", ".", "fit", "(", "X_train", ",", "y_train", ")", "return", "(", "pipeline", ".", "transform", "(", "X_test", ")", ",", "y_test", ")" ]
create a pipeline with pca and the column selector and use it to transform the dataset .
train
false
47,448
def update_variables(old_contents): new_contents = [] for line in old_contents: words = line.split() for word in words: if word.endswith(':'): word = word[:(-1)] if (word in VAR_MAPPINGS.keys()): line = line.replace(word, VAR_MAPPINGS[word]) new_contents.append(line) return new_contents
[ "def", "update_variables", "(", "old_contents", ")", ":", "new_contents", "=", "[", "]", "for", "line", "in", "old_contents", ":", "words", "=", "line", ".", "split", "(", ")", "for", "word", "in", "words", ":", "if", "word", ".", "endswith", "(", "':'", ")", ":", "word", "=", "word", "[", ":", "(", "-", "1", ")", "]", "if", "(", "word", "in", "VAR_MAPPINGS", ".", "keys", "(", ")", ")", ":", "line", "=", "line", ".", "replace", "(", "word", ",", "VAR_MAPPINGS", "[", "word", "]", ")", "new_contents", ".", "append", "(", "line", ")", "return", "new_contents" ]
replace all references to old variables .
train
false
47,449
def interleave_entries(queue_entries, special_tasks): _compute_next_job_for_tasks(queue_entries, special_tasks) interleaved_entries = [] for task in special_tasks: if (task.next_job_id is not None): break interleaved_entries.append(_special_task_to_dict(task)) special_task_index = len(interleaved_entries) for queue_entry in queue_entries: interleaved_entries.append(_queue_entry_to_dict(queue_entry)) for task in special_tasks[special_task_index:]: if (task.next_job_id < queue_entry.job.id): break interleaved_entries.append(_special_task_to_dict(task)) special_task_index += 1 return interleaved_entries
[ "def", "interleave_entries", "(", "queue_entries", ",", "special_tasks", ")", ":", "_compute_next_job_for_tasks", "(", "queue_entries", ",", "special_tasks", ")", "interleaved_entries", "=", "[", "]", "for", "task", "in", "special_tasks", ":", "if", "(", "task", ".", "next_job_id", "is", "not", "None", ")", ":", "break", "interleaved_entries", ".", "append", "(", "_special_task_to_dict", "(", "task", ")", ")", "special_task_index", "=", "len", "(", "interleaved_entries", ")", "for", "queue_entry", "in", "queue_entries", ":", "interleaved_entries", ".", "append", "(", "_queue_entry_to_dict", "(", "queue_entry", ")", ")", "for", "task", "in", "special_tasks", "[", "special_task_index", ":", "]", ":", "if", "(", "task", ".", "next_job_id", "<", "queue_entry", ".", "job", ".", "id", ")", ":", "break", "interleaved_entries", ".", "append", "(", "_special_task_to_dict", "(", "task", ")", ")", "special_task_index", "+=", "1", "return", "interleaved_entries" ]
both lists should be ordered by descending id .
train
false
47,453
def sdecode_if_string(value_): if isinstance(value_, string_types): value_ = sdecode(value_) return value_
[ "def", "sdecode_if_string", "(", "value_", ")", ":", "if", "isinstance", "(", "value_", ",", "string_types", ")", ":", "value_", "=", "sdecode", "(", "value_", ")", "return", "value_" ]
if the value is a string .
train
false
47,454
def getLumSeriesPR650(lumLevels=8, winSize=(800, 600), monitor=None, gamma=1.0, allGuns=True, useBits=False, autoMode='auto', stimSize=0.3, photometer='COM1'): logging.warning('DEPRECATED (since v1.60.01): Use monitors.getLumSeries() instead') val = getLumSeries(lumLevels, winSize, monitor, gamma, allGuns, useBits, autoMode, stimSize, photometer) return val
[ "def", "getLumSeriesPR650", "(", "lumLevels", "=", "8", ",", "winSize", "=", "(", "800", ",", "600", ")", ",", "monitor", "=", "None", ",", "gamma", "=", "1.0", ",", "allGuns", "=", "True", ",", "useBits", "=", "False", ",", "autoMode", "=", "'auto'", ",", "stimSize", "=", "0.3", ",", "photometer", "=", "'COM1'", ")", ":", "logging", ".", "warning", "(", "'DEPRECATED (since v1.60.01): Use monitors.getLumSeries() instead'", ")", "val", "=", "getLumSeries", "(", "lumLevels", ",", "winSize", ",", "monitor", ",", "gamma", ",", "allGuns", ",", "useBits", ",", "autoMode", ",", "stimSize", ",", "photometer", ")", "return", "val" ]
deprecated : use :class:psychopy .
train
false
47,455
@authenticated_json_post_view @has_request_variables def json_report_error(request, user_profile, message=REQ(), stacktrace=REQ(), ui_message=REQ(validator=check_bool), user_agent=REQ(), href=REQ(), log=REQ(), more_info=REQ(validator=check_dict([]), default=None)): if (not settings.ERROR_REPORTING): return json_success() if js_source_map: stacktrace = js_source_map.annotate_stacktrace(stacktrace) try: version = subprocess.check_output(['git', 'log', 'HEAD^..HEAD', '--oneline'], universal_newlines=True) except Exception: version = None queue_json_publish('error_reports', dict(type='browser', report=dict(user_email=user_profile.email, user_full_name=user_profile.full_name, user_visible=ui_message, server_path=settings.DEPLOY_ROOT, version=version, user_agent=user_agent, href=href, message=message, stacktrace=stacktrace, log=log, more_info=more_info)), (lambda x: None)) return json_success()
[ "@", "authenticated_json_post_view", "@", "has_request_variables", "def", "json_report_error", "(", "request", ",", "user_profile", ",", "message", "=", "REQ", "(", ")", ",", "stacktrace", "=", "REQ", "(", ")", ",", "ui_message", "=", "REQ", "(", "validator", "=", "check_bool", ")", ",", "user_agent", "=", "REQ", "(", ")", ",", "href", "=", "REQ", "(", ")", ",", "log", "=", "REQ", "(", ")", ",", "more_info", "=", "REQ", "(", "validator", "=", "check_dict", "(", "[", "]", ")", ",", "default", "=", "None", ")", ")", ":", "if", "(", "not", "settings", ".", "ERROR_REPORTING", ")", ":", "return", "json_success", "(", ")", "if", "js_source_map", ":", "stacktrace", "=", "js_source_map", ".", "annotate_stacktrace", "(", "stacktrace", ")", "try", ":", "version", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'log'", ",", "'HEAD^..HEAD'", ",", "'--oneline'", "]", ",", "universal_newlines", "=", "True", ")", "except", "Exception", ":", "version", "=", "None", "queue_json_publish", "(", "'error_reports'", ",", "dict", "(", "type", "=", "'browser'", ",", "report", "=", "dict", "(", "user_email", "=", "user_profile", ".", "email", ",", "user_full_name", "=", "user_profile", ".", "full_name", ",", "user_visible", "=", "ui_message", ",", "server_path", "=", "settings", ".", "DEPLOY_ROOT", ",", "version", "=", "version", ",", "user_agent", "=", "user_agent", ",", "href", "=", "href", ",", "message", "=", "message", ",", "stacktrace", "=", "stacktrace", ",", "log", "=", "log", ",", "more_info", "=", "more_info", ")", ")", ",", "(", "lambda", "x", ":", "None", ")", ")", "return", "json_success", "(", ")" ]
accepts an error report and stores in a queue for processing .
train
false
47,456
def mysql_connect(sockfile): (user, passwd) = mysqlconf.get_user_password(sockfile) return MySQLdb.connect(unix_socket=sockfile, connect_timeout=CONNECT_TIMEOUT, user=user, passwd=passwd)
[ "def", "mysql_connect", "(", "sockfile", ")", ":", "(", "user", ",", "passwd", ")", "=", "mysqlconf", ".", "get_user_password", "(", "sockfile", ")", "return", "MySQLdb", ".", "connect", "(", "unix_socket", "=", "sockfile", ",", "connect_timeout", "=", "CONNECT_TIMEOUT", ",", "user", "=", "user", ",", "passwd", "=", "passwd", ")" ]
connects to the mysql server using the specified socket file .
train
false
47,459
def is_metaclass(rdclass): if _metaclasses.has_key(rdclass): return True return False
[ "def", "is_metaclass", "(", "rdclass", ")", ":", "if", "_metaclasses", ".", "has_key", "(", "rdclass", ")", ":", "return", "True", "return", "False" ]
true if the class is a metaclass .
train
false
47,460
def message_from_event(event, secret): msg = event.serialize() msg['message_signature'] = compute_signature(msg, secret) return msg
[ "def", "message_from_event", "(", "event", ",", "secret", ")", ":", "msg", "=", "event", ".", "serialize", "(", ")", "msg", "[", "'message_signature'", "]", "=", "compute_signature", "(", "msg", ",", "secret", ")", "return", "msg" ]
make an event message ready to be published or stored .
train
false
47,461
def pascal(n, kind='symmetric', exact=True): from scipy.special import comb if (kind not in ['symmetric', 'lower', 'upper']): raise ValueError("kind must be 'symmetric', 'lower', or 'upper'") if exact: if (n >= 35): L_n = np.empty((n, n), dtype=object) L_n.fill(0) else: L_n = np.zeros((n, n), dtype=np.uint64) for i in range(n): for j in range((i + 1)): L_n[(i, j)] = comb(i, j, exact=True) else: L_n = comb(*np.ogrid[:n, :n]) if (kind is 'lower'): p = L_n elif (kind is 'upper'): p = L_n.T else: p = np.dot(L_n, L_n.T) return p
[ "def", "pascal", "(", "n", ",", "kind", "=", "'symmetric'", ",", "exact", "=", "True", ")", ":", "from", "scipy", ".", "special", "import", "comb", "if", "(", "kind", "not", "in", "[", "'symmetric'", ",", "'lower'", ",", "'upper'", "]", ")", ":", "raise", "ValueError", "(", "\"kind must be 'symmetric', 'lower', or 'upper'\"", ")", "if", "exact", ":", "if", "(", "n", ">=", "35", ")", ":", "L_n", "=", "np", ".", "empty", "(", "(", "n", ",", "n", ")", ",", "dtype", "=", "object", ")", "L_n", ".", "fill", "(", "0", ")", "else", ":", "L_n", "=", "np", ".", "zeros", "(", "(", "n", ",", "n", ")", ",", "dtype", "=", "np", ".", "uint64", ")", "for", "i", "in", "range", "(", "n", ")", ":", "for", "j", "in", "range", "(", "(", "i", "+", "1", ")", ")", ":", "L_n", "[", "(", "i", ",", "j", ")", "]", "=", "comb", "(", "i", ",", "j", ",", "exact", "=", "True", ")", "else", ":", "L_n", "=", "comb", "(", "*", "np", ".", "ogrid", "[", ":", "n", ",", ":", "n", "]", ")", "if", "(", "kind", "is", "'lower'", ")", ":", "p", "=", "L_n", "elif", "(", "kind", "is", "'upper'", ")", ":", "p", "=", "L_n", ".", "T", "else", ":", "p", "=", "np", ".", "dot", "(", "L_n", ",", "L_n", ".", "T", ")", "return", "p" ]
returns the n x n pascal matrix .
train
false
47,462
def ensure_dir(path): try: os.makedirs(path) except OSError as e: if (e.errno == errno.EEXIST): if (not os.path.isdir(path)): raise OSError(errno.ENOTDIR, ("Not a directory: '%s'" % path)) pass else: raise
[ "def", "ensure_dir", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "e", ":", "if", "(", "e", ".", "errno", "==", "errno", ".", "EEXIST", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ")", ":", "raise", "OSError", "(", "errno", ".", "ENOTDIR", ",", "(", "\"Not a directory: '%s'\"", "%", "path", ")", ")", "pass", "else", ":", "raise" ]
create the entire directory path .
train
false
47,463
@must_have_permission(ADMIN) @must_be_branched_from_node def update_draft_registration(auth, node, draft, *args, **kwargs): check_draft_state(draft) data = request.get_json() schema_data = data.get('schema_data', {}) schema_data = rapply(schema_data, strip_html) schema_name = data.get('schema_name') schema_version = data.get('schema_version', 1) if schema_name: meta_schema = get_schema_or_fail((Q('name', 'eq', schema_name) & Q('schema_version', 'eq', schema_version))) existing_schema = draft.registration_schema if ((existing_schema.name, existing_schema.schema_version) != (meta_schema.name, meta_schema.schema_version)): draft.registration_schema = meta_schema draft.update_metadata(schema_data) draft.save() return (serialize_draft_registration(draft, auth), http.OK)
[ "@", "must_have_permission", "(", "ADMIN", ")", "@", "must_be_branched_from_node", "def", "update_draft_registration", "(", "auth", ",", "node", ",", "draft", ",", "*", "args", ",", "**", "kwargs", ")", ":", "check_draft_state", "(", "draft", ")", "data", "=", "request", ".", "get_json", "(", ")", "schema_data", "=", "data", ".", "get", "(", "'schema_data'", ",", "{", "}", ")", "schema_data", "=", "rapply", "(", "schema_data", ",", "strip_html", ")", "schema_name", "=", "data", ".", "get", "(", "'schema_name'", ")", "schema_version", "=", "data", ".", "get", "(", "'schema_version'", ",", "1", ")", "if", "schema_name", ":", "meta_schema", "=", "get_schema_or_fail", "(", "(", "Q", "(", "'name'", ",", "'eq'", ",", "schema_name", ")", "&", "Q", "(", "'schema_version'", ",", "'eq'", ",", "schema_version", ")", ")", ")", "existing_schema", "=", "draft", ".", "registration_schema", "if", "(", "(", "existing_schema", ".", "name", ",", "existing_schema", ".", "schema_version", ")", "!=", "(", "meta_schema", ".", "name", ",", "meta_schema", ".", "schema_version", ")", ")", ":", "draft", ".", "registration_schema", "=", "meta_schema", "draft", ".", "update_metadata", "(", "schema_data", ")", "draft", ".", "save", "(", ")", "return", "(", "serialize_draft_registration", "(", "draft", ",", "auth", ")", ",", "http", ".", "OK", ")" ]
update an existing draft registration :return: serialized draft registration :rtype: dict :raises: httperror .
train
false
47,464
def LDL(matlist, K): new_matlist = copy.deepcopy(matlist) nrow = len(new_matlist) (L, D) = (eye(nrow, K), eye(nrow, K)) for i in range(nrow): for j in range((i + 1)): a = K.zero for k in range(j): a += ((L[i][k] * L[j][k]) * D[k][k]) if (i == j): D[j][j] = (new_matlist[j][j] - a) else: L[i][j] = ((new_matlist[i][j] - a) / D[j][j]) return (L, D, conjugate_transpose(L, K))
[ "def", "LDL", "(", "matlist", ",", "K", ")", ":", "new_matlist", "=", "copy", ".", "deepcopy", "(", "matlist", ")", "nrow", "=", "len", "(", "new_matlist", ")", "(", "L", ",", "D", ")", "=", "(", "eye", "(", "nrow", ",", "K", ")", ",", "eye", "(", "nrow", ",", "K", ")", ")", "for", "i", "in", "range", "(", "nrow", ")", ":", "for", "j", "in", "range", "(", "(", "i", "+", "1", ")", ")", ":", "a", "=", "K", ".", "zero", "for", "k", "in", "range", "(", "j", ")", ":", "a", "+=", "(", "(", "L", "[", "i", "]", "[", "k", "]", "*", "L", "[", "j", "]", "[", "k", "]", ")", "*", "D", "[", "k", "]", "[", "k", "]", ")", "if", "(", "i", "==", "j", ")", ":", "D", "[", "j", "]", "[", "j", "]", "=", "(", "new_matlist", "[", "j", "]", "[", "j", "]", "-", "a", ")", "else", ":", "L", "[", "i", "]", "[", "j", "]", "=", "(", "(", "new_matlist", "[", "i", "]", "[", "j", "]", "-", "a", ")", "/", "D", "[", "j", "]", "[", "j", "]", ")", "return", "(", "L", ",", "D", ",", "conjugate_transpose", "(", "L", ",", "K", ")", ")" ]
performs the ldl decomposition of a hermitian matrix and returns l .
train
false
47,465
def _owner_isinstance(inp, test_class): return (bool(inp.owner) and isinstance(inp.owner.op, test_class))
[ "def", "_owner_isinstance", "(", "inp", ",", "test_class", ")", ":", "return", "(", "bool", "(", "inp", ".", "owner", ")", "and", "isinstance", "(", "inp", ".", "owner", ".", "op", ",", "test_class", ")", ")" ]
tests whether input has an owner and if its owner is of type test_class .
train
false
47,466
def test_fit_sample_wrong_object(): ratio = 'auto' cluster = 'rnd' cc = ClusterCentroids(ratio=ratio, random_state=RND_SEED, estimator=cluster) assert_raises(ValueError, cc.fit_sample, X, Y)
[ "def", "test_fit_sample_wrong_object", "(", ")", ":", "ratio", "=", "'auto'", "cluster", "=", "'rnd'", "cc", "=", "ClusterCentroids", "(", "ratio", "=", "ratio", ",", "random_state", "=", "RND_SEED", ",", "estimator", "=", "cluster", ")", "assert_raises", "(", "ValueError", ",", "cc", ".", "fit_sample", ",", "X", ",", "Y", ")" ]
test fit and sample using a kmeans object .
train
false
47,467
def _neighbor_switch(G, w, unsat, h_node_residual, avoid_node_id=None): if ((avoid_node_id is None) or (h_node_residual[avoid_node_id] > 1)): w_prime = next(iter(unsat)) else: iter_var = iter(unsat) while True: w_prime = next(iter_var) if (w_prime != avoid_node_id): break w_prime_neighbs = G[w_prime] for v in G[w]: if ((v not in w_prime_neighbs) and (v != w_prime)): switch_node = v break G.remove_edge(w, switch_node) G.add_edge(w_prime, switch_node) h_node_residual[w] += 1 h_node_residual[w_prime] -= 1 if (h_node_residual[w_prime] == 0): unsat.remove(w_prime)
[ "def", "_neighbor_switch", "(", "G", ",", "w", ",", "unsat", ",", "h_node_residual", ",", "avoid_node_id", "=", "None", ")", ":", "if", "(", "(", "avoid_node_id", "is", "None", ")", "or", "(", "h_node_residual", "[", "avoid_node_id", "]", ">", "1", ")", ")", ":", "w_prime", "=", "next", "(", "iter", "(", "unsat", ")", ")", "else", ":", "iter_var", "=", "iter", "(", "unsat", ")", "while", "True", ":", "w_prime", "=", "next", "(", "iter_var", ")", "if", "(", "w_prime", "!=", "avoid_node_id", ")", ":", "break", "w_prime_neighbs", "=", "G", "[", "w_prime", "]", "for", "v", "in", "G", "[", "w", "]", ":", "if", "(", "(", "v", "not", "in", "w_prime_neighbs", ")", "and", "(", "v", "!=", "w_prime", ")", ")", ":", "switch_node", "=", "v", "break", "G", ".", "remove_edge", "(", "w", ",", "switch_node", ")", "G", ".", "add_edge", "(", "w_prime", ",", "switch_node", ")", "h_node_residual", "[", "w", "]", "+=", "1", "h_node_residual", "[", "w_prime", "]", "-=", "1", "if", "(", "h_node_residual", "[", "w_prime", "]", "==", "0", ")", ":", "unsat", ".", "remove", "(", "w_prime", ")" ]
releases one free stub for saturated node w .
train
false
47,468
def defer_fail(_failure): d = defer.Deferred() reactor.callLater(0.1, d.errback, _failure) return d
[ "def", "defer_fail", "(", "_failure", ")", ":", "d", "=", "defer", ".", "Deferred", "(", ")", "reactor", ".", "callLater", "(", "0.1", ",", "d", ".", "errback", ",", "_failure", ")", "return", "d" ]
same as twisted .
train
false
47,469
def bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=None, update_cells=True): rv = IMPL.bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=last_refreshed) if update_cells: try: cells_rpcapi.CellsAPI().bw_usage_update_at_top(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed) except Exception: LOG.exception(_('Failed to notify cells of bw_usage update')) return rv
[ "def", "bw_usage_update", "(", "context", ",", "uuid", ",", "mac", ",", "start_period", ",", "bw_in", ",", "bw_out", ",", "last_ctr_in", ",", "last_ctr_out", ",", "last_refreshed", "=", "None", ",", "update_cells", "=", "True", ")", ":", "rv", "=", "IMPL", ".", "bw_usage_update", "(", "context", ",", "uuid", ",", "mac", ",", "start_period", ",", "bw_in", ",", "bw_out", ",", "last_ctr_in", ",", "last_ctr_out", ",", "last_refreshed", "=", "last_refreshed", ")", "if", "update_cells", ":", "try", ":", "cells_rpcapi", ".", "CellsAPI", "(", ")", ".", "bw_usage_update_at_top", "(", "context", ",", "uuid", ",", "mac", ",", "start_period", ",", "bw_in", ",", "bw_out", ",", "last_ctr_in", ",", "last_ctr_out", ",", "last_refreshed", ")", "except", "Exception", ":", "LOG", ".", "exception", "(", "_", "(", "'Failed to notify cells of bw_usage update'", ")", ")", "return", "rv" ]
update cached bandwidth usage for an instances network based on mac address .
train
false
47,470
def spatial_pyramid_pooling_2d(x, pyramid_height, pooling_class, use_cudnn=True): return SpatialPyramidPooling2D(x.shape[1:], pyramid_height, pooling_class, use_cudnn=use_cudnn)(x)
[ "def", "spatial_pyramid_pooling_2d", "(", "x", ",", "pyramid_height", ",", "pooling_class", ",", "use_cudnn", "=", "True", ")", ":", "return", "SpatialPyramidPooling2D", "(", "x", ".", "shape", "[", "1", ":", "]", ",", "pyramid_height", ",", "pooling_class", ",", "use_cudnn", "=", "use_cudnn", ")", "(", "x", ")" ]
spatial pyramid pooling function .
train
false
47,471
def test_ncr_sample_wrong_X(): ncr = NeighbourhoodCleaningRule(random_state=RND_SEED) ncr.fit(X, Y) assert_raises(RuntimeError, ncr.sample, np.random.random((100, 40)), np.array((([0] * 50) + ([1] * 50))))
[ "def", "test_ncr_sample_wrong_X", "(", ")", ":", "ncr", "=", "NeighbourhoodCleaningRule", "(", "random_state", "=", "RND_SEED", ")", "ncr", ".", "fit", "(", "X", ",", "Y", ")", "assert_raises", "(", "RuntimeError", ",", "ncr", ".", "sample", ",", "np", ".", "random", ".", "random", "(", "(", "100", ",", "40", ")", ")", ",", "np", ".", "array", "(", "(", "(", "[", "0", "]", "*", "50", ")", "+", "(", "[", "1", "]", "*", "50", ")", ")", ")", ")" ]
test either if an error is raised when x is different at fitting and sampling .
train
false
47,472
def drop_protected_attrs(model_class, values): for attr in model_class.__protected_attributes__: if (attr in values): del values[attr]
[ "def", "drop_protected_attrs", "(", "model_class", ",", "values", ")", ":", "for", "attr", "in", "model_class", ".", "__protected_attributes__", ":", "if", "(", "attr", "in", "values", ")", ":", "del", "values", "[", "attr", "]" ]
removed protected attributes from values dictionary using the models __protected_attributes__ field .
train
false
47,473
def explode(df): return (df.index, df.columns, df.values)
[ "def", "explode", "(", "df", ")", ":", "return", "(", "df", ".", "index", ",", "df", ".", "columns", ",", "df", ".", "values", ")" ]
take a dataframe and return a triple of .
train
false
47,474
def _make_writable(fname): os.chmod(fname, (stat.S_IMODE(os.lstat(fname)[stat.ST_MODE]) | 128))
[ "def", "_make_writable", "(", "fname", ")", ":", "os", ".", "chmod", "(", "fname", ",", "(", "stat", ".", "S_IMODE", "(", "os", ".", "lstat", "(", "fname", ")", "[", "stat", ".", "ST_MODE", "]", ")", "|", "128", ")", ")" ]
make a file writable .
train
false
47,476
def _MakeOptional(property_dict, test_key): for (key, value) in property_dict.items(): if test_key(key): property_dict[key]['required'] = False return property_dict
[ "def", "_MakeOptional", "(", "property_dict", ",", "test_key", ")", ":", "for", "(", "key", ",", "value", ")", "in", "property_dict", ".", "items", "(", ")", ":", "if", "test_key", "(", "key", ")", ":", "property_dict", "[", "key", "]", "[", "'required'", "]", "=", "False", "return", "property_dict" ]
iterates through all key/value pairs in the property dictionary .
train
false
47,477
@shared_task def fanout_operation(feed_manager, feed_class, user_ids, operation, operation_kwargs): feed_manager.fanout(user_ids, feed_class, operation, operation_kwargs) return ('%d user_ids, %r, %r (%r)' % (len(user_ids), feed_class, operation, operation_kwargs))
[ "@", "shared_task", "def", "fanout_operation", "(", "feed_manager", ",", "feed_class", ",", "user_ids", ",", "operation", ",", "operation_kwargs", ")", ":", "feed_manager", ".", "fanout", "(", "user_ids", ",", "feed_class", ",", "operation", ",", "operation_kwargs", ")", "return", "(", "'%d user_ids, %r, %r (%r)'", "%", "(", "len", "(", "user_ids", ")", ",", "feed_class", ",", "operation", ",", "operation_kwargs", ")", ")" ]
simple task wrapper for _fanout task just making sure code is where you expect it :) .
train
false