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 |
|---|---|---|---|---|---|
27,579 | def dictsortreversed(value, arg):
decorated = [(resolve_variable(('var.' + arg), {'var': item}), item) for item in value]
decorated.sort()
decorated.reverse()
return [item[1] for item in decorated]
| [
"def",
"dictsortreversed",
"(",
"value",
",",
"arg",
")",
":",
"decorated",
"=",
"[",
"(",
"resolve_variable",
"(",
"(",
"'var.'",
"+",
"arg",
")",
",",
"{",
"'var'",
":",
"item",
"}",
")",
",",
"item",
")",
"for",
"item",
"in",
"value",
"]",
"deco... | takes a list of dicts . | train | false |
27,580 | def clean_whitespace(chatbot, statement):
import re
statement.text = statement.text.replace('\n', ' ').replace('\r', ' ').replace(' DCTB ', ' ')
statement.text = statement.text.strip()
statement.text = re.sub(' +', ' ', statement.text)
return statement
| [
"def",
"clean_whitespace",
"(",
"chatbot",
",",
"statement",
")",
":",
"import",
"re",
"statement",
".",
"text",
"=",
"statement",
".",
"text",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")",
".",
"replace",
"(",
"'\\r'",
",",
"' '",
")",
".",
"replace"... | remove any consecutive whitespace characters from the statement text . | train | true |
27,582 | def test_start_with_text(hist):
hist.start('f')
assert ('first' in hist._tmphist)
assert ('fourth' in hist._tmphist)
assert ('second' not in hist._tmphist)
| [
"def",
"test_start_with_text",
"(",
"hist",
")",
":",
"hist",
".",
"start",
"(",
"'f'",
")",
"assert",
"(",
"'first'",
"in",
"hist",
".",
"_tmphist",
")",
"assert",
"(",
"'fourth'",
"in",
"hist",
".",
"_tmphist",
")",
"assert",
"(",
"'second'",
"not",
... | test start with given text . | train | false |
27,584 | def ip_extra(mod_attr):
IPY_SHOULD_NOT_IMPL.write((mod_attr + '\n'))
IPY_SHOULD_NOT_IMPL.flush()
| [
"def",
"ip_extra",
"(",
"mod_attr",
")",
":",
"IPY_SHOULD_NOT_IMPL",
".",
"write",
"(",
"(",
"mod_attr",
"+",
"'\\n'",
")",
")",
"IPY_SHOULD_NOT_IMPL",
".",
"flush",
"(",
")"
] | logs a module attribute ip provides . | train | false |
27,585 | def fullVersion(partial):
if (partial in ('', 'latest', None)):
return latestVersion()
for tag in availableVersions(local=False):
if tag.startswith(partial):
return tag
return ''
| [
"def",
"fullVersion",
"(",
"partial",
")",
":",
"if",
"(",
"partial",
"in",
"(",
"''",
",",
"'latest'",
",",
"None",
")",
")",
":",
"return",
"latestVersion",
"(",
")",
"for",
"tag",
"in",
"availableVersions",
"(",
"local",
"=",
"False",
")",
":",
"i... | expands a special name or a partial tag to the highest patch level in that series . | train | false |
27,587 | def _send_command(cmd, worker, lbn, target, profile='default', tgt_type='glob'):
ret = {'code': False, 'msg': 'OK', 'minions': []}
func = 'modjk.{0}'.format(cmd)
args = [worker, lbn, profile]
response = __salt__['publish.publish'](target, func, args, tgt_type)
errors = []
minions = []
for minion in response:
minions.append(minion)
if (not response[minion]):
errors.append(minion)
if (not response):
ret['msg'] = 'no servers answered the published command {0}'.format(cmd)
return ret
elif (len(errors) > 0):
ret['msg'] = 'the following minions return False'
ret['minions'] = errors
return ret
else:
ret['code'] = True
ret['msg'] = 'the commad was published successfully'
ret['minions'] = minions
return ret
| [
"def",
"_send_command",
"(",
"cmd",
",",
"worker",
",",
"lbn",
",",
"target",
",",
"profile",
"=",
"'default'",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"ret",
"=",
"{",
"'code'",
":",
"False",
",",
"'msg'",
":",
"'OK'",
",",
"'minions'",
":",
"[",
... | send a command to the modjk loadbalancer the minion need to be able to publish the commands to the load balancer cmd: worker_stop - wont get any traffic from the lbn worker_activate - activate the worker worker_disable - will get traffic only for current sessions . | train | true |
27,589 | def GetHttpContext():
global _threadLocalContext
return _threadLocalContext.__dict__.setdefault('httpCtx', dict())
| [
"def",
"GetHttpContext",
"(",
")",
":",
"global",
"_threadLocalContext",
"return",
"_threadLocalContext",
".",
"__dict__",
".",
"setdefault",
"(",
"'httpCtx'",
",",
"dict",
"(",
")",
")"
] | get the http context for the current thread . | train | false |
27,590 | def _verify_run(out, cmd=None):
if (out.get('retcode', 0) and out['stderr']):
if cmd:
log.debug("Command: '{0}'".format(cmd))
log.debug('Return code: {0}'.format(out.get('retcode')))
log.debug('Error output:\n{0}'.format(out.get('stderr', 'N/A')))
raise CommandExecutionError(out['stderr'])
| [
"def",
"_verify_run",
"(",
"out",
",",
"cmd",
"=",
"None",
")",
":",
"if",
"(",
"out",
".",
"get",
"(",
"'retcode'",
",",
"0",
")",
"and",
"out",
"[",
"'stderr'",
"]",
")",
":",
"if",
"cmd",
":",
"log",
".",
"debug",
"(",
"\"Command: '{0}'\"",
".... | crash to the log if command execution was not successful . | train | true |
27,591 | def database_setup(context):
KALiteTestCase.setUpDatabase()
| [
"def",
"database_setup",
"(",
"context",
")",
":",
"KALiteTestCase",
".",
"setUpDatabase",
"(",
")"
] | behave features are analogous to test suites . | train | false |
27,593 | def normpdf(x, *args):
(mu, sigma) = args
return ((1.0 / (np.sqrt((2 * np.pi)) * sigma)) * np.exp(((-0.5) * (((1.0 / sigma) * (x - mu)) ** 2))))
| [
"def",
"normpdf",
"(",
"x",
",",
"*",
"args",
")",
":",
"(",
"mu",
",",
"sigma",
")",
"=",
"args",
"return",
"(",
"(",
"1.0",
"/",
"(",
"np",
".",
"sqrt",
"(",
"(",
"2",
"*",
"np",
".",
"pi",
")",
")",
"*",
"sigma",
")",
")",
"*",
"np",
... | return the normal pdf evaluated at *x*; args provides *mu* . | train | false |
27,594 | def AddELBInstance(region, instance_id, node_type):
balancers = GetLoadBalancers(region, node_types=[node_type])
assert balancers, ('No %s load balancer in region %s' % (node_type, region))
assert (len(balancers) == 1)
b = balancers[0]
b.register_instances([instance_id])
print ('Added instance %s to %s load balancer in region %s' % (instance_id, node_type, region))
| [
"def",
"AddELBInstance",
"(",
"region",
",",
"instance_id",
",",
"node_type",
")",
":",
"balancers",
"=",
"GetLoadBalancers",
"(",
"region",
",",
"node_types",
"=",
"[",
"node_type",
"]",
")",
"assert",
"balancers",
",",
"(",
"'No %s load balancer in region %s'",
... | add an instance to the load balancer in region . | train | false |
27,595 | def _expiry_range_all(session, upper_bound_func):
(yield upper_bound_func())
| [
"def",
"_expiry_range_all",
"(",
"session",
",",
"upper_bound_func",
")",
":",
"(",
"yield",
"upper_bound_func",
"(",
")",
")"
] | expire all tokens in one pass . | train | false |
27,596 | def deref_tag(tag):
while True:
try:
tag = tag.object
except AttributeError:
break
return tag
| [
"def",
"deref_tag",
"(",
"tag",
")",
":",
"while",
"True",
":",
"try",
":",
"tag",
"=",
"tag",
".",
"object",
"except",
"AttributeError",
":",
"break",
"return",
"tag"
] | recursively dereference a tag and return the resulting object . | train | false |
27,597 | def get_pil_version():
try:
__import__('PIL', fromlist=[str('Image')])
return (0,)
except ImportError:
return None
| [
"def",
"get_pil_version",
"(",
")",
":",
"try",
":",
"__import__",
"(",
"'PIL'",
",",
"fromlist",
"=",
"[",
"str",
"(",
"'Image'",
")",
"]",
")",
"return",
"(",
"0",
",",
")",
"except",
"ImportError",
":",
"return",
"None"
] | return image magick version or none if it is unavailable try importing pil . | train | false |
27,598 | @block_user_agents
@require_GET
def without_parent(request):
docs = Document.objects.filter_for_list(locale=request.LANGUAGE_CODE, noparent=True)
paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE)
context = {'documents': paginated_docs, 'count': docs.count(), 'noparent': True}
return render(request, 'wiki/list/documents.html', context)
| [
"@",
"block_user_agents",
"@",
"require_GET",
"def",
"without_parent",
"(",
"request",
")",
":",
"docs",
"=",
"Document",
".",
"objects",
".",
"filter_for_list",
"(",
"locale",
"=",
"request",
".",
"LANGUAGE_CODE",
",",
"noparent",
"=",
"True",
")",
"paginated... | lists wiki documents without parent . | train | false |
27,599 | def snippet_list(request, page=None):
if (not test_user_authenticated(request)):
return login(request, next='/cobbler_web/snippet/list', expired=True)
snippets = remote.get_autoinstall_snippets(request.session['token'])
snippet_list = []
for snippet in snippets:
snippet_list.append((snippet, 'editable'))
t = get_template('snippet_list.tmpl')
html = t.render(RequestContext(request, {'what': 'snippet', 'snippets': snippet_list, 'version': remote.extended_version(request.session['token'])['version'], 'username': username}))
return HttpResponse(html)
| [
"def",
"snippet_list",
"(",
"request",
",",
"page",
"=",
"None",
")",
":",
"if",
"(",
"not",
"test_user_authenticated",
"(",
"request",
")",
")",
":",
"return",
"login",
"(",
"request",
",",
"next",
"=",
"'/cobbler_web/snippet/list'",
",",
"expired",
"=",
... | this page lists all available snippets and has links to edit them . | train | false |
27,600 | def get_object_attrs(obj):
attrs = [k for k in dir(obj) if (not k.startswith('__'))]
if (not attrs):
attrs = dir(obj)
return attrs
| [
"def",
"get_object_attrs",
"(",
"obj",
")",
":",
"attrs",
"=",
"[",
"k",
"for",
"k",
"in",
"dir",
"(",
"obj",
")",
"if",
"(",
"not",
"k",
".",
"startswith",
"(",
"'__'",
")",
")",
"]",
"if",
"(",
"not",
"attrs",
")",
":",
"attrs",
"=",
"dir",
... | get the attributes of an object using dir . | train | true |
27,601 | def split_otu_table_on_taxonomy_to_files(otu_table_fp, level, output_dir, md_identifier='taxonomy', md_processor=process_md_as_list):
results = []
otu_table = load_table(otu_table_fp)
create_dir(output_dir)
def split_f(id_, obs_md):
try:
result = md_processor(obs_md, md_identifier, level)
except KeyError:
raise KeyError(('Metadata identifier (%s) is not associated with all (or any) observerations. You can modify the key with the md_identifier parameter.' % md_identifier))
except TypeError:
raise TypeError("Can't correctly process the metadata string. If your input file was generated from QIIME 1.4.0 or earlier you may need to pass --md_as_string.")
except AttributeError:
raise AttributeError('Metadata category not found. If your input file was generated from QIIME 1.4.0 or earlier you may need to pass --md_identifier "Consensus Lineage".')
return result
for (bin, sub_otu_table) in otu_table.partition(split_f, axis='observation'):
output_fp = ('%s/otu_table_%s.biom' % (output_dir, bin))
write_biom_table(sub_otu_table, output_fp)
results.append(output_fp)
return results
| [
"def",
"split_otu_table_on_taxonomy_to_files",
"(",
"otu_table_fp",
",",
"level",
",",
"output_dir",
",",
"md_identifier",
"=",
"'taxonomy'",
",",
"md_processor",
"=",
"process_md_as_list",
")",
":",
"results",
"=",
"[",
"]",
"otu_table",
"=",
"load_table",
"(",
"... | split otu table by taxonomic level . | train | false |
27,602 | @pytest.mark.parametrize('exc, name, exc_text', [(ValueError('exception'), 'ValueError', 'exception'), (ValueError, 'ValueError', 'none'), (ipc.Error, 'misc.ipc.Error', 'none'), (Error, 'test_error.Error', 'none')])
def test_no_err_windows(caplog, exc, name, exc_text, fake_args):
fake_args.no_err_windows = True
try:
raise exc
except Exception as e:
with caplog.at_level(logging.ERROR):
error.handle_fatal_exc(e, fake_args, 'title', pre_text='pre', post_text='post')
assert (len(caplog.records) == 1)
expected = ['Handling fatal {} with --no-err-windows!'.format(name), '', 'title: title', 'pre_text: pre', 'post_text: post', 'exception text: {}'.format(exc_text)]
assert (caplog.records[0].msg == '\n'.join(expected))
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'exc, name, exc_text'",
",",
"[",
"(",
"ValueError",
"(",
"'exception'",
")",
",",
"'ValueError'",
",",
"'exception'",
")",
",",
"(",
"ValueError",
",",
"'ValueError'",
",",
"'none'",
")",
",",
"(",
"ip... | test handle_fatal_exc with no_err_windows = true . | train | false |
27,604 | def location(mod_name):
source = ((mod_name.endswith('pyc') and mod_name[:(-1)]) or mod_name)
source = os.path.abspath(source)
return (source, os.path.dirname(source))
| [
"def",
"location",
"(",
"mod_name",
")",
":",
"source",
"=",
"(",
"(",
"mod_name",
".",
"endswith",
"(",
"'pyc'",
")",
"and",
"mod_name",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
"or",
"mod_name",
")",
"source",
"=",
"os",
".",
"path",
".",
"abspa... | return the file and directory that the code for *mod_name* is in . | train | false |
27,605 | def test_label_rotation(Chart):
chart = Chart(x_label_rotation=28, y_label_rotation=76)
chart.add('1', [4, (-5), 123, 59, 38])
chart.add('2', [89, 0, 8, 0.12, 8])
if (not chart._dual):
chart.x_labels = ['one', 'twoooooooooooooooooooooo', 'three', '4']
q = chart.render_pyquery()
if (Chart in (Line, Bar)):
assert (len(q('.axis.x text[transform^="rotate(28"]')) == 4)
assert (len(q('.axis.y text[transform^="rotate(76"]')) == 13)
| [
"def",
"test_label_rotation",
"(",
"Chart",
")",
":",
"chart",
"=",
"Chart",
"(",
"x_label_rotation",
"=",
"28",
",",
"y_label_rotation",
"=",
"76",
")",
"chart",
".",
"add",
"(",
"'1'",
",",
"[",
"4",
",",
"(",
"-",
"5",
")",
",",
"123",
",",
"59"... | test label rotation option . | train | false |
27,606 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | create a new rc2 cipher . | train | false |
27,607 | def user_agent():
data = {'installer': {'name': 'pip', 'version': pip.__version__}, 'python': platform.python_version(), 'implementation': {'name': platform.python_implementation()}}
if (data['implementation']['name'] == 'CPython'):
data['implementation']['version'] = platform.python_version()
elif (data['implementation']['name'] == 'PyPy'):
if (sys.pypy_version_info.releaselevel == 'final'):
pypy_version_info = sys.pypy_version_info[:3]
else:
pypy_version_info = sys.pypy_version_info
data['implementation']['version'] = '.'.join([str(x) for x in pypy_version_info])
elif (data['implementation']['name'] == 'Jython'):
data['implementation']['version'] = platform.python_version()
elif (data['implementation']['name'] == 'IronPython'):
data['implementation']['version'] = platform.python_version()
if sys.platform.startswith('linux'):
from pip._vendor import distro
distro_infos = dict(filter((lambda x: x[1]), zip(['name', 'version', 'id'], distro.linux_distribution())))
libc = dict(filter((lambda x: x[1]), zip(['lib', 'version'], libc_ver())))
if libc:
distro_infos['libc'] = libc
if distro_infos:
data['distro'] = distro_infos
if (sys.platform.startswith('darwin') and platform.mac_ver()[0]):
data['distro'] = {'name': 'macOS', 'version': platform.mac_ver()[0]}
if platform.system():
data.setdefault('system', {})['name'] = platform.system()
if platform.release():
data.setdefault('system', {})['release'] = platform.release()
if platform.machine():
data['cpu'] = platform.machine()
if (HAS_TLS and (sys.version_info[:2] > (2, 6))):
data['openssl_version'] = ssl.OPENSSL_VERSION
return '{data[installer][name]}/{data[installer][version]} {json}'.format(data=data, json=json.dumps(data, separators=(',', ':'), sort_keys=True))
| [
"def",
"user_agent",
"(",
")",
":",
"data",
"=",
"{",
"'installer'",
":",
"{",
"'name'",
":",
"'pip'",
",",
"'version'",
":",
"pip",
".",
"__version__",
"}",
",",
"'python'",
":",
"platform",
".",
"python_version",
"(",
")",
",",
"'implementation'",
":",... | builds a simple user-agent string to send in requests . | train | true |
27,610 | def chmod(target):
assert isinstance(target, str)
assert os.path.exists(target)
file_mode = (stat.S_IRUSR | stat.S_IWUSR)
folder_mode = ((stat.S_IRUSR | stat.S_IWUSR) | stat.S_IXUSR)
remove_immutable_attribute(target)
if os.path.isfile(target):
os.chmod(target, file_mode)
elif os.path.isdir(target):
os.chmod(target, folder_mode)
for (root, dirs, files) in os.walk(target):
for cur_dir in dirs:
os.chmod(os.path.join(root, cur_dir), folder_mode)
for cur_file in files:
os.chmod(os.path.join(root, cur_file), file_mode)
else:
raise ValueError('Unsupported file type: {}'.format(target))
| [
"def",
"chmod",
"(",
"target",
")",
":",
"assert",
"isinstance",
"(",
"target",
",",
"str",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
"file_mode",
"=",
"(",
"stat",
".",
"S_IRUSR",
"|",
"stat",
".",
"S_IWUSR",
")",
"folder_... | recursively set the chmod for files to 0600 and 0700 for folders . | train | true |
27,611 | def _tap(tap, runas=None):
if (tap in _list_taps()):
return True
cmd = 'brew tap {0}'.format(tap)
try:
_call_brew(cmd)
except CommandExecutionError:
log.error('Failed to tap "{0}"'.format(tap))
return False
return True
| [
"def",
"_tap",
"(",
"tap",
",",
"runas",
"=",
"None",
")",
":",
"if",
"(",
"tap",
"in",
"_list_taps",
"(",
")",
")",
":",
"return",
"True",
"cmd",
"=",
"'brew tap {0}'",
".",
"format",
"(",
"tap",
")",
"try",
":",
"_call_brew",
"(",
"cmd",
")",
"... | add unofficial github repos to the list of formulas that brew tracks . | train | true |
27,612 | def _findFriends(tg, sep=': ', lock=True, getLastMessage=False):
return _listFriends(_matchFriends(tg, _readFriends())[0:5], sep, lock, getLastMessage)
| [
"def",
"_findFriends",
"(",
"tg",
",",
"sep",
"=",
"': '",
",",
"lock",
"=",
"True",
",",
"getLastMessage",
"=",
"False",
")",
":",
"return",
"_listFriends",
"(",
"_matchFriends",
"(",
"tg",
",",
"_readFriends",
"(",
")",
")",
"[",
"0",
":",
"5",
"]"... | searches for friends and returns them . | train | false |
27,613 | def write_descriptor_styles(output_root):
return _write_styles('.xmodule_edit', output_root, _list_descriptors())
| [
"def",
"write_descriptor_styles",
"(",
"output_root",
")",
":",
"return",
"_write_styles",
"(",
"'.xmodule_edit'",
",",
"output_root",
",",
"_list_descriptors",
"(",
")",
")"
] | write all registered xmoduledescriptor css . | train | false |
27,614 | def _node_not_implemented(node_name, cls):
def f(self, *args, **kwargs):
raise NotImplementedError('{0!r} nodes are not implemented'.format(node_name))
return f
| [
"def",
"_node_not_implemented",
"(",
"node_name",
",",
"cls",
")",
":",
"def",
"f",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'{0!r} nodes are not implemented'",
".",
"format",
"(",
"node_name",
")",
... | return a function that raises a notimplementederror with a passed node name . | train | true |
27,615 | def test_invalid_location_download_noconnect():
from ..data import download_file
with pytest.raises(IOError):
download_file(u'http://astropy.org/nonexistentfile')
| [
"def",
"test_invalid_location_download_noconnect",
"(",
")",
":",
"from",
".",
".",
"data",
"import",
"download_file",
"with",
"pytest",
".",
"raises",
"(",
"IOError",
")",
":",
"download_file",
"(",
"u'http://astropy.org/nonexistentfile'",
")"
] | checks that download_file gives an ioerror if the socket is blocked . | train | false |
27,616 | def gethdr(fp):
if (fp.read(4) != MAGIC):
raise error, 'gethdr: bad magic word'
hdr_size = get_long_be(fp.read(4))
data_size = get_long_be(fp.read(4))
encoding = get_long_be(fp.read(4))
sample_rate = get_long_be(fp.read(4))
channels = get_long_be(fp.read(4))
excess = (hdr_size - 24)
if (excess < 0):
raise error, 'gethdr: bad hdr_size'
if (excess > 0):
info = fp.read(excess)
else:
info = ''
return (data_size, encoding, sample_rate, channels, info)
| [
"def",
"gethdr",
"(",
"fp",
")",
":",
"if",
"(",
"fp",
".",
"read",
"(",
"4",
")",
"!=",
"MAGIC",
")",
":",
"raise",
"error",
",",
"'gethdr: bad magic word'",
"hdr_size",
"=",
"get_long_be",
"(",
"fp",
".",
"read",
"(",
"4",
")",
")",
"data_size",
... | read a sound header from an open file . | train | false |
27,617 | def uptodate_index(quiet=True, max_age=86400):
from fabtools.require import file as require_file
require_file('/etc/apt/apt.conf.d/15fabtools-update-stamp', contents='APT::Update::Post-Invoke-Success {"touch /var/lib/apt/periodic/fabtools-update-success-stamp 2>/dev/null || true";};\n', use_sudo=True)
if ((system.time() - last_update_time()) > _to_seconds(max_age)):
update_index(quiet=quiet)
| [
"def",
"uptodate_index",
"(",
"quiet",
"=",
"True",
",",
"max_age",
"=",
"86400",
")",
":",
"from",
"fabtools",
".",
"require",
"import",
"file",
"as",
"require_file",
"require_file",
"(",
"'/etc/apt/apt.conf.d/15fabtools-update-stamp'",
",",
"contents",
"=",
"'AP... | require an up-to-date package index . | train | false |
27,618 | def splituser(host):
global _userprog
if (_userprog is None):
import re
_userprog = re.compile('^(.*)@(.*)$')
match = _userprog.match(host)
if match:
return match.group(1, 2)
return (None, host)
| [
"def",
"splituser",
"(",
"host",
")",
":",
"global",
"_userprog",
"if",
"(",
"_userprog",
"is",
"None",
")",
":",
"import",
"re",
"_userprog",
"=",
"re",
".",
"compile",
"(",
"'^(.*)@(.*)$'",
")",
"match",
"=",
"_userprog",
".",
"match",
"(",
"host",
"... | splituser --> user[:passwd] . | train | true |
27,619 | def get_encryption_oracle(secret_name):
assert (secret_name in ('SECRET_ENCRYPTION_KEY', 'BLOCK_ENCRYPTION_KEY'))
return _EncryptionOracle(secret_name)
| [
"def",
"get_encryption_oracle",
"(",
"secret_name",
")",
":",
"assert",
"(",
"secret_name",
"in",
"(",
"'SECRET_ENCRYPTION_KEY'",
",",
"'BLOCK_ENCRYPTION_KEY'",
")",
")",
"return",
"_EncryptionOracle",
"(",
"secret_name",
")"
] | return an encryption oracle for the given secret . | train | false |
27,621 | def AdvSearch(document, search, bs=3):
searchre = re.compile(search)
matches = []
searchels = []
for element in document.getiterator():
if (element.tag == ('{%s}t' % nsprefixes['w'])):
if element.text:
searchels.append(element)
if (len(searchels) > bs):
searchels.pop(0)
found = False
for l in range(1, (len(searchels) + 1)):
if found:
break
for s in range(len(searchels)):
if found:
break
if ((s + l) <= len(searchels)):
e = range(s, (s + l))
txtsearch = ''
for k in e:
txtsearch += searchels[k].text
match = searchre.search(txtsearch)
if match:
matches.append(match.group())
found = True
return set(matches)
| [
"def",
"AdvSearch",
"(",
"document",
",",
"search",
",",
"bs",
"=",
"3",
")",
":",
"searchre",
"=",
"re",
".",
"compile",
"(",
"search",
")",
"matches",
"=",
"[",
"]",
"searchels",
"=",
"[",
"]",
"for",
"element",
"in",
"document",
".",
"getiterator"... | return set of all regex matches this is an advanced version of python-docx . | train | true |
27,622 | def convert_all_kernels_in_model(model):
conv_classes = {'Convolution1D', 'Convolution2D', 'Convolution3D', 'AtrousConvolution2D', 'Deconvolution2D'}
to_assign = []
for layer in model.layers:
if (layer.__class__.__name__ in conv_classes):
original_w = K.get_value(layer.W)
converted_w = convert_kernel(original_w)
to_assign.append((layer.W, converted_w))
K.batch_set_value(to_assign)
| [
"def",
"convert_all_kernels_in_model",
"(",
"model",
")",
":",
"conv_classes",
"=",
"{",
"'Convolution1D'",
",",
"'Convolution2D'",
",",
"'Convolution3D'",
",",
"'AtrousConvolution2D'",
",",
"'Deconvolution2D'",
"}",
"to_assign",
"=",
"[",
"]",
"for",
"layer",
"in",... | converts all convolution kernels in a model from theano to tensorflow . | train | false |
27,623 | def variable_closure(variables, casify):
def render_variable(children):
'\n Replace greek letters, otherwise escape the variable names.\n '
varname = children[0].latex
if (casify(varname) not in variables):
pass
(first, _, second) = varname.partition('_')
if second:
varname = u'{a}_{{{b}}}'.format(a=enrich_varname(first), b=enrich_varname(second))
else:
varname = enrich_varname(varname)
return LatexRendered(varname)
return render_variable
| [
"def",
"variable_closure",
"(",
"variables",
",",
"casify",
")",
":",
"def",
"render_variable",
"(",
"children",
")",
":",
"varname",
"=",
"children",
"[",
"0",
"]",
".",
"latex",
"if",
"(",
"casify",
"(",
"varname",
")",
"not",
"in",
"variables",
")",
... | wrap render_variable so it knows the variables allowed . | train | false |
27,624 | def expanduser(path):
return path
| [
"def",
"expanduser",
"(",
"path",
")",
":",
"return",
"path"
] | expand ~ and ~user constructions . | train | false |
27,626 | def is_generator_function(obj):
CO_GENERATOR = 32
return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and (obj.func_code.co_flags & CO_GENERATOR)))
| [
"def",
"is_generator_function",
"(",
"obj",
")",
":",
"CO_GENERATOR",
"=",
"32",
"return",
"bool",
"(",
"(",
"(",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
")",
"and",
"(",
"obj",
".",
"func_code"... | return true if the object is a user-defined generator function . | train | true |
27,629 | def setAttributesToMultipliedTetragrid(elementNode, tetragrid):
setElementNodeDictionaryMatrix(elementNode, getBranchMatrix(elementNode).getOtherTimesSelf(tetragrid))
| [
"def",
"setAttributesToMultipliedTetragrid",
"(",
"elementNode",
",",
"tetragrid",
")",
":",
"setElementNodeDictionaryMatrix",
"(",
"elementNode",
",",
"getBranchMatrix",
"(",
"elementNode",
")",
".",
"getOtherTimesSelf",
"(",
"tetragrid",
")",
")"
] | set the element attribute dictionary and element matrix to the matrix times the tetragrid . | train | false |
27,631 | def _get_user_profile_dict(request, usernames):
request.GET = request.GET.copy()
request.GET['username'] = usernames
user_profile_details = AccountViewSet.as_view({'get': 'list'})(request).data
return {user['username']: user for user in user_profile_details}
| [
"def",
"_get_user_profile_dict",
"(",
"request",
",",
"usernames",
")",
":",
"request",
".",
"GET",
"=",
"request",
".",
"GET",
".",
"copy",
"(",
")",
"request",
".",
"GET",
"[",
"'username'",
"]",
"=",
"usernames",
"user_profile_details",
"=",
"AccountViewS... | gets user profile details for a list of usernames and creates a dictionary with profile details against username . | train | false |
27,632 | def validate_password_strength(value):
password_validators = [validate_password_length, validate_password_complexity, validate_password_dictionary]
for validator in password_validators:
validator(value)
| [
"def",
"validate_password_strength",
"(",
"value",
")",
":",
"password_validators",
"=",
"[",
"validate_password_length",
",",
"validate_password_complexity",
",",
"validate_password_dictionary",
"]",
"for",
"validator",
"in",
"password_validators",
":",
"validator",
"(",
... | this function loops through each validator defined in this file and applies it to a users proposed password args: value: a users proposed password returns: none . | train | false |
27,633 | def createsuperuser(settings_module, username, email, bin_env=None, database=None, pythonpath=None, env=None):
args = ['noinput']
kwargs = dict(email=email, username=username)
if database:
kwargs['database'] = database
return command(settings_module, 'createsuperuser', bin_env, pythonpath, env, *args, **kwargs)
| [
"def",
"createsuperuser",
"(",
"settings_module",
",",
"username",
",",
"email",
",",
"bin_env",
"=",
"None",
",",
"database",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"args",
"=",
"[",
"'noinput'",
"]",
"kwargs",
... | create a super user for the database . | train | true |
27,634 | def _retrieve_igd_profile(url):
try:
return urllib2.urlopen(url.geturl(), timeout=5).read().decode('utf-8')
except socket.error:
raise IGDError('IGD profile query timed out')
| [
"def",
"_retrieve_igd_profile",
"(",
"url",
")",
":",
"try",
":",
"return",
"urllib2",
".",
"urlopen",
"(",
"url",
".",
"geturl",
"(",
")",
",",
"timeout",
"=",
"5",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"socket",
... | retrieve the devices upnp profile . | train | false |
27,635 | def trace_api(f):
@functools.wraps(f)
def trace_api_logging_wrapper(*args, **kwargs):
if TRACE_API:
return trace(f)(*args, **kwargs)
return f(*args, **kwargs)
return trace_api_logging_wrapper
| [
"def",
"trace_api",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"trace_api_logging_wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"TRACE_API",
":",
"return",
"trace",
"(",
"f",
")",
"(",
"*",
"args",
... | decorates a function if trace_api is true . | train | false |
27,636 | def plot_with_error(y, error, x=None, axes=None, value_fmt='k', error_fmt='k--', alpha=0.05, stderr_type='asym'):
import matplotlib.pyplot as plt
if (axes is None):
axes = plt.gca()
x = (x if (x is not None) else lrange(len(y)))
plot_action = (lambda y, fmt: axes.plot(x, y, fmt))
plot_action(y, value_fmt)
if (error is not None):
if (stderr_type == 'asym'):
q = util.norm_signif_level(alpha)
plot_action((y - (q * error)), error_fmt)
plot_action((y + (q * error)), error_fmt)
if (stderr_type in ('mc', 'sz1', 'sz2', 'sz3')):
plot_action(error[0], error_fmt)
plot_action(error[1], error_fmt)
| [
"def",
"plot_with_error",
"(",
"y",
",",
"error",
",",
"x",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"value_fmt",
"=",
"'k'",
",",
"error_fmt",
"=",
"'k--'",
",",
"alpha",
"=",
"0.05",
",",
"stderr_type",
"=",
"'asym'",
")",
":",
"import",
"matplo... | make plot with optional error bars parameters y : error : array or none . | train | false |
27,638 | def tolux(raw):
return pow(10, (raw * LOG_LUX_RATIO))
| [
"def",
"tolux",
"(",
"raw",
")",
":",
"return",
"pow",
"(",
"10",
",",
"(",
"raw",
"*",
"LOG_LUX_RATIO",
")",
")"
] | used if lux_ain is set to between 0 and 7; indicating that the iosync light meter peripheral is attached to that analog input line . | train | false |
27,640 | def remove_accents(input_str):
nkfd_form = unicodedata.normalize(u'NFKD', force_text(input_str))
only_ascii = nkfd_form.encode(u'ASCII', u'ignore')
return only_ascii
| [
"def",
"remove_accents",
"(",
"input_str",
")",
":",
"nkfd_form",
"=",
"unicodedata",
".",
"normalize",
"(",
"u'NFKD'",
",",
"force_text",
"(",
"input_str",
")",
")",
"only_ascii",
"=",
"nkfd_form",
".",
"encode",
"(",
"u'ASCII'",
",",
"u'ignore'",
")",
"ret... | remove accents from characters in the given string . | train | false |
27,642 | @contextmanager
def webserver(app, port=0, host=None):
server = build_web_server(app, port, (host or '127.0.0.1'))
(host, port) = server.socket.getsockname()
import threading
thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': 0.5})
thread.setDaemon(True)
thread.start()
try:
(yield ('http://%s:%s/' % (host, port)))
finally:
server.shutdown()
server.server_close()
| [
"@",
"contextmanager",
"def",
"webserver",
"(",
"app",
",",
"port",
"=",
"0",
",",
"host",
"=",
"None",
")",
":",
"server",
"=",
"build_web_server",
"(",
"app",
",",
"port",
",",
"(",
"host",
"or",
"'127.0.0.1'",
")",
")",
"(",
"host",
",",
"port",
... | context manager entry point for the with statement . | train | false |
27,644 | def instance_tag_get_by_instance_uuid(context, instance_uuid):
return IMPL.instance_tag_get_by_instance_uuid(context, instance_uuid)
| [
"def",
"instance_tag_get_by_instance_uuid",
"(",
"context",
",",
"instance_uuid",
")",
":",
"return",
"IMPL",
".",
"instance_tag_get_by_instance_uuid",
"(",
"context",
",",
"instance_uuid",
")"
] | get all tags for a given instance . | train | false |
27,645 | def fileopen(file):
return _posixfile_().fileopen(file)
| [
"def",
"fileopen",
"(",
"file",
")",
":",
"return",
"_posixfile_",
"(",
")",
".",
"fileopen",
"(",
"file",
")"
] | public routine to get a posixfile object from a python file object . | train | false |
27,646 | def next_key(key):
mutable_key = list(key)
mutable_key[(-1)] = chr((ord(key[(-1)]) + 1))
return ''.join(mutable_key)
| [
"def",
"next_key",
"(",
"key",
")",
":",
"mutable_key",
"=",
"list",
"(",
"key",
")",
"mutable_key",
"[",
"(",
"-",
"1",
")",
"]",
"=",
"chr",
"(",
"(",
"ord",
"(",
"key",
"[",
"(",
"-",
"1",
")",
"]",
")",
"+",
"1",
")",
")",
"return",
"''... | processes a tuple of 2-element tuples and returns the key which comes after the given key . | train | false |
27,650 | def reset_all_groups():
useradmin.conf.DEFAULT_USER_GROUP.set_for_testing(None)
for grp in Group.objects.all():
grp.delete()
| [
"def",
"reset_all_groups",
"(",
")",
":",
"useradmin",
".",
"conf",
".",
"DEFAULT_USER_GROUP",
".",
"set_for_testing",
"(",
"None",
")",
"for",
"grp",
"in",
"Group",
".",
"objects",
".",
"all",
"(",
")",
":",
"grp",
".",
"delete",
"(",
")"
] | reset to a clean state by deleting all groups . | train | false |
27,652 | def get_last_seen_notifications_msec(user_id):
subscriptions_model = user_models.UserSubscriptionsModel.get(user_id, strict=False)
return (utils.get_time_in_millisecs(subscriptions_model.last_checked) if (subscriptions_model and subscriptions_model.last_checked) else None)
| [
"def",
"get_last_seen_notifications_msec",
"(",
"user_id",
")",
":",
"subscriptions_model",
"=",
"user_models",
".",
"UserSubscriptionsModel",
".",
"get",
"(",
"user_id",
",",
"strict",
"=",
"False",
")",
"return",
"(",
"utils",
".",
"get_time_in_millisecs",
"(",
... | returns the last time . | train | false |
27,653 | def device_count():
_lazy_init()
return torch._C._cuda_getDeviceCount()
| [
"def",
"device_count",
"(",
")",
":",
"_lazy_init",
"(",
")",
"return",
"torch",
".",
"_C",
".",
"_cuda_getDeviceCount",
"(",
")"
] | returns the number of gpus available . | train | false |
27,654 | def extract_background_data(background):
if (not background):
return None
step_data = [extract_step_data(step) for step in background.steps]
return {'meta': {'total': len(background.steps), 'success': sum([s['meta']['success'] for s in step_data]), 'failures': sum([s['meta']['failed'] for s in step_data]), 'skipped': sum([s['meta']['skipped'] for s in step_data]), 'undefined': sum([s['meta']['undefined'] for s in step_data])}, 'steps': step_data}
| [
"def",
"extract_background_data",
"(",
"background",
")",
":",
"if",
"(",
"not",
"background",
")",
":",
"return",
"None",
"step_data",
"=",
"[",
"extract_step_data",
"(",
"step",
")",
"for",
"step",
"in",
"background",
".",
"steps",
"]",
"return",
"{",
"'... | extract data from a background instance . | train | false |
27,655 | @aggregate(_(u'Count of'))
def aggregate_count(items, col):
return len(list(items))
| [
"@",
"aggregate",
"(",
"_",
"(",
"u'Count of'",
")",
")",
"def",
"aggregate_count",
"(",
"items",
",",
"col",
")",
":",
"return",
"len",
"(",
"list",
"(",
"items",
")",
")"
] | function to use on group by charts . | train | false |
27,656 | def run_state_change(change, deployer, state_persister):
with change.eliot_action.context():
context = DeferredContext(maybeDeferred(change.run, deployer=deployer, state_persister=state_persister))
context.addActionFinish()
return context.result
| [
"def",
"run_state_change",
"(",
"change",
",",
"deployer",
",",
"state_persister",
")",
":",
"with",
"change",
".",
"eliot_action",
".",
"context",
"(",
")",
":",
"context",
"=",
"DeferredContext",
"(",
"maybeDeferred",
"(",
"change",
".",
"run",
",",
"deplo... | apply the change to local state . | train | false |
27,657 | def _maybe_to_sparse(array):
if isinstance(array, ABCSparseSeries):
array = array.values.copy()
return array
| [
"def",
"_maybe_to_sparse",
"(",
"array",
")",
":",
"if",
"isinstance",
"(",
"array",
",",
"ABCSparseSeries",
")",
":",
"array",
"=",
"array",
".",
"values",
".",
"copy",
"(",
")",
"return",
"array"
] | array must be sparseseries or sparsearray . | train | true |
27,659 | def sh_command_with(f, *args):
args = list(args)
out = []
for n in range(len(args)):
args[n] = sh_string(args[n])
if hasattr(f, '__call__'):
out.append(f(*args))
else:
out.append((f % tuple(args)))
return ';'.join(out)
| [
"def",
"sh_command_with",
"(",
"f",
",",
"*",
"args",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"out",
"=",
"[",
"]",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"args",
")",
")",
":",
"args",
"[",
"n",
"]",
"=",
"sh_string",
"(",
"arg... | sh_command_with -> command returns a command create by evaluating f whenever f is a function and f % otherwise . | train | false |
27,660 | @register.tag
@blocktag(end_prefix=u'end_')
def for_review_request_field(context, nodelist, review_request_details, fieldset):
s = []
request = context.get(u'request')
if isinstance(fieldset, six.text_type):
fieldset = get_review_request_fieldset(fieldset)
for field_cls in fieldset.field_classes:
try:
field = field_cls(review_request_details, request=request)
except Exception as e:
logging.exception(u'Error instantiating field %r: %s', field_cls, e)
continue
try:
if field.should_render(field.value):
context.push()
context[u'field'] = field
s.append(nodelist.render(context))
context.pop()
except Exception as e:
logging.exception(u'Error running should_render for field %r: %s', field_cls, e)
return u''.join(s)
| [
"@",
"register",
".",
"tag",
"@",
"blocktag",
"(",
"end_prefix",
"=",
"u'end_'",
")",
"def",
"for_review_request_field",
"(",
"context",
",",
"nodelist",
",",
"review_request_details",
",",
"fieldset",
")",
":",
"s",
"=",
"[",
"]",
"request",
"=",
"context",... | loops through all fields in a fieldset . | train | false |
27,661 | def update_geometry(obj):
def _update_geometry():
'Actually update the geometry if the object still exists.'
if sip.isdeleted(obj):
return
obj.updateGeometry()
QTimer.singleShot(0, _update_geometry)
| [
"def",
"update_geometry",
"(",
"obj",
")",
":",
"def",
"_update_geometry",
"(",
")",
":",
"if",
"sip",
".",
"isdeleted",
"(",
"obj",
")",
":",
"return",
"obj",
".",
"updateGeometry",
"(",
")",
"QTimer",
".",
"singleShot",
"(",
"0",
",",
"_update_geometry... | weird workaround for some weird pyqt bug . | train | false |
27,664 | def upload_media(request, form_cls, up_file_callback, instance=None, **kwargs):
form = form_cls(request.POST, request.FILES)
if ((request.method == 'POST') and form.is_valid()):
return up_file_callback(request.FILES, request.user, **kwargs)
elif (not form.is_valid()):
return form.errors
return None
| [
"def",
"upload_media",
"(",
"request",
",",
"form_cls",
",",
"up_file_callback",
",",
"instance",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"form",
"=",
"form_cls",
"(",
"request",
".",
"POST",
",",
"request",
".",
"FILES",
")",
"if",
"(",
"(",
"requ... | uploads media files and returns a list with information about each media: name . | train | false |
27,667 | def task_status_show(context, data_dict):
model = context['model']
id = data_dict.get('id')
if id:
task_status = model.TaskStatus.get(id)
else:
query = model.Session.query(model.TaskStatus).filter(_and_((model.TaskStatus.entity_id == _get_or_bust(data_dict, 'entity_id')), (model.TaskStatus.task_type == _get_or_bust(data_dict, 'task_type')), (model.TaskStatus.key == _get_or_bust(data_dict, 'key'))))
task_status = query.first()
context['task_status'] = task_status
_check_access('task_status_show', context, data_dict)
if (task_status is None):
raise NotFound
task_status_dict = model_dictize.task_status_dictize(task_status, context)
return task_status_dict
| [
"def",
"task_status_show",
"(",
"context",
",",
"data_dict",
")",
":",
"model",
"=",
"context",
"[",
"'model'",
"]",
"id",
"=",
"data_dict",
".",
"get",
"(",
"'id'",
")",
"if",
"id",
":",
"task_status",
"=",
"model",
".",
"TaskStatus",
".",
"get",
"(",... | return a task status . | train | false |
27,668 | def _When(val):
try:
return (_EPOCH + datetime.timedelta(microseconds=val))
except OverflowError:
return _OverflowDateTime(val)
| [
"def",
"_When",
"(",
"val",
")",
":",
"try",
":",
"return",
"(",
"_EPOCH",
"+",
"datetime",
".",
"timedelta",
"(",
"microseconds",
"=",
"val",
")",
")",
"except",
"OverflowError",
":",
"return",
"_OverflowDateTime",
"(",
"val",
")"
] | coverts a gd_when value to the appropriate type . | train | false |
27,669 | def to_current_timezone(value):
if (settings.USE_TZ and (value is not None) and timezone.is_aware(value)):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
| [
"def",
"to_current_timezone",
"(",
"value",
")",
":",
"if",
"(",
"settings",
".",
"USE_TZ",
"and",
"(",
"value",
"is",
"not",
"None",
")",
"and",
"timezone",
".",
"is_aware",
"(",
"value",
")",
")",
":",
"current_timezone",
"=",
"timezone",
".",
"get_cur... | when time zone support is enabled . | train | false |
27,670 | def linmod(y, x, weights=None, sigma=None, add_const=True, filter_missing=True, **kwds):
if filter_missing:
(y, x) = remove_nanrows(y, x)
if add_const:
x = sm.add_constant(x, prepend=True)
if (not (sigma is None)):
return GLS(y, x, sigma=sigma, **kwds)
elif (not (weights is None)):
return WLS(y, x, weights=weights, **kwds)
else:
return OLS(y, x, **kwds)
| [
"def",
"linmod",
"(",
"y",
",",
"x",
",",
"weights",
"=",
"None",
",",
"sigma",
"=",
"None",
",",
"add_const",
"=",
"True",
",",
"filter_missing",
"=",
"True",
",",
"**",
"kwds",
")",
":",
"if",
"filter_missing",
":",
"(",
"y",
",",
"x",
")",
"="... | get linear model with extra options for entry dispatches to regular model class and does not wrap the output if several options are exclusive . | train | false |
27,671 | def update_vlan_binding(netid, newvlanid=None, newvlanname=None):
LOG.debug(_('update_vlan_binding() called'))
session = db.get_session()
try:
binding = session.query(l2network_models.VlanBinding).filter_by(network_id=netid).one()
if newvlanid:
binding['vlan_id'] = newvlanid
if newvlanname:
binding['vlan_name'] = newvlanname
session.merge(binding)
session.flush()
return binding
except exc.NoResultFound:
raise q_exc.NetworkNotFound(net_id=netid)
| [
"def",
"update_vlan_binding",
"(",
"netid",
",",
"newvlanid",
"=",
"None",
",",
"newvlanname",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"_",
"(",
"'update_vlan_binding() called'",
")",
")",
"session",
"=",
"db",
".",
"get_session",
"(",
")",
"try",... | updates a vlan to network association . | train | false |
27,675 | def memoize_generator(func):
cache = Cache()
def wrapped_func(*args, **kwargs):
params = (args, tuple(sorted(kwargs.items())))
try:
cached = cache[params]
except KeyError:
cached = []
for item in func(*args, **kwargs):
cached.append(item)
(yield item)
cache[params] = cached
else:
for item in cached:
(yield item)
return wrapped_func
| [
"def",
"memoize_generator",
"(",
"func",
")",
":",
"cache",
"=",
"Cache",
"(",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"params",
"=",
"(",
"args",
",",
"tuple",
"(",
"sorted",
"(",
"kwargs",
".",
"items",
"(",
"... | memoize decorator for generators store func results in a cache according to their arguments as memoize does but instead this works on decorators instead of regular functions . | train | false |
27,676 | def _get_runlevel():
out = __salt__['cmd.run']('runlevel')
if ('unknown' in out):
return '2'
else:
return out.split()[1]
| [
"def",
"_get_runlevel",
"(",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'runlevel'",
")",
"if",
"(",
"'unknown'",
"in",
"out",
")",
":",
"return",
"'2'",
"else",
":",
"return",
"out",
".",
"split",
"(",
")",
"[",
"1",
"]"
] | returns the current runlevel . | train | false |
27,677 | def console_pool_create(context, values):
return IMPL.console_pool_create(context, values)
| [
"def",
"console_pool_create",
"(",
"context",
",",
"values",
")",
":",
"return",
"IMPL",
".",
"console_pool_create",
"(",
"context",
",",
"values",
")"
] | create console pool . | train | false |
27,678 | def debug_logger(name='test'):
return DebugLogAdapter(DebugLogger(), name)
| [
"def",
"debug_logger",
"(",
"name",
"=",
"'test'",
")",
":",
"return",
"DebugLogAdapter",
"(",
"DebugLogger",
"(",
")",
",",
"name",
")"
] | get a named adapted debug logger . | train | false |
27,679 | def _sum_counters(*counters_list):
result = {}
for counters in counters_list:
for (group, counter_to_amount) in counters.items():
for (counter, amount) in counter_to_amount.items():
result.setdefault(group, {})
result[group].setdefault(counter, 0)
result[group][counter] += amount
return result
| [
"def",
"_sum_counters",
"(",
"*",
"counters_list",
")",
":",
"result",
"=",
"{",
"}",
"for",
"counters",
"in",
"counters_list",
":",
"for",
"(",
"group",
",",
"counter_to_amount",
")",
"in",
"counters",
".",
"items",
"(",
")",
":",
"for",
"(",
"counter",... | combine many maps from group to counter to amount . | train | false |
27,680 | def _protect_original_resources(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
ctx = request.context
if ('resources' in ctx):
orig = ctx.get('protected_resources')
if (not orig):
ctx['protected_resources'] = ctx['resources']
memo = {id(constants.ATTR_NOT_SPECIFIED): constants.ATTR_NOT_SPECIFIED}
ctx['resources'] = copy.deepcopy(ctx['protected_resources'], memo=memo)
return f(*args, **kwargs)
return wrapped
| [
"def",
"_protect_original_resources",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"ctx",
"=",
"request",
".",
"context",
"if",
"(",
"'resources'",
"in",
"ctx",
... | wrapper to ensure that mutated resources are discarded on retries . | train | false |
27,681 | def generate_project_list(config, path):
tmp = ('%s.%d.tmp' % (path, os.getpid()))
f = file(tmp, 'w')
try:
generate_project_list_fp(config=config, fp=f)
finally:
f.close()
os.rename(tmp, path)
| [
"def",
"generate_project_list",
"(",
"config",
",",
"path",
")",
":",
"tmp",
"=",
"(",
"'%s.%d.tmp'",
"%",
"(",
"path",
",",
"os",
".",
"getpid",
"(",
")",
")",
")",
"f",
"=",
"file",
"(",
"tmp",
",",
"'w'",
")",
"try",
":",
"generate_project_list_fp... | generate projects list for gitweb . | train | false |
27,683 | def create_glir_message(commands, array_serialization=None):
if (array_serialization is None):
array_serialization = 'binary'
(commands_modified, buffers) = _extract_buffers(commands)
commands_serialized = [_serialize_command(command_modified) for command_modified in commands_modified]
buffers_serialized = [_serialize_buffer(buffer, array_serialization) for buffer in buffers]
msg = {'msg_type': 'glir_commands', 'commands': commands_serialized, 'buffers': buffers_serialized}
return msg
| [
"def",
"create_glir_message",
"(",
"commands",
",",
"array_serialization",
"=",
"None",
")",
":",
"if",
"(",
"array_serialization",
"is",
"None",
")",
":",
"array_serialization",
"=",
"'binary'",
"(",
"commands_modified",
",",
"buffers",
")",
"=",
"_extract_buffer... | create a json-serializable message of glir commands . | train | true |
27,684 | def dataDecrypt(edata, password, keyLength=32):
if (not edata.startswith(CryptoMarker.encode())):
return (edata, False)
from .py3AES import decryptData
from .py3PBKDF2 import rehashPassword
(hashParametersBytes, edata) = edata[3:].rsplit(Delimiter.encode(), 1)
hashParameters = hashParametersBytes.decode()
try:
key = rehashPassword(password, hashParameters)[:keyLength]
plaintext = decryptData(key, base64.b64decode(edata))
except ValueError:
return (u'', False)
return (plaintext, True)
| [
"def",
"dataDecrypt",
"(",
"edata",
",",
"password",
",",
"keyLength",
"=",
"32",
")",
":",
"if",
"(",
"not",
"edata",
".",
"startswith",
"(",
"CryptoMarker",
".",
"encode",
"(",
")",
")",
")",
":",
"return",
"(",
"edata",
",",
"False",
")",
"from",
... | module function to decrypt a password . | train | false |
27,685 | def test_equality_numpy_scalar():
assert (10 != (10.0 * u.m))
assert (np.int64(10) != (10 * u.m))
assert ((10 * u.m) != np.int64(10))
| [
"def",
"test_equality_numpy_scalar",
"(",
")",
":",
"assert",
"(",
"10",
"!=",
"(",
"10.0",
"*",
"u",
".",
"m",
")",
")",
"assert",
"(",
"np",
".",
"int64",
"(",
"10",
")",
"!=",
"(",
"10",
"*",
"u",
".",
"m",
")",
")",
"assert",
"(",
"(",
"1... | a regression test to ensure that numpy scalars are correctly compared . | train | false |
27,686 | def _linux_set_networking():
vmware_tools_bin = None
if os.path.exists('/usr/sbin/vmtoolsd'):
vmware_tools_bin = '/usr/sbin/vmtoolsd'
elif os.path.exists('/usr/bin/vmtoolsd'):
vmware_tools_bin = '/usr/bin/vmtoolsd'
elif os.path.exists('/usr/sbin/vmware-guestd'):
vmware_tools_bin = '/usr/sbin/vmware-guestd'
elif os.path.exists('/usr/bin/vmware-guestd'):
vmware_tools_bin = '/usr/bin/vmware-guestd'
if vmware_tools_bin:
cmd = [vmware_tools_bin, '--cmd', 'machine.id.get']
network_details = _parse_network_details(_execute(cmd, check_exit_code=False))
if (platform.dist()[0] == 'Ubuntu'):
_set_ubuntu_networking(network_details)
elif (platform.dist()[0] == 'redhat'):
_set_rhel_networking(network_details)
else:
logging.warn((_("Distro '%s' not supported") % platform.dist()[0]))
else:
logging.warn(_('VMware Tools is not installed'))
| [
"def",
"_linux_set_networking",
"(",
")",
":",
"vmware_tools_bin",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'/usr/sbin/vmtoolsd'",
")",
":",
"vmware_tools_bin",
"=",
"'/usr/sbin/vmtoolsd'",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"'/us... | set ip address for the linux vm . | train | false |
27,687 | def set_indent(TokenClass, implicit=False):
def callback(lexer, match, context):
text = match.group()
if (context.indent < context.next_indent):
context.indent_stack.append(context.indent)
context.indent = context.next_indent
if (not implicit):
context.next_indent += len(text)
(yield (match.start(), TokenClass, text))
context.pos = match.end()
return callback
| [
"def",
"set_indent",
"(",
"TokenClass",
",",
"implicit",
"=",
"False",
")",
":",
"def",
"callback",
"(",
"lexer",
",",
"match",
",",
"context",
")",
":",
"text",
"=",
"match",
".",
"group",
"(",
")",
"if",
"(",
"context",
".",
"indent",
"<",
"context... | set the previously saved indentation level . | train | true |
27,688 | def get_certificate_header_context(is_secure=True):
data = dict(logo_src=branding_api.get_logo_url(is_secure), logo_url=branding_api.get_base_url(is_secure))
return data
| [
"def",
"get_certificate_header_context",
"(",
"is_secure",
"=",
"True",
")",
":",
"data",
"=",
"dict",
"(",
"logo_src",
"=",
"branding_api",
".",
"get_logo_url",
"(",
"is_secure",
")",
",",
"logo_url",
"=",
"branding_api",
".",
"get_base_url",
"(",
"is_secure",
... | return data to be used in certificate header . | train | false |
27,690 | @webob.dec.wsgify
@util.require_content('application/json')
def update_resource_provider(req):
uuid = util.wsgi_path_item(req.environ, 'uuid')
context = req.environ['placement.context']
resource_provider = objects.ResourceProvider.get_by_uuid(context, uuid)
data = util.extract_json(req.body, PUT_RESOURCE_PROVIDER_SCHEMA)
resource_provider.name = data['name']
try:
resource_provider.save()
except db_exc.DBDuplicateEntry as exc:
raise webob.exc.HTTPConflict((_('Conflicting resource provider already exists: %(error)s') % {'error': exc}), json_formatter=util.json_error_formatter)
except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest((_('Unable to save resource provider %(rp_uuid)s: %(error)s') % {'rp_uuid': uuid, 'error': exc}), json_formatter=util.json_error_formatter)
req.response.body = encodeutils.to_utf8(jsonutils.dumps(_serialize_provider(req.environ, resource_provider)))
req.response.status = 200
req.response.content_type = 'application/json'
return req.response
| [
"@",
"webob",
".",
"dec",
".",
"wsgify",
"@",
"util",
".",
"require_content",
"(",
"'application/json'",
")",
"def",
"update_resource_provider",
"(",
"req",
")",
":",
"uuid",
"=",
"util",
".",
"wsgi_path_item",
"(",
"req",
".",
"environ",
",",
"'uuid'",
")... | put to update a single resource provider . | train | false |
27,691 | def _check_coil_frame(coils, coord_frame, bem):
if (coord_frame != FIFF.FIFFV_COORD_MRI):
if (coord_frame == FIFF.FIFFV_COORD_HEAD):
(coils, coord_Frame) = _dup_coil_set(coils, coord_frame, bem['head_mri_t'])
else:
raise RuntimeError(('Bad coil coordinate frame %s' % coord_frame))
return (coils, coord_frame)
| [
"def",
"_check_coil_frame",
"(",
"coils",
",",
"coord_frame",
",",
"bem",
")",
":",
"if",
"(",
"coord_frame",
"!=",
"FIFF",
".",
"FIFFV_COORD_MRI",
")",
":",
"if",
"(",
"coord_frame",
"==",
"FIFF",
".",
"FIFFV_COORD_HEAD",
")",
":",
"(",
"coils",
",",
"c... | check to make sure the coils are in the correct coordinate frame . | train | false |
27,692 | @pytest.fixture(autouse=True, scope='session')
def instrument_jinja():
import jinja2
old_render = jinja2.Template.render
def instrumented_render(self, *args, **kwargs):
context = dict(*args, **kwargs)
test.signals.template_rendered.send(sender=self, template=self, context=context)
return old_render(self, *args, **kwargs)
jinja2.Template.render = instrumented_render
| [
"@",
"pytest",
".",
"fixture",
"(",
"autouse",
"=",
"True",
",",
"scope",
"=",
"'session'",
")",
"def",
"instrument_jinja",
"(",
")",
":",
"import",
"jinja2",
"old_render",
"=",
"jinja2",
".",
"Template",
".",
"render",
"def",
"instrumented_render",
"(",
"... | make sure the "templates" list in a response is properly updated . | train | false |
27,693 | def list_visitor(state, components):
(f, lpart, pstack) = state
partition = []
for i in range((lpart + 1)):
part = []
for ps in pstack[f[i]:f[(i + 1)]]:
if (ps.v > 0):
part.extend(([components[ps.c]] * ps.v))
partition.append(part)
return partition
| [
"def",
"list_visitor",
"(",
"state",
",",
"components",
")",
":",
"(",
"f",
",",
"lpart",
",",
"pstack",
")",
"=",
"state",
"partition",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"(",
"lpart",
"+",
"1",
")",
")",
":",
"part",
"=",
"[",
"]"... | return a list of lists to represent the partition . | train | false |
27,694 | def julia_code(expr, assign_to=None, **settings):
return JuliaCodePrinter(settings).doprint(expr, assign_to)
| [
"def",
"julia_code",
"(",
"expr",
",",
"assign_to",
"=",
"None",
",",
"**",
"settings",
")",
":",
"return",
"JuliaCodePrinter",
"(",
"settings",
")",
".",
"doprint",
"(",
"expr",
",",
"assign_to",
")"
] | converts expr to a string of julia code . | train | false |
27,695 | def setup_users():
from django.core.cache import cache
global TEST_USER_OBJECTS
if (TEST_USER_OBJECTS is None):
key = 'test_user_objects'
user_objects = cache.get(key)
if ((not user_objects) or TEST_USER_FORCE_CREATE):
logger.info('test user cache not found, rebuilding')
user_objects = {}
app_token = FacebookAuthorization.get_app_access_token()
for (user_slug, user_dict) in TEST_USER_DICT.items():
test_user = FacebookAuthorization.get_or_create_test_user(app_token, name=user_dict['name'], force_create=TEST_USER_FORCE_CREATE, permissions=user_dict.get('permissions'))
user_objects[user_slug] = test_user
cache.set(key, user_objects, (60 * 60))
TEST_USER_OBJECTS = user_objects
return TEST_USER_OBJECTS
| [
"def",
"setup_users",
"(",
")",
":",
"from",
"django",
".",
"core",
".",
"cache",
"import",
"cache",
"global",
"TEST_USER_OBJECTS",
"if",
"(",
"TEST_USER_OBJECTS",
"is",
"None",
")",
":",
"key",
"=",
"'test_user_objects'",
"user_objects",
"=",
"cache",
".",
... | since this is soo slow we only do this once for all tests . | train | false |
27,696 | def install_config(name, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.install_config'](name, **kwargs)
return ret
| [
"def",
"install_config",
"(",
"name",
",",
"**",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt... | loads and commits the configuration provided . | train | true |
27,697 | def glColor(*args, **kargs):
c = mkColor(*args, **kargs)
return ((c.red() / 255.0), (c.green() / 255.0), (c.blue() / 255.0), (c.alpha() / 255.0))
| [
"def",
"glColor",
"(",
"*",
"args",
",",
"**",
"kargs",
")",
":",
"c",
"=",
"mkColor",
"(",
"*",
"args",
",",
"**",
"kargs",
")",
"return",
"(",
"(",
"c",
".",
"red",
"(",
")",
"/",
"255.0",
")",
",",
"(",
"c",
".",
"green",
"(",
")",
"/",
... | convert a color to opengl color format floats 0 . | train | false |
27,698 | @pytest.fixture
def addon_with_files(db):
addon = Addon.objects.create(name='My Addon', slug='my-addon')
version = Version.objects.create(addon=addon)
for status in [amo.STATUS_BETA, amo.STATUS_DISABLED, amo.STATUS_AWAITING_REVIEW, amo.STATUS_AWAITING_REVIEW]:
File.objects.create(version=version, status=status)
return addon
| [
"@",
"pytest",
".",
"fixture",
"def",
"addon_with_files",
"(",
"db",
")",
":",
"addon",
"=",
"Addon",
".",
"objects",
".",
"create",
"(",
"name",
"=",
"'My Addon'",
",",
"slug",
"=",
"'my-addon'",
")",
"version",
"=",
"Version",
".",
"objects",
".",
"c... | return an add-on with one version and four files . | train | false |
27,700 | def right_multiplied_operator(J, d):
J = aslinearoperator(J)
def matvec(x):
return J.matvec((np.ravel(x) * d))
def matmat(X):
return J.matmat((X * d[:, np.newaxis]))
def rmatvec(x):
return (d * J.rmatvec(x))
return LinearOperator(J.shape, matvec=matvec, matmat=matmat, rmatvec=rmatvec)
| [
"def",
"right_multiplied_operator",
"(",
"J",
",",
"d",
")",
":",
"J",
"=",
"aslinearoperator",
"(",
"J",
")",
"def",
"matvec",
"(",
"x",
")",
":",
"return",
"J",
".",
"matvec",
"(",
"(",
"np",
".",
"ravel",
"(",
"x",
")",
"*",
"d",
")",
")",
"... | return j diag(d) as linearoperator . | train | false |
27,701 | def get_rc_exc(rc):
try:
return rc_exc_cache[rc]
except KeyError:
pass
if (rc > 0):
name = ('ErrorReturnCode_%d' % rc)
base = ErrorReturnCode
else:
signame = SIGNAL_MAPPING[abs(rc)]
name = ('SignalException_' + signame)
base = SignalException
exc = ErrorReturnCodeMeta(name, (base,), {'exit_code': rc})
rc_exc_cache[rc] = exc
return exc
| [
"def",
"get_rc_exc",
"(",
"rc",
")",
":",
"try",
":",
"return",
"rc_exc_cache",
"[",
"rc",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"(",
"rc",
">",
"0",
")",
":",
"name",
"=",
"(",
"'ErrorReturnCode_%d'",
"%",
"rc",
")",
"base",
"=",
"ErrorRetur... | takes a exit code or negative signal number and produces an exception that corresponds to that return code . | train | true |
27,702 | def _sort_by_recency(ds):
return sorted(ds, key=_time_sort_key, reverse=True)
| [
"def",
"_sort_by_recency",
"(",
"ds",
")",
":",
"return",
"sorted",
"(",
"ds",
",",
"key",
"=",
"_time_sort_key",
",",
"reverse",
"=",
"True",
")"
] | sort the given list/sequence of dicts containing ids so that the most recent ones come first . | train | false |
27,703 | def _footer_navigation_links():
platform_name = configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME)
return [{'name': link_name, 'title': link_title, 'url': link_url} for (link_name, link_url, link_title) in [('about', marketing_link('ABOUT'), _('About')), ('enterprise', marketing_link('ENTERPRISE'), _('{platform_name} for Business').format(platform_name=platform_name)), ('blog', marketing_link('BLOG'), _('Blog')), ('news', marketing_link('NEWS'), _('News')), ('help-center', settings.SUPPORT_SITE_LINK, _('Help Center')), ('contact', marketing_link('CONTACT'), _('Contact')), ('careers', marketing_link('CAREERS'), _('Careers')), ('donate', marketing_link('DONATE'), _('Donate'))] if (link_url and (link_url != '#'))]
| [
"def",
"_footer_navigation_links",
"(",
")",
":",
"platform_name",
"=",
"configuration_helpers",
".",
"get_value",
"(",
"'platform_name'",
",",
"settings",
".",
"PLATFORM_NAME",
")",
"return",
"[",
"{",
"'name'",
":",
"link_name",
",",
"'title'",
":",
"link_title"... | return the navigation links to display in the footer . | train | false |
27,704 | def add_nonblank_xml_subelement(parent, tag, value):
if ((value is not None) and (value != '')):
XML.SubElement(parent, tag).text = value
| [
"def",
"add_nonblank_xml_subelement",
"(",
"parent",
",",
"tag",
",",
"value",
")",
":",
"if",
"(",
"(",
"value",
"is",
"not",
"None",
")",
"and",
"(",
"value",
"!=",
"''",
")",
")",
":",
"XML",
".",
"SubElement",
"(",
"parent",
",",
"tag",
")",
".... | adds an xml subelement with the name tag to parent if value is a non-empty string . | train | false |
27,705 | def extract_identity_response_info(data):
major = data[12]
minor = data[13]
build = from_7L7M(data[14], data[15])
sn = from_7L7777M(data[16:21])
board_revision = (data[21] if (len(data) > 22) else 0)
return (major, minor, build, sn, board_revision)
| [
"def",
"extract_identity_response_info",
"(",
"data",
")",
":",
"major",
"=",
"data",
"[",
"12",
"]",
"minor",
"=",
"data",
"[",
"13",
"]",
"build",
"=",
"from_7L7M",
"(",
"data",
"[",
"14",
"]",
",",
"data",
"[",
"15",
"]",
")",
"sn",
"=",
"from_7... | extracts the arguments from the identity response: - major version - minor version - build number - serial number - board revision . | train | false |
27,706 | def create_embargo_countries(apps, schema_editor):
country_model = apps.get_model(u'embargo', u'Country')
for (country_code, __) in list(countries):
country_model.objects.get_or_create(country=country_code)
| [
"def",
"create_embargo_countries",
"(",
"apps",
",",
"schema_editor",
")",
":",
"country_model",
"=",
"apps",
".",
"get_model",
"(",
"u'embargo'",
",",
"u'Country'",
")",
"for",
"(",
"country_code",
",",
"__",
")",
"in",
"list",
"(",
"countries",
")",
":",
... | populate the available countries with all 2-character iso country codes . | train | false |
27,708 | @contextmanager
def requirements_file(contents, tmpdir):
path = (tmpdir / 'reqs.txt')
path.write(contents)
(yield path)
path.remove()
| [
"@",
"contextmanager",
"def",
"requirements_file",
"(",
"contents",
",",
"tmpdir",
")",
":",
"path",
"=",
"(",
"tmpdir",
"/",
"'reqs.txt'",
")",
"path",
".",
"write",
"(",
"contents",
")",
"(",
"yield",
"path",
")",
"path",
".",
"remove",
"(",
")"
] | return a path to a requirements file of given contents . | train | false |
27,709 | def encode_json(obj, inline=False, **kwargs):
encoder = JSONEncoder(encoding=u'UTF-8', default=functools.partial(_object_encoder, inline=inline), **kwargs)
return encoder.encode(obj)
| [
"def",
"encode_json",
"(",
"obj",
",",
"inline",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"encoder",
"=",
"JSONEncoder",
"(",
"encoding",
"=",
"u'UTF-8'",
",",
"default",
"=",
"functools",
".",
"partial",
"(",
"_object_encoder",
",",
"inline",
"=",
"... | encode the given object as json . | train | false |
27,712 | def is_valid_multipart_boundary(boundary):
return (_multipart_boundary_re.match(boundary) is not None)
| [
"def",
"is_valid_multipart_boundary",
"(",
"boundary",
")",
":",
"return",
"(",
"_multipart_boundary_re",
".",
"match",
"(",
"boundary",
")",
"is",
"not",
"None",
")"
] | checks if the string given is a valid multipart boundary . | train | false |
27,713 | def _getAdmlDisplayName(adml_xml_data, display_name):
if (display_name.startswith('$(') and display_name.endswith(')')):
display_name = re.sub('(^\\$\\(|\\)$)', '', display_name)
display_name = display_name.split('.')
displayname_type = display_name[0]
displayname_id = display_name[1]
search_results = ADML_DISPLAY_NAME_XPATH(adml_xml_data, displayNameType=displayname_type, displayNameId=displayname_id)
if search_results:
for result in search_results:
return result.text
return None
| [
"def",
"_getAdmlDisplayName",
"(",
"adml_xml_data",
",",
"display_name",
")",
":",
"if",
"(",
"display_name",
".",
"startswith",
"(",
"'$('",
")",
"and",
"display_name",
".",
"endswith",
"(",
"')'",
")",
")",
":",
"display_name",
"=",
"re",
".",
"sub",
"("... | helper function to take the displayname attribute of an element and find the value from the adml data adml_xml_data :: xml data of all adml files to search display_name :: the value of the displayname attribute from the admx entry to search the adml data for . | train | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.