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
46,807
def ensure_vpn_forward(public_ip, port, private_ip): iptables_manager.ipv4['filter'].add_rule('FORWARD', ('-d %s -p udp --dport 1194 -j ACCEPT' % private_ip)) iptables_manager.ipv4['nat'].add_rule('PREROUTING', ('-d %s -p udp --dport %s -j DNAT --to %s:1194' % (public_ip, port, private_ip))) iptables_manager.ipv4['nat'].add_rule('OUTPUT', ('-d %s -p udp --dport %s -j DNAT --to %s:1194' % (public_ip, port, private_ip))) iptables_manager.apply()
[ "def", "ensure_vpn_forward", "(", "public_ip", ",", "port", ",", "private_ip", ")", ":", "iptables_manager", ".", "ipv4", "[", "'filter'", "]", ".", "add_rule", "(", "'FORWARD'", ",", "(", "'-d %s -p udp --dport 1194 -j ACCEPT'", "%", "private_ip", ")", ")", "ip...
sets up forwarding rules for vlan .
train
false
46,808
def set_timeout(name, value, power='ac', scheme=None): ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} comment = [] if (name not in ['monitor', 'disk', 'standby', 'hibernate']): ret['result'] = False comment.append('{0} is not a valid setting'.format(name)) elif (power not in ['ac', 'dc']): ret['result'] = False comment.append('{0} is not a power type'.format(power)) else: check_func = __salt__['powercfg.get_{0}_timeout'.format(name)] set_func = __salt__['powercfg.set_{0}_timeout'.format(name)] values = check_func(scheme=scheme) if (values[power] == value): comment.append('{0} {1} is already set with the value {2}.'.format(name, power, value)) else: ret['changes'] = {name: {power: value}} set_func(value, power, scheme=scheme) ret['comment'] = ' '.join(comment) return ret
[ "def", "set_timeout", "(", "name", ",", "value", ",", "power", "=", "'ac'", ",", "scheme", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", ...
set the sleep timeouts of specific items such as disk .
train
false
46,809
def iterhosts(resources): for (module_name, key, resource) in resources: (resource_type, name) = key.split(u'.', 1) try: parser = PARSERS[resource_type] except KeyError: continue (yield parser(resource, module_name))
[ "def", "iterhosts", "(", "resources", ")", ":", "for", "(", "module_name", ",", "key", ",", "resource", ")", "in", "resources", ":", "(", "resource_type", ",", "name", ")", "=", "key", ".", "split", "(", "u'.'", ",", "1", ")", "try", ":", "parser", ...
yield host tuples of .
train
false
46,810
def directed_hausdorff(u, v, seed=0): u = np.asarray(u, dtype=np.float64, order='c') v = np.asarray(v, dtype=np.float64, order='c') result = _hausdorff.directed_hausdorff(u, v, seed) return result
[ "def", "directed_hausdorff", "(", "u", ",", "v", ",", "seed", "=", "0", ")", ":", "u", "=", "np", ".", "asarray", "(", "u", ",", "dtype", "=", "np", ".", "float64", ",", "order", "=", "'c'", ")", "v", "=", "np", ".", "asarray", "(", "v", ",",...
computes the directed hausdorff distance between two n-d arrays .
train
false
46,811
def mount_volume(volume, mnt_base, configfile=None): fileutils.ensure_tree(mnt_base) command = ['mount.quobyte', volume, mnt_base] if configfile: command.extend(['-c', configfile]) LOG.debug('Mounting volume %s at mount point %s ...', volume, mnt_base) utils.execute(check_exit_code=[0, 4], *command) LOG.info(_LI('Mounted volume: %s'), volume)
[ "def", "mount_volume", "(", "volume", ",", "mnt_base", ",", "configfile", "=", "None", ")", ":", "fileutils", ".", "ensure_tree", "(", "mnt_base", ")", "command", "=", "[", "'mount.quobyte'", ",", "volume", ",", "mnt_base", "]", "if", "configfile", ":", "c...
wraps execute calls for mounting a quobyte volume .
train
false
46,812
def get_python_version(): return sys.version[:3]
[ "def", "get_python_version", "(", ")", ":", "return", "sys", ".", "version", "[", ":", "3", "]" ]
get a 3 element tuple with the python version .
train
false
46,813
def program_version_greater(ver1, ver2): v1f = version_to_float(ver1) v2f = version_to_float(ver2) return (v1f > v2f)
[ "def", "program_version_greater", "(", "ver1", ",", "ver2", ")", ":", "v1f", "=", "version_to_float", "(", "ver1", ")", "v2f", "=", "version_to_float", "(", "ver2", ")", "return", "(", "v1f", ">", "v2f", ")" ]
return true if ver1 > ver2 using semantics of comparing version numbers .
train
false
46,814
def _setHashDB(): if (not conf.hashDBFile): conf.hashDBFile = (conf.sessionFile or os.path.join(conf.outputPath, 'session.sqlite')) if os.path.exists(conf.hashDBFile): if conf.flushSession: try: os.remove(conf.hashDBFile) logger.info('flushing session file') except OSError as msg: errMsg = ('unable to flush the session file (%s)' % msg) raise SqlmapFilePathException(errMsg) conf.hashDB = HashDB(conf.hashDBFile)
[ "def", "_setHashDB", "(", ")", ":", "if", "(", "not", "conf", ".", "hashDBFile", ")", ":", "conf", ".", "hashDBFile", "=", "(", "conf", ".", "sessionFile", "or", "os", ".", "path", ".", "join", "(", "conf", ".", "outputPath", ",", "'session.sqlite'", ...
check and set the hashdb sqlite file for query resume functionality .
train
false
46,815
@pytest.mark.cmd @pytest.mark.django_db def test_dump_stop_level(capfd): call_command('dump', '--stats', '--stop-level=1') (out, err) = capfd.readouterr() assert ('None,None' in out) assert out.startswith('/') assert ('/language0/project0/' in out) assert ('/language1/project0/' in out) assert ('/projects/project0/' in out) assert ('/language0/project0/store0.po' not in out) assert ('/language0/project0/subdir0' not in out)
[ "@", "pytest", ".", "mark", ".", "cmd", "@", "pytest", ".", "mark", ".", "django_db", "def", "test_dump_stop_level", "(", "capfd", ")", ":", "call_command", "(", "'dump'", ",", "'--stats'", ",", "'--stop-level=1'", ")", "(", "out", ",", "err", ")", "=", ...
set the depth for data .
train
false
46,816
@scopes.add_arg_scope def avg_pool(inputs, kernel_size, stride=2, padding='VALID', scope=None): with tf.name_scope(scope, 'AvgPool', [inputs]): (kernel_h, kernel_w) = _two_element_tuple(kernel_size) (stride_h, stride_w) = _two_element_tuple(stride) return tf.nn.avg_pool(inputs, ksize=[1, kernel_h, kernel_w, 1], strides=[1, stride_h, stride_w, 1], padding=padding)
[ "@", "scopes", ".", "add_arg_scope", "def", "avg_pool", "(", "inputs", ",", "kernel_size", ",", "stride", "=", "2", ",", "padding", "=", "'VALID'", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'AvgPool'", ",...
adds a avg pooling layer .
train
false
46,817
def fake_disk_info_json(instance, type='qcow2'): disk_info = fake_disk_info_byname(instance, type) return jsonutils.dumps(disk_info.values())
[ "def", "fake_disk_info_json", "(", "instance", ",", "type", "=", "'qcow2'", ")", ":", "disk_info", "=", "fake_disk_info_byname", "(", "instance", ",", "type", ")", "return", "jsonutils", ".", "dumps", "(", "disk_info", ".", "values", "(", ")", ")" ]
return fake instance_disk_info corresponding accurately to the properties of the given instance object .
train
false
46,818
def ParseExpiration(expiration): delta = 0 for match in re.finditer(_DELTA_REGEX, expiration): amount = int(match.group(1)) units = _EXPIRATION_CONVERSIONS.get(match.group(2).lower(), 1) delta += (amount * units) return delta
[ "def", "ParseExpiration", "(", "expiration", ")", ":", "delta", "=", "0", "for", "match", "in", "re", ".", "finditer", "(", "_DELTA_REGEX", ",", "expiration", ")", ":", "amount", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "units", "=...
parses an expiration delta string .
train
false
46,819
def inplace_tanh_derivative(Z, delta): delta *= (1 - (Z ** 2))
[ "def", "inplace_tanh_derivative", "(", "Z", ",", "delta", ")", ":", "delta", "*=", "(", "1", "-", "(", "Z", "**", "2", ")", ")" ]
apply the derivative of the hyperbolic tanh function .
train
false
46,820
def SocketClient(address): family = address_type(address) with socket.socket(getattr(socket, family)) as s: s.setblocking(True) s.connect(address) return Connection(s.detach())
[ "def", "SocketClient", "(", "address", ")", ":", "family", "=", "address_type", "(", "address", ")", "with", "socket", ".", "socket", "(", "getattr", "(", "socket", ",", "family", ")", ")", "as", "s", ":", "s", ".", "setblocking", "(", "True", ")", "...
return a connection object connected to the socket given by address .
train
false
46,821
def get_topic_similarities_as_csv(): output = StringIO.StringIO() writer = csv.writer(output) writer.writerow(RECOMMENDATION_CATEGORIES) topic_similarities = get_topic_similarities_dict() for topic in RECOMMENDATION_CATEGORIES: topic_similarities_row = [value for (_, value) in sorted(topic_similarities[topic].iteritems())] writer.writerow(topic_similarities_row) return output.getvalue()
[ "def", "get_topic_similarities_as_csv", "(", ")", ":", "output", "=", "StringIO", ".", "StringIO", "(", ")", "writer", "=", "csv", ".", "writer", "(", "output", ")", "writer", ".", "writerow", "(", "RECOMMENDATION_CATEGORIES", ")", "topic_similarities", "=", "...
downloads all similarities corresponding to the current topics as a string which contains the contents of a csv file .
train
false
46,822
def cross_entropy_seq_with_mask(logits, target_seqs, input_mask, return_details=False): targets = tf.reshape(target_seqs, [(-1)]) weights = tf.to_float(tf.reshape(input_mask, [(-1)])) losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, targets) loss = tf.div(tf.reduce_sum(tf.mul(losses, weights)), tf.reduce_sum(weights), name='seq_loss_with_mask') if return_details: return (loss, losses, weights, targets) else: return loss
[ "def", "cross_entropy_seq_with_mask", "(", "logits", ",", "target_seqs", ",", "input_mask", ",", "return_details", "=", "False", ")", ":", "targets", "=", "tf", ".", "reshape", "(", "target_seqs", ",", "[", "(", "-", "1", ")", "]", ")", "weights", "=", "...
returns the expression of cross-entropy of two sequences .
train
true
46,823
def _get_destination(script_parts): for part in script_parts: if ((part not in {'ln', '-s', '--symbolic'}) and os.path.exists(part)): return part
[ "def", "_get_destination", "(", "script_parts", ")", ":", "for", "part", "in", "script_parts", ":", "if", "(", "(", "part", "not", "in", "{", "'ln'", ",", "'-s'", ",", "'--symbolic'", "}", ")", "and", "os", ".", "path", ".", "exists", "(", "part", ")...
when arguments order is wrong first argument will be destination .
train
true
46,824
def gaussian_random_matrix(n_components, n_features, random_state=None): _check_input_size(n_components, n_features) rng = check_random_state(random_state) components = rng.normal(loc=0.0, scale=(1.0 / np.sqrt(n_components)), size=(n_components, n_features)) return components
[ "def", "gaussian_random_matrix", "(", "n_components", ",", "n_features", ",", "random_state", "=", "None", ")", ":", "_check_input_size", "(", "n_components", ",", "n_features", ")", "rng", "=", "check_random_state", "(", "random_state", ")", "components", "=", "r...
generate a dense gaussian random matrix .
train
false
46,826
def get_install_lng(): lng = 0 try: hive = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) key = _winreg.OpenKey(hive, 'Software\\SABnzbd') for i in range(0, _winreg.QueryInfoKey(key)[1]): (name, value, val_type) = _winreg.EnumValue(key, i) if (name == 'Installer Language'): lng = value _winreg.CloseKey(key) except WindowsError: pass finally: _winreg.CloseKey(hive) return lng
[ "def", "get_install_lng", "(", ")", ":", "lng", "=", "0", "try", ":", "hive", "=", "_winreg", ".", "ConnectRegistry", "(", "None", ",", "_winreg", ".", "HKEY_LOCAL_MACHINE", ")", "key", "=", "_winreg", ".", "OpenKey", "(", "hive", ",", "'Software\\\\SABnzb...
return language-code used by the installer .
train
false
46,827
def GASpecificConfig(r, info): assert isinstance(info, DecoderSpecificInfo) r.skip(1) dependsOnCoreCoder = r.bits(1) if dependsOnCoreCoder: r.skip(14) extensionFlag = r.bits(1) if (not info.channelConfiguration): pce = ProgramConfigElement(r) info.pce_channels = pce.channels if ((info.audioObjectType == 6) or (info.audioObjectType == 20)): r.skip(3) if extensionFlag: if (info.audioObjectType == 22): r.skip((5 + 11)) if (info.audioObjectType in (17, 19, 20, 23)): r.skip(((1 + 1) + 1)) extensionFlag3 = r.bits(1) if (extensionFlag3 != 0): raise NotImplementedError('extensionFlag3 set')
[ "def", "GASpecificConfig", "(", "r", ",", "info", ")", ":", "assert", "isinstance", "(", "info", ",", "DecoderSpecificInfo", ")", "r", ".", "skip", "(", "1", ")", "dependsOnCoreCoder", "=", "r", ".", "bits", "(", "1", ")", "if", "dependsOnCoreCoder", ":"...
reads gaspecificconfig which is needed to get the data after that and to read program_config_element which can contain channel counts .
train
true
46,828
def flipPoints(points, prefix, xmlElement): origin = evaluate.getVector3ByPrefix(Vector3(), (prefix + 'origin'), xmlElement) axis = evaluate.getVector3ByPrefix(Vector3(1.0, 0.0, 0.0), (prefix + 'axis'), xmlElement).getNormalized() for point in points: point.setToVector3((point - ((2.0 * axis.dot((point - origin))) * axis)))
[ "def", "flipPoints", "(", "points", ",", "prefix", ",", "xmlElement", ")", ":", "origin", "=", "evaluate", ".", "getVector3ByPrefix", "(", "Vector3", "(", ")", ",", "(", "prefix", "+", "'origin'", ")", ",", "xmlElement", ")", "axis", "=", "evaluate", "."...
flip the points .
train
false
46,829
def check_db(cursor): _check_balances(cursor) _check_no_team_balances(cursor) _check_tips(cursor) _check_orphans(cursor) _check_orphans_no_tips(cursor)
[ "def", "check_db", "(", "cursor", ")", ":", "_check_balances", "(", "cursor", ")", "_check_no_team_balances", "(", "cursor", ")", "_check_tips", "(", "cursor", ")", "_check_orphans", "(", "cursor", ")", "_check_orphans_no_tips", "(", "cursor", ")" ]
runs all available self checks on the given cursor .
train
false
46,830
def json_mapping_parser(path, template): mapping_blocks = {} with open(path, 'r') as handle: for (tid, rows) in json.load(handle).iteritems(): mappings = {} for (key, values) in rows.iteritems(): mapping = {template.get(k, k): v for (k, v) in values.iteritems()} mappings[int(key)] = mapping mapping_blocks[tid] = mappings return mapping_blocks
[ "def", "json_mapping_parser", "(", "path", ",", "template", ")", ":", "mapping_blocks", "=", "{", "}", "with", "open", "(", "path", ",", "'r'", ")", "as", "handle", ":", "for", "(", "tid", ",", "rows", ")", "in", "json", ".", "load", "(", "handle", ...
given a json file of the the mapping data for a modbus device .
train
false
46,832
def _get_ansi_code(color=None, style=None): ansi_code = [] if style: style_attrs = splitstrip(style) for effect in style_attrs: ansi_code.append(ANSI_STYLES[effect]) if color: if color.isdigit(): ansi_code.extend(['38', '5']) ansi_code.append(color) else: ansi_code.append(ANSI_COLORS[color]) if ansi_code: return ((ANSI_PREFIX + ';'.join(ansi_code)) + ANSI_END) return ''
[ "def", "_get_ansi_code", "(", "color", "=", "None", ",", "style", "=", "None", ")", ":", "ansi_code", "=", "[", "]", "if", "style", ":", "style_attrs", "=", "splitstrip", "(", "style", ")", "for", "effect", "in", "style_attrs", ":", "ansi_code", ".", "...
return ansi escape code corresponding to color and style :type color: str or none .
train
true
46,833
def exactly_one(l): return exactly_n(l)
[ "def", "exactly_one", "(", "l", ")", ":", "return", "exactly_n", "(", "l", ")" ]
check if only one item is not none .
train
false
46,835
def ascii_lower(string): return string.encode(u'utf8').lower().decode(u'utf8')
[ "def", "ascii_lower", "(", "string", ")", ":", "return", "string", ".", "encode", "(", "u'utf8'", ")", ".", "lower", "(", ")", ".", "decode", "(", "u'utf8'", ")" ]
transform ascii letters to lower case: a-z is mapped to a-z .
train
false
46,836
def identity(x): return x
[ "def", "identity", "(", "x", ")", ":", "return", "x" ]
simply return the input array .
train
false
46,837
def _fastq_sanger_convert_fastq_sanger(in_handle, out_handle, alphabet=None): mapping = ''.join((([chr(0) for ascii in range(0, 33)] + [chr(ascii) for ascii in range(33, 127)]) + [chr(0) for ascii in range(127, 256)])) assert (len(mapping) == 256) return _fastq_generic(in_handle, out_handle, mapping)
[ "def", "_fastq_sanger_convert_fastq_sanger", "(", "in_handle", ",", "out_handle", ",", "alphabet", "=", "None", ")", ":", "mapping", "=", "''", ".", "join", "(", "(", "(", "[", "chr", "(", "0", ")", "for", "ascii", "in", "range", "(", "0", ",", "33", ...
fast sanger fastq to sanger fastq conversion .
train
false
46,838
def all_queries(fn, obj, *param_lists): results = [] params = [[obj]] for pl in param_lists: new_params = [] for p in pl: for c in params: new_param = list(c) new_param.append(p) new_params.append(new_param) params = new_params results = [fn(*p) for p in params] return results
[ "def", "all_queries", "(", "fn", ",", "obj", ",", "*", "param_lists", ")", ":", "results", "=", "[", "]", "params", "=", "[", "[", "obj", "]", "]", "for", "pl", "in", "param_lists", ":", "new_params", "=", "[", "]", "for", "p", "in", "pl", ":", ...
given a fn and a first argument obj .
train
false
46,839
@core_helper @maintain.deprecated("h.subnav_link is deprecated please use h.nav_link\nNOTE: if action is passed as the second parameter make sure it is passed as a named parameter eg. `action='my_action'") def subnav_link(text, action, **kwargs): kwargs['action'] = action return nav_link(text, **kwargs)
[ "@", "core_helper", "@", "maintain", ".", "deprecated", "(", "\"h.subnav_link is deprecated please use h.nav_link\\nNOTE: if action is passed as the second parameter make sure it is passed as a named parameter eg. `action='my_action'\"", ")", "def", "subnav_link", "(", "text", ",", "acti...
create a link for a named route .
train
false
46,840
def translate_masks(modifiers): masks = [] for i in modifiers: try: masks.append(xcbq.ModMasks[i]) except KeyError: raise KeyError(('Unknown modifier: %s' % i)) if masks: return reduce(operator.or_, masks) else: return 0
[ "def", "translate_masks", "(", "modifiers", ")", ":", "masks", "=", "[", "]", "for", "i", "in", "modifiers", ":", "try", ":", "masks", ".", "append", "(", "xcbq", ".", "ModMasks", "[", "i", "]", ")", "except", "KeyError", ":", "raise", "KeyError", "(...
translate a modifier mask specified as a list of strings into an or-ed bit representation .
train
false
46,841
def optimizeAngle(angle): if (angle < 0): angle %= (-360) else: angle %= 360 if (angle >= 270): angle -= 360 elif (angle < (-90)): angle += 360 return angle
[ "def", "optimizeAngle", "(", "angle", ")", ":", "if", "(", "angle", "<", "0", ")", ":", "angle", "%=", "(", "-", "360", ")", "else", ":", "angle", "%=", "360", "if", "(", "angle", ">=", "270", ")", ":", "angle", "-=", "360", "elif", "(", "angle...
because any rotation can be expressed within 360 degrees of any given number .
train
true
46,842
def _create_dicts(): short2rgb_dict = dict(CLUT) rgb2short_dict = {} for (k, v) in short2rgb_dict.items(): rgb2short_dict[v] = k return (rgb2short_dict, short2rgb_dict)
[ "def", "_create_dicts", "(", ")", ":", "short2rgb_dict", "=", "dict", "(", "CLUT", ")", "rgb2short_dict", "=", "{", "}", "for", "(", "k", ",", "v", ")", "in", "short2rgb_dict", ".", "items", "(", ")", ":", "rgb2short_dict", "[", "v", "]", "=", "k", ...
create dictionary .
train
true
46,845
def _responseFromMessage(responseConstructor, message, **kwargs): response = responseConstructor(id=message.id, answer=True, **kwargs) response.queries = message.queries[:] return response
[ "def", "_responseFromMessage", "(", "responseConstructor", ",", "message", ",", "**", "kwargs", ")", ":", "response", "=", "responseConstructor", "(", "id", "=", "message", ".", "id", ",", "answer", "=", "True", ",", "**", "kwargs", ")", "response", ".", "...
generate a l{message} like instance suitable for use as the response to c{message} .
train
false
46,847
def only_if_coordinator(func): def wrapper(*args, **kwargs): 'Decorator wrapper.' if args[0].is_coordinator: from soco.exceptions import SoCoUPnPException try: func(*args, **kwargs) except SoCoUPnPException: _LOGGER.error('command "%s" for Sonos device "%s" not available in this mode', func.__name__, args[0].name) else: _LOGGER.debug('Ignore command "%s" for Sonos device "%s" (%s)', func.__name__, args[0].name, 'not coordinator') return wrapper
[ "def", "only_if_coordinator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "if", "args", "[", "0", "]", ".", "is_coordinator", ":", "from", "soco", ".", "exceptions", "import", "SoCoUPnPException", "try", ":",...
decorator for coordinator .
train
false
46,848
@register.filter def microsite_template_path(template_name): template_name = theming_helpers.get_template_path(template_name) return (template_name[1:] if (template_name[0] == '/') else template_name)
[ "@", "register", ".", "filter", "def", "microsite_template_path", "(", "template_name", ")", ":", "template_name", "=", "theming_helpers", ".", "get_template_path", "(", "template_name", ")", "return", "(", "template_name", "[", "1", ":", "]", "if", "(", "templa...
django template filter to apply template overriding to microsites .
train
false
46,852
def test_login_logout(client): rv = register_and_login(client, 'user1', 'default') assert ('You were logged in' in rv.data) rv = logout(client) assert ('You were logged out' in rv.data) rv = login(client, 'user1', 'wrongpassword') assert ('Invalid password' in rv.data) rv = login(client, 'user2', 'wrongpassword') assert ('Invalid username' in rv.data)
[ "def", "test_login_logout", "(", "client", ")", ":", "rv", "=", "register_and_login", "(", "client", ",", "'user1'", ",", "'default'", ")", "assert", "(", "'You were logged in'", "in", "rv", ".", "data", ")", "rv", "=", "logout", "(", "client", ")", "asser...
make sure logging in and logging out works .
train
false
46,853
def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files): options = params['options'] build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir) for filename in params['build_files_arg']] gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'], options.toplevel_dir) if (not gyp_binary.startswith(os.sep)): gyp_binary = os.path.join('.', gyp_binary) root_makefile.write(('quiet_cmd_regen_makefile = ACTION Regenerating $@\ncmd_regen_makefile = cd $(srcdir); %(cmd)s\n%(makefile_name)s: %(deps)s\n DCTB $(call do_cmd,regen_makefile)\n\n' % {'makefile_name': makefile_name, 'deps': ' '.join(map(Sourceify, build_files)), 'cmd': gyp.common.EncodePOSIXShellList((([gyp_binary, '-fmake'] + gyp.RegenerateFlags(options)) + build_files_args))}))
[ "def", "WriteAutoRegenerationRule", "(", "params", ",", "root_makefile", ",", "makefile_name", ",", "build_files", ")", ":", "options", "=", "params", "[", "'options'", "]", "build_files_args", "=", "[", "gyp", ".", "common", ".", "RelativePath", "(", "filename"...
write the target to regenerate the makefile .
train
false
46,854
@cleanup def test_log_scatter(): (fig, ax) = plt.subplots(1) x = np.arange(10) y = (np.arange(10) - 1) ax.scatter(x, y) buf = io.BytesIO() fig.savefig(buf, format='pdf') buf = io.BytesIO() fig.savefig(buf, format='eps') buf = io.BytesIO() fig.savefig(buf, format='svg')
[ "@", "cleanup", "def", "test_log_scatter", "(", ")", ":", "(", "fig", ",", "ax", ")", "=", "plt", ".", "subplots", "(", "1", ")", "x", "=", "np", ".", "arange", "(", "10", ")", "y", "=", "(", "np", ".", "arange", "(", "10", ")", "-", "1", "...
issue #1799 .
train
false
46,855
def get_unsupported_upper_protocol(): if (Version(CASSANDRA_VERSION) >= Version('2.2')): return None if (Version(CASSANDRA_VERSION) >= Version('2.1')): return 4 elif (Version(CASSANDRA_VERSION) >= Version('2.0')): return 3 else: return None
[ "def", "get_unsupported_upper_protocol", "(", ")", ":", "if", "(", "Version", "(", "CASSANDRA_VERSION", ")", ">=", "Version", "(", "'2.2'", ")", ")", ":", "return", "None", "if", "(", "Version", "(", "CASSANDRA_VERSION", ")", ">=", "Version", "(", "'2.1'", ...
this is used to determine the highest protocol version that is not supported by the version of c* running .
train
false
46,856
def get_include_dirs(): include_dirs = [os.path.join(d, 'include') for d in get_base_dirs()] if (sys.platform != 'win32'): include_dirs.extend(os.environ.get('CPLUS_INCLUDE_PATH', '').split(os.pathsep)) return include_dirs
[ "def", "get_include_dirs", "(", ")", ":", "include_dirs", "=", "[", "os", ".", "path", ".", "join", "(", "d", ",", "'include'", ")", "for", "d", "in", "get_base_dirs", "(", ")", "]", "if", "(", "sys", ".", "platform", "!=", "'win32'", ")", ":", "in...
returns a list of standard include directories on this platform .
train
false
46,857
def remove_extension(template): return template[:(- len('.template'))]
[ "def", "remove_extension", "(", "template", ")", ":", "return", "template", "[", ":", "(", "-", "len", "(", "'.template'", ")", ")", "]" ]
given a filename or path of a template file .
train
false
46,858
def Frechet(name, a, s=1, m=0): return rv(name, FrechetDistribution, (a, s, m))
[ "def", "Frechet", "(", "name", ",", "a", ",", "s", "=", "1", ",", "m", "=", "0", ")", ":", "return", "rv", "(", "name", ",", "FrechetDistribution", ",", "(", "a", ",", "s", ",", "m", ")", ")" ]
create a continuous random variable with a frechet distribution .
train
false
46,860
@register.filter(is_safe=True) @stringfilter def iriencode(value): return force_text(iri_to_uri(value))
[ "@", "register", ".", "filter", "(", "is_safe", "=", "True", ")", "@", "stringfilter", "def", "iriencode", "(", "value", ")", ":", "return", "force_text", "(", "iri_to_uri", "(", "value", ")", ")" ]
escapes an iri value for use in a url .
train
false
46,861
def BetaPrime(name, alpha, beta): return rv(name, BetaPrimeDistribution, (alpha, beta))
[ "def", "BetaPrime", "(", "name", ",", "alpha", ",", "beta", ")", ":", "return", "rv", "(", "name", ",", "BetaPrimeDistribution", ",", "(", "alpha", ",", "beta", ")", ")" ]
create a continuous random variable with a beta prime distribution .
train
false
46,862
def get_field_type(model, fieldname): field = getattr(model, fieldname) if isinstance(field, ColumnElement): return field.type if isinstance(field, AssociationProxy): field = field.remote_attr if hasattr(field, 'property'): prop = field.property if isinstance(prop, RelProperty): return None return prop.columns[0].type return None
[ "def", "get_field_type", "(", "model", ",", "fieldname", ")", ":", "field", "=", "getattr", "(", "model", ",", "fieldname", ")", "if", "isinstance", "(", "field", ",", "ColumnElement", ")", ":", "return", "field", ".", "type", "if", "isinstance", "(", "f...
given the database connection .
train
false
46,863
def get_user_model_path(): return getattr(settings, u'AUTH_USER_MODEL', u'auth.User')
[ "def", "get_user_model_path", "(", ")", ":", "return", "getattr", "(", "settings", ",", "u'AUTH_USER_MODEL'", ",", "u'auth.User'", ")" ]
returns app_label .
train
false
46,864
def test_qapp_name(qapp): assert (qapp.applicationName() == 'qute_test')
[ "def", "test_qapp_name", "(", "qapp", ")", ":", "assert", "(", "qapp", ".", "applicationName", "(", ")", "==", "'qute_test'", ")" ]
make sure the qapplication name is changed when we use qapp .
train
false
46,865
@register(u'unix-word-rubout') def unix_word_rubout(event, WORD=True): buff = event.current_buffer pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD) if (pos is None): pos = (- buff.cursor_position) if pos: deleted = buff.delete_before_cursor(count=(- pos)) if event.is_repeat: deleted += event.cli.clipboard.get_data().text event.cli.clipboard.set_text(deleted) else: event.cli.output.bell()
[ "@", "register", "(", "u'unix-word-rubout'", ")", "def", "unix_word_rubout", "(", "event", ",", "WORD", "=", "True", ")", ":", "buff", "=", "event", ".", "current_buffer", "pos", "=", "buff", ".", "document", ".", "find_start_of_previous_word", "(", "count", ...
kill the word behind point .
train
true
46,867
def visit_snippet_literal(self, node): self.visit_literal_block(node)
[ "def", "visit_snippet_literal", "(", "self", ",", "node", ")", ":", "self", ".", "visit_literal_block", "(", "node", ")" ]
default literal block handler .
train
false
46,868
def list_entries(logger_name): logging_client = logging.Client() logger = logging_client.logger(logger_name) print 'Listing entries for logger {}:'.format(logger.name) for entry in logger.list_entries(): timestamp = entry.timestamp.isoformat() print '* {}: {}'.format(timestamp, entry.payload)
[ "def", "list_entries", "(", "logger_name", ")", ":", "logging_client", "=", "logging", ".", "Client", "(", ")", "logger", "=", "logging_client", ".", "logger", "(", "logger_name", ")", "print", "'Listing entries for logger {}:'", ".", "format", "(", "logger", "....
lists the most recent entries for a given logger .
train
false
46,869
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) @utils.arg('action', metavar='<action>', choices=['set', 'delete'], help=_("Actions: 'set' or 'delete'.")) @utils.arg('metadata', metavar='<key=value>', nargs='+', action='append', default=[], help=_('Metadata to set or delete (only key is necessary on delete).')) def do_meta(cs, args): server = _find_server(cs, args.server) metadata = _extract_metadata(args) if (args.action == 'set'): cs.servers.set_meta(server, metadata) elif (args.action == 'delete'): cs.servers.delete_meta(server, sorted(metadata.keys(), reverse=True))
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "@", "utils", ".", "arg", "(", "'action'", ",", "metavar", "=", "'<action>'", ",", "choices", "=", "[", "'set...
set or delete metadata on a server .
train
false
46,870
def Clf(): global LOC LOC = None _Brewer.ClearIter() pyplot.clf() fig = pyplot.gcf() fig.set_size_inches(8, 6)
[ "def", "Clf", "(", ")", ":", "global", "LOC", "LOC", "=", "None", "_Brewer", ".", "ClearIter", "(", ")", "pyplot", ".", "clf", "(", ")", "fig", "=", "pyplot", ".", "gcf", "(", ")", "fig", ".", "set_size_inches", "(", "8", ",", "6", ")" ]
clears the figure and any hints that have been set .
train
false
46,871
def check_url(url): good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY] return (_get_server_status_code(url) in good_codes)
[ "def", "check_url", "(", "url", ")", ":", "good_codes", "=", "[", "httplib", ".", "OK", ",", "httplib", ".", "FOUND", ",", "httplib", ".", "MOVED_PERMANENTLY", "]", "return", "(", "_get_server_status_code", "(", "url", ")", "in", "good_codes", ")" ]
check if a url exists without downloading the whole file .
train
false
46,873
def salt_master(): import salt.cli.daemons master = salt.cli.daemons.Master() master.start()
[ "def", "salt_master", "(", ")", ":", "import", "salt", ".", "cli", ".", "daemons", "master", "=", "salt", ".", "cli", ".", "daemons", ".", "Master", "(", ")", "master", ".", "start", "(", ")" ]
start the salt master .
train
false
46,874
def get_alias(ip): hosts = _list_hosts() if (ip in hosts): return hosts[ip] return []
[ "def", "get_alias", "(", "ip", ")", ":", "hosts", "=", "_list_hosts", "(", ")", "if", "(", "ip", "in", "hosts", ")", ":", "return", "hosts", "[", "ip", "]", "return", "[", "]" ]
return the list of aliases associated with an ip aliases are returned in the order in which they appear in the hosts file .
train
false
46,876
def signal_handler(signal, frame): logging.warning('Caught signal: {0}'.format(signal)) IOLoop.instance().add_callback(shutdown)
[ "def", "signal_handler", "(", "signal", ",", "frame", ")", ":", "logging", ".", "warning", "(", "'Caught signal: {0}'", ".", "format", "(", "signal", ")", ")", "IOLoop", ".", "instance", "(", ")", ".", "add_callback", "(", "shutdown", ")" ]
signal handler for graceful shutdown .
train
false
46,877
def send_saml_audit_notification(action, request, user_id, group_ids, identity_provider, protocol, token_id, outcome): initiator = request.audit_initiator target = resource.Resource(typeURI=taxonomy.ACCOUNT_USER) audit_type = SAML_AUDIT_TYPE user_id = (user_id or taxonomy.UNKNOWN) token_id = (token_id or taxonomy.UNKNOWN) group_ids = (group_ids or []) cred = credential.FederatedCredential(token=token_id, type=audit_type, identity_provider=identity_provider, user=user_id, groups=group_ids) initiator.credential = cred event_type = ('%s.%s' % (SERVICE, action)) _send_audit_notification(action, initiator, outcome, target, event_type)
[ "def", "send_saml_audit_notification", "(", "action", ",", "request", ",", "user_id", ",", "group_ids", ",", "identity_provider", ",", "protocol", ",", "token_id", ",", "outcome", ")", ":", "initiator", "=", "request", ".", "audit_initiator", "target", "=", "res...
send notification to inform observers about saml events .
train
false
46,878
def import_submodules(module): submodules = {} for (loader, name, ispkg) in pkgutil.iter_modules(module.__path__, (module.__name__ + '.')): try: submodule = import_module(name) except ImportError as e: logging.warning(('Error importing %s' % name)) logging.exception(e) else: (parent, child) = name.rsplit('.', 1) submodules[child] = submodule return submodules
[ "def", "import_submodules", "(", "module", ")", ":", "submodules", "=", "{", "}", "for", "(", "loader", ",", "name", ",", "ispkg", ")", "in", "pkgutil", ".", "iter_modules", "(", "module", ".", "__path__", ",", "(", "module", ".", "__name__", "+", "'.'...
import all submodules and make them available in a dict .
train
true
46,880
def test_step_clipping_no_threshold_regression(): rule1 = StepClipping() assert (rule1.threshold is None) gradients = {0: shared_floatx(3.0), 1: shared_floatx(4.0)} (clipped1, updates) = rule1.compute_steps(gradients) assert (len(updates) == 0) assert (clipped1 == gradients)
[ "def", "test_step_clipping_no_threshold_regression", "(", ")", ":", "rule1", "=", "StepClipping", "(", ")", "assert", "(", "rule1", ".", "threshold", "is", "None", ")", "gradients", "=", "{", "0", ":", "shared_floatx", "(", "3.0", ")", ",", "1", ":", "shar...
test regression for #1145 .
train
false
46,881
def distribute(A, B): def distribute_rl(expr): for (i, arg) in enumerate(expr.args): if isinstance(arg, B): (first, b, tail) = (expr.args[:i], expr.args[i], expr.args[(i + 1):]) return B(*[A(*((first + (arg,)) + tail)) for arg in b.args]) return expr return distribute_rl
[ "def", "distribute", "(", "A", ",", "B", ")", ":", "def", "distribute_rl", "(", "expr", ")", ":", "for", "(", "i", ",", "arg", ")", "in", "enumerate", "(", "expr", ".", "args", ")", ":", "if", "isinstance", "(", "arg", ",", "B", ")", ":", "(", ...
turns an a containing bs into a b of as where a .
train
false
46,884
def _normalize_image_location_for_db(image_data): if (('locations' not in image_data) and ('location_data' not in image_data)): image_data['locations'] = None return image_data locations = image_data.pop('locations', []) location_data = image_data.pop('location_data', []) location_data_dict = {} for l in locations: location_data_dict[l] = {} for l in location_data: location_data_dict[l['url']] = {'metadata': l['metadata'], 'status': l['status'], 'id': (l['id'] if ('id' in l) else None)} ordered_keys = locations[:] for ld in location_data: if (ld['url'] not in ordered_keys): ordered_keys.append(ld['url']) location_data = [] for loc in ordered_keys: data = location_data_dict[loc] if data: location_data.append({'url': loc, 'metadata': data['metadata'], 'status': data['status'], 'id': data['id']}) else: location_data.append({'url': loc, 'metadata': {}, 'status': 'active', 'id': None}) image_data['locations'] = location_data return image_data
[ "def", "_normalize_image_location_for_db", "(", "image_data", ")", ":", "if", "(", "(", "'locations'", "not", "in", "image_data", ")", "and", "(", "'location_data'", "not", "in", "image_data", ")", ")", ":", "image_data", "[", "'locations'", "]", "=", "None", ...
this function takes the legacy locations field and the newly added location_data field from the image_data values dictionary which flows over the wire between the registry and api servers and converts it into the location_data format only which is then consumable by the image object .
train
false
46,885
def getEvaluatedString(key, xmlElement=None): if (xmlElement == None): return None if (key in xmlElement.attributeDictionary): return str(getEvaluatedValueObliviously(key, xmlElement)) return None
[ "def", "getEvaluatedString", "(", "key", ",", "xmlElement", "=", "None", ")", ":", "if", "(", "xmlElement", "==", "None", ")", ":", "return", "None", "if", "(", "key", "in", "xmlElement", ".", "attributeDictionary", ")", ":", "return", "str", "(", "getEv...
get the evaluated value as a string .
train
false
46,886
def stubout_session(stubs, cls, product_version=(5, 6, 2), product_brand='XenServer', platform_version=(1, 9, 0), **opt_args): stubs.Set(session.XenAPISession, '_create_session', (lambda s, url: cls(url, **opt_args))) stubs.Set(session.XenAPISession, '_get_product_version_and_brand', (lambda s: (product_version, product_brand))) stubs.Set(session.XenAPISession, '_get_platform_version', (lambda s: platform_version))
[ "def", "stubout_session", "(", "stubs", ",", "cls", ",", "product_version", "=", "(", "5", ",", "6", ",", "2", ")", ",", "product_brand", "=", "'XenServer'", ",", "platform_version", "=", "(", "1", ",", "9", ",", "0", ")", ",", "**", "opt_args", ")",...
stubs out methods from xenapisession .
train
false
46,887
def json_error_handler(request): errors = request.errors sorted_errors = sorted(errors, key=(lambda x: six.text_type(x['name']))) error = sorted_errors[0] name = error['name'] description = error['description'] if isinstance(description, six.binary_type): description = error['description'].decode('utf-8') if (name is not None): if (name in description): message = description else: message = ('%(name)s in %(location)s: %(description)s' % error) else: message = ('%(location)s: %(description)s' % error) response = http_error(httpexceptions.HTTPBadRequest(), code=errors.status, errno=ERRORS.INVALID_PARAMETERS.value, error='Invalid parameters', message=message, details=errors) response.status = errors.status response = reapply_cors(request, response) return response
[ "def", "json_error_handler", "(", "request", ")", ":", "errors", "=", "request", ".", "errors", "sorted_errors", "=", "sorted", "(", "errors", ",", "key", "=", "(", "lambda", "x", ":", "six", ".", "text_type", "(", "x", "[", "'name'", "]", ")", ")", ...
cornice json error handler .
train
false
46,888
def remove_dark_lang_config(apps, schema_editor): raise RuntimeError(u'Cannot reverse this migration.')
[ "def", "remove_dark_lang_config", "(", "apps", ",", "schema_editor", ")", ":", "raise", "RuntimeError", "(", "u'Cannot reverse this migration.'", ")" ]
write your backwards methods here .
train
false
46,889
def clone_bs4_elem(el): if isinstance(el, NavigableString): return type(el)(el) copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix) copy.attrs = dict(el.attrs) for attr in ('can_be_empty_element', 'hidden'): setattr(copy, attr, getattr(el, attr)) for child in el.contents: copy.append(clone_bs4_elem(child)) return copy
[ "def", "clone_bs4_elem", "(", "el", ")", ":", "if", "isinstance", "(", "el", ",", "NavigableString", ")", ":", "return", "type", "(", "el", ")", "(", "el", ")", "copy", "=", "Tag", "(", "None", ",", "el", ".", "builder", ",", "el", ".", "name", "...
clone a bs4 tag before modifying it .
train
true
46,892
def _optimize_clone(optimizer, clone, num_clones, regularization_losses, **kwargs): sum_loss = _gather_clone_loss(clone, num_clones, regularization_losses) clone_grad = None if (sum_loss is not None): with tf.device(clone.device): clone_grad = optimizer.compute_gradients(sum_loss, **kwargs) return (sum_loss, clone_grad)
[ "def", "_optimize_clone", "(", "optimizer", ",", "clone", ",", "num_clones", ",", "regularization_losses", ",", "**", "kwargs", ")", ":", "sum_loss", "=", "_gather_clone_loss", "(", "clone", ",", "num_clones", ",", "regularization_losses", ")", "clone_grad", "=", ...
compute losses and gradients for a single clone .
train
false
46,893
def format_str_for_message(msg_str): lines = msg_str.splitlines() num_lines = len(lines) sr = '\n'.join(lines) if (num_lines == 0): return '' elif (num_lines == 1): return (' ' + sr) else: return ('\n' + sr)
[ "def", "format_str_for_message", "(", "msg_str", ")", ":", "lines", "=", "msg_str", ".", "splitlines", "(", ")", "num_lines", "=", "len", "(", "lines", ")", "sr", "=", "'\\n'", ".", "join", "(", "lines", ")", "if", "(", "num_lines", "==", "0", ")", "...
format msg_str so that it can be appended to a message .
train
false
46,894
def ensure_cached(task_cls, expected_num_artifacts=None): def decorator(test_fn): def wrapper(self, *args, **kwargs): with temporary_dir() as artifact_cache: self.set_options_for_scope(u'cache.{}'.format(self.options_scope), write_to=[artifact_cache]) task_cache = os.path.join(artifact_cache, task_cls.stable_name()) os.mkdir(task_cache) test_fn(self, *args, **kwargs) num_artifacts = 0 for (_, _, files) in os.walk(task_cache): num_artifacts += len(files) if (expected_num_artifacts is None): self.assertNotEqual(num_artifacts, 0) else: self.assertEqual(num_artifacts, expected_num_artifacts) return wrapper return decorator
[ "def", "ensure_cached", "(", "task_cls", ",", "expected_num_artifacts", "=", "None", ")", ":", "def", "decorator", "(", "test_fn", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "with", "temporary_dir", "(", ")"...
decorator for a task-executing unit test .
train
false
46,895
def npy_cdouble_from_double_complex(var): res = '_complexstuff.npy_cdouble_from_double_complex({})'.format(var) return res
[ "def", "npy_cdouble_from_double_complex", "(", "var", ")", ":", "res", "=", "'_complexstuff.npy_cdouble_from_double_complex({})'", ".", "format", "(", "var", ")", "return", "res" ]
cast a cython double complex to a numpy cdouble .
train
false
46,896
def deactivateAaPdpContextRequest(): a = TpPd(pd=8) b = MessageType(mesType=83) c = AaDeactivationCauseAndSpareHalfOctets() packet = ((a / b) / c) return packet
[ "def", "deactivateAaPdpContextRequest", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "8", ")", "b", "=", "MessageType", "(", "mesType", "=", "83", ")", "c", "=", "AaDeactivationCauseAndSpareHalfOctets", "(", ")", "packet", "=", "(", "(", "a", "/", ...
deactivate aa pdp context request section 9 .
train
true
46,897
def get_view_plugin(view_type): for plugin in p.PluginImplementations(p.IResourceView): info = plugin.info() name = info.get('name') if (name == view_type): return plugin
[ "def", "get_view_plugin", "(", "view_type", ")", ":", "for", "plugin", "in", "p", ".", "PluginImplementations", "(", "p", ".", "IResourceView", ")", ":", "info", "=", "plugin", ".", "info", "(", ")", "name", "=", "info", ".", "get", "(", "'name'", ")",...
returns the iresourceview plugin associated with the given view_type .
train
false
46,898
def convolution_2d(x, W, b=None, stride=1, pad=0, use_cudnn=True, cover_all=False, deterministic=False): func = Convolution2DFunction(stride, pad, use_cudnn, cover_all, deterministic) if (b is None): return func(x, W) else: return func(x, W, b)
[ "def", "convolution_2d", "(", "x", ",", "W", ",", "b", "=", "None", ",", "stride", "=", "1", ",", "pad", "=", "0", ",", "use_cudnn", "=", "True", ",", "cover_all", "=", "False", ",", "deterministic", "=", "False", ")", ":", "func", "=", "Convolutio...
two-dimensional convolution function .
train
false
46,900
def proportion_effectsize(prop1, prop2, method='normal'): if (method != 'normal'): raise ValueError('only "normal" is implemented') es = (2 * (np.arcsin(np.sqrt(prop1)) - np.arcsin(np.sqrt(prop2)))) return es
[ "def", "proportion_effectsize", "(", "prop1", ",", "prop2", ",", "method", "=", "'normal'", ")", ":", "if", "(", "method", "!=", "'normal'", ")", ":", "raise", "ValueError", "(", "'only \"normal\" is implemented'", ")", "es", "=", "(", "2", "*", "(", "np",...
effect size for a test comparing two proportions for use in power function parameters prop1 .
train
false
46,901
@pytest.fixture() def p(tmpdir, *args): return partial(os.path.join, tmpdir)
[ "@", "pytest", ".", "fixture", "(", ")", "def", "p", "(", "tmpdir", ",", "*", "args", ")", ":", "return", "partial", "(", "os", ".", "path", ".", "join", ",", "tmpdir", ")" ]
creates an ui property inside an :class:uielement:: @p @p @p class sectionplugin : typeid = main:section .
train
false
46,903
def last_bytes(file_like_object, num): try: file_like_object.seek((- num), os.SEEK_END) except IOError as e: if (e.errno == 22): file_like_object.seek(0, os.SEEK_SET) else: raise remaining = file_like_object.tell() return (file_like_object.read(), remaining)
[ "def", "last_bytes", "(", "file_like_object", ",", "num", ")", ":", "try", ":", "file_like_object", ".", "seek", "(", "(", "-", "num", ")", ",", "os", ".", "SEEK_END", ")", "except", "IOError", "as", "e", ":", "if", "(", "e", ".", "errno", "==", "2...
return num bytes from the end of the file .
train
true
46,904
def increment_ip_cidr(ip_cidr, offset=1): net0 = netaddr.IPNetwork(ip_cidr) net = netaddr.IPNetwork(ip_cidr) net.value += offset if (not (net0.network < net.ip < net0[(-1)])): tools.fail(('Incorrect ip_cidr,offset tuple (%s,%s): "incremented" ip_cidr is outside ip_cidr' % (ip_cidr, offset))) return str(net)
[ "def", "increment_ip_cidr", "(", "ip_cidr", ",", "offset", "=", "1", ")", ":", "net0", "=", "netaddr", ".", "IPNetwork", "(", "ip_cidr", ")", "net", "=", "netaddr", ".", "IPNetwork", "(", "ip_cidr", ")", "net", ".", "value", "+=", "offset", "if", "(", ...
increment ip_cidr offset times .
train
false
46,905
def get_valid_breeds(): if ('breeds' in SIGNATURE_CACHE): return SIGNATURE_CACHE['breeds'].keys() else: return []
[ "def", "get_valid_breeds", "(", ")", ":", "if", "(", "'breeds'", "in", "SIGNATURE_CACHE", ")", ":", "return", "SIGNATURE_CACHE", "[", "'breeds'", "]", ".", "keys", "(", ")", "else", ":", "return", "[", "]" ]
return a list of valid breeds found in the import signatures .
train
false
46,907
def _read_temp_ifaces(iface, data): try: template = JINJA.get_template('debian_eth.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template debian_eth.jinja') return '' ifcfg = template.render({'name': iface, 'data': data}) return [(item + '\n') for item in ifcfg.split('\n')]
[ "def", "_read_temp_ifaces", "(", "iface", ",", "data", ")", ":", "try", ":", "template", "=", "JINJA", ".", "get_template", "(", "'debian_eth.jinja'", ")", "except", "jinja2", ".", "exceptions", ".", "TemplateNotFound", ":", "log", ".", "error", "(", "'Could...
return what would be written to disk for interfaces .
train
true
46,908
def _upgrade_other(t_images, t_image_members, t_image_properties, dialect): foreign_keys = _get_foreign_keys(t_images, t_image_members, t_image_properties, dialect) for fk in foreign_keys: fk.drop() t_images.c.id.alter(sqlalchemy.String(36), primary_key=True) t_image_members.c.image_id.alter(sqlalchemy.String(36)) t_image_properties.c.image_id.alter(sqlalchemy.String(36)) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) for fk in foreign_keys: fk.create()
[ "def", "_upgrade_other", "(", "t_images", ",", "t_image_members", ",", "t_image_properties", ",", "dialect", ")", ":", "foreign_keys", "=", "_get_foreign_keys", "(", "t_images", ",", "t_image_members", ",", "t_image_properties", ",", "dialect", ")", "for", "fk", "...
upgrade 011 -> 012 with logic for non-sqlite databases .
train
false
46,910
def get_bootstrap_modules(): mod_struct = __import__('struct') loader_mods = [] loaderpath = os.path.join(HOMEPATH, 'PyInstaller', 'loader') for mod_name in ['_struct', 'zlib']: mod = __import__(mod_name) if hasattr(mod, '__file__'): loader_mods.append((mod_name, os.path.abspath(mod.__file__), 'EXTENSION')) loader_mods += [('struct', os.path.abspath(mod_struct.__file__), 'PYMODULE'), ('pyimod01_os_path', os.path.join(loaderpath, 'pyimod01_os_path.pyc'), 'PYMODULE'), ('pyimod02_archive', os.path.join(loaderpath, 'pyimod02_archive.pyc'), 'PYMODULE'), ('pyimod03_importers', os.path.join(loaderpath, 'pyimod03_importers.pyc'), 'PYMODULE'), ('pyiboot01_bootstrap', os.path.join(loaderpath, 'pyiboot01_bootstrap.py'), 'PYSOURCE')] toc = TOC(loader_mods) return toc
[ "def", "get_bootstrap_modules", "(", ")", ":", "mod_struct", "=", "__import__", "(", "'struct'", ")", "loader_mods", "=", "[", "]", "loaderpath", "=", "os", ".", "path", ".", "join", "(", "HOMEPATH", ",", "'PyInstaller'", ",", "'loader'", ")", "for", "mod_...
get toc with the bootstrapping modules and their dependencies .
train
false
46,911
def push_connection(redis): _connection_stack.push(patch_connection(redis))
[ "def", "push_connection", "(", "redis", ")", ":", "_connection_stack", ".", "push", "(", "patch_connection", "(", "redis", ")", ")" ]
pushes the given connection on the stack .
train
false
46,912
def org_site_top_req_priority(row, tablename='org_facility'): if (not current.deployment_settings.has_module('req')): return None try: from req import REQ_STATUS_COMPLETE except ImportError: return None if hasattr(row, tablename): row = row[tablename] try: id = row.id except AttributeError: return None s3db = current.s3db rtable = s3db.req_req stable = s3db[tablename] query = (((((rtable.deleted != True) & (stable.id == id)) & (rtable.site_id == stable.site_id)) & (rtable.fulfil_status != REQ_STATUS_COMPLETE)) & (rtable.is_template == False)) req = current.db(query).select(rtable.id, rtable.priority, orderby=(~ rtable.priority), limitby=(0, 1)).first() if req: return req.priority else: return None
[ "def", "org_site_top_req_priority", "(", "row", ",", "tablename", "=", "'org_facility'", ")", ":", "if", "(", "not", "current", ".", "deployment_settings", ".", "has_module", "(", "'req'", ")", ")", ":", "return", "None", "try", ":", "from", "req", "import",...
highest priority of open requests for a site .
train
false
46,915
def usageExit(msg=None): if msg: print msg print USAGE sys.exit(2)
[ "def", "usageExit", "(", "msg", "=", "None", ")", ":", "if", "msg", ":", "print", "msg", "print", "USAGE", "sys", ".", "exit", "(", "2", ")" ]
print usage and exit .
train
false
46,916
def compile_single(source, options, full_module_name=None): return run_pipeline(source, options, full_module_name)
[ "def", "compile_single", "(", "source", ",", "options", ",", "full_module_name", "=", "None", ")", ":", "return", "run_pipeline", "(", "source", ",", "options", ",", "full_module_name", ")" ]
compile_single compile the given pyrex implementation file and return a compilationresult .
train
false
46,917
def formatFileSize(size): if (size < 1024): return ('%iB' % size) elif (size < (1024 ** 2)): return ('%iK' % (size / 1024)) elif (size < (1024 ** 3)): return ('%iM' % (size / (1024 ** 2))) else: return ('%iG' % (size / (1024 ** 3)))
[ "def", "formatFileSize", "(", "size", ")", ":", "if", "(", "size", "<", "1024", ")", ":", "return", "(", "'%iB'", "%", "size", ")", "elif", "(", "size", "<", "(", "1024", "**", "2", ")", ")", ":", "return", "(", "'%iK'", "%", "(", "size", "/", ...
format the given file size in bytes to human readable format .
train
false
46,918
def nowtime(): return now_datetime().strftime(TIME_FORMAT)
[ "def", "nowtime", "(", ")", ":", "return", "now_datetime", "(", ")", ".", "strftime", "(", "TIME_FORMAT", ")" ]
return current time in hh:mm .
train
false
46,919
def run_git(args, git_path=_DEFAULT_GIT, input=None, capture_stdout=False, **popen_kwargs): env = popen_kwargs.pop('env', {}) env['LC_ALL'] = env['LANG'] = 'C' args = ([git_path] + args) popen_kwargs['stdin'] = subprocess.PIPE if capture_stdout: popen_kwargs['stdout'] = subprocess.PIPE else: popen_kwargs.pop('stdout', None) p = subprocess.Popen(args, env=env, **popen_kwargs) (stdout, stderr) = p.communicate(input=input) return (p.returncode, stdout)
[ "def", "run_git", "(", "args", ",", "git_path", "=", "_DEFAULT_GIT", ",", "input", "=", "None", ",", "capture_stdout", "=", "False", ",", "**", "popen_kwargs", ")", ":", "env", "=", "popen_kwargs", ".", "pop", "(", "'env'", ",", "{", "}", ")", "env", ...
run a git command .
train
false
46,920
def test_add_contacts_case_insensitive(contacts_provider, contact_sync, db, default_namespace): num_original_contacts = db.session.query(Contact).filter_by(namespace_id=default_namespace.id).count() contacts_provider._next_uid = 'foo' contacts_provider._get_next_uid = (lambda current: 'FOO') contacts_provider.supply_contact('Contact One', 'contact.one@email.address') contacts_provider.supply_contact('Contact Two', 'contact.two@email.address') contact_sync.provider = contacts_provider contact_sync.sync() num_current_contacts = db.session.query(Contact).filter_by(namespace_id=default_namespace.id).count() assert ((num_current_contacts - num_original_contacts) == 2)
[ "def", "test_add_contacts_case_insensitive", "(", "contacts_provider", ",", "contact_sync", ",", "db", ",", "default_namespace", ")", ":", "num_original_contacts", "=", "db", ".", "session", ".", "query", "(", "Contact", ")", ".", "filter_by", "(", "namespace_id", ...
tests that syncing two contacts with uids that differ only in case sensitivity doesnt cause an error .
train
false
46,921
def is_rich_text_default_for_user(user): if user.is_authenticated(): try: return user.get_profile().should_use_rich_text except ObjectDoesNotExist: pass siteconfig = SiteConfiguration.objects.get_current() return siteconfig.get(u'default_use_rich_text')
[ "def", "is_rich_text_default_for_user", "(", "user", ")", ":", "if", "user", ".", "is_authenticated", "(", ")", ":", "try", ":", "return", "user", ".", "get_profile", "(", ")", ".", "should_use_rich_text", "except", "ObjectDoesNotExist", ":", "pass", "siteconfig...
returns whether the user edits in markdown by default .
train
false
46,922
def create_terminal_writer(config, *args, **kwargs): tw = py.io.TerminalWriter(*args, **kwargs) if (config.option.color == 'yes'): tw.hasmarkup = True if (config.option.color == 'no'): tw.hasmarkup = False return tw
[ "def", "create_terminal_writer", "(", "config", ",", "*", "args", ",", "**", "kwargs", ")", ":", "tw", "=", "py", ".", "io", ".", "TerminalWriter", "(", "*", "args", ",", "**", "kwargs", ")", "if", "(", "config", ".", "option", ".", "color", "==", ...
create a terminalwriter instance configured according to the options in the config object .
train
false
46,923
def parallel_bulk(client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=((100 * 1024) * 1024), expand_action_callback=expand_action, **kwargs): from multiprocessing.dummy import Pool actions = map(expand_action_callback, actions) pool = Pool(thread_count) try: for result in pool.imap((lambda chunk: list(_process_bulk_chunk(client, chunk, **kwargs))), _chunk_actions(actions, chunk_size, max_chunk_bytes, client.transport.serializer)): for item in result: (yield item) finally: pool.close() pool.join()
[ "def", "parallel_bulk", "(", "client", ",", "actions", ",", "thread_count", "=", "4", ",", "chunk_size", "=", "500", ",", "max_chunk_bytes", "=", "(", "(", "100", "*", "1024", ")", "*", "1024", ")", ",", "expand_action_callback", "=", "expand_action", ",",...
parallel version of the bulk helper run in multiple threads at once .
train
true
46,924
def get_domains(name): name = name.split('.') return ('.'.join(name[i:]) for i in xrange(len(name)))
[ "def", "get_domains", "(", "name", ")", ":", "name", "=", "name", ".", "split", "(", "'.'", ")", "return", "(", "'.'", ".", "join", "(", "name", "[", "i", ":", "]", ")", "for", "i", "in", "xrange", "(", "len", "(", "name", ")", ")", ")" ]
generates the upper domains from a domain name .
train
false
46,925
@register.simple_tag def project_name(prj): return escape(force_text(Project.objects.get(slug=prj)))
[ "@", "register", ".", "simple_tag", "def", "project_name", "(", "prj", ")", ":", "return", "escape", "(", "force_text", "(", "Project", ".", "objects", ".", "get", "(", "slug", "=", "prj", ")", ")", ")" ]
gets project name based on slug .
train
false
46,926
def parse_message(message): events = [] if (message['action'] in ['create', 'delete']): events.append(parse_create_or_delete(message)) elif (message['action'] == 'change'): if message['change']['diff']: for value in message['change']['diff']: parsed_event = parse_change_event(value, message) if parsed_event: events.append(parsed_event) if message['change']['comment']: events.append(parse_comment(message)) return events
[ "def", "parse_message", "(", "message", ")", ":", "events", "=", "[", "]", "if", "(", "message", "[", "'action'", "]", "in", "[", "'create'", ",", "'delete'", "]", ")", ":", "events", ".", "append", "(", "parse_create_or_delete", "(", "message", ")", "...
parses the payload by delegating to specialized functions .
train
false
46,930
def gc_histogram(): result = {} for o in gc.get_objects(): t = type(o) count = result.get(t, 0) result[t] = (count + 1) return result
[ "def", "gc_histogram", "(", ")", ":", "result", "=", "{", "}", "for", "o", "in", "gc", ".", "get_objects", "(", ")", ":", "t", "=", "type", "(", "o", ")", "count", "=", "result", ".", "get", "(", "t", ",", "0", ")", "result", "[", "t", "]", ...
returns per-class counts of existing objects .
train
false
46,932
def security_hash(request, form, *args): import warnings warnings.warn('security_hash is deprecated; use form_hmac instead', PendingDeprecationWarning) data = [] for bf in form: if (form.empty_permitted and (not form.has_changed())): value = (bf.data or '') else: value = (bf.field.clean(bf.data) or '') if isinstance(value, basestring): value = value.strip() data.append((bf.name, value)) data.extend(args) data.append(settings.SECRET_KEY) pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL) return md5_constructor(pickled).hexdigest()
[ "def", "security_hash", "(", "request", ",", "form", ",", "*", "args", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "'security_hash is deprecated; use form_hmac instead'", ",", "PendingDeprecationWarning", ")", "data", "=", "[", "]", "for", "bf", ...
calculates a security hash for the given form instance .
train
false
46,933
def _createTPs(numCols, cellsPerColumn=4, checkSynapseConsistency=True): minThreshold = 4 activationThreshold = 4 newSynapseCount = 5 initialPerm = 0.6 connectedPerm = 0.5 permanenceInc = 0.1 permanenceDec = 0.001 globalDecay = 0.0 if (VERBOSITY > 1): print 'Creating TP10X instance' cppTp = TP10X2(numberOfCols=numCols, cellsPerColumn=cellsPerColumn, initialPerm=initialPerm, connectedPerm=connectedPerm, minThreshold=minThreshold, newSynapseCount=newSynapseCount, permanenceInc=permanenceInc, permanenceDec=permanenceDec, activationThreshold=activationThreshold, globalDecay=globalDecay, burnIn=1, seed=SEED, verbosity=VERBOSITY, checkSynapseConsistency=checkSynapseConsistency, pamLength=1000) if (VERBOSITY > 1): print 'Creating PY TP instance' pyTp = TP(numberOfCols=numCols, cellsPerColumn=cellsPerColumn, initialPerm=initialPerm, connectedPerm=connectedPerm, minThreshold=minThreshold, newSynapseCount=newSynapseCount, permanenceInc=permanenceInc, permanenceDec=permanenceDec, activationThreshold=activationThreshold, globalDecay=globalDecay, burnIn=1, seed=SEED, verbosity=VERBOSITY, pamLength=1000) return (cppTp, pyTp)
[ "def", "_createTPs", "(", "numCols", ",", "cellsPerColumn", "=", "4", ",", "checkSynapseConsistency", "=", "True", ")", ":", "minThreshold", "=", "4", "activationThreshold", "=", "4", "newSynapseCount", "=", "5", "initialPerm", "=", "0.6", "connectedPerm", "=", ...
create tp and tp10x instances with identical parameters .
train
false
46,934
def parse_date_or_fatal(str, fatal): try: date = float(str) except ValueError as e: raise fatal(('invalid date format (should be a float): %r' % e)) else: return date
[ "def", "parse_date_or_fatal", "(", "str", ",", "fatal", ")", ":", "try", ":", "date", "=", "float", "(", "str", ")", "except", "ValueError", "as", "e", ":", "raise", "fatal", "(", "(", "'invalid date format (should be a float): %r'", "%", "e", ")", ")", "e...
parses the given date or calls option .
train
false