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 |
|---|---|---|---|---|---|
34,570 | def get_installed_repository_info(elem, last_galaxy_test_file_dir, last_tested_repository_name, last_tested_changeset_revision, tool_path):
tool_config_path = elem.get('file')
installed_tool_path_items = tool_config_path.split('/repos/')
sans_shed = installed_tool_path_items[1]
path_items = sans_shed.split('/')
repository_owner = path_items[0]
repository_name = path_items[1]
changeset_revision = path_items[2]
if ((repository_name != last_tested_repository_name) or (changeset_revision != last_tested_changeset_revision)):
installed_tool_path = os.path.join(installed_tool_path_items[0], 'repos', repository_owner, repository_name, changeset_revision)
for (root, dirs, files) in os.walk(os.path.join(tool_path, installed_tool_path)):
if ('.' in dirs):
dirs.remove('.hg')
if ('test-data' in dirs):
return (os.path.join(root, 'test-data'), repository_name, changeset_revision)
return (None, repository_name, changeset_revision)
return (last_galaxy_test_file_dir, last_tested_repository_name, last_tested_changeset_revision)
| [
"def",
"get_installed_repository_info",
"(",
"elem",
",",
"last_galaxy_test_file_dir",
",",
"last_tested_repository_name",
",",
"last_tested_changeset_revision",
",",
"tool_path",
")",
":",
"tool_config_path",
"=",
"elem",
".",
"get",
"(",
"'file'",
")",
"installed_tool_p... | return the galaxy_test_file_dir . | train | false |
34,571 | def _get_current_tags(name, runas=None):
try:
return list(__salt__['rabbitmq.list_users'](runas=runas)[name])
except CommandExecutionError as err:
log.error('Error: {0}'.format(err))
return []
| [
"def",
"_get_current_tags",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"try",
":",
"return",
"list",
"(",
"__salt__",
"[",
"'rabbitmq.list_users'",
"]",
"(",
"runas",
"=",
"runas",
")",
"[",
"name",
"]",
")",
"except",
"CommandExecutionError",
"as",... | whether rabbitmq users tags need to be changed . | train | true |
34,572 | def deviceCount(devType=None):
if (os.name == 'nt'):
if (devType is None):
numdev = len(listAll(3))
numdev += len(listAll(9))
numdev += len(listAll(6))
if (skymoteLib is not None):
numdev += len(listAll(1281))
return numdev
else:
return len(listAll(devType))
elif (devType == None):
numdev = staticLib.LJUSB_GetDevCount(3)
numdev += staticLib.LJUSB_GetDevCount(9)
numdev += staticLib.LJUSB_GetDevCount(6)
numdev += staticLib.LJUSB_GetDevCount(1281)
return numdev
else:
return staticLib.LJUSB_GetDevCount(devType)
| [
"def",
"deviceCount",
"(",
"devType",
"=",
"None",
")",
":",
"if",
"(",
"os",
".",
"name",
"==",
"'nt'",
")",
":",
"if",
"(",
"devType",
"is",
"None",
")",
":",
"numdev",
"=",
"len",
"(",
"listAll",
"(",
"3",
")",
")",
"numdev",
"+=",
"len",
"(... | returns the number of devices connected . | train | false |
34,573 | def InitSecrets(callback=None, shared_only=False, can_prompt=True):
if (options.options.devbox and (not shared_only)):
GetUserSecretsManager()
else:
GetSharedSecretsManager()
if (callback is not None):
callback()
| [
"def",
"InitSecrets",
"(",
"callback",
"=",
"None",
",",
"shared_only",
"=",
"False",
",",
"can_prompt",
"=",
"True",
")",
":",
"if",
"(",
"options",
".",
"options",
".",
"devbox",
"and",
"(",
"not",
"shared_only",
")",
")",
":",
"GetUserSecretsManager",
... | init secrets . | train | false |
34,574 | @hug.startup()
def add_more_data(api):
data.append('Even subsequent calls')
| [
"@",
"hug",
".",
"startup",
"(",
")",
"def",
"add_more_data",
"(",
"api",
")",
":",
"data",
".",
"append",
"(",
"'Even subsequent calls'",
")"
] | adds initial data to the api on startup . | train | false |
34,575 | @contextlib.contextmanager
def signal_receiver(signums):
signals = []
prev_handlers = {}
prev_handlers = get_signals(signums)
set_signals(dict(((s, (lambda s, _: signals.append(s))) for s in signums)))
(yield signals)
set_signals(prev_handlers)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"signal_receiver",
"(",
"signums",
")",
":",
"signals",
"=",
"[",
"]",
"prev_handlers",
"=",
"{",
"}",
"prev_handlers",
"=",
"get_signals",
"(",
"signums",
")",
"set_signals",
"(",
"dict",
"(",
"(",
"(",
"s"... | context manager to catch signals . | train | false |
34,576 | def _upstart_enable(name):
if _upstart_is_enabled(name):
return _upstart_is_enabled(name)
override = '/etc/init/{0}.override'.format(name)
files = ['/etc/init/{0}.conf'.format(name), override]
for file_name in itertools.ifilter(os.path.isfile, files):
with salt.utils.fopen(file_name, 'r+') as fp_:
new_text = re.sub('^\\s*manual\\n?', '', fp_.read(), 0, re.MULTILINE)
fp_.seek(0)
fp_.write(new_text)
fp_.truncate()
if (os.access(override, os.R_OK) and (os.path.getsize(override) == 0)):
os.unlink(override)
return _upstart_is_enabled(name)
| [
"def",
"_upstart_enable",
"(",
"name",
")",
":",
"if",
"_upstart_is_enabled",
"(",
"name",
")",
":",
"return",
"_upstart_is_enabled",
"(",
"name",
")",
"override",
"=",
"'/etc/init/{0}.override'",
".",
"format",
"(",
"name",
")",
"files",
"=",
"[",
"'/etc/init... | enable an upstart service . | train | false |
34,577 | def _raise_if(predicate, *args):
if predicate:
raise InvalidChunk(*args)
| [
"def",
"_raise_if",
"(",
"predicate",
",",
"*",
"args",
")",
":",
"if",
"predicate",
":",
"raise",
"InvalidChunk",
"(",
"*",
"args",
")"
] | helper for validation methods . | train | false |
34,578 | def partition_dataset(data, labels, nb_teachers, teacher_id):
assert (len(data) == len(labels))
assert (int(teacher_id) < int(nb_teachers))
batch_len = int((len(data) / nb_teachers))
start = (teacher_id * batch_len)
end = ((teacher_id + 1) * batch_len)
partition_data = data[start:end]
partition_labels = labels[start:end]
return (partition_data, partition_labels)
| [
"def",
"partition_dataset",
"(",
"data",
",",
"labels",
",",
"nb_teachers",
",",
"teacher_id",
")",
":",
"assert",
"(",
"len",
"(",
"data",
")",
"==",
"len",
"(",
"labels",
")",
")",
"assert",
"(",
"int",
"(",
"teacher_id",
")",
"<",
"int",
"(",
"nb_... | simple partitioning algorithm that returns the right portion of the data needed by a given teacher out of a certain nb of teachers . | train | false |
34,579 | def get_class_traits(klass):
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
(yield (name, rhs, doc))
| [
"def",
"get_class_traits",
"(",
"klass",
")",
":",
"source",
"=",
"inspect",
".",
"getsource",
"(",
"klass",
")",
"cb",
"=",
"CommentBlocker",
"(",
")",
"cb",
".",
"process_file",
"(",
"StringIO",
"(",
"source",
")",
")",
"mod_ast",
"=",
"compiler",
".",... | yield all of the documentation for trait definitions on a class object . | train | true |
34,580 | def nocoverage(func):
if hasattr(func, 'uncovered'):
return func
func.uncovered = True
def not_covered(*args, **kwargs):
with pause_trace():
return func(*args, **kwargs)
not_covered.uncovered = True
return not_covered
| [
"def",
"nocoverage",
"(",
"func",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"'uncovered'",
")",
":",
"return",
"func",
"func",
".",
"uncovered",
"=",
"True",
"def",
"not_covered",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"with",
"pause_trace... | function decorator that pauses tracing functions . | train | false |
34,581 | def monomial_mul(A, B):
return tuple([(a + b) for (a, b) in zip(A, B)])
| [
"def",
"monomial_mul",
"(",
"A",
",",
"B",
")",
":",
"return",
"tuple",
"(",
"[",
"(",
"a",
"+",
"b",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"zip",
"(",
"A",
",",
"B",
")",
"]",
")"
] | multiplication of tuples representing monomials . | train | false |
34,582 | @register.simple_tag(takes_context=True)
def header_action_hooks(context):
return action_hooks(context, HeaderActionHook)
| [
"@",
"register",
".",
"simple_tag",
"(",
"takes_context",
"=",
"True",
")",
"def",
"header_action_hooks",
"(",
"context",
")",
":",
"return",
"action_hooks",
"(",
"context",
",",
"HeaderActionHook",
")"
] | displays all single-entry action hooks for the header bar . | train | false |
34,583 | def has_handshake(target, capfile):
global RUN_CONFIG
valid_handshake = True
tried = False
if RUN_CONFIG.WPA_HANDSHAKE_TSHARK:
tried = True
valid_handshake = has_handshake_tshark(target, capfile)
if (valid_handshake and RUN_CONFIG.WPA_HANDSHAKE_COWPATTY):
tried = True
valid_handshake = has_handshake_cowpatty(target, capfile)
if (valid_handshake and RUN_CONFIG.WPA_HANDSHAKE_COWPATTY):
tried = True
valid_handshake = has_handshake_cowpatty(target, capfile)
if (valid_handshake and RUN_CONFIG.WPA_HANDSHAKE_PYRIT):
tried = True
valid_handshake = has_handshake_pyrit(target, capfile)
if (valid_handshake and RUN_CONFIG.WPA_HANDSHAKE_AIRCRACK):
tried = True
valid_handshake = has_handshake_aircrack(target, capfile)
if tried:
return valid_handshake
print (((R + ' [!]') + O) + ' unable to check for handshake: all handshake options are disabled!')
exit_gracefully(1)
| [
"def",
"has_handshake",
"(",
"target",
",",
"capfile",
")",
":",
"global",
"RUN_CONFIG",
"valid_handshake",
"=",
"True",
"tried",
"=",
"False",
"if",
"RUN_CONFIG",
".",
"WPA_HANDSHAKE_TSHARK",
":",
"tried",
"=",
"True",
"valid_handshake",
"=",
"has_handshake_tshar... | checks if . | train | false |
34,585 | def resolve_name(name, namespace_, remappings=None):
if (not name):
return namespace(namespace_)
name = canonicalize_name(name)
if (name[0] == SEP):
resolved_name = name
elif is_private(name):
resolved_name = canonicalize_name(((namespace_ + SEP) + name[1:]))
else:
resolved_name = (namespace(namespace_) + name)
if (remappings and (resolved_name in remappings)):
return remappings[resolved_name]
else:
return resolved_name
| [
"def",
"resolve_name",
"(",
"name",
",",
"namespace_",
",",
"remappings",
"=",
"None",
")",
":",
"if",
"(",
"not",
"name",
")",
":",
"return",
"namespace",
"(",
"namespace_",
")",
"name",
"=",
"canonicalize_name",
"(",
"name",
")",
"if",
"(",
"name",
"... | resolve a relative module name to an absolute one . | train | false |
34,587 | def bindir_def(*args):
return os.path.join('$bindir', *args)
| [
"def",
"bindir_def",
"(",
"*",
"args",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"'$bindir'",
",",
"*",
"args",
")"
] | return an uninterpolated path relative to $bindir . | train | false |
34,589 | def policy_key(location):
return u'{cat}/{name}'.format(cat=location.category, name=location.name)
| [
"def",
"policy_key",
"(",
"location",
")",
":",
"return",
"u'{cat}/{name}'",
".",
"format",
"(",
"cat",
"=",
"location",
".",
"category",
",",
"name",
"=",
"location",
".",
"name",
")"
] | get the key for a location in a policy file . | train | false |
34,591 | def create_le_config(parent_dir):
config = copy.deepcopy(constants.CLI_DEFAULTS)
le_dir = os.path.join(parent_dir, 'certbot')
config['config_dir'] = os.path.join(le_dir, 'config')
config['work_dir'] = os.path.join(le_dir, 'work')
config['logs_dir'] = os.path.join(le_dir, 'logs_dir')
os.makedirs(config['config_dir'])
os.mkdir(config['work_dir'])
os.mkdir(config['logs_dir'])
config['domains'] = None
return argparse.Namespace(**config)
| [
"def",
"create_le_config",
"(",
"parent_dir",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"constants",
".",
"CLI_DEFAULTS",
")",
"le_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"parent_dir",
",",
"'certbot'",
")",
"config",
"[",
"'config_dir... | sets up le dirs in parent_dir and returns the config dict . | train | false |
34,594 | def make_trivial_sdist(dist_path, setup_py):
setup_py_file = tarfile.TarInfo(name='setup.py')
try:
MemFile = BytesIO
except AttributeError:
MemFile = StringIO
setup_py_bytes = MemFile(setup_py.encode('utf-8'))
setup_py_file.size = len(setup_py_bytes.getvalue())
dist = tarfile.open(dist_path, 'w:gz')
try:
dist.addfile(setup_py_file, fileobj=setup_py_bytes)
finally:
dist.close()
| [
"def",
"make_trivial_sdist",
"(",
"dist_path",
",",
"setup_py",
")",
":",
"setup_py_file",
"=",
"tarfile",
".",
"TarInfo",
"(",
"name",
"=",
"'setup.py'",
")",
"try",
":",
"MemFile",
"=",
"BytesIO",
"except",
"AttributeError",
":",
"MemFile",
"=",
"StringIO",
... | create a simple sdist tarball at dist_path . | train | false |
34,596 | def _add_global_secondary_index(ret, name, index_name, changes_old, changes_new, comments, gsi_config, region, key, keyid, profile):
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Dynamo table {0} will have a GSI added: {1}'.format(name, index_name)
return
changes_new.setdefault('global_indexes', {})
success = __salt__['boto_dynamodb.create_global_secondary_index'](name, __salt__['boto_dynamodb.extract_index'](gsi_config[index_name], global_index=True), region=region, key=key, keyid=keyid, profile=profile)
if success:
comments.append('Created GSI {0}'.format(index_name))
changes_new['global_indexes'][index_name] = gsi_config[index_name]
else:
ret['result'] = False
ret['comment'] = 'Failed to create GSI {0}'.format(index_name)
| [
"def",
"_add_global_secondary_index",
"(",
"ret",
",",
"name",
",",
"index_name",
",",
"changes_old",
",",
"changes_new",
",",
"comments",
",",
"gsi_config",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
":",
"if",
"__opts__",
"[",
"'test'",
... | updates ret iff there was a failure or in test mode . | train | true |
34,599 | def check_directory_permission(permission_codename, request, directory):
if request.user.is_superuser:
return True
if (permission_codename == 'view'):
context = None
context = getattr(directory, 'tp', None)
if (context is None):
context = getattr(directory, 'project', None)
if (context is None):
return True
return context.is_accessible_by(request.user)
return (('administrate' in request.permissions) or (permission_codename in request.permissions))
| [
"def",
"check_directory_permission",
"(",
"permission_codename",
",",
"request",
",",
"directory",
")",
":",
"if",
"request",
".",
"user",
".",
"is_superuser",
":",
"return",
"True",
"if",
"(",
"permission_codename",
"==",
"'view'",
")",
":",
"context",
"=",
"... | checks if the current user has permission_codename permissions for a given directory . | train | false |
34,600 | def queue_get_for(context, topic, host):
return (('%s.%s' % (topic, host)) if host else topic)
| [
"def",
"queue_get_for",
"(",
"context",
",",
"topic",
",",
"host",
")",
":",
"return",
"(",
"(",
"'%s.%s'",
"%",
"(",
"topic",
",",
"host",
")",
")",
"if",
"host",
"else",
"topic",
")"
] | get a queue name for a given topic + host . | train | false |
34,602 | def _parse_config_args(args):
config_dict = dict()
for config_str in args:
try:
components = config_str.split('=')
if (len(components) >= 2):
config_dict[components[0]] = '='.join(components[1:])
except:
print "Warning: could not interpret config value '{0}'".format(config_str)
return config_dict
| [
"def",
"_parse_config_args",
"(",
"args",
")",
":",
"config_dict",
"=",
"dict",
"(",
")",
"for",
"config_str",
"in",
"args",
":",
"try",
":",
"components",
"=",
"config_str",
".",
"split",
"(",
"'='",
")",
"if",
"(",
"len",
"(",
"components",
")",
">="... | parse stub configuration arguments . | train | false |
34,604 | def locate_dir(path, dir_name):
paths = []
for (root, sub_dirs, files) in os.walk(path):
for sub_dir in sub_dirs:
if (dir_name == sub_dir):
result = os.path.abspath(os.path.join(root, sub_dir))
if (sub_dir == 'WEB-INF'):
logging.info('Found WEB-INF/ at: {0}'.format(result))
paths.append(result)
elif ((sub_dir == 'lib') and (result.count(os.sep) <= (path.count(os.sep) + 2)) and result.endswith('/WEB-INF/{0}'.format(sub_dir))):
logging.info('Found lib/ at: {0}'.format(result))
paths.append(result)
if (len(paths) > 0):
sorted_paths = sorted(paths, key=(lambda s: len(s)))
return sorted_paths[0]
else:
return None
| [
"def",
"locate_dir",
"(",
"path",
",",
"dir_name",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"(",
"root",
",",
"sub_dirs",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"sub_dir",
"in",
"sub_dirs",
":",
"if",
"(",
"dir_... | locates a directory inside the given path . | train | false |
34,605 | def eval_parallel(parse_result):
if (len(parse_result) == 1):
return parse_result[0]
if (0 in parse_result):
return float('nan')
reciprocals = [(1.0 / e) for e in parse_result if isinstance(e, numbers.Number)]
return (1.0 / sum(reciprocals))
| [
"def",
"eval_parallel",
"(",
"parse_result",
")",
":",
"if",
"(",
"len",
"(",
"parse_result",
")",
"==",
"1",
")",
":",
"return",
"parse_result",
"[",
"0",
"]",
"if",
"(",
"0",
"in",
"parse_result",
")",
":",
"return",
"float",
"(",
"'nan'",
")",
"re... | compute numbers according to the parallel resistors operator . | train | false |
34,606 | def update_title_paths(instance, **kwargs):
for title in instance.title_set.all():
title.save()
| [
"def",
"update_title_paths",
"(",
"instance",
",",
"**",
"kwargs",
")",
":",
"for",
"title",
"in",
"instance",
".",
"title_set",
".",
"all",
"(",
")",
":",
"title",
".",
"save",
"(",
")"
] | update child pages paths in case when page was moved . | train | false |
34,607 | def subscription():
output = s3_rest_controller()
return output
| [
"def",
"subscription",
"(",
")",
":",
"output",
"=",
"s3_rest_controller",
"(",
")",
"return",
"output"
] | declare a test to only be run if subscription testing is enabled . | train | false |
34,608 | def encode_unicode_characters_in_url(url):
(scheme, netloc, path, params, query, fragment) = urlparse(url)
query_params = parse_qsl(query)
updated_query_params = []
for (query_name, query_val) in query_params:
updated_query_params.append((query_name, urlquote(query_val)))
return urlunparse((scheme, netloc, urlquote(path, '/:+@'), params, urlencode(query_params), fragment))
| [
"def",
"encode_unicode_characters_in_url",
"(",
"url",
")",
":",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
")",
"=",
"urlparse",
"(",
"url",
")",
"query_params",
"=",
"parse_qsl",
"(",
"query",
")",
"updated_q... | encodes all unicode characters to their percent-encoding representation in both the path portion and query parameter portion of the given url . | train | false |
34,609 | def cpu_count_logical():
return cext.cpu_count_logical()
| [
"def",
"cpu_count_logical",
"(",
")",
":",
"return",
"cext",
".",
"cpu_count_logical",
"(",
")"
] | return the number of logical cpus in the system . | train | false |
34,610 | def is_not_(a, b, msg=None):
assert (a is not b), (msg or ('%r is %r' % (a, b)))
| [
"def",
"is_not_",
"(",
"a",
",",
"b",
",",
"msg",
"=",
"None",
")",
":",
"assert",
"(",
"a",
"is",
"not",
"b",
")",
",",
"(",
"msg",
"or",
"(",
"'%r is %r'",
"%",
"(",
"a",
",",
"b",
")",
")",
")"
] | assert a is not b . | train | false |
34,612 | def enc(data, **kwargs):
key = _get_key(**kwargs)
sk = base64.b64decode(key)
b = libnacl.secret.SecretBox(sk)
return base64.b64encode(b.encrypt(data))
| [
"def",
"enc",
"(",
"data",
",",
"**",
"kwargs",
")",
":",
"key",
"=",
"_get_key",
"(",
"**",
"kwargs",
")",
"sk",
"=",
"base64",
".",
"b64decode",
"(",
"key",
")",
"b",
"=",
"libnacl",
".",
"secret",
".",
"SecretBox",
"(",
"sk",
")",
"return",
"b... | encodes a string for sgml/xml/html . | train | false |
34,613 | def test_timeit_arguments():
_ip.magic("timeit ('#')")
| [
"def",
"test_timeit_arguments",
"(",
")",
":",
"_ip",
".",
"magic",
"(",
"\"timeit ('#')\"",
")"
] | test valid timeit arguments . | train | false |
34,614 | @require_GET
def confirm_change_email(request, activation_key):
activation_key = activation_key.lower()
email_change = get_object_or_404(EmailChange, activation_key=activation_key)
u = email_change.user
old_email = u.email
new_email = email_change.email
duplicate = User.objects.filter(email=new_email).exists()
if (not duplicate):
u.email = new_email
u.save()
email_change.delete()
return render(request, 'users/change_email_complete.html', {'old_email': old_email, 'new_email': new_email, 'username': u.username, 'duplicate': duplicate})
| [
"@",
"require_GET",
"def",
"confirm_change_email",
"(",
"request",
",",
"activation_key",
")",
":",
"activation_key",
"=",
"activation_key",
".",
"lower",
"(",
")",
"email_change",
"=",
"get_object_or_404",
"(",
"EmailChange",
",",
"activation_key",
"=",
"activation... | confirm the new email for the user . | train | false |
34,615 | def flat2triu(a, dim):
res = zeros((dim, dim))
index = 0
for row in range(dim):
res[row, row:] = a[index:((index + dim) - row)]
index += (dim - row)
return res
| [
"def",
"flat2triu",
"(",
"a",
",",
"dim",
")",
":",
"res",
"=",
"zeros",
"(",
"(",
"dim",
",",
"dim",
")",
")",
"index",
"=",
"0",
"for",
"row",
"in",
"range",
"(",
"dim",
")",
":",
"res",
"[",
"row",
",",
"row",
":",
"]",
"=",
"a",
"[",
... | produces an upper triangular matrix of dimension dim from the elements of the given vector . | train | false |
34,616 | @receiver(pre_save, sender=AccessToken)
def on_access_token_presave(sender, instance, *args, **kwargs):
is_application_restricted = RestrictedApplication.objects.filter(application=instance.application).exists()
if is_application_restricted:
RestrictedApplication.set_access_token_as_expired(instance)
| [
"@",
"receiver",
"(",
"pre_save",
",",
"sender",
"=",
"AccessToken",
")",
"def",
"on_access_token_presave",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"is_application_restricted",
"=",
"RestrictedApplication",
".",
"objects"... | a hook on the accesstoken . | train | false |
34,617 | def fake_is_vim_object(arg, module):
return isinstance(module, fake.FakeVim)
| [
"def",
"fake_is_vim_object",
"(",
"arg",
",",
"module",
")",
":",
"return",
"isinstance",
"(",
"module",
",",
"fake",
".",
"FakeVim",
")"
] | stubs out the vmwareapisessions is_vim_object method . | train | false |
34,618 | def check_gateway_invalid_in_subnet(cidr, gateway):
ip = netaddr.IPAddress(gateway)
net = netaddr.IPNetwork(cidr)
return ((ip in net) and ((ip == net.network) or ((net.version == constants.IP_VERSION_4) and (ip == net[(-1)]))))
| [
"def",
"check_gateway_invalid_in_subnet",
"(",
"cidr",
",",
"gateway",
")",
":",
"ip",
"=",
"netaddr",
".",
"IPAddress",
"(",
"gateway",
")",
"net",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"cidr",
")",
"return",
"(",
"(",
"ip",
"in",
"net",
")",
"and",
... | check whether the gw ip address is invalid on the subnet . | train | false |
34,619 | def apply_request_middleware(request, **attrs):
for middleware_path in settings.MIDDLEWARE_CLASSES:
mw_class = import_string(middleware_path)
try:
mw_instance = mw_class()
except MiddlewareNotUsed:
continue
if hasattr(mw_instance, 'process_request'):
mw_instance.process_request(request)
for (key, value) in attrs.items():
setattr(request, key, value)
return request
| [
"def",
"apply_request_middleware",
"(",
"request",
",",
"**",
"attrs",
")",
":",
"for",
"middleware_path",
"in",
"settings",
".",
"MIDDLEWARE_CLASSES",
":",
"mw_class",
"=",
"import_string",
"(",
"middleware_path",
")",
"try",
":",
"mw_instance",
"=",
"mw_class",
... | apply all the process_request capable middleware configured into the given request . | train | false |
34,621 | def _run_test_complete_on_exit(f):
def wrapped(self, *args, **dargs):
try:
return f(self, *args, **dargs)
finally:
if (self._logger.global_filename == 'status'):
self.harness.run_test_complete()
if self.drop_caches:
utils_memory.drop_caches()
wrapped.__name__ = f.__name__
wrapped.__doc__ = f.__doc__
wrapped.__dict__.update(f.__dict__)
return wrapped
| [
"def",
"_run_test_complete_on_exit",
"(",
"f",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"**",
"dargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"**",
"dargs",
")",
"finally",
":",
"if",
"(",
... | decorator for job methods that automatically calls self . | train | false |
34,622 | @conf.commands.register
def etherleak(target, **kargs):
return srpflood((Ether() / ARP(pdst=target)), prn=(lambda (s, r): ((conf.padding_layer in r) and hexstr(r[conf.padding_layer].load))), filter='arp', **kargs)
| [
"@",
"conf",
".",
"commands",
".",
"register",
"def",
"etherleak",
"(",
"target",
",",
"**",
"kargs",
")",
":",
"return",
"srpflood",
"(",
"(",
"Ether",
"(",
")",
"/",
"ARP",
"(",
"pdst",
"=",
"target",
")",
")",
",",
"prn",
"=",
"(",
"lambda",
"... | exploit etherleak flaw . | train | false |
34,624 | def redact_http_basic_auth(output):
url_re = '(https?)://.*@'
redacted = '\\1://<redacted>@'
if (sys.version_info >= (2, 7)):
return re.sub(url_re, redacted, output, flags=re.IGNORECASE)
elif re.search(url_re, output.lower()):
return re.sub(url_re, redacted, output.lower())
return output
| [
"def",
"redact_http_basic_auth",
"(",
"output",
")",
":",
"url_re",
"=",
"'(https?)://.*@'",
"redacted",
"=",
"'\\\\1://<redacted>@'",
"if",
"(",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"7",
")",
")",
":",
"return",
"re",
".",
"sub",
"(",
"url_re"... | remove http user and password . | train | true |
34,625 | def get_kernel():
return ('python%s' % sys.version_info.major)
| [
"def",
"get_kernel",
"(",
")",
":",
"return",
"(",
"'python%s'",
"%",
"sys",
".",
"version_info",
".",
"major",
")"
] | find the kernel name for your python version . | train | false |
34,628 | def comment_form_target():
return comments.get_form_target()
| [
"def",
"comment_form_target",
"(",
")",
":",
"return",
"comments",
".",
"get_form_target",
"(",
")"
] | get the target url for the comment form . | train | false |
34,629 | def test_data_url():
data = jinja.render('test3.html')
print data
url = QUrl(data)
assert url.isValid()
assert (data == 'data:text/plain;base64,Zm9v')
| [
"def",
"test_data_url",
"(",
")",
":",
"data",
"=",
"jinja",
".",
"render",
"(",
"'test3.html'",
")",
"print",
"data",
"url",
"=",
"QUrl",
"(",
"data",
")",
"assert",
"url",
".",
"isValid",
"(",
")",
"assert",
"(",
"data",
"==",
"'data:text/plain;base64,... | test data_url() which can be used from templates . | train | false |
34,630 | def _init():
parser = OptionParser()
parser.add_option('--platform', dest='platform', help="Platform ('os' grain)")
parser.add_option('--log-level', dest='log_level', default='warning', help='Control verbosity of logging. Default: %default')
path_group = OptionGroup(parser, 'File/Directory Options')
path_group.add_option('--source-dir', default='/testing', help='Source directory. Must be a git checkout. (default: %default)')
path_group.add_option('--build-dir', default='/tmp/salt-buildpackage', help='Build root, will be removed if it exists prior to running script. (default: %default)')
path_group.add_option('--artifact-dir', default='/tmp/salt-packages', help='Location where build artifacts should be placed for Jenkins to retrieve them (default: %default)')
parser.add_option_group(path_group)
rpm_group = OptionGroup(parser, 'RPM-specific File/Directory Options')
rpm_group.add_option('--spec', dest='spec_file', default='/tmp/salt.spec', help='Spec file to use as a template to build RPM. (default: %default)')
parser.add_option_group(rpm_group)
opts = parser.parse_args()[0]
for group in (path_group, rpm_group):
for path_opt in [opt.dest for opt in group.option_list]:
path = getattr(opts, path_opt)
if (not os.path.isabs(path)):
path = os.path.expanduser(path)
if (not os.path.isabs(path)):
path = os.path.realpath(path)
setattr(opts, path_opt, path)
problems = []
if (not opts.platform):
problems.append("Platform ('os' grain) required")
if (not os.path.isdir(opts.source_dir)):
problems.append('Source directory {0} not found'.format(opts.source_dir))
try:
shutil.rmtree(opts.build_dir)
except OSError as exc:
if (exc.errno not in (errno.ENOENT, errno.ENOTDIR)):
problems.append('Unable to remove pre-existing destination directory {0}: {1}'.format(opts.build_dir, exc))
finally:
try:
os.makedirs(opts.build_dir)
except OSError as exc:
problems.append('Unable to create destination directory {0}: {1}'.format(opts.build_dir, exc))
try:
shutil.rmtree(opts.artifact_dir)
except OSError as exc:
if (exc.errno not in (errno.ENOENT, errno.ENOTDIR)):
problems.append('Unable to remove pre-existing artifact directory {0}: {1}'.format(opts.artifact_dir, exc))
finally:
try:
os.makedirs(opts.artifact_dir)
except OSError as exc:
problems.append('Unable to create artifact directory {0}: {1}'.format(opts.artifact_dir, exc))
opts.log_file = os.path.join(opts.artifact_dir, 'salt-buildpackage.log')
if problems:
_abort(problems)
return opts
| [
"def",
"_init",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"'--platform'",
",",
"dest",
"=",
"'platform'",
",",
"help",
"=",
"\"Platform ('os' grain)\"",
")",
"parser",
".",
"add_option",
"(",
"'--log-level'",
"... | internal function to install the module finder . | train | false |
34,632 | def is_authorized_boolean(action, context, data_dict=None):
outcome = is_authorized(action, context, data_dict=data_dict)
return outcome.get('success', False)
| [
"def",
"is_authorized_boolean",
"(",
"action",
",",
"context",
",",
"data_dict",
"=",
"None",
")",
":",
"outcome",
"=",
"is_authorized",
"(",
"action",
",",
"context",
",",
"data_dict",
"=",
"data_dict",
")",
"return",
"outcome",
".",
"get",
"(",
"'success'"... | runs the auth function but just returns true if allowed else false . | train | false |
34,633 | def _run_hook(shell_cmd):
(err, _) = execute(shell_cmd)
return err
| [
"def",
"_run_hook",
"(",
"shell_cmd",
")",
":",
"(",
"err",
",",
"_",
")",
"=",
"execute",
"(",
"shell_cmd",
")",
"return",
"err"
] | run a hook command . | train | false |
34,634 | def classmarkEnquiry():
a = TpPd(pd=6)
b = MessageType(mesType=19)
packet = (a / b)
return packet
| [
"def",
"classmarkEnquiry",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"6",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"19",
")",
"packet",
"=",
"(",
"a",
"/",
"b",
")",
"return",
"packet"
] | classmark enquiry section 9 . | train | true |
34,635 | @register.filter()
def decryptable_by(secret, user):
return secret.decryptable_by(user)
| [
"@",
"register",
".",
"filter",
"(",
")",
"def",
"decryptable_by",
"(",
"secret",
",",
"user",
")",
":",
"return",
"secret",
".",
"decryptable_by",
"(",
"user",
")"
] | determine whether a given user is permitted to decrypt a secret . | train | false |
34,636 | def get_stable_hash(obj):
if isinstance(obj, dict):
return get_stable_hash(list(obj.items()))
elif isinstance(obj, (list, tuple)):
obj = sorted((get_stable_hash(o) for o in obj))
return md5(unicode(obj).encode('utf8')).hexdigest()
| [
"def",
"get_stable_hash",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"get_stable_hash",
"(",
"list",
"(",
"obj",
".",
"items",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
... | return a stable hash for a python data structure . | train | false |
34,637 | def create_graph():
with tf.gfile.FastGFile(os.path.join(FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
| [
"def",
"create_graph",
"(",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"FastGFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"FLAGS",
".",
"model_dir",
",",
"'classify_image_graph_def.pb'",
")",
",",
"'rb'",
")",
"as",
"f",
":",
"graph_def",
"=",
"tf"... | creates a graph from saved graphdef file and returns a saver . | train | true |
34,638 | def url_path(url):
return urlparse.urlsplit(url).path
| [
"def",
"url_path",
"(",
"url",
")",
":",
"return",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
".",
"path"
] | return the path portion of a url . | train | false |
34,639 | def version_process(versions, filter_prefix):
output = []
for version in versions:
prefix = ''
if filter_prefix:
if (version[0:len(filter_prefix)] != filter_prefix):
continue
check_version = version[len(filter_prefix):]
prefix = filter_prefix
else:
check_version = re.sub('^v', '', version)
if (check_version != version):
prefix = 'v'
if (not SemVer.valid(check_version)):
continue
output.append({'version': check_version, 'prefix': prefix})
return output
| [
"def",
"version_process",
"(",
"versions",
",",
"filter_prefix",
")",
":",
"output",
"=",
"[",
"]",
"for",
"version",
"in",
"versions",
":",
"prefix",
"=",
"''",
"if",
"filter_prefix",
":",
"if",
"(",
"version",
"[",
"0",
":",
"len",
"(",
"filter_prefix"... | filter a list of versions to ones that are valid semvers . | train | false |
34,641 | @app.route('/gzip')
@filters.gzip
def view_gzip_encoded_content():
return jsonify(get_dict('origin', 'headers', method=request.method, gzipped=True))
| [
"@",
"app",
".",
"route",
"(",
"'/gzip'",
")",
"@",
"filters",
".",
"gzip",
"def",
"view_gzip_encoded_content",
"(",
")",
":",
"return",
"jsonify",
"(",
"get_dict",
"(",
"'origin'",
",",
"'headers'",
",",
"method",
"=",
"request",
".",
"method",
",",
"gz... | returns gzip-encoded data . | train | false |
34,642 | @composite
def persistent_state_strategy(draw):
return PersistentState()
| [
"@",
"composite",
"def",
"persistent_state_strategy",
"(",
"draw",
")",
":",
"return",
"PersistentState",
"(",
")"
] | a hypothesis strategy to generate a persistentstate presently just returns and empty persistentstate . | train | false |
34,646 | def load_demo(collection_id):
delete_demo(collection_id)
if (not collection_domain.Collection.is_demo_collection_id(collection_id)):
raise Exception(('Invalid demo collection id %s' % collection_id))
demo_filepath = os.path.join(feconf.SAMPLE_COLLECTIONS_DIR, feconf.DEMO_COLLECTIONS[collection_id])
if demo_filepath.endswith('yaml'):
yaml_content = utils.get_file_contents(demo_filepath)
else:
raise Exception(('Unrecognized file path: %s' % demo_filepath))
collection = save_new_collection_from_yaml(feconf.SYSTEM_COMMITTER_ID, yaml_content, collection_id)
publish_collection_and_update_user_profiles(feconf.SYSTEM_COMMITTER_ID, collection_id)
index_collections_given_ids([collection_id])
for collection_node in collection.nodes:
exp_id = collection_node.exploration_id
if (exp_services.get_exploration_by_id(exp_id, strict=False) is None):
exp_services.load_demo(exp_id)
logging.info(('Collection with id %s was loaded.' % collection_id))
| [
"def",
"load_demo",
"(",
"collection_id",
")",
":",
"delete_demo",
"(",
"collection_id",
")",
"if",
"(",
"not",
"collection_domain",
".",
"Collection",
".",
"is_demo_collection_id",
"(",
"collection_id",
")",
")",
":",
"raise",
"Exception",
"(",
"(",
"'Invalid d... | loads a demo exploration . | train | false |
34,647 | def getRandomPipe():
gapYs = [20, 30, 40, 50, 60, 70, 80, 90]
index = random.randint(0, (len(gapYs) - 1))
gapY = gapYs[index]
gapY += int((BASEY * 0.2))
pipeX = (SCREENWIDTH + 10)
return [{'x': pipeX, 'y': (gapY - PIPE_HEIGHT)}, {'x': pipeX, 'y': (gapY + PIPEGAPSIZE)}]
| [
"def",
"getRandomPipe",
"(",
")",
":",
"gapYs",
"=",
"[",
"20",
",",
"30",
",",
"40",
",",
"50",
",",
"60",
",",
"70",
",",
"80",
",",
"90",
"]",
"index",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"(",
"len",
"(",
"gapYs",
")",
"-",
"1"... | returns a randomly generated pipe . | train | false |
34,648 | def rgb2dklCart(picture, conversionMatrix=None):
picture = numpy.array(picture)
origShape = picture.shape
if (conversionMatrix is None):
conversionMatrix = numpy.asarray([[0.25145542, 0.64933633, 0.09920825], [0.78737943, (-0.55586618), (-0.23151325)], [0.26562825, 0.63933074, (-0.90495899)]])
logging.warning('This monitor has not been color-calibrated. Using default DKL conversion matrix.')
else:
conversionMatrix = numpy.linalg.inv(conversionMatrix)
red = picture[:, :, 0]
green = picture[:, :, 1]
blue = picture[:, :, 2]
dkl = numpy.asarray([red.reshape([(-1)]), green.reshape([(-1)]), blue.reshape([(-1)])])
dkl = numpy.dot(conversionMatrix, dkl)
dklPicture = numpy.reshape(numpy.transpose(dkl), origShape)
return dklPicture
| [
"def",
"rgb2dklCart",
"(",
"picture",
",",
"conversionMatrix",
"=",
"None",
")",
":",
"picture",
"=",
"numpy",
".",
"array",
"(",
"picture",
")",
"origShape",
"=",
"picture",
".",
"shape",
"if",
"(",
"conversionMatrix",
"is",
"None",
")",
":",
"conversionM... | convert an rgb image into cartesian dkl space . | train | false |
34,649 | def configure_distutils_command(cmdline):
d = Distribution(attrs={'cmdclass': vars(frontend), 'script_args': shlex.split(cmdline)})
d.parse_command_line()
assert (len(d.commands) == 1)
cmdinst = d.get_command_obj(d.commands[0])
cmdinst.ensure_finalized()
return cmdinst
| [
"def",
"configure_distutils_command",
"(",
"cmdline",
")",
":",
"d",
"=",
"Distribution",
"(",
"attrs",
"=",
"{",
"'cmdclass'",
":",
"vars",
"(",
"frontend",
")",
",",
"'script_args'",
":",
"shlex",
".",
"split",
"(",
"cmdline",
")",
"}",
")",
"d",
".",
... | helper to configure a command class . | train | false |
34,650 | def streaming_change_generator(namespace, poll_interval, timeout, transaction_pointer, exclude_types=None, include_types=None, exclude_folders=True, exclude_metadata=True, exclude_account=True, expand=False, is_n1=False):
encoder = APIEncoder(is_n1=is_n1)
start_time = time.time()
while ((time.time() - start_time) < timeout):
with session_scope(namespace.id) as db_session:
(deltas, new_pointer) = format_transactions_after_pointer(namespace, transaction_pointer, db_session, 100, exclude_types, include_types, exclude_folders, exclude_metadata, exclude_account, expand=expand, is_n1=is_n1)
if ((new_pointer is not None) and (new_pointer != transaction_pointer)):
transaction_pointer = new_pointer
for delta in deltas:
(yield (encoder.cereal(delta) + '\n'))
else:
(yield '\n')
gevent.sleep(poll_interval)
| [
"def",
"streaming_change_generator",
"(",
"namespace",
",",
"poll_interval",
",",
"timeout",
",",
"transaction_pointer",
",",
"exclude_types",
"=",
"None",
",",
"include_types",
"=",
"None",
",",
"exclude_folders",
"=",
"True",
",",
"exclude_metadata",
"=",
"True",
... | poll the transaction log for the given namespace_id until timeout expires . | train | false |
34,652 | def update_stats(get_innodb=True, get_master=True, get_slave=True):
logging.debug('updating stats')
global last_update
global mysql_stats, mysql_stats_last
cur_time = time.time()
time_delta = (cur_time - last_update)
if (time_delta <= 0):
logging.debug(' system clock set backwards, probably ntp')
if ((cur_time - last_update) < MAX_UPDATE_TIME):
logging.debug(((' wait ' + str(int((MAX_UPDATE_TIME - (cur_time - last_update))))) + ' seconds'))
return True
else:
last_update = cur_time
logging.debug('refreshing stats')
mysql_stats = {}
try:
conn = MySQLdb.connect(**mysql_conn_opts)
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT GET_LOCK('gmetric-mysql', 0) as ok")
lock_stat = cursor.fetchone()
cursor.close()
if (lock_stat['ok'] == 0):
return False
cursor = conn.cursor(MySQLdb.cursors.Cursor)
cursor.execute('SHOW VARIABLES')
variables = {}
for (k, v) in cursor:
variables[k.lower()] = v
cursor.close()
cursor = conn.cursor(MySQLdb.cursors.Cursor)
cursor.execute('SHOW /*!50002 GLOBAL */ STATUS')
global_status = {}
for (k, v) in cursor:
global_status[k.lower()] = v
cursor.close()
cursor = conn.cursor(MySQLdb.cursors.Cursor)
cursor.execute("SELECT PLUGIN_STATUS, PLUGIN_VERSION FROM `information_schema`.Plugins WHERE PLUGIN_NAME LIKE '%innodb%' AND PLUGIN_TYPE LIKE 'STORAGE ENGINE';")
have_innodb = False
innodb_version = 1.0
row = cursor.fetchone()
if (row[0] == 'ACTIVE'):
have_innodb = True
innodb_version = row[1]
cursor.close()
get_innodb = (get_innodb and have_innodb)
get_master = (get_master and (variables['log_bin'].lower() == 'on'))
innodb_status = defaultdict(int)
if get_innodb:
cursor = conn.cursor(MySQLdb.cursors.Cursor)
cursor.execute('SHOW /*!50000 ENGINE*/ INNODB STATUS')
innodb_status = parse_innodb_status(cursor.fetchone()[2].split('\n'), innodb_version)
cursor.close()
logging.debug(('innodb_status: ' + str(innodb_status)))
master_logs = tuple
if get_master:
cursor = conn.cursor(MySQLdb.cursors.Cursor)
cursor.execute('SHOW MASTER LOGS')
master_logs = cursor.fetchall()
cursor.close()
slave_status = {}
if get_slave:
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SHOW SLAVE STATUS')
res = cursor.fetchone()
if res:
for (k, v) in res.items():
slave_status[k.lower()] = v
else:
get_slave = False
cursor.close()
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT RELEASE_LOCK('gmetric-mysql') as ok")
cursor.close()
conn.close()
except MySQLdb.OperationalError as (errno, errmsg):
logging.error('error updating stats')
logging.error(errmsg)
return False
mysql_stats['version'] = variables['version']
mysql_stats['max_connections'] = variables['max_connections']
mysql_stats['query_cache_size'] = variables['query_cache_size']
interesting_global_status_vars = ('aborted_clients', 'aborted_connects', 'binlog_cache_disk_use', 'binlog_cache_use', 'bytes_received', 'bytes_sent', 'com_delete', 'com_delete_multi', 'com_insert', 'com_insert_select', 'com_load', 'com_replace', 'com_replace_select', 'com_select', 'com_update', 'com_update_multi', 'connections', 'created_tmp_disk_tables', 'created_tmp_files', 'created_tmp_tables', 'key_reads', 'key_read_requests', 'key_writes', 'key_write_requests', 'max_used_connections', 'open_files', 'open_tables', 'opened_tables', 'qcache_free_blocks', 'qcache_free_memory', 'qcache_hits', 'qcache_inserts', 'qcache_lowmem_prunes', 'qcache_not_cached', 'qcache_queries_in_cache', 'qcache_total_blocks', 'questions', 'select_full_join', 'select_full_range_join', 'select_range', 'select_range_check', 'select_scan', 'slave_open_temp_tables', 'slave_retried_transactions', 'slow_launch_threads', 'slow_queries', 'sort_range', 'sort_rows', 'sort_scan', 'table_locks_immediate', 'table_locks_waited', 'threads_cached', 'threads_connected', 'threads_created', 'threads_running', 'uptime')
non_delta = ('max_used_connections', 'open_files', 'open_tables', 'qcache_free_blocks', 'qcache_free_memory', 'qcache_total_blocks', 'slave_open_temp_tables', 'threads_cached', 'threads_connected', 'threads_running', 'uptime')
for key in interesting_global_status_vars:
if (key in non_delta):
mysql_stats[key] = global_status[key]
else:
if (time_delta <= 0):
pass
elif (key in mysql_stats_last):
if delta_per_second:
mysql_stats[key] = ((int(global_status[key]) - int(mysql_stats_last[key])) / time_delta)
else:
mysql_stats[key] = (int(global_status[key]) - int(mysql_stats_last[key]))
else:
mysql_stats[key] = float(0)
mysql_stats_last[key] = global_status[key]
mysql_stats['open_files_used'] = (int(global_status['open_files']) / int(variables['open_files_limit']))
innodb_delta = ('data_fsyncs', 'data_reads', 'data_writes', 'log_writes')
if get_innodb:
for istat in innodb_status:
key = ('innodb_' + istat)
if (istat in innodb_delta):
if (time_delta <= 0):
pass
elif (key in mysql_stats_last):
if delta_per_second:
mysql_stats[key] = ((int(innodb_status[istat]) - int(mysql_stats_last[key])) / time_delta)
else:
mysql_stats[key] = (int(innodb_status[istat]) - int(mysql_stats_last[key]))
else:
mysql_stats[key] = float(0)
mysql_stats_last[key] = innodb_status[istat]
else:
mysql_stats[key] = innodb_status[istat]
if get_master:
mysql_stats['binlog_count'] = len(master_logs)
mysql_stats['binlog_space_current'] = master_logs[(-1)][1]
mysql_stats['binlog_space_total'] = 0
for s in master_logs:
mysql_stats['binlog_space_total'] += int(s[1])
mysql_stats['binlog_space_used'] = ((float(master_logs[(-1)][1]) / float(variables['max_binlog_size'])) * 100)
if get_slave:
mysql_stats['slave_exec_master_log_pos'] = slave_status['exec_master_log_pos']
if (slave_status['slave_io_running'].lower() == 'yes'):
mysql_stats['slave_io'] = 1
else:
mysql_stats['slave_io'] = 0
if (slave_status['slave_sql_running'].lower() == 'yes'):
mysql_stats['slave_sql'] = 1
else:
mysql_stats['slave_sql'] = 0
mysql_stats['slave_lag'] = slave_status['seconds_behind_master']
mysql_stats['slave_relay_log_pos'] = slave_status['relay_log_pos']
mysql_stats['slave_relay_log_space'] = slave_status['relay_log_space']
logging.debug('success updating stats')
logging.debug(('mysql_stats: ' + str(mysql_stats)))
| [
"def",
"update_stats",
"(",
"get_innodb",
"=",
"True",
",",
"get_master",
"=",
"True",
",",
"get_slave",
"=",
"True",
")",
":",
"logging",
".",
"debug",
"(",
"'updating stats'",
")",
"global",
"last_update",
"global",
"mysql_stats",
",",
"mysql_stats_last",
"c... | refresh stats by polling memcached server . | train | false |
34,653 | def test_ast_bad_raise():
cant_compile(u'(raise Exception Exception)')
| [
"def",
"test_ast_bad_raise",
"(",
")",
":",
"cant_compile",
"(",
"u'(raise Exception Exception)'",
")"
] | make sure ast cant compile invalid raise . | train | false |
34,654 | def install_agent(agent_key, agent_version=1):
work_dir = os.path.join(__opts__['cachedir'], 'tmp')
if (not os.path.isdir(work_dir)):
os.mkdir(work_dir)
install_file = tempfile.NamedTemporaryFile(dir=work_dir, suffix='.sh', delete=False)
install_filename = install_file.name
install_file.close()
account_field = 'account_url'
url = 'https://www.serverdensity.com/downloads/agent-install.sh'
if (agent_version == 2):
account_field = 'account_name'
url = 'https://archive.serverdensity.com/agent-install.sh'
account = get_sd_auth(account_field)
__salt__['cmd.run'](cmd='curl -L {0} -o {1}'.format(url, install_filename), cwd=work_dir)
__salt__['cmd.run'](cmd='chmod +x {0}'.format(install_filename), cwd=work_dir)
return __salt__['cmd.run'](cmd='{filename} -a {account} -k {agent_key}'.format(filename=install_filename, account=account, agent_key=agent_key), cwd=work_dir)
| [
"def",
"install_agent",
"(",
"agent_key",
",",
"agent_version",
"=",
"1",
")",
":",
"work_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'tmp'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
... | function downloads server density installation agent . | train | true |
34,655 | def batches2id(batches):
s = ([''] * batches[0].shape[0])
for b in batches:
s = [''.join(x) for x in zip(s, ids(b))]
return s
| [
"def",
"batches2id",
"(",
"batches",
")",
":",
"s",
"=",
"(",
"[",
"''",
"]",
"*",
"batches",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"b",
"in",
"batches",
":",
"s",
"=",
"[",
"''",
".",
"join",
"(",
"x",
")",
"for",
"x",
... | convert a sequence of batches back into their string representation . | train | false |
34,656 | @sync_performer
def perform_download_s3_key(dispatcher, intent):
s3 = boto.connect_s3()
bucket = s3.get_bucket(intent.source_bucket)
key = bucket.get_key(intent.source_key)
with intent.target_path.open('w') as target_file:
key.get_contents_to_file(target_file)
| [
"@",
"sync_performer",
"def",
"perform_download_s3_key",
"(",
"dispatcher",
",",
"intent",
")",
":",
"s3",
"=",
"boto",
".",
"connect_s3",
"(",
")",
"bucket",
"=",
"s3",
".",
"get_bucket",
"(",
"intent",
".",
"source_bucket",
")",
"key",
"=",
"bucket",
"."... | see :class:downloads3key . | train | false |
34,657 | def _cart_to_sph(cart):
assert ((cart.ndim == 2) and (cart.shape[1] == 3))
cart = np.atleast_2d(cart)
out = np.empty((len(cart), 3))
out[:, 0] = np.sqrt(np.sum((cart * cart), axis=1))
out[:, 1] = np.arctan2(cart[:, 1], cart[:, 0])
out[:, 2] = np.arccos((cart[:, 2] / out[:, 0]))
return out
| [
"def",
"_cart_to_sph",
"(",
"cart",
")",
":",
"assert",
"(",
"(",
"cart",
".",
"ndim",
"==",
"2",
")",
"and",
"(",
"cart",
".",
"shape",
"[",
"1",
"]",
"==",
"3",
")",
")",
"cart",
"=",
"np",
".",
"atleast_2d",
"(",
"cart",
")",
"out",
"=",
"... | convert cartesian coordinates to spherical coordinates . | train | false |
34,658 | def sync_after(f):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
result = f(self, *args, **kwargs)
self._cell_data_sync(force=True)
return result
return wrapper
| [
"def",
"sync_after",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"result",
"=",
"f",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",... | use as a decorator to wrap methods that update cell information in the database to make sure the data is synchronized immediately . | train | false |
34,660 | def Application_Error(app, e):
pass
| [
"def",
"Application_Error",
"(",
"app",
",",
"e",
")",
":",
"pass"
] | code that runs when an unhandled error occurs . | train | false |
34,661 | @login_required
def financial_assistance(_request):
return render_to_response('financial-assistance/financial-assistance.html', {'header_text': FINANCIAL_ASSISTANCE_HEADER})
| [
"@",
"login_required",
"def",
"financial_assistance",
"(",
"_request",
")",
":",
"return",
"render_to_response",
"(",
"'financial-assistance/financial-assistance.html'",
",",
"{",
"'header_text'",
":",
"FINANCIAL_ASSISTANCE_HEADER",
"}",
")"
] | render the initial financial assistance page . | train | false |
34,664 | def _execute_load_graph_streaming(filename):
scripts = utils.scriptpath()
infile = utils.copy_test_data(filename)
in_dir = os.path.dirname(infile)
args = u'-x 1e7 -N 2 -k 20 out -'
cmd = u'cat {infile} | {scripts}/load-graph.py {args}'.format(infile=infile, scripts=scripts, args=args)
(status, out, err) = utils.run_shell_cmd(cmd, in_directory=in_dir)
if (status != 0):
print(out)
print(err)
assert (status == 0), status
assert (u'Total number of unique k-mers: 3960' in err), err
ht_file = os.path.join(in_dir, u'out')
assert os.path.exists(ht_file), ht_file
tagset_file = os.path.join(in_dir, u'out.tagset')
assert os.path.exists(tagset_file), tagset_file
ht = khmer.load_nodegraph(ht_file)
ht.load_tagset(tagset_file)
subset = ht.do_subset_partition(0, 0)
x = ht.subset_count_partitions(subset)
assert (x == (1, 0)), x
| [
"def",
"_execute_load_graph_streaming",
"(",
"filename",
")",
":",
"scripts",
"=",
"utils",
".",
"scriptpath",
"(",
")",
"infile",
"=",
"utils",
".",
"copy_test_data",
"(",
"filename",
")",
"in_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"infile",
"... | helper function for the matrix of streaming tests using screed via filter-abund-single . | train | false |
34,665 | def setup_win32():
import py2exe
origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
if (os.path.basename(pathname).lower() in ['sdl_ttf.dll']):
return 0
return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL
| [
"def",
"setup_win32",
"(",
")",
":",
"import",
"py2exe",
"origIsSystemDLL",
"=",
"py2exe",
".",
"build_exe",
".",
"isSystemDLL",
"def",
"isSystemDLL",
"(",
"pathname",
")",
":",
"if",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"pathname",
")",
".",
"l... | packing setup for windows 32/64 . | train | false |
34,666 | @util.positional(2)
def format_python_file(file_descriptor, output, indent_space=2):
out = generate.IndentWriter(output, indent_space=indent_space)
(out << 'from protorpc import message_types')
(out << 'from protorpc import messages')
if file_descriptor.service_types:
(out << 'from protorpc import remote')
if file_descriptor.package:
(out << ("package = '%s'" % file_descriptor.package))
_write_enums(file_descriptor.enum_types, out)
_write_messages(file_descriptor.message_types, out)
_write_services(file_descriptor.service_types, out)
| [
"@",
"util",
".",
"positional",
"(",
"2",
")",
"def",
"format_python_file",
"(",
"file_descriptor",
",",
"output",
",",
"indent_space",
"=",
"2",
")",
":",
"out",
"=",
"generate",
".",
"IndentWriter",
"(",
"output",
",",
"indent_space",
"=",
"indent_space",
... | format filedescriptor object as a single python module . | train | false |
34,667 | def directional_variance_gradient_i(x_i, w):
projection_length = dot(x_i, direction(w))
return [((2 * projection_length) * x_ij) for x_ij in x_i]
| [
"def",
"directional_variance_gradient_i",
"(",
"x_i",
",",
"w",
")",
":",
"projection_length",
"=",
"dot",
"(",
"x_i",
",",
"direction",
"(",
"w",
")",
")",
"return",
"[",
"(",
"(",
"2",
"*",
"projection_length",
")",
"*",
"x_ij",
")",
"for",
"x_ij",
"... | the contribution of row x_i to the gradient of the direction-w variance . | train | false |
34,669 | def add_at(arr, ind, vals):
if hasattr(np.ufunc, 'at'):
return np.add.at(arr, ind, vals)
else:
warnings.warn('Using slow replacement for numpy.add.at(). For ~100x faster results update to numpy 1.8+')
arr = np.asarray(arr)
(ind, vals) = np.broadcast_arrays(ind, vals)
unq = np.unique(ind)
arr[unq] += [vals[(ind == i)].sum() for i in unq]
| [
"def",
"add_at",
"(",
"arr",
",",
"ind",
",",
"vals",
")",
":",
"if",
"hasattr",
"(",
"np",
".",
"ufunc",
",",
"'at'",
")",
":",
"return",
"np",
".",
"add",
".",
"at",
"(",
"arr",
",",
"ind",
",",
"vals",
")",
"else",
":",
"warnings",
".",
"w... | utility that computes np . | train | false |
34,670 | def rec_test(sequence, test_func):
for x in sequence:
if isinstance(x, (list, tuple)):
for y in rec_test(x, test_func):
(yield y)
else:
(yield test_func(x))
| [
"def",
"rec_test",
"(",
"sequence",
",",
"test_func",
")",
":",
"for",
"x",
"in",
"sequence",
":",
"if",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"y",
"in",
"rec_test",
"(",
"x",
",",
"test_func",
")",
":",
"(... | tests test_func on all items of sequence and items of included sub-iterables . | train | true |
34,672 | def _validate_parse_dates_arg(parse_dates):
msg = "Only booleans, lists, and dictionaries are accepted for the 'parse_dates' parameter"
if (parse_dates is not None):
if is_scalar(parse_dates):
if (not lib.is_bool(parse_dates)):
raise TypeError(msg)
elif (not isinstance(parse_dates, (list, dict))):
raise TypeError(msg)
return parse_dates
| [
"def",
"_validate_parse_dates_arg",
"(",
"parse_dates",
")",
":",
"msg",
"=",
"\"Only booleans, lists, and dictionaries are accepted for the 'parse_dates' parameter\"",
"if",
"(",
"parse_dates",
"is",
"not",
"None",
")",
":",
"if",
"is_scalar",
"(",
"parse_dates",
")",
":... | check whether or not the parse_dates parameter is a non-boolean scalar . | train | true |
34,673 | def _get_free_port(host):
s = socket.socket()
s.bind((host, 0))
port = s.getsockname()[1]
s.close()
return port
| [
"def",
"_get_free_port",
"(",
"host",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
")",
"s",
".",
"bind",
"(",
"(",
"host",
",",
"0",
")",
")",
"port",
"=",
"s",
".",
"getsockname",
"(",
")",
"[",
"1",
"]",
"s",
".",
"close",
"(",
")",
... | gets a free port by opening a socket . | train | false |
34,675 | def load_iris():
return np.load(load_data_file('iris/iris.npz', force_download='2014-09-04'))
| [
"def",
"load_iris",
"(",
")",
":",
"return",
"np",
".",
"load",
"(",
"load_data_file",
"(",
"'iris/iris.npz'",
",",
"force_download",
"=",
"'2014-09-04'",
")",
")"
] | load the iris dataset returns iris : npzfile data[data] : a numpy array with the iris features data[group] : a numpy array with the iris group . | train | false |
34,676 | def build_wedge_text_source(df, start_col='start', end_col='end', center_col='centers'):
(x, y) = polar_to_cartesian(df[center_col], df[start_col], df[end_col])
df = add_text_label_from_index(df)
df['text_angle'] = calc_text_angle(df['start'], df['end'])
df.ix[((df.level == 0), 'text_angle')] = 0.0
text_source = ColumnDataSource(dict(text=df['text'], x=x, y=y, text_angle=df['text_angle']))
return text_source
| [
"def",
"build_wedge_text_source",
"(",
"df",
",",
"start_col",
"=",
"'start'",
",",
"end_col",
"=",
"'end'",
",",
"center_col",
"=",
"'centers'",
")",
":",
"(",
"x",
",",
"y",
")",
"=",
"polar_to_cartesian",
"(",
"df",
"[",
"center_col",
"]",
",",
"df",
... | generate columndatasource for text representation of donut levels . | train | false |
34,677 | @task(throws=(StaleDocumentsRenderingInProgress,))
def acquire_render_lock():
if render_lock.locked():
raise StaleDocumentsRenderingInProgress
render_lock.acquire()
| [
"@",
"task",
"(",
"throws",
"=",
"(",
"StaleDocumentsRenderingInProgress",
",",
")",
")",
"def",
"acquire_render_lock",
"(",
")",
":",
"if",
"render_lock",
".",
"locked",
"(",
")",
":",
"raise",
"StaleDocumentsRenderingInProgress",
"render_lock",
".",
"acquire",
... | a task to acquire the render document lock . | train | false |
34,678 | def inc_ts(timestamp, milliseconds=1):
dt = ts_to_dt(timestamp)
dt += datetime.timedelta(milliseconds=milliseconds)
return dt_to_ts(dt)
| [
"def",
"inc_ts",
"(",
"timestamp",
",",
"milliseconds",
"=",
"1",
")",
":",
"dt",
"=",
"ts_to_dt",
"(",
"timestamp",
")",
"dt",
"+=",
"datetime",
".",
"timedelta",
"(",
"milliseconds",
"=",
"milliseconds",
")",
"return",
"dt_to_ts",
"(",
"dt",
")"
] | increment a timestamp by milliseconds . | train | false |
34,679 | def debug_cohort_mgmt(request, course_key_string):
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string)
get_course_with_access(request.user, 'staff', course_key)
context = {'cohorts_url': reverse('cohorts', kwargs={'course_key': course_key.to_deprecated_string()})}
return render_to_response('/course_groups/debug.html', context)
| [
"def",
"debug_cohort_mgmt",
"(",
"request",
",",
"course_key_string",
")",
":",
"course_key",
"=",
"SlashSeparatedCourseKey",
".",
"from_deprecated_string",
"(",
"course_key_string",
")",
"get_course_with_access",
"(",
"request",
".",
"user",
",",
"'staff'",
",",
"cou... | debugging view for dev . | train | false |
34,680 | def dup_zz_factor_sqf(f, K):
(cont, g) = dup_primitive(f, K)
n = dup_degree(g)
if (dup_LC(g, K) < 0):
(cont, g) = ((- cont), dup_neg(g, K))
if (n <= 0):
return (cont, [])
elif (n == 1):
return (cont, [g])
if query('USE_IRREDUCIBLE_IN_FACTOR'):
if dup_zz_irreducible_p(g, K):
return (cont, [g])
factors = None
if query('USE_CYCLOTOMIC_FACTOR'):
factors = dup_zz_cyclotomic_factor(g, K)
if (factors is None):
factors = dup_zz_zassenhaus(g, K)
return (cont, _sort_factors(factors, multiple=False))
| [
"def",
"dup_zz_factor_sqf",
"(",
"f",
",",
"K",
")",
":",
"(",
"cont",
",",
"g",
")",
"=",
"dup_primitive",
"(",
"f",
",",
"K",
")",
"n",
"=",
"dup_degree",
"(",
"g",
")",
"if",
"(",
"dup_LC",
"(",
"g",
",",
"K",
")",
"<",
"0",
")",
":",
"(... | factor square-free polyomials in z[x] . | train | false |
34,682 | def indexOf(a, b):
for (i, j) in enumerate(a):
if (j == b):
return i
else:
raise ValueError('sequence.index(x): x not in sequence')
| [
"def",
"indexOf",
"(",
"a",
",",
"b",
")",
":",
"for",
"(",
"i",
",",
"j",
")",
"in",
"enumerate",
"(",
"a",
")",
":",
"if",
"(",
"j",
"==",
"b",
")",
":",
"return",
"i",
"else",
":",
"raise",
"ValueError",
"(",
"'sequence.index(x): x not in sequen... | return the first index of b in a . | train | true |
34,683 | def safe_copyfileobj(fsrc, fdst, length=(16 * 1024), size=0):
if (not size):
return
while (size > 0):
buf = fsrc.read(min(length, size))
if (not buf):
break
fdst.write(buf)
size -= len(buf)
| [
"def",
"safe_copyfileobj",
"(",
"fsrc",
",",
"fdst",
",",
"length",
"=",
"(",
"16",
"*",
"1024",
")",
",",
"size",
"=",
"0",
")",
":",
"if",
"(",
"not",
"size",
")",
":",
"return",
"while",
"(",
"size",
">",
"0",
")",
":",
"buf",
"=",
"fsrc",
... | a version of shutil . | train | false |
34,684 | def config_fallocate_value(reserve_value):
try:
if (str(reserve_value[(-1):]) == '%'):
reserve_value = float(reserve_value[:(-1)])
is_percent = True
else:
reserve_value = int(reserve_value)
is_percent = False
except ValueError:
raise ValueError(('Error: %s is an invalid value for fallocate_reserve.' % reserve_value))
return (reserve_value, is_percent)
| [
"def",
"config_fallocate_value",
"(",
"reserve_value",
")",
":",
"try",
":",
"if",
"(",
"str",
"(",
"reserve_value",
"[",
"(",
"-",
"1",
")",
":",
"]",
")",
"==",
"'%'",
")",
":",
"reserve_value",
"=",
"float",
"(",
"reserve_value",
"[",
":",
"(",
"-... | returns fallocate reserve_value as an int or float . | train | false |
34,686 | def get_dasharray(obj):
if (obj.__dict__.get('_dashSeq') is not None):
return ','.join(map(str, obj._dashSeq))
else:
ls = obj.get_linestyle()
dasharray = LINESTYLES.get(ls, 'not found')
if (dasharray == 'not found'):
warnings.warn("line style '{0}' not understood: defaulting to solid line.".format(ls))
dasharray = LINESTYLES['solid']
return dasharray
| [
"def",
"get_dasharray",
"(",
"obj",
")",
":",
"if",
"(",
"obj",
".",
"__dict__",
".",
"get",
"(",
"'_dashSeq'",
")",
"is",
"not",
"None",
")",
":",
"return",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"obj",
".",
"_dashSeq",
")",
")",
"else... | get an svg dash array for the given matplotlib linestyle parameters obj : matplotlib object the matplotlib line or path object . | train | true |
34,687 | def _resolve_map(request, id, permission='base.change_resourcebase', msg=_PERMISSION_MSG_GENERIC, **kwargs):
if id.isdigit():
key = 'pk'
else:
key = 'urlsuffix'
return resolve_object(request, Map, {key: id}, permission=permission, permission_msg=msg, **kwargs)
| [
"def",
"_resolve_map",
"(",
"request",
",",
"id",
",",
"permission",
"=",
"'base.change_resourcebase'",
",",
"msg",
"=",
"_PERMISSION_MSG_GENERIC",
",",
"**",
"kwargs",
")",
":",
"if",
"id",
".",
"isdigit",
"(",
")",
":",
"key",
"=",
"'pk'",
"else",
":",
... | resolve the map by the provided typename and check the optional permission . | train | false |
34,688 | @register.inclusion_tag('zinnia/tags/dummy.html')
def get_recent_comments(number=5, template='zinnia/tags/comments_recent.html'):
entry_published_pks = map(smart_text, Entry.published.values_list('id', flat=True))
content_type = ContentType.objects.get_for_model(Entry)
comments = get_comment_model().objects.filter((Q(flags=None) | Q(flags__flag=CommentFlag.MODERATOR_APPROVAL)), content_type=content_type, object_pk__in=entry_published_pks, is_public=True).order_by('-pk')[:number]
comments = comments.prefetch_related('content_object')
return {'template': template, 'comments': comments}
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"'zinnia/tags/dummy.html'",
")",
"def",
"get_recent_comments",
"(",
"number",
"=",
"5",
",",
"template",
"=",
"'zinnia/tags/comments_recent.html'",
")",
":",
"entry_published_pks",
"=",
"map",
"(",
"smart_text",
",",
"Entr... | return the most recent comments . | train | true |
34,690 | def neighborhood(centerIndex, radius, dimensions):
centerPosition = coordinatesFromIndex(centerIndex, dimensions)
intervals = []
for (i, dimension) in enumerate(dimensions):
left = max(0, (centerPosition[i] - radius))
right = min((dimension - 1), (centerPosition[i] + radius))
intervals.append(xrange(left, (right + 1)))
coords = numpy.array(list(itertools.product(*intervals)))
return numpy.ravel_multi_index(coords.T, dimensions)
| [
"def",
"neighborhood",
"(",
"centerIndex",
",",
"radius",
",",
"dimensions",
")",
":",
"centerPosition",
"=",
"coordinatesFromIndex",
"(",
"centerIndex",
",",
"dimensions",
")",
"intervals",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"dimension",
")",
"in",
"enume... | get the points in the neighborhood of a point . | train | true |
34,691 | def clean_str(string, TREC=False):
string = re.sub("[^A-Za-z0-9(),!?\\'\\`]", ' ', string)
string = re.sub("\\'s", " 's", string)
string = re.sub("\\'ve", " 've", string)
string = re.sub("n\\'t", " n't", string)
string = re.sub("\\'re", " 're", string)
string = re.sub("\\'d", " 'd", string)
string = re.sub("\\'ll", " 'll", string)
string = re.sub(',', ' , ', string)
string = re.sub('!', ' ! ', string)
string = re.sub('\\(', ' \\( ', string)
string = re.sub('\\)', ' \\) ', string)
string = re.sub('\\?', ' \\? ', string)
string = re.sub('\\s{2,}', ' ', string)
return (string.strip() if TREC else string.strip().lower())
| [
"def",
"clean_str",
"(",
"string",
",",
"TREC",
"=",
"False",
")",
":",
"string",
"=",
"re",
".",
"sub",
"(",
"\"[^A-Za-z0-9(),!?\\\\'\\\\`]\"",
",",
"' '",
",",
"string",
")",
"string",
"=",
"re",
".",
"sub",
"(",
"\"\\\\'s\"",
",",
"\" 's\"",
",",
"s... | tokenization/string cleaning for all datasets except for sst . | train | false |
34,692 | def DeleteUser(username, token=None):
token = data_store.GetDefaultToken(token)
user_urn = ('aff4:/users/%s' % username)
try:
aff4.FACTORY.Open(user_urn, users.GRRUser, token=token)
except aff4.InstantiationError:
EPrint(('User %s not found.' % username))
return
aff4.FACTORY.Delete(user_urn, token=token)
EPrint(('User %s has been deleted.' % username))
events.Events.PublishEvent('Audit', events.AuditEvent(user=token.username, action='USER_DELETE', urn=user_urn), token=token)
| [
"def",
"DeleteUser",
"(",
"username",
",",
"token",
"=",
"None",
")",
":",
"token",
"=",
"data_store",
".",
"GetDefaultToken",
"(",
"token",
")",
"user_urn",
"=",
"(",
"'aff4:/users/%s'",
"%",
"username",
")",
"try",
":",
"aff4",
".",
"FACTORY",
".",
"Op... | deletes an existing user . | train | false |
34,693 | def symptom_usability_of_credential_fernet_key_repository():
fernet_utils = utils.FernetUtils(CONF.credential.key_repository, credential_fernet.MAX_ACTIVE_KEYS)
return (('fernet' in CONF.credential.provider) and (not fernet_utils.validate_key_repository()))
| [
"def",
"symptom_usability_of_credential_fernet_key_repository",
"(",
")",
":",
"fernet_utils",
"=",
"utils",
".",
"FernetUtils",
"(",
"CONF",
".",
"credential",
".",
"key_repository",
",",
"credential_fernet",
".",
"MAX_ACTIVE_KEYS",
")",
"return",
"(",
"(",
"'fernet'... | credential key repository is not setup correctly . | train | false |
34,694 | def close_cn(cn=None):
if cn:
cn.close()
print(u'Closed connection: {0}.'.format(cn.dsn))
| [
"def",
"close_cn",
"(",
"cn",
"=",
"None",
")",
":",
"if",
"cn",
":",
"cn",
".",
"close",
"(",
")",
"print",
"(",
"u'Closed connection: {0}.'",
".",
"format",
"(",
"cn",
".",
"dsn",
")",
")"
] | close connection . | train | false |
34,695 | @aborts
@with_settings(foo=())
def test_require_key_exists_empty_tuple():
require('foo')
| [
"@",
"aborts",
"@",
"with_settings",
"(",
"foo",
"=",
"(",
")",
")",
"def",
"test_require_key_exists_empty_tuple",
"(",
")",
":",
"require",
"(",
"'foo'",
")"
] | when given a single existing key but the value is an empty tuple . | train | false |
34,696 | def configuration(f):
import click
from functools import update_wrapper
@click.pass_context
def inner(ctx, *args, **kwargs):
if (os.environ.get('_SENTRY_SKIP_CONFIGURATION') != '1'):
from sentry.runner import configure
configure()
return ctx.invoke(f, *args, **kwargs)
return update_wrapper(inner, f)
| [
"def",
"configuration",
"(",
"f",
")",
":",
"import",
"click",
"from",
"functools",
"import",
"update_wrapper",
"@",
"click",
".",
"pass_context",
"def",
"inner",
"(",
"ctx",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"os",
".",
"envir... | load and configure sentry . | train | false |
34,697 | def get_ordered_locations(locations, **kwargs):
return locations
| [
"def",
"get_ordered_locations",
"(",
"locations",
",",
"**",
"kwargs",
")",
":",
"return",
"locations"
] | order image location list by configured strategy . | train | false |
34,698 | @qutescheme.add_handler('pdfjs', backend=usertypes.Backend.QtWebKit)
def qute_pdfjs(url):
try:
data = pdfjs.get_pdfjs_res(url.path())
except pdfjs.PDFJSNotFound as e:
log.misc.warning('pdfjs resource requested but not found: {}'.format(e.path))
raise qutescheme.QuteSchemeError("Can't find pdfjs resource '{}'".format(e.path), QNetworkReply.ContentNotFoundError)
else:
(mimetype, _encoding) = mimetypes.guess_type(url.fileName())
assert (mimetype is not None), url
return (mimetype, data)
| [
"@",
"qutescheme",
".",
"add_handler",
"(",
"'pdfjs'",
",",
"backend",
"=",
"usertypes",
".",
"Backend",
".",
"QtWebKit",
")",
"def",
"qute_pdfjs",
"(",
"url",
")",
":",
"try",
":",
"data",
"=",
"pdfjs",
".",
"get_pdfjs_res",
"(",
"url",
".",
"path",
"... | handler for qute://pdfjs . | train | false |
34,699 | def send_email_when_changes_email(old_email, new_email):
send_email(to=old_email, action=USER_CHANGE_EMAIL, subject=MAILS[USER_CHANGE_EMAIL]['subject'], html=MAILS[USER_CHANGE_EMAIL]['message'].format(email=old_email, new_email=new_email))
| [
"def",
"send_email_when_changes_email",
"(",
"old_email",
",",
"new_email",
")",
":",
"send_email",
"(",
"to",
"=",
"old_email",
",",
"action",
"=",
"USER_CHANGE_EMAIL",
",",
"subject",
"=",
"MAILS",
"[",
"USER_CHANGE_EMAIL",
"]",
"[",
"'subject'",
"]",
",",
"... | account confirmation . | train | false |
34,700 | def handle_reindex(request):
mapping_type_names = [name.replace('check_', '') for name in request.POST.keys() if name.startswith('check_')]
reindex(mapping_type_names)
return HttpResponseRedirect(request.path)
| [
"def",
"handle_reindex",
"(",
"request",
")",
":",
"mapping_type_names",
"=",
"[",
"name",
".",
"replace",
"(",
"'check_'",
",",
"''",
")",
"for",
"name",
"in",
"request",
".",
"POST",
".",
"keys",
"(",
")",
"if",
"name",
".",
"startswith",
"(",
"'chec... | caculates and kicks off indexing tasks . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.