_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4400 | get_permission_request | train | def get_permission_request(parser, token):
"""
Performs a permission request check with the given signature, user and objects
and assigns the result to a context variable.
Syntax::
{% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %}
{% get_permissi... | python | {
"resource": ""
} |
q4401 | permission_delete_link | train | def permission_delete_link(context, perm):
"""
Renders a html link to the delete view of the given permission. Returns
no content if the request-user has no permission to delete foreign
permissions.
"""
user = context['request'].user
if user.is_authenticated():
if (user.has_perm('aut... | python | {
"resource": ""
} |
q4402 | permission_request_delete_link | train | def permission_request_delete_link(context, perm):
"""
Renders a html link to the delete view of the given permission request.
Returns no content if the request-user has no permission to delete foreign
permissions.
"""
user = context['request'].user
if user.is_authenticated():
link_k... | python | {
"resource": ""
} |
q4403 | permission_request_approve_link | train | def permission_request_approve_link(context, perm):
"""
Renders a html link to the approve view of the given permission request.
Returns no content if the request-user has no permission to delete foreign
permissions.
"""
user = context['request'].user
if user.is_authenticated():
if u... | python | {
"resource": ""
} |
q4404 | ResolverNode.resolve | train | def resolve(self, var, context):
"""Resolves a variable out of context if it's not in quotes"""
if var is None:
return var
if var[0] in ('"', "'") and var[-1] == var[0]:
return var[1:-1]
else:
return template.Variable(var).resolve(context) | python | {
"resource": ""
} |
q4405 | PermissionManager.group_permissions | train | def group_permissions(self, group, perm, obj, approved=True):
"""
Get objects that have Group perm permission on
"""
return self.get_for_model(obj).select_related(
'user', 'group', 'creator').filter(group=group, codename=perm,
ap... | python | {
"resource": ""
} |
q4406 | PermissionManager.delete_user_permissions | train | def delete_user_permissions(self, user, perm, obj, check_groups=False):
"""
Remove granular permission perm from user on an object instance
"""
user_perms = self.user_permissions(user, perm, obj, check_groups=False)
if not user_perms.filter(object_id=obj.id):
return
... | python | {
"resource": ""
} |
q4407 | ParsedWhois.flattened | train | def flattened(self):
"""Returns a flattened version of the parsed whois data"""
parsed = self['parsed_whois']
flat = OrderedDict()
for key in ('domain', 'created_date', 'updated_date', 'expired_date', 'statuses', 'name_servers'):
value = parsed[key]
flat[key] = ' ... | python | {
"resource": ""
} |
q4408 | permission_denied | train | def permission_denied(request, template_name=None, extra_context=None):
"""
Default 403 handler.
Templates: `403.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
if template_name is None:
template_name = ('403.html', 'autho... | python | {
"resource": ""
} |
q4409 | Permission.approve | train | def approve(self, creator):
"""
Approve granular permission request setting a Permission entry as
approved=True for a specific action from an user on an object instance.
"""
self.approved = True
self.creator = creator
self.save() | python | {
"resource": ""
} |
q4410 | autodiscover_modules | train | def autodiscover_modules():
"""
Goes and imports the permissions submodule of every app in INSTALLED_APPS
to make sure the permission set classes are registered correctly.
"""
import imp
from django.conf import settings
for app in settings.INSTALLED_APPS:
try:
__import__... | python | {
"resource": ""
} |
q4411 | BasePermission._get_user_cached_perms | train | def _get_user_cached_perms(self):
"""
Set up both the user and group caches.
"""
if not self.user:
return {}, {}
group_pks = set(self.user.groups.values_list(
'pk',
flat=True,
))
perms = Permission.objects.filter(
Q(... | python | {
"resource": ""
} |
q4412 | BasePermission._get_group_cached_perms | train | def _get_group_cached_perms(self):
"""
Set group cache.
"""
if not self.group:
return {}
perms = Permission.objects.filter(
group=self.group,
)
group_permissions = {}
for perm in perms:
group_permissions[(
... | python | {
"resource": ""
} |
q4413 | BasePermission._prime_user_perm_caches | train | def _prime_user_perm_caches(self):
"""
Prime both the user and group caches and put them on the ``self.user``.
In addition add a cache filled flag on ``self.user``.
"""
perm_cache, group_perm_cache = self._get_user_cached_perms()
self.user._authority_perm_cache = perm_cac... | python | {
"resource": ""
} |
q4414 | BasePermission._prime_group_perm_caches | train | def _prime_group_perm_caches(self):
"""
Prime the group cache and put them on the ``self.group``.
In addition add a cache filled flag on ``self.group``.
"""
perm_cache = self._get_group_cached_perms()
self.group._authority_perm_cache = perm_cache
self.group._autho... | python | {
"resource": ""
} |
q4415 | BasePermission.invalidate_permissions_cache | train | def invalidate_permissions_cache(self):
"""
In the event that the Permission table is changed during the use of a
permission the Permission cache will need to be invalidated and
regenerated. By calling this method the invalidation will occur, and
the next time the cached_permissi... | python | {
"resource": ""
} |
q4416 | BasePermission.has_group_perms | train | def has_group_perms(self, perm, obj, approved):
"""
Check if group has the permission for the given object
"""
if not self.group:
return False
if self.use_smart_cache:
content_type_pk = Permission.objects.get_content_type(obj).pk
def _group_h... | python | {
"resource": ""
} |
q4417 | BasePermission.has_perm | train | def has_perm(self, perm, obj, check_groups=True, approved=True):
"""
Check if user has the permission for the given object
"""
if self.user:
if self.has_user_perms(perm, obj, approved, check_groups):
return True
if self.group:
return self.h... | python | {
"resource": ""
} |
q4418 | BasePermission.requested_perm | train | def requested_perm(self, perm, obj, check_groups=True):
"""
Check if user requested a permission for the given object
"""
return self.has_perm(perm, obj, check_groups, False) | python | {
"resource": ""
} |
q4419 | BasePermission.assign | train | def assign(self, check=None, content_object=None, generic=False):
"""
Assign a permission to a user.
To assign permission for all checks: let check=None.
To assign permission for all objects: let content_object=None.
If generic is True then "check" will be suffixed with _modeln... | python | {
"resource": ""
} |
q4420 | delimited | train | def delimited(items, character='|'):
"""Returns a character delimited version of the provided list as a Python string"""
return '|'.join(items) if type(items) in (list, tuple, set) else items | python | {
"resource": ""
} |
q4421 | API._rate_limit | train | def _rate_limit(self):
"""Pulls in and enforces the latest rate limits for the specified user"""
self.limits_set = True
for product in self.account_information():
self.limits[product['id']] = {'interval': timedelta(seconds=60 / float(product['per_minute_limit']))} | python | {
"resource": ""
} |
q4422 | API.domain_search | train | def domain_search(self, query, exclude_query=[], max_length=25, min_length=2, has_hyphen=True, has_number=True,
active_only=False, deleted_only=False, anchor_left=False, anchor_right=False, page=1, **kwargs):
"""Each term in the query string must be at least three characters long.
... | python | {
"resource": ""
} |
q4423 | API.domain_suggestions | train | def domain_suggestions(self, query, **kwargs):
"""Passed in name must be at least two characters long. Use a list or spaces to separate multiple terms."""
return self._results('domain-suggestions', '/v1/domain-suggestions', query=delimited(query, ' '),
items_path=('suggestion... | python | {
"resource": ""
} |
q4424 | API.hosting_history | train | def hosting_history(self, query, **kwargs):
"""Returns the hosting history from the given domain name"""
return self._results('hosting-history', '/v1/{0}/hosting-history'.format(query), cls=GroupedIterable, **kwargs) | python | {
"resource": ""
} |
q4425 | API.ip_registrant_monitor | train | def ip_registrant_monitor(self, query, days_back=0, search_type="all", server=None, country=None, org=None, page=1,
include_total_count=False, **kwargs):
"""Query based on free text query terms"""
return self._results('ip-registrant-monitor', '/v1/ip-registrant-monitor', qu... | python | {
"resource": ""
} |
q4426 | API.parsed_whois | train | def parsed_whois(self, query, **kwargs):
"""Pass in a domain name"""
return self._results('parsed-whois', '/v1/{0}/whois/parsed'.format(query), cls=ParsedWhois, **kwargs) | python | {
"resource": ""
} |
q4427 | API.reputation | train | def reputation(self, query, include_reasons=False, **kwargs):
"""Pass in a domain name to see its reputation score"""
return self._results('reputation', '/v1/reputation', domain=query, include_reasons=include_reasons,
cls=Reputation, **kwargs) | python | {
"resource": ""
} |
q4428 | API.host_domains | train | def host_domains(self, ip=None, limit=None, **kwargs):
"""Pass in an IP address."""
return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs) | python | {
"resource": ""
} |
q4429 | API.reverse_ip_whois | train | def reverse_ip_whois(self, query=None, ip=None, country=None, server=None, include_total_count=False, page=1,
**kwargs):
"""Pass in an IP address or a list of free text query terms."""
if (ip and query) or not (ip or query):
raise ValueError('Query or IP Address (but... | python | {
"resource": ""
} |
q4430 | API.reverse_name_server | train | def reverse_name_server(self, query, limit=None, **kwargs):
"""Pass in a domain name or a name server."""
return self._results('reverse-name-server', '/v1/{0}/name-server-domains'.format(query),
items_path=('primary_domains', ), limit=limit, **kwargs) | python | {
"resource": ""
} |
q4431 | API.phisheye_term_list | train | def phisheye_term_list(self, include_inactive=False, **kwargs):
"""Provides a list of terms that are set up for this account.
This call is not charged against your API usage limit.
NOTE: The terms must be configured in the PhishEye web interface: https://research.domaintools.com/phisheye.... | python | {
"resource": ""
} |
q4432 | API.iris | train | def iris(self, domain=None, ip=None, email=None, nameserver=None, registrar=None, registrant=None,
registrant_org=None, **kwargs):
"""Performs a search for the provided search terms ANDed together,
returning the pivot engine row data for the resulting domains.
"""
if ((no... | python | {
"resource": ""
} |
q4433 | API.risk | train | def risk(self, domain, **kwargs):
"""Returns back the risk score for a given domain"""
return self._results('risk', '/v1/risk', items_path=('components', ), domain=domain, cls=Reputation,
**kwargs) | python | {
"resource": ""
} |
q4434 | API.risk_evidence | train | def risk_evidence(self, domain, **kwargs):
"""Returns back the detailed risk evidence associated with a given domain"""
return self._results('risk-evidence', '/v1/risk/evidence/', items_path=('components', ), domain=domain,
**kwargs) | python | {
"resource": ""
} |
q4435 | Fetcher.init | train | def init(self):
"""Returns a tuple pair of cookie and crumb used in the request"""
url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker)
r = requests.get(url)
txt = r.content
cookie = r.cookies['B']
pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^... | python | {
"resource": ""
} |
q4436 | Fetcher.getData | train | def getData(self, events):
"""Returns a list of historical data from Yahoo Finance"""
if self.interval not in ["1d", "1wk", "1mo"]:
raise ValueError("Incorrect interval: valid intervals are 1d, 1wk, 1mo")
url = self.api_url % (self.ticker, self.start, self.end, self.interval, events... | python | {
"resource": ""
} |
q4437 | Disk._get_mount_methods | train | def _get_mount_methods(self, disk_type):
"""Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount
methods.
"""
if self.disk_mounter == 'auto':
methods = []
def add_method_if_exists(method):
if (me... | python | {
"resource": ""
} |
q4438 | Disk._mount_avfs | train | def _mount_avfs(self):
"""Mounts the AVFS filesystem."""
self._paths['avfs'] = tempfile.mkdtemp(prefix='image_mounter_avfs_')
# start by calling the mountavfs command to initialize avfs
_util.check_call_(['avfsd', self._paths['avfs'], '-o', 'allow_other'], stdout=subprocess.PIPE)
... | python | {
"resource": ""
} |
q4439 | Disk.init_volumes | train | def init_volumes(self, single=None, only_mount=None, skip_mount=None, swallow_exceptions=True):
"""Generator that detects and mounts all volumes in the disk.
:param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`.
If *single* is False, only... | python | {
"resource": ""
} |
q4440 | Disk.get_volumes | train | def get_volumes(self):
"""Gets a list of all volumes in this disk, including volumes that are contained in other volumes."""
volumes = []
for v in self.volumes:
volumes.extend(v.get_volumes())
return volumes | python | {
"resource": ""
} |
q4441 | Disk.unmount | train | def unmount(self, remove_rw=False, allow_lazy=False):
"""Removes all ties of this disk to the filesystem, so the image can be unmounted successfully.
:raises SubsystemError: when one of the underlying commands fails. Some are swallowed.
:raises CleanupError: when actual cleanup fails. Some are ... | python | {
"resource": ""
} |
q4442 | ArgumentParsedShell._make_argparser | train | def _make_argparser(self):
"""Makes a new argument parser."""
self.argparser = ShellArgumentParser(prog='')
subparsers = self.argparser.add_subparsers()
for name in self.get_names():
if name.startswith('parser_'):
parser = subparsers.add_parser(name[7:])
... | python | {
"resource": ""
} |
q4443 | ArgumentParsedShell.default | train | def default(self, line):
"""Overriding default to get access to any argparse commands we have specified."""
if any((line.startswith(x) for x in self.argparse_names())):
try:
args = self.argparser.parse_args(shlex.split(line))
except Exception: # intentionally ca... | python | {
"resource": ""
} |
q4444 | ArgumentParsedShell.completedefault | train | def completedefault(self, text, line, begidx, endidx):
"""Accessing the argcompleter if available."""
if self.argparser_completer and any((line.startswith(x) for x in self.argparse_names())):
self.argparser_completer.rl_complete(line, 0)
return [x[begidx:] for x in self.argparser... | python | {
"resource": ""
} |
q4445 | ArgumentParsedShell.completenames | train | def completenames(self, text, *ignored):
"""Patched to also return argparse commands"""
return sorted(cmd.Cmd.completenames(self, text, *ignored) + self.argparse_names(text)) | python | {
"resource": ""
} |
q4446 | ArgumentParsedShell.do_help | train | def do_help(self, arg):
"""Patched to show help for arparse commands"""
if not arg or arg not in self.argparse_names():
cmd.Cmd.do_help(self, arg)
else:
try:
self.argparser.parse_args([arg, '--help'])
except Exception:
pass | python | {
"resource": ""
} |
q4447 | ArgumentParsedShell.print_topics | train | def print_topics(self, header, cmds, cmdlen, maxcol):
"""Patched to show all argparse commands as being documented"""
if header == self.doc_header:
cmds.extend(self.argparse_names())
cmd.Cmd.print_topics(self, header, sorted(cmds), cmdlen, maxcol) | python | {
"resource": ""
} |
q4448 | ImageMounterShell.preloop | train | def preloop(self):
"""if the parser is not already set, loads the parser."""
if not self.parser:
self.stdout.write("Welcome to imagemounter {version}".format(version=__version__))
self.stdout.write("\n")
self.parser = ImageParser()
for p in self.args.path... | python | {
"resource": ""
} |
q4449 | ImageMounterShell.onecmd | train | def onecmd(self, line):
"""Do not crash the entire program when a single command fails."""
try:
return cmd.Cmd.onecmd(self, line)
except Exception as e:
print("Critical error.", e) | python | {
"resource": ""
} |
q4450 | ImageMounterShell._get_all_indexes | train | def _get_all_indexes(self):
"""Returns all indexes available in the parser"""
if self.parser:
return [v.index for v in self.parser.get_volumes()] + [d.index for d in self.parser.disks]
else:
return None | python | {
"resource": ""
} |
q4451 | ImageMounterShell._get_by_index | train | def _get_by_index(self, index):
"""Returns a volume,disk tuple for the specified index"""
volume_or_disk = self.parser.get_by_index(index)
volume, disk = (volume_or_disk, None) if not isinstance(volume_or_disk, Disk) else (None, volume_or_disk)
return volume, disk | python | {
"resource": ""
} |
q4452 | ImageMounterShell.do_quit | train | def do_quit(self, arg):
"""Quits the program."""
if self.saved:
self.save()
else:
self.parser.clean()
return True | python | {
"resource": ""
} |
q4453 | Unmounter.unmount | train | def unmount(self):
"""Calls all unmount methods in the correct order."""
self.unmount_bindmounts()
self.unmount_mounts()
self.unmount_volume_groups()
self.unmount_loopbacks()
self.unmount_base_images()
self.clean_dirs() | python | {
"resource": ""
} |
q4454 | ImageParser.add_disk | train | def add_disk(self, path, force_disk_indexes=True, **args):
"""Adds a disk specified by the path to the ImageParser.
:param path: The path to the disk volume
:param force_disk_indexes: If true, always uses disk indexes. If False, only uses disk indexes if this is the
... | python | {
"resource": ""
} |
q4455 | ImageParser.rw_active | train | def rw_active(self):
"""Indicates whether a read-write cache is active in any of the disks.
:rtype: bool"""
result = False
for disk in self.disks:
result = disk.rw_active() or result
return result | python | {
"resource": ""
} |
q4456 | ImageParser.get_by_index | train | def get_by_index(self, index):
"""Returns a Volume or Disk by its index."""
try:
return self[index]
except KeyError:
for v in self.get_volumes():
if v.index == str(index):
return v
raise KeyError(index) | python | {
"resource": ""
} |
q4457 | ImageParser.force_clean | train | def force_clean(self, remove_rw=False, allow_lazy=False, retries=5, sleep_interval=0.5):
"""Attempts to call the clean method, but will retry automatically if an error is raised. When the attempts
run out, it will raise the last error.
Note that the method will only catch :class:`ImageMounterEr... | python | {
"resource": ""
} |
q4458 | ImageParser.reconstruct | train | def reconstruct(self):
"""Reconstructs the filesystem of all volumes mounted by the parser by inspecting the last mount point and
bind mounting everything.
:raises: NoRootFoundError if no root could be found
:return: the root :class:`Volume`
"""
volumes = list(sorted((v ... | python | {
"resource": ""
} |
q4459 | VolumeSystem._make_subvolume | train | def _make_subvolume(self, **args):
"""Creates a subvolume, adds it to this class and returns it."""
from imagemounter.volume import Volume
v = Volume(disk=self.disk, parent=self.parent,
volume_detector=self.volume_detector,
**args) # vstype is not passed d... | python | {
"resource": ""
} |
q4460 | VolumeSystem._make_single_subvolume | train | def _make_single_subvolume(self, only_one=True, **args):
"""Creates a subvolume, adds it to this class, sets the volume index to 0 and returns it.
:param bool only_one: if this volume system already has at least one volume, it is returned instead.
"""
if only_one and self.volumes:
... | python | {
"resource": ""
} |
q4461 | VolumeSystem.detect_volumes | train | def detect_volumes(self, vstype=None, method=None, force=False):
"""Iterator for detecting volumes within this volume system.
:param str vstype: The volume system type to use. If None, uses :attr:`vstype`
:param str method: The detection method to use. If None, uses :attr:`detection`
:p... | python | {
"resource": ""
} |
q4462 | VolumeSystem._determine_auto_detection_method | train | def _determine_auto_detection_method():
"""Return the detection method to use when the detection method is 'auto'"""
if dependencies.pytsk3.is_available:
return 'pytsk3'
elif dependencies.mmls.is_available:
return 'mmls'
elif dependencies.parted.is_available:
... | python | {
"resource": ""
} |
q4463 | VolumeSystem._assign_disktype_data | train | def _assign_disktype_data(self, volume, slot=None):
"""Assigns cached disktype data to a volume."""
if slot is None:
slot = volume.slot
if slot in self._disktype:
data = self._disktype[slot]
if not volume.info.get('guid') and 'guid' in data:
v... | python | {
"resource": ""
} |
q4464 | VolumeDetector._format_index | train | def _format_index(self, volume_system, idx):
"""Returns a formatted index given the disk index idx."""
if volume_system.parent.index is not None:
return '{0}.{1}'.format(volume_system.parent.index, idx)
else:
return str(idx) | python | {
"resource": ""
} |
q4465 | Pytsk3VolumeDetector._find_volumes | train | def _find_volumes(self, volume_system, vstype='detect'):
"""Finds all volumes based on the pytsk3 library."""
try:
# noinspection PyUnresolvedReferences
import pytsk3
except ImportError:
logger.error("pytsk3 not installed, could not detect volumes")
... | python | {
"resource": ""
} |
q4466 | Pytsk3VolumeDetector.detect | train | def detect(self, volume_system, vstype='detect'):
"""Generator that mounts every partition of this image and yields the mountpoint."""
# Loop over all volumes in image.
for p in self._find_volumes(volume_system, vstype):
import pytsk3
volume = volume_system._make_subvol... | python | {
"resource": ""
} |
q4467 | PartedVolumeDetector.detect | train | def detect(self, volume_system, vstype='detect'):
"""Finds and mounts all volumes based on parted.
:param VolumeSystem volume_system: The volume system.
"""
# for some reason, parted does not properly return extended volume types in its machine
# output, so we need to execute i... | python | {
"resource": ""
} |
q4468 | VssVolumeDetector.detect | train | def detect(self, volume_system, vstype='detect'):
"""Detect volume shadow copy volumes in the specified path."""
path = volume_system.parent._paths['vss']
try:
volume_info = _util.check_output_(["vshadowinfo", "-o", str(volume_system.parent.offset),
... | python | {
"resource": ""
} |
q4469 | LvmVolumeDetector.detect | train | def detect(self, volume_system, vstype='detect'):
"""Gather information about lvolumes, gathering their label, size and raw path"""
volume_group = volume_system.parent.info.get('volume_group')
result = _util.check_output_(["lvm", "lvdisplay", volume_group])
cur_v = None
for l i... | python | {
"resource": ""
} |
q4470 | Volume._get_fstype_from_parser | train | def _get_fstype_from_parser(self, fstype=None):
"""Load fstype information from the parser instance."""
if fstype:
self.fstype = fstype
elif self.index in self.disk.parser.fstypes:
self.fstype = self.disk.parser.fstypes[self.index]
elif '*' in self.disk.parser.fst... | python | {
"resource": ""
} |
q4471 | Volume._get_blkid_type | train | def _get_blkid_type(self):
"""Retrieves the FS type from the blkid command."""
try:
result = _util.check_output_(['blkid', '-p', '-O', str(self.offset), self.get_raw_path()])
if not result:
return None
# noinspection PyTypeChecker
blkid_re... | python | {
"resource": ""
} |
q4472 | Volume._get_magic_type | train | def _get_magic_type(self):
"""Checks the volume for its magic bytes and returns the magic."""
try:
with io.open(self.disk.get_fs_path(), "rb") as file:
file.seek(self.offset)
fheader = file.read(min(self.size, 4096) if self.size else 4096)
except IOEr... | python | {
"resource": ""
} |
q4473 | Volume.get_safe_label | train | def get_safe_label(self):
"""Returns a label that is safe to add to a path in the mountpoint for this volume."""
if self.info.get('label') == '/':
return 'root'
suffix = re.sub(r"[/ \(\)]+", "_", self.info.get('label')) if self.info.get('label') else ""
if suffix and suffix... | python | {
"resource": ""
} |
q4474 | Volume.detect_volume_shadow_copies | train | def detect_volume_shadow_copies(self):
"""Method to call vshadowmount and mount NTFS volume shadow copies.
:return: iterable with the :class:`Volume` objects of the VSS
:raises CommandNotFoundError: if the underlying command does not exist
:raises SubSystemError: if the underlying comma... | python | {
"resource": ""
} |
q4475 | Volume._should_mount | train | def _should_mount(self, only_mount=None, skip_mount=None):
"""Indicates whether this volume should be mounted. Internal method, used by imount.py"""
om = only_mount is None or \
self.index in only_mount or \
self.info.get('lastmountpoint') in only_mount or \
self.inf... | python | {
"resource": ""
} |
q4476 | Volume.init | train | def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True):
"""Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mou... | python | {
"resource": ""
} |
q4477 | Volume._clear_mountpoint | train | def _clear_mountpoint(self):
"""Clears a created mountpoint. Does not unmount it, merely deletes it."""
if self.mountpoint:
os.rmdir(self.mountpoint)
self.mountpoint = "" | python | {
"resource": ""
} |
q4478 | Volume.bindmount | train | def bindmount(self, mountpoint):
"""Bind mounts the volume to another mountpoint. Only works if the volume is already mounted.
:raises NotMountedError: when the volume is not yet mounted
:raises SubsystemError: when the underlying command failed
"""
if not self.mountpoint:
... | python | {
"resource": ""
} |
q4479 | Volume.get_volumes | train | def get_volumes(self):
"""Recursively gets a list of all subvolumes and the current volume."""
if self.volumes:
volumes = []
for v in self.volumes:
volumes.extend(v.get_volumes())
volumes.append(self)
return volumes
else:
... | python | {
"resource": ""
} |
q4480 | require | train | def require(*requirements, **kwargs):
"""Decorator that can be used to require requirements.
:param requirements: List of requirements that should be verified
:param none_on_failure: If true, does not raise a PrerequisiteFailedError, but instead returns None
"""
# TODO: require(*requirements, none_... | python | {
"resource": ""
} |
q4481 | CommandDependency.status_message | train | def status_message(self):
"""Detailed message about whether the dependency is installed.
:rtype: str
"""
if self.is_available:
return "INSTALLED {0!s}"
elif self.why and self.package:
return "MISSING {0!s:<20}needed for {0.why}, part of the {0.package} ... | python | {
"resource": ""
} |
q4482 | FileSystemType.mount | train | def mount(self, volume):
"""Mounts the given volume on the provided mountpoint. The default implementation simply calls mount.
:param Volume volume: The volume to be mounted
:param mountpoint: The file system path to mount the filesystem on.
:raises UnsupportedFilesystemError: when the ... | python | {
"resource": ""
} |
q4483 | FileSystemType._call_mount | train | def _call_mount(self, volume, mountpoint, type=None, opts=""):
"""Calls the mount command, specifying the mount type and mount options."""
# default arguments for calling mount
if opts and not opts.endswith(','):
opts += ","
opts += 'loop,offset=' + str(volume.offset) + ',si... | python | {
"resource": ""
} |
q4484 | Jffs2FileSystemType.mount | train | def mount(self, volume):
"""Perform specific operations to mount a JFFS2 image. This kind of image is sometimes used for things like
bios images. so external tools are required but given this method you don't have to memorize anything and it
works fast and easy.
Note that this module mi... | python | {
"resource": ""
} |
q4485 | RaidFileSystemType.mount | train | def mount(self, volume):
"""Add the volume to a RAID system. The RAID array is activated as soon as the array can be activated.
:raises NoLoopbackAvailableError: if no loopback device was found
"""
volume._find_loopback()
raid_status = None
try:
# use mdadm... | python | {
"resource": ""
} |
q4486 | escape | train | def escape(s, fold_newlines=True):
"""Escapes a string to make it usable in LaTeX text mode. Will replace
special characters as well as newlines.
Some problematic characters like ``[`` and ``]`` are escaped into groups
(e.g. ``{[}``), because they tend to cause problems when mixed with ``\\``
newli... | python | {
"resource": ""
} |
q4487 | build_pdf | train | def build_pdf(source, texinputs=[], builder=None):
"""Builds a LaTeX source to PDF.
Will automatically instantiate an available builder (or raise a
:class:`exceptions.RuntimeError` if none are available) and build the
supplied source with it.
Parameters are passed on to the builder's
:meth:`~l... | python | {
"resource": ""
} |
q4488 | parse_log | train | def parse_log(log, context_size=3):
"""Parses latex log output and tries to extract error messages.
Requires ``-file-line-error`` to be active.
:param log: The contents of the logfile as a string.
:param context_size: Number of lines to keep as context, including the
original ... | python | {
"resource": ""
} |
q4489 | split_metadata_params | train | def split_metadata_params(headers):
"""
Given a dict of headers for s3, seperates those that are boto3
parameters and those that must be metadata
"""
params = {}
metadata = {}
for header_name in headers:
if header_name.lower() in header_mapping:
params[header_mapping[hea... | python | {
"resource": ""
} |
q4490 | hash_file | train | def hash_file(filename):
"""
Generate a hash for the contents of a file
"""
hasher = hashlib.sha1()
with open(filename, 'rb') as f:
buf = f.read(65536)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(65536)
return hasher.hexdigest() | python | {
"resource": ""
} |
q4491 | _get_bucket_name | train | def _get_bucket_name(**values):
"""
Generates the bucket name for url_for.
"""
app = current_app
# manage other special values, all have no meaning for static urls
values.pop('_external', False) # external has no meaning here
values.pop('_anchor', None) # anchor as well
values.pop('_me... | python | {
"resource": ""
} |
q4492 | url_for | train | def url_for(endpoint, **values):
"""
Generates a URL to the given endpoint.
If the endpoint is for a static resource then an Amazon S3 URL is
generated, otherwise the call is passed on to `flask.url_for`.
Because this function is set as a jinja environment variable when
`FlaskS3.init_app` is i... | python | {
"resource": ""
} |
q4493 | _bp_static_url | train | def _bp_static_url(blueprint):
""" builds the absolute url path for a blueprint's static folder """
u = six.u('%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or ''))
return u | python | {
"resource": ""
} |
q4494 | _gather_files | train | def _gather_files(app, hidden, filepath_filter_regex=None):
""" Gets all files in static folders and returns in dict."""
dirs = [(six.text_type(app.static_folder), app.static_url_path)]
if hasattr(app, 'blueprints'):
blueprints = app.blueprints.values()
bp_details = lambda x: (x.static_folde... | python | {
"resource": ""
} |
q4495 | _static_folder_path | train | def _static_folder_path(static_url, static_folder, static_asset):
"""
Returns a path to a file based on the static folder, and not on the
filesystem holding the file.
Returns a path relative to static_url for static_asset
"""
# first get the asset path relative to the static folder.
# stati... | python | {
"resource": ""
} |
q4496 | _write_files | train | def _write_files(s3, app, static_url_loc, static_folder, files, bucket,
ex_keys=None, hashes=None):
""" Writes all the files inside a static folder to S3. """
should_gzip = app.config.get('FLASKS3_GZIP')
add_mime = app.config.get('FLASKS3_FORCE_MIMETYPE')
gzip_include_only = app.config.... | python | {
"resource": ""
} |
q4497 | create_all | train | def create_all(app, user=None, password=None, bucket_name=None,
location=None, include_hidden=False,
filepath_filter_regex=None, put_bucket_acl=True):
"""
Uploads of the static assets associated with a Flask application to
Amazon S3.
All static assets are identified on the... | python | {
"resource": ""
} |
q4498 | _expand | train | def _expand(subsequence, sequence, max_l_dist):
"""Expand a partial match of a Levenstein search.
An expansion must begin at the beginning of the sequence, which makes
this much simpler than a full search, and allows for greater optimization.
"""
# If given a long sub-sequence and relatively small ... | python | {
"resource": ""
} |
q4499 | _py_expand_short | train | def _py_expand_short(subsequence, sequence, max_l_dist):
"""Straightforward implementation of partial match expansion."""
# The following diagram shows the score calculation step.
#
# Each new score is the minimum of:
# * a OR a + 1 (substitution, if needed)
# * b + 1 (deletion, i.e. skipping ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.