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 |
|---|---|---|---|---|---|
45,556 | def _parse_ddwrt_response(data_str):
return {key: val for (key, val) in _DDWRT_DATA_REGEX.findall(data_str)}
| [
"def",
"_parse_ddwrt_response",
"(",
"data_str",
")",
":",
"return",
"{",
"key",
":",
"val",
"for",
"(",
"key",
",",
"val",
")",
"in",
"_DDWRT_DATA_REGEX",
".",
"findall",
"(",
"data_str",
")",
"}"
] | parse the dd-wrt data format . | train | false |
45,557 | def rotate_right(x, y):
if (len(x) == 0):
return []
y = (len(x) - (y % len(x)))
return (x[y:] + x[:y])
| [
"def",
"rotate_right",
"(",
"x",
",",
"y",
")",
":",
"if",
"(",
"len",
"(",
"x",
")",
"==",
"0",
")",
":",
"return",
"[",
"]",
"y",
"=",
"(",
"len",
"(",
"x",
")",
"-",
"(",
"y",
"%",
"len",
"(",
"x",
")",
")",
")",
"return",
"(",
"x",
... | right rotates a list x by the number of steps specified in y . | train | false |
45,558 | def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None):
if (hostMap is None):
hostMap = {}
hostMap = hostMap.copy()
@provider(IHostnameResolver)
class SimpleNameResolver(object, ):
@staticmethod
def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transpor... | [
"def",
"deterministicResolvingReactor",
"(",
"reactor",
",",
"expectedAddresses",
"=",
"(",
")",
",",
"hostMap",
"=",
"None",
")",
":",
"if",
"(",
"hostMap",
"is",
"None",
")",
":",
"hostMap",
"=",
"{",
"}",
"hostMap",
"=",
"hostMap",
".",
"copy",
"(",
... | create a reactor that will deterministically resolve all hostnames it is passed to the list of addresses given . | train | false |
45,561 | def sin(x):
return Sin()(x)
| [
"def",
"sin",
"(",
"x",
")",
":",
"return",
"Sin",
"(",
")",
"(",
"x",
")"
] | apply sin to each element of the matrix mat . | train | false |
45,562 | def volume_type_get_all_by_group(context, group_id):
return IMPL.volume_type_get_all_by_group(context, group_id)
| [
"def",
"volume_type_get_all_by_group",
"(",
"context",
",",
"group_id",
")",
":",
"return",
"IMPL",
".",
"volume_type_get_all_by_group",
"(",
"context",
",",
"group_id",
")"
] | get all volumes in a group . | train | false |
45,564 | def commit():
connection._commit()
set_clean()
| [
"def",
"commit",
"(",
")",
":",
"connection",
".",
"_commit",
"(",
")",
"set_clean",
"(",
")"
] | commits pending changes . | train | false |
45,565 | def parallel(iterable, count, callable, *args, **named):
coop = task.Cooperator()
work = (callable(elem, *args, **named) for elem in iterable)
return defer.DeferredList([coop.coiterate(work) for _ in range(count)])
| [
"def",
"parallel",
"(",
"iterable",
",",
"count",
",",
"callable",
",",
"*",
"args",
",",
"**",
"named",
")",
":",
"coop",
"=",
"task",
".",
"Cooperator",
"(",
")",
"work",
"=",
"(",
"callable",
"(",
"elem",
",",
"*",
"args",
",",
"**",
"named",
... | execute a callable over the objects in the given iterable . | train | false |
45,566 | def unpack_chunks(hg_unbundle10_obj):
while True:
(length,) = struct.unpack('>l', readexactly(hg_unbundle10_obj, 4))
if (length <= 4):
break
if (length < 84):
raise Exception('negative data length')
(node, p1, p2, cs) = struct.unpack('20s20s20s20s', readexactly(hg_unbundle10_obj, 80))
(yield {'node': n... | [
"def",
"unpack_chunks",
"(",
"hg_unbundle10_obj",
")",
":",
"while",
"True",
":",
"(",
"length",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"'>l'",
",",
"readexactly",
"(",
"hg_unbundle10_obj",
",",
"4",
")",
")",
"if",
"(",
"length",
"<=",
"4",
")",... | this method provides a generator of parsed chunks of a "group" in a mercurial unbundle10 object which is created when a changeset that is pushed to a tool shed repository using hg push from the command line is read using readbundle . | train | false |
45,567 | @subscriber(ResourceChanged, for_resources=('group',), for_actions=(ACTIONS.DELETE,))
def on_groups_deleted(event):
permission_backend = event.request.registry.permission
for change in event.impacted_records:
group = change['old']
bucket_id = event.payload['bucket_id']
group_uri = utils.instance_uri(event.reque... | [
"@",
"subscriber",
"(",
"ResourceChanged",
",",
"for_resources",
"=",
"(",
"'group'",
",",
")",
",",
"for_actions",
"=",
"(",
"ACTIONS",
".",
"DELETE",
",",
")",
")",
"def",
"on_groups_deleted",
"(",
"event",
")",
":",
"permission_backend",
"=",
"event",
"... | some groups were deleted . | train | false |
45,568 | def quota_destroy_all_by_project_and_user(context, project_id, user_id):
return IMPL.quota_destroy_all_by_project_and_user(context, project_id, user_id)
| [
"def",
"quota_destroy_all_by_project_and_user",
"(",
"context",
",",
"project_id",
",",
"user_id",
")",
":",
"return",
"IMPL",
".",
"quota_destroy_all_by_project_and_user",
"(",
"context",
",",
"project_id",
",",
"user_id",
")"
] | destroy all quotas associated with a given project and user . | train | false |
45,569 | def windows_get_size(path):
import win32file
if isbytestring(path):
path = path.decode(filesystem_encoding)
h = win32file.CreateFileW(path, 0, ((win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE) | win32file.FILE_SHARE_DELETE), None, win32file.OPEN_EXISTING, 0, None)
try:
return win32file.GetFileSize(h)
f... | [
"def",
"windows_get_size",
"(",
"path",
")",
":",
"import",
"win32file",
"if",
"isbytestring",
"(",
"path",
")",
":",
"path",
"=",
"path",
".",
"decode",
"(",
"filesystem_encoding",
")",
"h",
"=",
"win32file",
".",
"CreateFileW",
"(",
"path",
",",
"0",
"... | on windows file sizes are only accurately stored in the actual file . | train | false |
45,570 | def _compute_type_url(klass, prefix=_GOOGLE_APIS_PREFIX):
name = klass.DESCRIPTOR.full_name
return ('%s/%s' % (prefix, name))
| [
"def",
"_compute_type_url",
"(",
"klass",
",",
"prefix",
"=",
"_GOOGLE_APIS_PREFIX",
")",
":",
"name",
"=",
"klass",
".",
"DESCRIPTOR",
".",
"full_name",
"return",
"(",
"'%s/%s'",
"%",
"(",
"prefix",
",",
"name",
")",
")"
] | compute a type url for a klass . | train | true |
45,571 | def teardown_environment():
(oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff
os.chdir(old_wd)
reload(path)
for key in list(env):
if (key not in oldenv):
del env[key]
env.update(oldenv)
if hasattr(sys, 'frozen'):
del sys.frozen
| [
"def",
"teardown_environment",
"(",
")",
":",
"(",
"oldenv",
",",
"os",
".",
"name",
",",
"sys",
".",
"platform",
",",
"path",
".",
"get_home_dir",
",",
"IPython",
".",
"__file__",
",",
"old_wd",
")",
"=",
"oldstuff",
"os",
".",
"chdir",
"(",
"old_wd",... | restore things that were remembered by the setup_environment function . | train | false |
45,572 | @register.filter
def is_locked(model):
return (model.current_revision and model.current_revision.locked)
| [
"@",
"register",
".",
"filter",
"def",
"is_locked",
"(",
"model",
")",
":",
"return",
"(",
"model",
".",
"current_revision",
"and",
"model",
".",
"current_revision",
".",
"locked",
")"
] | check if article is locked . | train | false |
45,574 | @post_required
@user_view
def remove_locale(request, user):
POST = request.POST
if (('locale' in POST) and (POST['locale'] != settings.LANGUAGE_CODE)):
user.remove_locale(POST['locale'])
return http.HttpResponse()
return http.HttpResponseBadRequest()
| [
"@",
"post_required",
"@",
"user_view",
"def",
"remove_locale",
"(",
"request",
",",
"user",
")",
":",
"POST",
"=",
"request",
".",
"POST",
"if",
"(",
"(",
"'locale'",
"in",
"POST",
")",
"and",
"(",
"POST",
"[",
"'locale'",
"]",
"!=",
"settings",
".",
... | remove a locale from the users translations . | train | false |
45,575 | def _DefaultNamespace():
return namespace_manager.get_namespace()
| [
"def",
"_DefaultNamespace",
"(",
")",
":",
"return",
"namespace_manager",
".",
"get_namespace",
"(",
")"
] | return the default namespace . | train | false |
45,578 | @command('mix\\s*(\\d{1,4})')
def mix(num):
g.content = (g.content or content.generate_songlist_display())
if (g.browse_mode != 'normal'):
g.message = util.F('mix only videos')
else:
item = g.model[(int(num) - 1)]
if (item is None):
g.message = util.F('invalid item')
return
item = util.get_pafy(item)
... | [
"@",
"command",
"(",
"'mix\\\\s*(\\\\d{1,4})'",
")",
"def",
"mix",
"(",
"num",
")",
":",
"g",
".",
"content",
"=",
"(",
"g",
".",
"content",
"or",
"content",
".",
"generate_songlist_display",
"(",
")",
")",
"if",
"(",
"g",
".",
"browse_mode",
"!=",
"'n... | returns an iterator that alternates the given lists . | train | false |
45,580 | def removeGeneratedFiles():
gcodeFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['gcode'])
for gcodeFilePath in gcodeFilePaths:
if ('alterations' not in gcodeFilePath):
os.remove(gcodeFilePath)
print ('removeGeneratedFiles deleted ' + gcodeFilePath)
svgFilePaths = archive.getFilesWithFileTy... | [
"def",
"removeGeneratedFiles",
"(",
")",
":",
"gcodeFilePaths",
"=",
"archive",
".",
"getFilesWithFileTypesWithoutWordsRecursively",
"(",
"[",
"'gcode'",
"]",
")",
"for",
"gcodeFilePath",
"in",
"gcodeFilePaths",
":",
"if",
"(",
"'alterations'",
"not",
"in",
"gcodeFi... | remove generated files . | train | false |
45,582 | def _fetch_secret(pass_path):
cmd = 'pass show {0}'.format(pass_path.strip())
log.debug('Fetching secret: {0}'.format(cmd))
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(pass_data, pass_error) = proc.communicate()
if (proc.returncode or (not pass_data)):
msg = 'Could not fetch secret: {0} {1}'.format(p... | [
"def",
"_fetch_secret",
"(",
"pass_path",
")",
":",
"cmd",
"=",
"'pass show {0}'",
".",
"format",
"(",
"pass_path",
".",
"strip",
"(",
")",
")",
"log",
".",
"debug",
"(",
"'Fetching secret: {0}'",
".",
"format",
"(",
"cmd",
")",
")",
"proc",
"=",
"Popen"... | fetch secret from pass based on pass_path . | train | true |
45,583 | def SetOutputFile(file=None, needclose=0):
global _File, _NeedClose
if _NeedClose:
tmp = _File
_NeedClose = 0
_File = None
tmp.close()
if (file is None):
import sys
file = sys.stdout
_File = file
_NeedClose = (file and needclose)
| [
"def",
"SetOutputFile",
"(",
"file",
"=",
"None",
",",
"needclose",
"=",
"0",
")",
":",
"global",
"_File",
",",
"_NeedClose",
"if",
"_NeedClose",
":",
"tmp",
"=",
"_File",
"_NeedClose",
"=",
"0",
"_File",
"=",
"None",
"tmp",
".",
"close",
"(",
")",
"... | call this with an open file object to make it the output file . | train | false |
45,584 | def read_timit_block(stream):
line = stream.readline()
if (not line):
return []
(n, sent) = line.split(u' ', 1)
return [sent]
| [
"def",
"read_timit_block",
"(",
"stream",
")",
":",
"line",
"=",
"stream",
".",
"readline",
"(",
")",
"if",
"(",
"not",
"line",
")",
":",
"return",
"[",
"]",
"(",
"n",
",",
"sent",
")",
"=",
"line",
".",
"split",
"(",
"u' '",
",",
"1",
")",
"re... | block reader for timit tagged sentences . | train | false |
45,586 | @requires_sklearn
def test_gat_plot_matrix():
gat = _get_data()
gat.plot()
del gat.scores_
assert_raises(RuntimeError, gat.plot)
| [
"@",
"requires_sklearn",
"def",
"test_gat_plot_matrix",
"(",
")",
":",
"gat",
"=",
"_get_data",
"(",
")",
"gat",
".",
"plot",
"(",
")",
"del",
"gat",
".",
"scores_",
"assert_raises",
"(",
"RuntimeError",
",",
"gat",
".",
"plot",
")"
] | test gat matrix plot . | train | false |
45,588 | def date(*args, **kwargs):
d = None
f = None
if ((len(args) == 0) and (kwargs.get('year') is not None) and kwargs.get('month') and kwargs.get('day')):
d = Date(**kwargs)
elif kwargs.get('week'):
f = kwargs.pop('format', None)
d = Date(*_yyyywwd2yyyymmdd(kwargs.pop('year', ((args and args[0]) or Date.now().yea... | [
"def",
"date",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"d",
"=",
"None",
"f",
"=",
"None",
"if",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"0",
")",
"and",
"(",
"kwargs",
".",
"get",
"(",
"'year'",
")",
"is",
"not",
"None",
")",
"an... | return the current date . | train | false |
45,589 | def register_run_keyword(library, keyword, args_to_process=None, deprecation_warning=True):
RUN_KW_REGISTER.register_run_keyword(library, keyword, args_to_process, deprecation_warning)
| [
"def",
"register_run_keyword",
"(",
"library",
",",
"keyword",
",",
"args_to_process",
"=",
"None",
",",
"deprecation_warning",
"=",
"True",
")",
":",
"RUN_KW_REGISTER",
".",
"register_run_keyword",
"(",
"library",
",",
"keyword",
",",
"args_to_process",
",",
"dep... | registers run keyword so that its arguments can be handled correctly . | train | false |
45,590 | def _create_cadf_payload(operation, resource_type, resource_id, outcome, initiator, reason=None):
if (resource_type not in CADF_TYPE_MAP):
target_uri = taxonomy.UNKNOWN
else:
target_uri = CADF_TYPE_MAP.get(resource_type)
target = resource.Resource(typeURI=target_uri, id=resource_id)
audit_kwargs = {'resource_in... | [
"def",
"_create_cadf_payload",
"(",
"operation",
",",
"resource_type",
",",
"resource_id",
",",
"outcome",
",",
"initiator",
",",
"reason",
"=",
"None",
")",
":",
"if",
"(",
"resource_type",
"not",
"in",
"CADF_TYPE_MAP",
")",
":",
"target_uri",
"=",
"taxonomy"... | prepare data for cadf audit notifier . | train | false |
45,591 | @require_context
@require_volume_exists
def volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id):
session = get_session()
with session.begin():
metadata = _volume_glance_metadata_get(context, src_volume_id, session=session)
for meta in metadata:
vol_glance_metadata = models.Volu... | [
"@",
"require_context",
"@",
"require_volume_exists",
"def",
"volume_glance_metadata_copy_from_volume_to_volume",
"(",
"context",
",",
"src_volume_id",
",",
"volume_id",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":... | update the glance metadata for a volume . | train | false |
45,592 | def _is_dev_environment():
return os.environ.get('SERVER_SOFTWARE', '').startswith('Development')
| [
"def",
"_is_dev_environment",
"(",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"'SERVER_SOFTWARE'",
",",
"''",
")",
".",
"startswith",
"(",
"'Development'",
")"
] | indicates whether this code is being run in the development environment . | train | false |
45,593 | def set_audio_mode(new_mode):
if (new_mode in ('voice and sound', 'silent', 'voice only', 'sound only')):
global audio_mode
audio_mode = new_mode
| [
"def",
"set_audio_mode",
"(",
"new_mode",
")",
":",
"if",
"(",
"new_mode",
"in",
"(",
"'voice and sound'",
",",
"'silent'",
",",
"'voice only'",
",",
"'sound only'",
")",
")",
":",
"global",
"audio_mode",
"audio_mode",
"=",
"new_mode"
] | a save way to set the audio mode . | train | false |
45,594 | def export_host_info(inventory):
export_info = {'hosts': {}}
host_info = export_info['hosts']
export_info['all'] = inventory['all']['vars']
for (host, hostvars) in inventory['_meta']['hostvars'].items():
host_info[host] = {}
host_info[host]['hostvars'] = hostvars
for (group_name, group_info) in inventory.items... | [
"def",
"export_host_info",
"(",
"inventory",
")",
":",
"export_info",
"=",
"{",
"'hosts'",
":",
"{",
"}",
"}",
"host_info",
"=",
"export_info",
"[",
"'hosts'",
"]",
"export_info",
"[",
"'all'",
"]",
"=",
"inventory",
"[",
"'all'",
"]",
"[",
"'vars'",
"]"... | pivot variable information to be a per-host dict this command is meant for exporting an existing inventorys information . | train | false |
45,595 | def tokenize_string(source):
line_reader = StringIO(source).readline
for (toknum, tokval, _, _, _) in tokenize.generate_tokens(line_reader):
(yield (toknum, tokval))
| [
"def",
"tokenize_string",
"(",
"source",
")",
":",
"line_reader",
"=",
"StringIO",
"(",
"source",
")",
".",
"readline",
"for",
"(",
"toknum",
",",
"tokval",
",",
"_",
",",
"_",
",",
"_",
")",
"in",
"tokenize",
".",
"generate_tokens",
"(",
"line_reader",
... | tokenize a python source code string . | train | false |
45,596 | def printError(failure, hostname):
failure.trap(error.DNSNameError)
sys.stderr.write(('ERROR: hostname not found %r\n' % (hostname,)))
| [
"def",
"printError",
"(",
"failure",
",",
"hostname",
")",
":",
"failure",
".",
"trap",
"(",
"error",
".",
"DNSNameError",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"(",
"'ERROR: hostname not found %r\\n'",
"%",
"(",
"hostname",
",",
")",
")",
")"
] | print a friendly error message if the hostname could not be resolved . | train | false |
45,597 | def resource_absent(resource, identifier_fields, profile='pagerduty', subdomain=None, api_key=None, **kwargs):
ret = {'name': kwargs['name'], 'changes': {}, 'result': None, 'comment': ''}
for (k, v) in kwargs.items():
if (k not in identifier_fields):
continue
result = delete_resource(resource, v, identifier_fi... | [
"def",
"resource_absent",
"(",
"resource",
",",
"identifier_fields",
",",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"kwargs",
"[",
"'name'",
"... | generic resource . | train | true |
45,598 | def rotate_key(bucket, obj, current_encryption_key, current_key_hash, new_encryption_key, new_key_hash):
service = create_service()
request = service.objects().rewrite(sourceBucket=bucket, sourceObject=obj, destinationBucket=bucket, destinationObject=obj, body={})
while True:
request.headers.update({'x-goog-copy-s... | [
"def",
"rotate_key",
"(",
"bucket",
",",
"obj",
",",
"current_encryption_key",
",",
"current_key_hash",
",",
"new_encryption_key",
",",
"new_key_hash",
")",
":",
"service",
"=",
"create_service",
"(",
")",
"request",
"=",
"service",
".",
"objects",
"(",
")",
"... | changes the encryption key used to store an existing object . | train | false |
45,599 | def printUsage():
format = 'Usage: %s <opts1> [<opts2>] <root> [<resources>]'
print (format % basename(sys.argv[0]))
print
print ' with arguments:'
print ' (mandatory) root: the package root folder'
print ' (optional) resources: the package resources folder'
print
print ' ... | [
"def",
"printUsage",
"(",
")",
":",
"format",
"=",
"'Usage: %s <opts1> [<opts2>] <root> [<resources>]'",
"print",
"(",
"format",
"%",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"print",
"print",
"' with arguments:'",
"print",
"' ... | print usage message . | train | false |
45,601 | def validate_templates_configuration():
for template_engine in django.conf.settings.TEMPLATES:
backend = template_engine[u'BACKEND']
if (u'DjangoTemplates' in backend):
raise ImproperlyConfigured(u'The DjangoTemplates engine was encountered in your template configuration before Django-Jinja. This configuration ... | [
"def",
"validate_templates_configuration",
"(",
")",
":",
"for",
"template_engine",
"in",
"django",
".",
"conf",
".",
"settings",
".",
"TEMPLATES",
":",
"backend",
"=",
"template_engine",
"[",
"u'BACKEND'",
"]",
"if",
"(",
"u'DjangoTemplates'",
"in",
"backend",
... | validate the templates configuration in the django settings . | train | false |
45,602 | def backend_setting(backend, name, default=None):
backend_name = get_backend_name(backend)
setting_name = ('%s_%s' % (backend_name.upper().replace('-', '_'), name))
if hasattr(settings, setting_name):
return setting(setting_name)
elif hasattr(settings, name):
return setting(name)
else:
return default
| [
"def",
"backend_setting",
"(",
"backend",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"backend_name",
"=",
"get_backend_name",
"(",
"backend",
")",
"setting_name",
"=",
"(",
"'%s_%s'",
"%",
"(",
"backend_name",
".",
"upper",
"(",
")",
".",
"replace... | looks for setting value following these rules: 1 . | train | false |
45,603 | def _read_dipole_fixed(fname):
logger.info(('Reading %s ...' % fname))
_check_fname(fname, overwrite=True, must_exist=True)
(info, nave, aspect_kind, first, last, comment, times, data) = _read_evoked(fname)
return DipoleFixed(info, data, times, nave, aspect_kind, first, last, comment)
| [
"def",
"_read_dipole_fixed",
"(",
"fname",
")",
":",
"logger",
".",
"info",
"(",
"(",
"'Reading %s ...'",
"%",
"fname",
")",
")",
"_check_fname",
"(",
"fname",
",",
"overwrite",
"=",
"True",
",",
"must_exist",
"=",
"True",
")",
"(",
"info",
",",
"nave",
... | helper to read a fixed dipole fif file . | train | false |
45,605 | def tools_binscope():
mobsf_subdir_tools = CONFIG['MobSF']['tools']
binscope_path = (mobsf_subdir_tools + 'BinScope')
if platform.machine().endswith('64'):
binscope_url = CONFIG['binscope']['url_x64']
binscope_installer_path = (binscope_path + '\\BinScope_x64.msi')
else:
binscope_url = CONFIG['binscope']['url... | [
"def",
"tools_binscope",
"(",
")",
":",
"mobsf_subdir_tools",
"=",
"CONFIG",
"[",
"'MobSF'",
"]",
"[",
"'tools'",
"]",
"binscope_path",
"=",
"(",
"mobsf_subdir_tools",
"+",
"'BinScope'",
")",
"if",
"platform",
".",
"machine",
"(",
")",
".",
"endswith",
"(",
... | download and install binscope for mobsf . | train | false |
45,606 | def vb_xpcom_to_attribute_dict(xpcom, interface_name=None, attributes=None, excluded_attributes=None, extra_attributes=None):
if interface_name:
m = re.search('XPCOM.+implementing {0}'.format(interface_name), str(xpcom))
if (not m):
log.warning('Interface %s is unknown and cannot be converted to dict', interfac... | [
"def",
"vb_xpcom_to_attribute_dict",
"(",
"xpcom",
",",
"interface_name",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"excluded_attributes",
"=",
"None",
",",
"extra_attributes",
"=",
"None",
")",
":",
"if",
"interface_name",
":",
"m",
"=",
"re",
".",
... | attempts to build a dict from an xpcom object . | train | true |
45,607 | def _enhook(klass, name):
if hasattr(klass, ORIG(klass, name)):
return
def newfunc(*args, **kw):
for preMethod in getattr(klass, PRE(klass, name)):
preMethod(*args, **kw)
try:
return getattr(klass, ORIG(klass, name))(*args, **kw)
finally:
for postMethod in getattr(klass, POST(klass, name)):
postM... | [
"def",
"_enhook",
"(",
"klass",
",",
"name",
")",
":",
"if",
"hasattr",
"(",
"klass",
",",
"ORIG",
"(",
"klass",
",",
"name",
")",
")",
":",
"return",
"def",
"newfunc",
"(",
"*",
"args",
",",
"**",
"kw",
")",
":",
"for",
"preMethod",
"in",
"getat... | causes a certain method name to be hooked on a class . | train | false |
45,611 | def irc_raw(triggers_param, **kwargs):
def _raw_hook(func):
hook = _get_hook(func, 'irc_raw')
if (hook is None):
hook = _RawHook(func)
_add_hook(func, hook)
hook.add_hook(triggers_param, kwargs)
return func
if callable(triggers_param):
raise TypeError('@irc_raw() must be used as a function that return... | [
"def",
"irc_raw",
"(",
"triggers_param",
",",
"**",
"kwargs",
")",
":",
"def",
"_raw_hook",
"(",
"func",
")",
":",
"hook",
"=",
"_get_hook",
"(",
"func",
",",
"'irc_raw'",
")",
"if",
"(",
"hook",
"is",
"None",
")",
":",
"hook",
"=",
"_RawHook",
"(",
... | external raw decorator . | train | false |
45,613 | def pportDataStrobe(state):
global ctrlReg
if (state == 0):
ctrlReg = (ctrlReg | 1)
else:
ctrlReg = (ctrlReg & (~ 1))
port.DlPortWritePortUchar(ctrlRegAdrs, ctrlReg)
| [
"def",
"pportDataStrobe",
"(",
"state",
")",
":",
"global",
"ctrlReg",
"if",
"(",
"state",
"==",
"0",
")",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"|",
"1",
")",
"else",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"&",
"(",
"~",
"1",
")",
")",
"port",
".",... | toggle control register data strobe bit . | train | false |
45,614 | def filesharing():
status = (-1)
finder = _getfinder()
args = {}
attrs = {}
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=aetypes.Type('fshr'), fr=None)
(_reply, args, attrs) = finder.send('core', 'getd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerr... | [
"def",
"filesharing",
"(",
")",
":",
"status",
"=",
"(",
"-",
"1",
")",
"finder",
"=",
"_getfinder",
"(",
")",
"args",
"=",
"{",
"}",
"attrs",
"=",
"{",
"}",
"args",
"[",
"'----'",
"]",
"=",
"aetypes",
".",
"ObjectSpecifier",
"(",
"want",
"=",
"a... | return the current status of filesharing and whether it is starting up or not: -1 file sharing is off and not starting up 0 file sharing is off and starting up 1 file sharing is on . | train | false |
45,615 | def _key_id_or_name_n(key, index):
if (not key):
return None
path = key.to_path()
if (not path):
return None
path_index = ((index * 2) + 1)
return path[path_index]
| [
"def",
"_key_id_or_name_n",
"(",
"key",
",",
"index",
")",
":",
"if",
"(",
"not",
"key",
")",
":",
"return",
"None",
"path",
"=",
"key",
".",
"to_path",
"(",
")",
"if",
"(",
"not",
"path",
")",
":",
"return",
"None",
"path_index",
"=",
"(",
"(",
... | internal helper function for key id and name transforms . | train | false |
45,617 | def selectables_overlap(left, right):
return bool(set(surface_selectables(left)).intersection(surface_selectables(right)))
| [
"def",
"selectables_overlap",
"(",
"left",
",",
"right",
")",
":",
"return",
"bool",
"(",
"set",
"(",
"surface_selectables",
"(",
"left",
")",
")",
".",
"intersection",
"(",
"surface_selectables",
"(",
"right",
")",
")",
")"
] | return true if left/right have some overlapping selectable . | train | false |
45,619 | def ellipk(m):
return ellipkm1((1 - asarray(m)))
| [
"def",
"ellipk",
"(",
"m",
")",
":",
"return",
"ellipkm1",
"(",
"(",
"1",
"-",
"asarray",
"(",
"m",
")",
")",
")"
] | complete elliptic integral of the first kind . | train | false |
45,620 | def get_mako(factory=Mako, key=_registry_key, app=None):
app = (app or webapp2.get_app())
mako = app.registry.get(key)
if (not mako):
mako = app.registry[key] = factory(app)
return mako
| [
"def",
"get_mako",
"(",
"factory",
"=",
"Mako",
",",
"key",
"=",
"_registry_key",
",",
"app",
"=",
"None",
")",
":",
"app",
"=",
"(",
"app",
"or",
"webapp2",
".",
"get_app",
"(",
")",
")",
"mako",
"=",
"app",
".",
"registry",
".",
"get",
"(",
"ke... | returns an instance of :class:mako from the app registry . | train | false |
45,621 | def sleep(at_time=None):
cmd = 'shutdown -s now'
return _execute_command(cmd, at_time)
| [
"def",
"sleep",
"(",
"at_time",
"=",
"None",
")",
":",
"cmd",
"=",
"'shutdown -s now'",
"return",
"_execute_command",
"(",
"cmd",
",",
"at_time",
")"
] | sleep t seconds . | train | false |
45,622 | def _log_dirichlet_norm(dirichlet_concentration):
return (gammaln(np.sum(dirichlet_concentration)) - np.sum(gammaln(dirichlet_concentration)))
| [
"def",
"_log_dirichlet_norm",
"(",
"dirichlet_concentration",
")",
":",
"return",
"(",
"gammaln",
"(",
"np",
".",
"sum",
"(",
"dirichlet_concentration",
")",
")",
"-",
"np",
".",
"sum",
"(",
"gammaln",
"(",
"dirichlet_concentration",
")",
")",
")"
] | compute the log of the dirichlet distribution normalization term . | train | false |
45,624 | def show_instance(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The show_instance action must be called with -a or --action.')
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
| [
"def",
"show_instance",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'action'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_instance action must be called with -a or --action.'",
")",
"node",
"=",
"_get_node",
"(",
"name... | show the details from opennebula concerning a named vm . | train | true |
45,625 | def _poll_until_success_returning_result(should_retry, steps, sleep, function, args, kwargs):
saved_result = [None]
def pollable():
Message.new(message_type=_TRY_RETRYING).write()
try:
result = function(*args, **kwargs)
except Exception as e:
saved_result[0] = exc_info()
should_retry(*saved_result[0])
... | [
"def",
"_poll_until_success_returning_result",
"(",
"should_retry",
",",
"steps",
",",
"sleep",
",",
"function",
",",
"args",
",",
"kwargs",
")",
":",
"saved_result",
"=",
"[",
"None",
"]",
"def",
"pollable",
"(",
")",
":",
"Message",
".",
"new",
"(",
"mes... | call a function until it does not raise an exception or should_retry says it shouldnt be tried anymore . | train | false |
45,626 | def write_t2b(t2bfile, coverdata=None):
from PIL import Image
if (coverdata is not None):
coverdata = StringIO.StringIO(coverdata)
cover = Image.open(coverdata).convert('L')
cover.thumbnail((96, 144), Image.ANTIALIAS)
t2bcover = Image.new('L', (96, 144), 'white')
(x, y) = cover.size
t2bcover.paste(cover, ... | [
"def",
"write_t2b",
"(",
"t2bfile",
",",
"coverdata",
"=",
"None",
")",
":",
"from",
"PIL",
"import",
"Image",
"if",
"(",
"coverdata",
"is",
"not",
"None",
")",
":",
"coverdata",
"=",
"StringIO",
".",
"StringIO",
"(",
"coverdata",
")",
"cover",
"=",
"I... | t2bfile is a file handle ready to write binary data to disk . | train | false |
45,627 | @cronjobs.register
def process_exit_surveys():
_process_exit_survey_results()
if settings.STAGE:
return
startdate = (date.today() - timedelta(days=2))
enddate = (date.today() - timedelta(days=1))
for survey in SURVEYS.keys():
if ('email_collection_survey_id' not in SURVEYS[survey]):
continue
emails = get_... | [
"@",
"cronjobs",
".",
"register",
"def",
"process_exit_surveys",
"(",
")",
":",
"_process_exit_survey_results",
"(",
")",
"if",
"settings",
".",
"STAGE",
":",
"return",
"startdate",
"=",
"(",
"date",
".",
"today",
"(",
")",
"-",
"timedelta",
"(",
"days",
"... | exit survey handling . | train | false |
45,628 | def render_form(form, **kwargs):
renderer_cls = get_form_renderer(**kwargs)
return renderer_cls(form, **kwargs).render()
| [
"def",
"render_form",
"(",
"form",
",",
"**",
"kwargs",
")",
":",
"renderer_cls",
"=",
"get_form_renderer",
"(",
"**",
"kwargs",
")",
"return",
"renderer_cls",
"(",
"form",
",",
"**",
"kwargs",
")",
".",
"render",
"(",
")"
] | render a form to a bootstrap layout . | train | true |
45,629 | def hash_thesubdb(video_path):
readsize = (64 * 1024)
if (os.path.getsize(video_path) < readsize):
return
with open(video_path, 'rb') as f:
data = f.read(readsize)
f.seek((- readsize), os.SEEK_END)
data += f.read(readsize)
return hashlib.md5(data).hexdigest()
| [
"def",
"hash_thesubdb",
"(",
"video_path",
")",
":",
"readsize",
"=",
"(",
"64",
"*",
"1024",
")",
"if",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"video_path",
")",
"<",
"readsize",
")",
":",
"return",
"with",
"open",
"(",
"video_path",
",",
"'rb... | compute a hash using thesubdbs algorithm . | train | true |
45,630 | def require_docker_version(minimum_docker_version, message):
minimum_docker_version = LooseVersion(minimum_docker_version)
def decorator(wrapped):
@wraps(wrapped)
def wrapper(*args, **kwargs):
client = DockerClient()
docker_version = LooseVersion(client._client.version()['Version'])
if (docker_version < ... | [
"def",
"require_docker_version",
"(",
"minimum_docker_version",
",",
"message",
")",
":",
"minimum_docker_version",
"=",
"LooseVersion",
"(",
"minimum_docker_version",
")",
"def",
"decorator",
"(",
"wrapped",
")",
":",
"@",
"wraps",
"(",
"wrapped",
")",
"def",
"wr... | skip the wrapped test if the actual docker version is less than minimum_docker_version . | train | false |
45,631 | def dmp_one_p(f, u, K):
return dmp_ground_p(f, K.one, u)
| [
"def",
"dmp_one_p",
"(",
"f",
",",
"u",
",",
"K",
")",
":",
"return",
"dmp_ground_p",
"(",
"f",
",",
"K",
".",
"one",
",",
"u",
")"
] | return true if f is one in k[x] . | train | false |
45,634 | def test_exp_schedule(backend_default):
lr_init = 0.1
decay = 0.01
sch = ExpSchedule(decay)
for epoch in range(10):
lr = sch.get_learning_rate(learning_rate=lr_init, epoch=epoch)
assert np.allclose(lr, (lr_init / (1.0 + (decay * epoch))))
| [
"def",
"test_exp_schedule",
"(",
"backend_default",
")",
":",
"lr_init",
"=",
"0.1",
"decay",
"=",
"0.01",
"sch",
"=",
"ExpSchedule",
"(",
"decay",
")",
"for",
"epoch",
"in",
"range",
"(",
"10",
")",
":",
"lr",
"=",
"sch",
".",
"get_learning_rate",
"(",
... | test exponential learning rate schedule . | train | false |
45,635 | def check_master(client, master_only=False):
if (master_only and (not is_master_node(client))):
logger.info('Master-only flag detected. Connected to non-master node. Aborting.')
sys.exit(0)
| [
"def",
"check_master",
"(",
"client",
",",
"master_only",
"=",
"False",
")",
":",
"if",
"(",
"master_only",
"and",
"(",
"not",
"is_master_node",
"(",
"client",
")",
")",
")",
":",
"logger",
".",
"info",
"(",
"'Master-only flag detected. Connected to non-master n... | check if connected client is the elected master node of the cluster . | train | false |
45,636 | def _get_all_files():
jscsrc_path = os.path.join(os.getcwd(), '.jscsrc')
parsed_args = _PARSER.parse_args()
if parsed_args.path:
input_path = os.path.join(os.getcwd(), parsed_args.path)
if (not os.path.exists(input_path)):
print ('Could not locate file or directory %s. Exiting.' % input_path)
print '------... | [
"def",
"_get_all_files",
"(",
")",
":",
"jscsrc_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'.jscsrc'",
")",
"parsed_args",
"=",
"_PARSER",
".",
"parse_args",
"(",
")",
"if",
"parsed_args",
".",
"path",
":",
... | this function is used to check if this script is ran from root directory and to return a list of all the files for linting and pattern checks . | train | false |
45,637 | def get_event_differences(expected, actual, tolerate=None):
tolerate = EventMatchTolerates.default_if_not_defined(tolerate)
if (EventMatchTolerates.STRING_PAYLOAD in tolerate):
expected = parse_event_payload(expected)
actual = parse_event_payload(actual)
def should_strict_compare(path):
'\n We want to b... | [
"def",
"get_event_differences",
"(",
"expected",
",",
"actual",
",",
"tolerate",
"=",
"None",
")",
":",
"tolerate",
"=",
"EventMatchTolerates",
".",
"default_if_not_defined",
"(",
"tolerate",
")",
"if",
"(",
"EventMatchTolerates",
".",
"STRING_PAYLOAD",
"in",
"tol... | given two events . | train | false |
45,638 | def test_invalid_service_provider_type(rf, admin_user):
get_default_shop()
view = ServiceProviderEditView.as_view()
url = '/?type=SomethingThatIsNotProvided'
soup = get_bs_object_for_view(rf.get(url), view, admin_user)
provider_form = soup.find('form', attrs={'id': 'service_provider_form'})
type_select = provider... | [
"def",
"test_invalid_service_provider_type",
"(",
"rf",
",",
"admin_user",
")",
":",
"get_default_shop",
"(",
")",
"view",
"=",
"ServiceProviderEditView",
".",
"as_view",
"(",
")",
"url",
"=",
"'/?type=SomethingThatIsNotProvided'",
"soup",
"=",
"get_bs_object_for_view",... | test serviceprovideeditview with invalid type parameter . | train | false |
45,639 | def get_cohort_by_id(course_key, cohort_id):
return CourseUserGroup.objects.get(course_id=course_key, group_type=CourseUserGroup.COHORT, id=cohort_id)
| [
"def",
"get_cohort_by_id",
"(",
"course_key",
",",
"cohort_id",
")",
":",
"return",
"CourseUserGroup",
".",
"objects",
".",
"get",
"(",
"course_id",
"=",
"course_key",
",",
"group_type",
"=",
"CourseUserGroup",
".",
"COHORT",
",",
"id",
"=",
"cohort_id",
")"
] | return the courseusergroup object for the given cohort . | train | false |
45,640 | def change_ls(table):
if ('total' in table):
for field in ['files', 'bytes']:
if ((field in table['total']) and table['total'][field].isdigit()):
table['total'][field] = int(table['total'][field])
for volume in table.get('volumes', []):
for fileentry in volume.get('files', []):
if (('size' in fileentry)... | [
"def",
"change_ls",
"(",
"table",
")",
":",
"if",
"(",
"'total'",
"in",
"table",
")",
":",
"for",
"field",
"in",
"[",
"'files'",
",",
"'bytes'",
"]",
":",
"if",
"(",
"(",
"field",
"in",
"table",
"[",
"'total'",
"]",
")",
"and",
"table",
"[",
"'to... | adapt structured data from "ls" nse module to convert some fields to integers . | train | false |
45,642 | @world.absorb
def css_check(css_selector, wait_time=GLOBAL_WAIT_FOR_TIMEOUT):
css_click(css_selector=css_selector, wait_time=wait_time)
wait_for((lambda _: css_find(css_selector).selected))
return True
| [
"@",
"world",
".",
"absorb",
"def",
"css_check",
"(",
"css_selector",
",",
"wait_time",
"=",
"GLOBAL_WAIT_FOR_TIMEOUT",
")",
":",
"css_click",
"(",
"css_selector",
"=",
"css_selector",
",",
"wait_time",
"=",
"wait_time",
")",
"wait_for",
"(",
"(",
"lambda",
"_... | checks a check box based on a css selector . | train | false |
45,643 | def Scalar(obj):
return Sequence([obj])
| [
"def",
"Scalar",
"(",
"obj",
")",
":",
"return",
"Sequence",
"(",
"[",
"obj",
"]",
")"
] | shortcut for sequence creation . | train | false |
45,644 | def sync_desktop_icons():
for app in frappe.get_installed_apps():
sync_from_app(app)
| [
"def",
"sync_desktop_icons",
"(",
")",
":",
"for",
"app",
"in",
"frappe",
".",
"get_installed_apps",
"(",
")",
":",
"sync_from_app",
"(",
"app",
")"
] | sync desktop icons from all apps . | train | false |
45,645 | def toTypeURIs(namespace_map, alias_list_s):
uris = []
if alias_list_s:
for alias in alias_list_s.split(','):
type_uri = namespace_map.getNamespaceURI(alias)
if (type_uri is None):
raise KeyError(('No type is defined for attribute name %r' % (alias,)))
else:
uris.append(type_uri)
return uris
| [
"def",
"toTypeURIs",
"(",
"namespace_map",
",",
"alias_list_s",
")",
":",
"uris",
"=",
"[",
"]",
"if",
"alias_list_s",
":",
"for",
"alias",
"in",
"alias_list_s",
".",
"split",
"(",
"','",
")",
":",
"type_uri",
"=",
"namespace_map",
".",
"getNamespaceURI",
... | given a namespace mapping and a string containing a comma-separated list of namespace aliases . | train | true |
45,646 | def onLoggerAppReady():
INFO_MSG(('onLoggerAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s' % (os.getenv('KBE_BOOTIDX_GROUP'), os.getenv('KBE_BOOTIDX_GLOBAL'))))
| [
"def",
"onLoggerAppReady",
"(",
")",
":",
"INFO_MSG",
"(",
"(",
"'onLoggerAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s'",
"%",
"(",
"os",
".",
"getenv",
"(",
"'KBE_BOOTIDX_GROUP'",
")",
",",
"os",
".",
"getenv",
"(",
"'KBE_BOOTIDX_GLOBAL'",
")",
")",
")... | kbengine method . | train | false |
45,647 | def idd_frmi(m):
return _id.idd_frmi(m)
| [
"def",
"idd_frmi",
"(",
"m",
")",
":",
"return",
"_id",
".",
"idd_frmi",
"(",
"m",
")"
] | initialize data for :func:idd_frm . | train | false |
45,648 | def url_escape(value, plus=True):
quote = (urllib_parse.quote_plus if plus else urllib_parse.quote)
return quote(utf8(value))
| [
"def",
"url_escape",
"(",
"value",
",",
"plus",
"=",
"True",
")",
":",
"quote",
"=",
"(",
"urllib_parse",
".",
"quote_plus",
"if",
"plus",
"else",
"urllib_parse",
".",
"quote",
")",
"return",
"quote",
"(",
"utf8",
"(",
"value",
")",
")"
] | returns a url-encoded version of the given value . | train | true |
45,650 | def read_no_interrupt(p):
import errno
try:
return p.read()
except IOError as err:
if (err.errno != errno.EINTR):
raise
| [
"def",
"read_no_interrupt",
"(",
"p",
")",
":",
"import",
"errno",
"try",
":",
"return",
"p",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"err",
":",
"if",
"(",
"err",
".",
"errno",
"!=",
"errno",
".",
"EINTR",
")",
":",
"raise"
] | read from a pipe ignoring eintr errors . | train | true |
45,652 | def get_view_config(context, global_type=False):
request = context.get(u'request')
config_key = (u'_xtheme_global_view_config' if global_type else u'_xtheme_view_config')
config = context.vars.get(config_key)
if (config is None):
view_object = context.get(u'view')
if view_object:
view_class = view_object.__c... | [
"def",
"get_view_config",
"(",
"context",
",",
"global_type",
"=",
"False",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"u'request'",
")",
"config_key",
"=",
"(",
"u'_xtheme_global_view_config'",
"if",
"global_type",
"else",
"u'_xtheme_view_config'",
")"... | get a view configuration object for a jinja2 rendering context . | train | false |
45,654 | def nottest(f):
f.__test__ = False
return f
| [
"def",
"nottest",
"(",
"f",
")",
":",
"f",
".",
"__test__",
"=",
"False",
"return",
"f"
] | decorator to mark a function as not a test . | train | false |
45,655 | def get_action_parameters_specs(action_ref):
action_db = get_action_by_ref(ref=action_ref)
parameters = {}
if (not action_db):
return parameters
runner_type_name = action_db.runner_type['name']
runner_type_db = get_runnertype_by_name(runnertype_name=runner_type_name)
parameters.update(runner_type_db['runner_par... | [
"def",
"get_action_parameters_specs",
"(",
"action_ref",
")",
":",
"action_db",
"=",
"get_action_by_ref",
"(",
"ref",
"=",
"action_ref",
")",
"parameters",
"=",
"{",
"}",
"if",
"(",
"not",
"action_db",
")",
":",
"return",
"parameters",
"runner_type_name",
"=",
... | retrieve parameters specifications schema for the provided action reference . | train | false |
45,656 | def valid_certificate(name, weeks=0, days=0, hours=0, minutes=0, seconds=0):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
now = time.time()
cert_info = __salt__['tls.cert_info'](name)
if (now < cert_info['not_before']):
ret['comment'] = 'Certificate is not yet valid'
return ret
if (now >... | [
"def",
"valid_certificate",
"(",
"name",
",",
"weeks",
"=",
"0",
",",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}... | verify that a tls certificate is valid now and will be valid for the time specified through weeks . | train | true |
45,660 | def menu():
return s3_rest_controller()
| [
"def",
"menu",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | restful crud controller . | train | false |
45,662 | def s3_has_foreign_key(field, m2m=True):
try:
ftype = str(field.type)
except:
return False
if ((ftype[:9] == 'reference') or (m2m and (ftype[:14] == 'list:reference')) or current.s3db.virtual_reference(field)):
return True
return False
| [
"def",
"s3_has_foreign_key",
"(",
"field",
",",
"m2m",
"=",
"True",
")",
":",
"try",
":",
"ftype",
"=",
"str",
"(",
"field",
".",
"type",
")",
"except",
":",
"return",
"False",
"if",
"(",
"(",
"ftype",
"[",
":",
"9",
"]",
"==",
"'reference'",
")",
... | check whether a field contains a foreign key constraint . | train | false |
45,663 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | return a signature scheme object pss_sigscheme that can be used to perform pkcs#1 pss signature or verification . | train | false |
45,665 | def set_restart_mode(restart_file, flag='reload'):
with open(restart_file, 'w') as f:
f.write(str(flag))
| [
"def",
"set_restart_mode",
"(",
"restart_file",
",",
"flag",
"=",
"'reload'",
")",
":",
"with",
"open",
"(",
"restart_file",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"flag",
")",
")"
] | this sets a flag file for the restart mode . | train | false |
45,666 | def test_ast_invalid_let():
cant_compile(u'(let 1)')
cant_compile(u'(let [1])')
cant_compile(u'(let [a 1 2])')
cant_compile(u'(let [a])')
cant_compile(u'(let [1])')
| [
"def",
"test_ast_invalid_let",
"(",
")",
":",
"cant_compile",
"(",
"u'(let 1)'",
")",
"cant_compile",
"(",
"u'(let [1])'",
")",
"cant_compile",
"(",
"u'(let [a 1 2])'",
")",
"cant_compile",
"(",
"u'(let [a])'",
")",
"cant_compile",
"(",
"u'(let [1])'",
")"
] | make sure ast cant compile invalid let . | train | false |
45,667 | def parse_volgroup(rule):
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
partitions = []
newrules = []
for count in range(0, len(rules)):
if (count == 0):
newrules.append(rules[count])
continue
elif rules[count].startswith('--'):
newrules.append(rules[count])
continue
... | [
"def",
"parse_volgroup",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"partitions",
"=",
"[",
"]",
"newrules",
"=",
"[",
... | parse the volgroup line . | train | true |
45,668 | def escape_rfc3986(s):
if ((sys.version_info < (3, 0)) and isinstance(s, compat_str)):
s = s.encode(u'utf-8')
return compat_urllib_parse.quote(s, "%/;:@&=+$,!~*'()?#[]")
| [
"def",
"escape_rfc3986",
"(",
"s",
")",
":",
"if",
"(",
"(",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
")",
"and",
"isinstance",
"(",
"s",
",",
"compat_str",
")",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"u'utf-8'",
")",
"re... | escape non-ascii characters as suggested by rfc 3986 . | train | false |
45,669 | def komodo(exe=u'komodo'):
install_editor((exe + u' -l {line} {filename}'), wait=True)
| [
"def",
"komodo",
"(",
"exe",
"=",
"u'komodo'",
")",
":",
"install_editor",
"(",
"(",
"exe",
"+",
"u' -l {line} {filename}'",
")",
",",
"wait",
"=",
"True",
")"
] | activestate komodo [edit] . | train | false |
45,671 | def choice_param(registry, xml_parent, data):
pdef = base_param(registry, xml_parent, data, False, 'hudson.model.ChoiceParameterDefinition')
choices = XML.SubElement(pdef, 'choices', {'class': 'java.util.Arrays$ArrayList'})
a = XML.SubElement(choices, 'a', {'class': 'string-array'})
for choice in data['choices']:
... | [
"def",
"choice_param",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"pdef",
"=",
"base_param",
"(",
"registry",
",",
"xml_parent",
",",
"data",
",",
"False",
",",
"'hudson.model.ChoiceParameterDefinition'",
")",
"choices",
"=",
"XML",
".",
"SubEl... | yaml: choice a single selection parameter . | train | false |
45,672 | def set_geofence_all(instance):
resource = instance.get_self_resource()
if hasattr(resource, 'layer'):
try:
'\n curl -X POST -u admin:geoserver -H "Content-Type: text/xml" -d "<Rule><workspace>geonode</workspace><layer>{layer}</layer><access>ALLOW</access></Rule>" http://<host>... | [
"def",
"set_geofence_all",
"(",
"instance",
")",
":",
"resource",
"=",
"instance",
".",
"get_self_resource",
"(",
")",
"if",
"hasattr",
"(",
"resource",
",",
"'layer'",
")",
":",
"try",
":",
"url",
"=",
"settings",
".",
"OGC_SERVER",
"[",
"'default'",
"]",... | assign access permissions to all users . | train | false |
45,674 | def count_blocks(A, blocksize):
(r, c) = blocksize
if ((r < 1) or (c < 1)):
raise ValueError('r and c must be positive')
if isspmatrix_csr(A):
(M, N) = A.shape
return csr_count_blocks(M, N, r, c, A.indptr, A.indices)
elif isspmatrix_csc(A):
return count_blocks(A.T, (c, r))
else:
return count_blocks(csr_m... | [
"def",
"count_blocks",
"(",
"A",
",",
"blocksize",
")",
":",
"(",
"r",
",",
"c",
")",
"=",
"blocksize",
"if",
"(",
"(",
"r",
"<",
"1",
")",
"or",
"(",
"c",
"<",
"1",
")",
")",
":",
"raise",
"ValueError",
"(",
"'r and c must be positive'",
")",
"i... | for a given blocksize= count the number of occupied blocks in a sparse matrix a . | train | false |
45,675 | def print_dict(dct, dict_property='Property', wrap=0, dict_value='Value'):
pt = prettytable.PrettyTable([dict_property, dict_value])
pt.align = 'l'
for (k, v) in sorted(dct.items()):
if isinstance(v, dict):
v = six.text_type(v)
if (wrap > 0):
v = textwrap.fill(six.text_type(v), wrap)
if (v and isinstance... | [
"def",
"print_dict",
"(",
"dct",
",",
"dict_property",
"=",
"'Property'",
",",
"wrap",
"=",
"0",
",",
"dict_value",
"=",
"'Value'",
")",
":",
"pt",
"=",
"prettytable",
".",
"PrettyTable",
"(",
"[",
"dict_property",
",",
"dict_value",
"]",
")",
"pt",
".",... | print a dict as a table of two columns . | train | false |
45,676 | def ns_join(ns, name):
if (is_private(name) or is_global(name)):
return name
if (ns == PRIV_NAME):
return (PRIV_NAME + name)
if (not ns):
return name
if (ns[(-1)] == SEP):
return (ns + name)
return ((ns + SEP) + name)
| [
"def",
"ns_join",
"(",
"ns",
",",
"name",
")",
":",
"if",
"(",
"is_private",
"(",
"name",
")",
"or",
"is_global",
"(",
"name",
")",
")",
":",
"return",
"name",
"if",
"(",
"ns",
"==",
"PRIV_NAME",
")",
":",
"return",
"(",
"PRIV_NAME",
"+",
"name",
... | join a namespace and name . | train | false |
45,677 | @cachedmethod
def getConsoleWidth(default=80):
width = None
if os.getenv('COLUMNS', '').isdigit():
width = int(os.getenv('COLUMNS'))
else:
try:
try:
FNULL = open(os.devnull, 'w')
except IOError:
FNULL = None
process = subprocess.Popen('stty size', shell=True, stdout=subprocess.PIPE, stderr=(FNUL... | [
"@",
"cachedmethod",
"def",
"getConsoleWidth",
"(",
"default",
"=",
"80",
")",
":",
"width",
"=",
"None",
"if",
"os",
".",
"getenv",
"(",
"'COLUMNS'",
",",
"''",
")",
".",
"isdigit",
"(",
")",
":",
"width",
"=",
"int",
"(",
"os",
".",
"getenv",
"("... | returns console width . | train | false |
45,678 | def fixclasspath():
paths = []
classpaths = []
for path in sys.path:
if ((path == '__classpath__') or path.startswith('__pyclasspath__')):
classpaths.append(path)
else:
paths.append(path)
sys.path = paths
sys.path.extend(classpaths)
| [
"def",
"fixclasspath",
"(",
")",
":",
"paths",
"=",
"[",
"]",
"classpaths",
"=",
"[",
"]",
"for",
"path",
"in",
"sys",
".",
"path",
":",
"if",
"(",
"(",
"path",
"==",
"'__classpath__'",
")",
"or",
"path",
".",
"startswith",
"(",
"'__pyclasspath__'",
... | adjust the special classpath sys . | train | true |
45,679 | @register.inclusion_tag(u'wagtailusers/groups/includes/formatted_permissions.html')
def format_permissions(permission_bound_field):
permissions = permission_bound_field.field._queryset
content_type_ids = set(permissions.values_list(u'content_type_id', flat=True))
checkboxes_by_id = {int(checkbox.choice_value): check... | [
"@",
"register",
".",
"inclusion_tag",
"(",
"u'wagtailusers/groups/includes/formatted_permissions.html'",
")",
"def",
"format_permissions",
"(",
"permission_bound_field",
")",
":",
"permissions",
"=",
"permission_bound_field",
".",
"field",
".",
"_queryset",
"content_type_ids... | given a bound field with a queryset of permission objects - which must be using the checkboxselectmultiple widget - construct a list of dictionaries for objects: objects: [ object: name_of_some_content_object . | train | false |
45,680 | def show_backends(socket='/var/run/haproxy.sock'):
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.showBackends()
return ha_conn.sendCmd(ha_cmd)
| [
"def",
"show_backends",
"(",
"socket",
"=",
"'/var/run/haproxy.sock'",
")",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"showBackends",
"(",
")",
"return",
"ha_conn",
".",
"sendCmd",
"(",
"ha_cmd",
")"
] | show haproxy backends socket haproxy stats socket cli example: . | train | true |
45,681 | def pretty_print_prediction(emissions, real_state, predicted_state, emission_title='Emissions', real_title='Real State', predicted_title='Predicted State', line_width=75):
title_length = (max(len(emission_title), len(real_title), len(predicted_title)) + 1)
seq_length = (line_width - title_length)
emission_title = em... | [
"def",
"pretty_print_prediction",
"(",
"emissions",
",",
"real_state",
",",
"predicted_state",
",",
"emission_title",
"=",
"'Emissions'",
",",
"real_title",
"=",
"'Real State'",
",",
"predicted_title",
"=",
"'Predicted State'",
",",
"line_width",
"=",
"75",
")",
":"... | print out a state sequence prediction in a nice manner . | train | false |
45,682 | def _sqrt_numeric_denest(a, b, r, d2):
from sympy.simplify.simplify import radsimp
depthr = sqrt_depth(r)
d = sqrt(d2)
vad = (a + d)
if ((sqrt_depth(vad) < (depthr + 1)) or (vad ** 2).is_Rational):
vad1 = radsimp((1 / vad))
return (sqrt((vad / 2)) + (sign(b) * sqrt(((((b ** 2) * r) * vad1) / 2).expand()))).exp... | [
"def",
"_sqrt_numeric_denest",
"(",
"a",
",",
"b",
",",
"r",
",",
"d2",
")",
":",
"from",
"sympy",
".",
"simplify",
".",
"simplify",
"import",
"radsimp",
"depthr",
"=",
"sqrt_depth",
"(",
"r",
")",
"d",
"=",
"sqrt",
"(",
"d2",
")",
"vad",
"=",
"(",... | helper that denest expr = a + b*sqrt(r) . | train | false |
45,683 | @click.command(name='open')
@click.option('--ignore_empty_list', is_flag=True, help='Do not raise exception if there are no actionable indices')
@click.option('--filter_list', callback=validate_filter_json, help='JSON string representing an array of filters.', required=True)
@click.pass_context
def open_singleton(ctx, ... | [
"@",
"click",
".",
"command",
"(",
"name",
"=",
"'open'",
")",
"@",
"click",
".",
"option",
"(",
"'--ignore_empty_list'",
",",
"is_flag",
"=",
"True",
",",
"help",
"=",
"'Do not raise exception if there are no actionable indices'",
")",
"@",
"click",
".",
"optio... | open indices . | train | false |
45,685 | @pytest.mark.parametrize('user_input, output', [('qutebrowser.org', 'http://qutebrowser.org'), ('http://qutebrowser.org', 'http://qutebrowser.org'), ('::1/foo', 'http://[::1]/foo'), ('[::1]/foo', 'http://[::1]/foo'), ('http://[::1]', 'http://[::1]'), ('qutebrowser.org', 'http://qutebrowser.org'), ('http://qutebrowser.o... | [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'user_input, output'",
",",
"[",
"(",
"'qutebrowser.org'",
",",
"'http://qutebrowser.org'",
")",
",",
"(",
"'http://qutebrowser.org'",
",",
"'http://qutebrowser.org'",
")",
",",
"(",
"'::1/foo'",
",",
"'http://[:... | test qurl_from_user_input . | train | false |
45,686 | def decode_pair(s, pos=0):
nameLength = ord(s[pos])
if (nameLength & 128):
nameLength = (struct.unpack('!L', s[pos:(pos + 4)])[0] & 2147483647)
pos += 4
else:
pos += 1
valueLength = ord(s[pos])
if (valueLength & 128):
valueLength = (struct.unpack('!L', s[pos:(pos + 4)])[0] & 2147483647)
pos += 4
else:
... | [
"def",
"decode_pair",
"(",
"s",
",",
"pos",
"=",
"0",
")",
":",
"nameLength",
"=",
"ord",
"(",
"s",
"[",
"pos",
"]",
")",
"if",
"(",
"nameLength",
"&",
"128",
")",
":",
"nameLength",
"=",
"(",
"struct",
".",
"unpack",
"(",
"'!L'",
",",
"s",
"["... | decodes a name/value pair . | train | false |
45,687 | @task
@timed
def install_prereqs():
if no_prereq_install():
print NO_PREREQ_MESSAGE
return
install_node_prereqs()
install_python_prereqs()
log_installed_python_prereqs()
| [
"@",
"task",
"@",
"timed",
"def",
"install_prereqs",
"(",
")",
":",
"if",
"no_prereq_install",
"(",
")",
":",
"print",
"NO_PREREQ_MESSAGE",
"return",
"install_node_prereqs",
"(",
")",
"install_python_prereqs",
"(",
")",
"log_installed_python_prereqs",
"(",
")"
] | installs node and python prerequisites . | train | false |
45,688 | @deprecated_network
def do_floating_ip_list(cs, _args):
_print_floating_ip_list(cs.floating_ips.list())
| [
"@",
"deprecated_network",
"def",
"do_floating_ip_list",
"(",
"cs",
",",
"_args",
")",
":",
"_print_floating_ip_list",
"(",
"cs",
".",
"floating_ips",
".",
"list",
"(",
")",
")"
] | list floating ips . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.