output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def _parse_response_for_dict(response):
''' Extracts name-values from response header. Filter out the standard
http headers.'''
if response is None:
return None
http_headers = ['server', 'date', 'location', 'host',
'via', 'proxy-connection', 'connection']
return_dict = _... | Create a Python 3 function for
extracting name - values from response header. Filter out the standard http headers. | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert XML to ServiceProperties. | Can you generate a brief explanation for the following Python 3 code
def _convert_xml_to_service_properties(xml):
'''
<?xml version="1.0" encoding="utf-8"?>
<StorageServiceProperties>
<Logging>
<Version>version-number</Version>
<Delete>true|false</Delete>
<Read>tr... | You are a Python code generator, capable of creating scripts from specifications. |
def insert_entity(self, entity):
'''
Adds an insert entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.insert_entity` for more
information on inserts.
The operation will not be executed until the batch is committed.
:param... | Write a Python 3 script to
add an insert entity operation to the BatchService. | You are a Python code generator, capable of creating scripts from specifications. |
def update_entity(self, entity, if_match='*'):
'''
Adds an update entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.update_entity` for more
information on updates.
The operation will not be executed until the batch is committed.
... | How would you implement a function in Python 3 that
updates the metadata of an entity in the table. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def merge_entity(self, entity, if_match='*'):
'''
Adds a merge entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.merge_entity` for more
information on merges.
The operation will not be executed until the batch is committed.
... | Write a Python 3 script for
adding a merge entity operation to the BatchService. | You are a Python code analyst, evaluating scripts for potential improvements. |
Adds an insert or replace entity operation to the batch. | Can you generate the documentation for the following Python 3 function
def insert_or_replace_entity(self, entity):
'''
Adds an insert or replace entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.insert_or_replace_entity` for more
information on in... | You are a Python code analyst, evaluating scripts for potential improvements. |
def insert_or_merge_entity(self, entity):
'''
Adds an insert or merge entity operation to the batch. See
:func:`~azure.storage.table.tableservice.TableService.insert_or_merge_entity` for more
information on insert or merge operations.
The operation will not be executed until t... | Can you implement a function in Python 3 that
adds an insert or merge entity operation to the Batch. | As a Python code composer, you craft elegant and concise scripts. |
def update_iscsi_settings(self, iscsi_data):
"""Update iscsi data
:param data: default iscsi config data
"""
self._conn.patch(self.path, data=iscsi_data) | Write a Python 3 script to
update iscsi data :param data: default iscsi config data | As a Python code composer, you craft elegant and concise scripts. |
This property gets the list of instances of array controllers | Here you have a function in Python 3, explain what it does
def array_controllers(self):
return array_controller.HPEArrayControllerCollection(
self._conn, utils.get_subresource_path_by(
self, ['Links', 'ArrayControllers']),
redfish_version=self.redfish_version) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Waits until the operation is completed. | How would you explain what the following Python 3 function does
def wait_for_operation_to_complete(
has_operation_completed, retries=10, delay_bw_retries=5,
delay_before_attempts=10, failover_exc=exception.IloError,
failover_msg=("Operation did not complete even after multiple "
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Gets the base filename and extension of the target file. | Explain what the following Python 3 code does
def get_filename_and_extension_of(target_file):
base_target_filename = os.path.basename(target_file)
file_name, file_ext_with_dot = os.path.splitext(base_target_filename)
return file_name, file_ext_with_dot | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add executable permissions to the file
| Can you tell what is the following Python 3 function doing
def add_exec_permission_to(target_file):
mode = os.stat(target_file).st_mode
os.chmod(target_file, mode | stat.S_IXUSR) | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_major_minor(ilo_ver_str):
"""Extract the major and minor number from the passed string
:param ilo_ver_str: the string that contains the version information
:returns: String of the form "<major>.<minor>" or None
"""
if not ilo_ver_str:
return None
try:
# Note(vmud213):Thi... | Write a Python 3 script to
extract the major and minor number from the passed string | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieves the server supported boot modes as a namedtuple containing boot_mode_bios and boot_mode_uefi as true/'false. | Can you generate a brief explanation for the following Python 3 code
def get_supported_boot_modes(supported_boot_mode_constant):
boot_mode_bios = 'false'
boot_mode_uefi = 'false'
if (supported_boot_mode_constant ==
constants.SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY):
boot_mode_bios = 'true'
... | As a python code expert, you are capable of creating scripts from specifications. |
Return the key and value from a string. | Here you have a function in Python 3, explain what it does
def _get_key_value(string):
# Normally all properties look like this:
# Unique Identifier: 600508B1001CE4ACF473EE9C826230FF
# Disk Name: /dev/sda
# Mount Points: None
key = ''
value = ''
try:
key, value = string.split('... | As a Python code composer, you craft elegant and concise scripts. |
def _convert_to_dict(stdout):
"""Wrapper function for parsing hpssacli/ssacli command.
This function gets the output from hpssacli/ssacli command
and calls the recursive function _get_dict to return
the complete dictionary containing the RAID information.
"""
lines = stdout.split("\n")
lin... | Write a Python 3 script for
wrapping function for parsing hpssacli command. | As a python code expert, you are capable of creating scripts from specifications. |
def _ssacli(*args, **kwargs):
"""Wrapper function for executing hpssacli/ssacli command.
This function executes ssacli command if it exists, else it
falls back to hpssacli.
:param args: args to be provided to hpssacli/ssacli command
:param kwargs: kwargs to be sent to processutils except the
... | How would you code a function in Python 3 to
wrap function for executing the ssacli command. | You are a Python code generator, capable of creating scripts from specifications. |
def refresh(self):
"""Refresh the server and it's child objects.
This method removes all the cache information in the server
and it's child objects, and fetches the information again from
the server using hpssacli/ssacli command.
:raises: HPSSAOperationError, if hpssacli/ssacli... | Implement a Python 3 function for
refreshing the server and it s child objects. | As a Python code composer, you craft elegant and concise scripts. |
Get the controller object given the id. | Explain what the following Python 3 code does
def get_controller_by_id(self, id):
for controller in self.controllers:
if controller.id == id:
return controller
return None | As a python code expert, you are capable of creating scripts from specifications. |
Get all the RAID logical drives in the Server. | How would you explain what the following Python 3 function does
def get_logical_drives(self):
logical_drives = []
for controller in self.controllers:
for array in controller.raid_arrays:
for logical_drive in array.logical_drives:
logical_drives.append(logi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get all the RAID physical drives on the Server. | How would you explain what the following Python 3 function does
def get_physical_drives(self):
physical_drives = []
for controller in self.controllers:
# First add unassigned physical drives.
for physical_drive in controller.unassigned_physical_drives:
physical_dr... | As a python code expert, you are capable of creating scripts from specifications. |
def get_logical_drive_by_wwn(self, wwn):
"""Get the logical drive object given the wwn.
This method returns the logical drive object with the given wwn.
:param wwn: wwn of the logical drive
:returns: LogicalDrive object which has the wwn or None if
logical drive is not foun... | Create a Python 3 function for
getting the logical drive object given the wwn. This method returns the logical drive object with the given wwn. :param wwn: wwn of the logical drive :returns: LogicalDrive object which has the wwn or None if logical drive is not found. | You are a Python code generator, capable of creating scripts from specifications. |
Get a PhysicalDrive object for given id. | Given the following Python 3 function, write the documentation
def get_physical_drive_by_id(self, id):
for phy_drive in self.unassigned_physical_drives:
if phy_drive.id == id:
return phy_drive
for array in self.raid_arrays:
for phy_drive in array.physical_drives:
... | As a python code expert, you are capable of creating scripts from specifications. |
def execute_cmd(self, *args, **kwargs):
"""Execute a given hpssacli/ssacli command on the controller.
This method executes a given command on the controller.
:params args: a tuple consisting of sub-commands to be appended
after specifying the controller in hpssacli/ssacli command.
... | Write a Python 3 function that can
execute a given hpssacli command on the controller. | As a python code expert, you are capable of creating scripts from specifications. |
def create_logical_drive(self, logical_drive_info):
"""Create a logical drive on the controller.
This method creates a logical drive on the controller when the
logical drive details and physical drive ids are passed to it.
:param logical_drive_info: a dictionary containing the details
... | Can you implement a function in Python 3 that
creates a logical drive on the controller. This method creates a logical drive on the controller when the logical drive details and physical drive ids are passed to it. :param logical_drive_info: a dictionary containing the details of the logical drive as specified in raid ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_erase_command(self, drive, pattern):
"""Return the command arguments based on the pattern.
Erase command examples:
1) Sanitize: "ssacli ctrl slot=0 pd 1I:1:1 modify erase
erasepattern=overwrite unrestricted=off forced"
2) Zeros: "ssacli ctrl slot=0 pd 1I:1... | How would you implement a function in Python 3 that
returns the command arguments based on the pattern. | You are a Python code architect, reviewing and designing scalable and efficient code |
def erase_devices(self, drives):
"""Perform Erase on all the drives in the controller.
This method erases all the hdd and ssd drives in the controller
by overwriting the drives with patterns for hdd and erasing storage
blocks for ssd drives. The drives would be unavailable until
... | Write a Python 3 function that can
erase all the HDD and SSD drives in the controller. | You are a Python code analyst, evaluating scripts for potential improvements. |
Check if this RAID array can accomodate the logical disk. | Here you have a function in Python 3, explain what it does
def can_accomodate(self, logical_disk):
raid_level = constants.RAID_LEVEL_INPUT_TO_HPSSA_MAPPING.get(
logical_disk['raid_level'], logical_disk['raid_level'])
args = ("array", self.id, "create", "type=logicaldrive",
"r... | As a Python code composer, you craft elegant and concise scripts. |
Returns a dictionary of with the details of the physical drive. | Can you generate a brief explanation for the following Python 3 code
def get_physical_drive_dict(self):
if isinstance(self.parent, RaidArray):
controller = self.parent.parent.id
status = 'active'
else:
controller = self.parent.id
status = 'ready'
... | As a Python code composer, you craft elegant and concise scripts. |
def logical_raid_levels(self):
"""Gets the raid level for each logical volume
:returns the set of list of raid levels configured.
"""
lg_raid_lvls = set()
for member in self.get_members():
lg_raid_lvls.add(mappings.RAID_LEVEL_MAP_REV.get(member.raid))
return ... | Can you write a function in Python 3 where it
gets the set of raid levels for each logical volume | As a Python code analyst, you investigate and solve complex coding mysteries |
def send_stream(stream, filename, size, mtime, mimetype=None, restricted=True,
as_attachment=False, etag=None, content_md5=None,
chunk_size=None, conditional=True, trusted=False):
"""Send the contents of a file to the client.
.. warning::
It is very easy to be exposed t... | Can you create a Python 3 function that
sends a file to the client. | You are a Python code architect, reviewing and designing scalable and efficient code |
def sanitize_mimetype(mimetype, filename=None):
"""Sanitize a MIME type so the browser does not render the file."""
# Allow some few mime type like plain text, images and audio.
if mimetype in MIMETYPE_WHITELIST:
return mimetype
# Rewrite HTML, JavaScript, CSS etc to text/plain.
if mimetype ... | Implement a Python 3 function for
sanitizing a MIME type so the browser does not render the file. | You are a Python code architect, reviewing and designing scalable and efficient code |
Generates a path as base location for a file instance. | Here you have a function in Python 3, explain what it does
def make_path(base_uri, path, filename, path_dimensions, split_length):
assert len(path) > path_dimensions * split_length
uri_parts = []
for i in range(path_dimensions):
uri_parts.append(path[0:split_length])
path = path[split_lengt... | As a Python code composer, you craft elegant and concise scripts. |
def compute_checksum(stream, algo, message_digest, chunk_size=None,
progress_callback=None):
"""Get helper method to compute checksum from a stream.
:param stream: File-like object.
:param algo: Identifier for checksum algorithm.
:param messsage_digest: A message digest instance.
... | Can you implement a function in Python 3 that
computes checksum from a file - like object. | As a python code expert, you are capable of creating scripts from specifications. |
Populate a list of objects from a file or directory path. | How would you explain what the following Python 3 function does
def populate_from_path(bucket, source, checksum=True, key_prefix='',
chunk_size=None):
"""Populate a ``bucket`` from all files in path.
:param bucket: The bucket (instance or id) to create the object in.
:param source: T... | You are a Python code generator, capable of creating scripts from specifications. |
def set_options(self, options):
"""
Sets instance variables based on an options dict
"""
# COMMAND LINE OPTIONS
self.wipe = options.get("wipe")
self.test_run = options.get("test_run")
self.quiet = options.get("test_run")
self.container_name = options.get("... | Implement a function in Python 3 to
set instance variables based on an options dict. | You are a Python code analyst, evaluating scripts for potential improvements. |
def match_cloud(self, includes, excludes):
"""
Returns the cloud objects that match the include and exclude patterns.
"""
cloud_objs = [cloud_obj.name for cloud_obj in self.container.get_objects()]
includes_pattern = r"|".join([fnmatch.translate(x) for x in includes])
exc... | How would you code a function in Python 3 to
return the cloud objects that match the include and exclude patterns. | As a python code expert, you are capable of creating scripts from specifications. |
Determines files to be uploaded and call upload_file on each. | Explain what the following Python 3 code does
def upload_files(self, abspaths, relpaths, remote_objects):
for relpath in relpaths:
abspath = [p for p in abspaths if p[len(self.file_root):] == relpath][0]
cloud_datetime = remote_objects[relpath] if relpath in remote_objects else None
... | You are a Python code generator, capable of creating scripts from specifications. |
def upload_file(self, abspath, cloud_filename):
"""
Uploads a file to the container.
"""
if not self.test_run:
content = open(abspath, "rb")
content_type = get_content_type(cloud_filename, content)
headers = get_headers(cloud_filename, content_type)
... | Create a Python 3 function for
uploading a file to the container. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def delete_extra_files(self, relpaths, cloud_objs):
"""
Deletes any objects from the container that do not exist locally.
"""
for cloud_obj in cloud_objs:
if cloud_obj not in relpaths:
if not self.test_run:
self.delete_cloud_obj(cloud_obj)
... | Write a Python 3 script for
deleting any extra files from the container that do not exist locally. | As a python code expert, you are capable of creating scripts from specifications. |
Deletes an object from the container. | Make a summary of the following Python 3 code
def delete_cloud_obj(self, cloud_obj):
self._connection.delete_object(
container=self.container_name,
obj=cloud_obj,
) | As a python code expert, you are capable of creating scripts from specifications. |
def print_tally(self):
"""
Prints the final tally to stdout.
"""
self.update_count = self.upload_count - self.create_count
if self.test_run:
print("Test run complete with the following results:")
print("Skipped {0}. Created {1}. Updated {2}. Deleted {3}.".form... | Write a Python 3 function for
printing the final tally to stdout. | As a python code expert, you are capable of creating scripts from specifications. |
def handle(self, *args, **options):
"""
Lists all the items in a container to stdout.
"""
self._connection = Auth()._get_connection()
if len(args) == 0:
containers = self._connection.list_containers()
if not containers:
print("No container... | Implement a Python 3 function for
listing all the items in a container to stdout. | As a Python code analyst, you investigate and solve complex coding mysteries |
def progress_updater(size, total):
"""Progress reporter for checksum verification."""
current_task.update_state(
state=state('PROGRESS'),
meta=dict(size=size, total=total)
) | Write a Python 3 script to
progress reporter for checksum verification. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Verify checksum of a file instance. | Here you have a function in Python 3, explain what it does
def verify_checksum(file_id, pessimistic=False, chunk_size=None, throws=True,
checksum_kwargs=None):
"""Verify checksum of a file instance.
:param file_id: The file ID.
"""
f = FileInstance.query.get(uuid.UUID(file_id))
... | You are a Python code generator, capable of creating scripts from specifications. |
def schedule_checksum_verification(frequency=None, batch_interval=None,
max_count=None, max_size=None,
files_query=None,
checksum_kwargs=None):
"""Schedule a batch of files for checksum verification.
The pu... | Implement a function in Python 3 to
schedule a batch of files for checksum verification. | You are a Python code architect, reviewing and designing scalable and efficient code |
def migrate_file(src_id, location_name, post_fixity_check=False):
"""Task to migrate a file instance to a new location.
.. note:: If something goes wrong during the content copy, the destination
file instance is removed.
:param src_id: The :class:`invenio_files_rest.models.FileInstance` ID.
:p... | Create a Python 3 function to
task to migrate a file instance to a new location. .. note:: If something goes wrong during the content copy, the destination file instance is removed. :param src_id: The :class:`invenio_files_rest.models.FileInstance` ID. :param location_name: Where to migrate the file. :param post_fixity... | You are a Python code analyst, evaluating scripts for potential improvements. |
def remove_file_data(file_id, silent=True):
"""Remove file instance and associated data.
:param file_id: The :class:`invenio_files_rest.models.FileInstance` ID.
:param silent: It stops propagation of a possible arised IntegrityError
exception. (Default: ``True``)
:raises sqlalchemy.exc.Integrit... | Can you write a function in Python 3 where it
removes the file instance and associated data. | You are a Python code generator, capable of creating scripts from specifications. |
Merge a multipart object. | Make a summary of the following Python 3 code
def merge_multipartobject(upload_id, version_id=None):
mp = MultipartObject.query.filter_by(upload_id=upload_id).one_or_none()
if not mp:
raise RuntimeError('Upload ID does not exists.')
if not mp.completed:
raise RuntimeError('MultipartObject is... | As a Python code analyst, you investigate and solve complex coding mysteries |
Remove expired multipart objects. | Can you generate a brief explanation for the following Python 3 code
def remove_expired_multipartobjects():
delta = current_app.config['FILES_REST_MULTIPART_EXPIRES']
expired_dt = datetime.utcnow() - delta
file_ids = []
for mp in MultipartObject.query_expired(expired_dt):
file_ids.append(str(mp... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a factory function for creating a PyFS file storage instance. | Explain what the following Python 3 code does
def pyfs_storage_factory(fileinstance=None, default_location=None,
default_storage_class=None,
filestorage_class=PyFSFileStorage, fileurl=None,
size=None, modified=None, clean_dir=True):
"""Get f... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return tuple with filesystem and filename. | Here you have a function in Python 3, explain what it does
def _get_fs(self, create_dir=True):
filedir = dirname(self.fileurl)
filename = basename(self.fileurl)
return (
opener.opendir(filedir, writeable=True, create_dir=create_dir),
filename
) | You are a Python code architect, reviewing and designing scalable and efficient code |
def open(self, mode='rb'):
"""Open file.
The caller is responsible for closing the file.
"""
fs, path = self._get_fs()
return fs.open(path, mode=mode) | Can you create a Python 3 function that
opens file. The caller is responsible for closing the file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def delete(self):
"""Delete a file.
The base directory is also removed, as it is assumed that only one file
exists in the directory.
"""
fs, path = self._get_fs(create_dir=False)
if fs.exists(path):
fs.remove(path)
if self.clean_dir and fs.exists('.')... | Implement a function in Python 3 to
delete a file. The base directory is also removed, as it is assumed that only one file exists in the directory. | As a Python code analyst, you investigate and solve complex coding mysteries |
def initialize(self, size=0):
"""Initialize file on storage and truncate to given size."""
fs, path = self._get_fs()
# Required for reliably opening the file on certain file systems:
if fs.exists(path):
fp = fs.open(path, mode='r+b')
else:
fp = fs.open(pa... | Implement a Python 3 function for
initializing file on storage and truncate to given size. | You are a Python code generator, capable of creating scripts from specifications. |
def save(self, incoming_stream, size_limit=None, size=None,
chunk_size=None, progress_callback=None):
"""Save file in the file system."""
fp = self.open(mode='wb')
try:
bytes_written, checksum = self._write_stream(
incoming_stream, fp, chunk_size=chunk_si... | Write a Python 3 function for
saving file in the file system. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update(self, incoming_stream, seek=0, size=None, chunk_size=None,
progress_callback=None):
"""Update a file in the file system."""
fp = self.open(mode='r+b')
try:
fp.seek(seek)
bytes_written, checksum = self._write_stream(
incoming_strea... | Write a Python 3 script to
update a file in the file system. | You are a Python code analyst, evaluating scripts for potential improvements. |
def permission_factory(obj, action):
"""Get default permission factory.
:param obj: An instance of :class:`invenio_files_rest.models.Bucket` or
:class:`invenio_files_rest.models.ObjectVersion` or
:class:`invenio_files_rest.models.MultipartObject` or ``None`` if
the action is global.
... | Can you create a Python 3 function that
gets default permission factory. | As a python code expert, you are capable of creating scripts from specifications. |
def delete_file(self, path, prefixed_path, source_storage):
"""
Checks if the target file should be deleted if it already exists
"""
if isinstance(self.storage, CumulusStorage):
if self.storage.exists(prefixed_path):
try:
etag = self.storag... | Can you implement a function in Python 3 that
checks if the target file should be deleted if it already exists and if it should be deleted if it should be skipped if it should be deleted if it already exists | As a Python code analyst, you investigate and solve complex coding mysteries |
def cp(source, bucket, checksum, key_prefix):
"""Create new bucket from all files in directory."""
from .models import Bucket
from .helpers import populate_from_path
for object_version in populate_from_path(
Bucket.get(bucket), source, checksum=checksum,
key_prefix=key_prefix):
... | Can you write a function in Python 3 where it
creates new bucket from all files in directory. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the content type of the given name. | Make a summary of the following Python 3 code
def get_content_type(name, content):
if hasattr(content, "content_type"):
content_type = content.content_type
else:
mime_type, encoding = mimetypes.guess_type(name)
content_type = mime_type
return content_type | You are a Python code architect, reviewing and designing scalable and efficient code |
Synchronizes the given cloud_obj s headers with the ones given as headers. | Given the following Python 3 function, write the documentation
def sync_headers(cloud_obj, headers=None, header_patterns=HEADER_PATTERNS):
if headers is None:
headers = {}
# don't set headers on directories
content_type = getattr(cloud_obj, "content_type", None)
if content_type == "application/... | You are a Python code generator, capable of creating scripts from specifications. |
def get_gzipped_contents(input_file):
"""
Returns a gzipped version of a previously opened file's buffer.
"""
zbuf = StringIO()
zfile = GzipFile(mode="wb", compresslevel=6, fileobj=zbuf)
zfile.write(input_file.read())
zfile.close()
return ContentFile(zbuf.getvalue()) | Implement a Python 3 function for
returning a gzipped version of a previously opened file s buffer. | You are a Python code generator, capable of creating scripts from specifications. |
Determine which schema to use based on context. | Can you tell what is the following Python 3 function doing
def schema_from_context(context):
item_class = context.get('class')
return (
serializer_mapping[item_class] if item_class else BaseSchema,
context.get('many', False)
) | As a python code expert, you are capable of creating scripts from specifications. |
Get helper to wait for async task result to finish. | Make a summary of the following Python 3 code
def wait_for_taskresult(task_result, content, interval, max_rounds):
assert max_rounds > 0
def _whitespace_waiting():
current = 0
while current < max_rounds and current != -1:
if task_result.ready():
# Task is done and we... | As a python code expert, you are capable of creating scripts from specifications. |
Builds a json flask response using the given data. | Can you generate the documentation for the following Python 3 function
def json_serializer(data=None, code=200, headers=None, context=None,
etag=None, task_result=None):
"""Build a json flask response using the given data.
:param data: The data to serialize. (Default: ``None``)
:param c... | You are a Python code architect, reviewing and designing scalable and efficient code |
def dump_links(self, o):
"""Dump links."""
return {
'self': url_for('.bucket_api', bucket_id=o.id, _external=True),
'versions': url_for(
'.bucket_api', bucket_id=o.id, _external=True) + '?versions',
'uploads': url_for(
'.bucket_api', bu... | Create a Python 3 function for
dumping links for a specific object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Wrap response in envelope. | Here you have a function in Python 3, explain what it does
def wrap(self, data, many):
if not many:
return data
else:
data = {'contents': data}
bucket = self.context.get('bucket')
if bucket:
data.update(BucketSchema().dump(bucket).data)
... | As a Python code composer, you craft elegant and concise scripts. |
Wrap response in envelope. | Can you generate a brief explanation for the following Python 3 code
def wrap(self, data, many):
if not many:
return data
else:
data = {'parts': data}
multipart = self.context.get('multipart')
if multipart:
data.update(MultipartObjectSchema... | As a python code expert, you are capable of creating scripts from specifications. |
def directions(self, origin, destination, mode=None, alternatives=None,
waypoints=None, optimize_waypoints=False,
avoid=None, language=None, units=None,
region=None, departure_time=None,
arrival_time=None, sensor=None):
"""Get direction... | Write a Python 3 script to
get directions between locations in a specific language. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Upgrade database to version 1. 0. | Explain what the following Python 3 code does
def upgrade():
# Variant types:
def created():
"""Return instance of a column."""
return sa.Column(
'created',
sa.DateTime().with_variant(mysql.DATETIME(fsp=6), 'mysql'),
nullable=False
)
def updated()... | You are a Python code architect, reviewing and designing scalable and efficient code |
Map extra mimetype with the encoding provided. | Can you generate a brief explanation for the following Python 3 code
def guess_mimetype(filename):
m, encoding = mimetypes.guess_type(filename)
if encoding:
m = ENCODING_MIMETYPES.get(encoding, None)
return m or 'application/octet-stream' | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate a formatter for links. | How would you explain what the following Python 3 function does
def link(text, link_func):
def object_formatter(v, c, m, p):
"""Format object view link."""
return Markup('<a href="{0}">{1}</a>'.format(
link_func(m), text))
return object_formatter | You are a Python code generator, capable of creating scripts from specifications. |
def validate_tag(key, value):
"""Validate a tag.
Keys must be less than 128 chars and values must be less than 256 chars.
"""
# Note, parse_sql does not include a keys if the value is an empty string
# (e.g. 'key=&test=a'), and thus technically we should not get strings
# which have zero length... | Create a Python 3 function for
validating a tag. Keys must be less than 128 chars and values must be less than 256 chars. | As a Python code composer, you craft elegant and concise scripts. |
Parse tags specified in the HTTP request header. | Given the following Python 3 function, write the documentation
def parse_header_tags():
# Get the value of the custom HTTP header and interpret it as an query
# string
qs = request.headers.get(
current_app.config['FILES_REST_FILE_TAGS_HEADER'], '')
tags = {}
for key, value in parse_qsl(qs):... | As a python code expert, you are capable of creating scripts from specifications. |
Get default part factory. | Can you generate a brief explanation for the following Python 3 code
def default_partfactory(part_number=None, content_length=None,
content_type=None, content_md5=None):
"""Get default part factory.
:param part_number: The part number. (Default: ``None``)
:param content_length: The ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def stream_uploadfactory(content_md5=None, content_length=None,
content_type=None):
"""Get default put factory.
If Content-Type is ``'multipart/form-data'`` then the stream is aborted.
:param content_md5: The content MD5. (Default: ``None``)
:param content_length: The content ... | How would you implement a function in Python 3 that
gets default put factory. | You are a Python code generator, capable of creating scripts from specifications. |
Part factory for ng - file - upload. | Can you generate the documentation for the following Python 3 function
def ngfileupload_partfactory(part_number=None, content_length=None,
uploaded_file=None):
"""Part factory for ng-file-upload.
:param part_number: The part number. (Default: ``None``)
:param content_length: Th... | As a Python code composer, you craft elegant and concise scripts. |
Get default put factory. | Can you generate a brief explanation for the following Python 3 code
def ngfileupload_uploadfactory(content_length=None, content_type=None,
uploaded_file=None):
"""Get default put factory.
If Content-Type is ``'multipart/form-data'`` then the stream is aborted.
:param conten... | As a Python code composer, you craft elegant and concise scripts. |
Decorate to retrieve a bucket. | Make a summary of the following Python 3 code
def pass_bucket(f):
@wraps(f)
def decorate(*args, **kwargs):
bucket_id = kwargs.pop('bucket_id')
bucket = Bucket.get(as_uuid(bucket_id))
if not bucket:
abort(404, 'Bucket does not exist.')
return f(bucket=bucket, *args, **... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorate to retrieve an object. | How would you explain what the following Python 3 function does
def pass_multipart(with_completed=False):
def decorate(f):
@wraps(f)
def inner(self, bucket, key, upload_id, *args, **kwargs):
obj = MultipartObject.get(
bucket, key, upload_id, with_completed=with_completed)... | You are a Python code generator, capable of creating scripts from specifications. |
Check if permission is allowed. | Explain what the following Python 3 code does
def check_permission(permission, hidden=True):
if permission is not None and not permission.can():
if hidden:
abort(404)
else:
if current_user.is_authenticated:
abort(403,
'You do not have a p... | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator for functions that need permissions for buckets or aborts. | Can you tell what is the following Python 3 function doing
def need_permissions(object_getter, action, hidden=True):
def decorator_builder(f):
@wraps(f)
def decorate(*args, **kwargs):
check_permission(current_permission_factory(
object_getter(*args, **kwargs),
... | You are a Python code analyst, evaluating scripts for potential improvements. |
List objects in a bucket. | Can you generate a brief explanation for the following Python 3 code
def multipart_listuploads(self, bucket):
return self.make_response(
data=MultipartObject.query_by_bucket(bucket).limit(1000).all(),
context={
'class': MultipartObject,
'bucket': bucket,
... | You are a Python code generator, capable of creating scripts from specifications. |
def listobjects(self, bucket, versions):
"""List objects in a bucket.
:param bucket: A :class:`invenio_files_rest.models.Bucket` instance.
:returns: The Flask response.
"""
if versions is not missing:
check_permission(
current_permission_factory(bucke... | Create a Python 3 function to
list objects in a bucket. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get list of objects in the bucket. | Can you tell what is the following Python 3 function doing
def get(self, bucket=None, versions=missing, uploads=missing):
if uploads is not missing:
return self.multipart_listuploads(bucket)
else:
return self.listobjects(bucket, versions) | As a Python code composer, you craft elegant and concise scripts. |
def check_object_permission(obj):
"""Retrieve object and abort if it doesn't exists."""
check_permission(current_permission_factory(
obj,
'object-read'
))
if not obj.is_head:
check_permission(
current_permission_factory(obj, 'object-rea... | How would you implement a function in Python 3 that
retrieves object and abort if it doesn t exist. | As a Python code composer, you craft elegant and concise scripts. |
Retrieve object and abort if it doesn t exist. | Can you generate a brief explanation for the following Python 3 code
def get_object(cls, bucket, key, version_id):
obj = ObjectVersion.get(bucket, key, version_id=version_id)
if not obj:
abort(404, 'Object does not exists.')
cls.check_object_permission(obj)
return obj | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_object(self, bucket, key):
"""Create a new object.
:param bucket: The bucket (instance or id) to get the object from.
:param key: The file key.
:returns: A Flask response.
"""
# Initial validation of size based on Content-Length.
# User can tamper with... | Create a Python 3 function to
create a new object in the specified bucket. | You are a Python code architect, reviewing and designing scalable and efficient code |
Delete an existing object. | Can you generate the documentation for the following Python 3 function
def delete_object(self, bucket, obj, version_id):
if version_id is None:
# Create a delete marker.
with db.session.begin_nested():
ObjectVersion.delete(bucket, obj.key)
db.session.commit()
... | As a python code expert, you are capable of creating scripts from specifications. |
def send_object(bucket, obj, expected_chksum=None,
logger_data=None, restricted=True, as_attachment=False):
"""Send an object for a given bucket.
:param bucket: The bucket (instance or id) to get the object from.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion`... | Write a Python 3 script for
sending an object to a given bucket. | As a Python code analyst, you investigate and solve complex coding mysteries |
def multipart_listparts(self, multipart):
"""Get parts of a multipart upload.
:param multipart: A :class:`invenio_files_rest.models.MultipartObject`
instance.
:returns: A Flask response.
"""
return self.make_response(
data=Part.query_by_multipart(
... | How would you code a function in Python 3 to
return a Flask response for listing the parts of a multipart upload. | As a Python code composer, you craft elegant and concise scripts. |
def multipart_init(self, bucket, key, size=None, part_size=None):
"""Initialize a multipart upload.
:param bucket: The bucket (instance or id) to get the object from.
:param key: The file key.
:param size: The total size.
:param part_size: The part size.
:raises invenio_... | Write a Python 3 function that can
initialize a multipart upload. | As a Python code composer, you craft elegant and concise scripts. |
Upload a part.
:param multipart: A :class:`invenio_files_rest.models.MultipartObject`
instance.
:returns: A Flask response. | How would you explain what the following Python 3 function does
def multipart_uploadpart(self, multipart):
content_length, part_number, stream, content_type, content_md5, tags =\
current_files_rest.multipart_partfactory()
if content_length:
ck = multipart.last_part_size if \
... | As a python code expert, you are capable of creating scripts from specifications. |
Complete a multipart upload. | Given the following Python 3 function, write the documentation
def multipart_complete(self, multipart):
multipart.complete()
db.session.commit()
version_id = str(uuid.uuid4())
return self.make_response(
data=multipart,
context={
'class': Multipar... | As a python code expert, you are capable of creating scripts from specifications. |
Abort a multipart upload. | Can you generate a brief explanation for the following Python 3 code
def multipart_delete(self, multipart):
multipart.delete()
db.session.commit()
if multipart.file_id:
remove_file_data.delay(str(multipart.file_id))
return self.make_response('', 204) | You are a Python code architect, reviewing and designing scalable and efficient code |
def get(self, bucket=None, key=None, version_id=None, upload_id=None,
uploads=None, download=None):
"""Get object or list parts of a multpart upload.
:param bucket: The bucket (instance or id) to get the object from.
(Default: ``None``)
:param key: The file key. (Default... | Create a Python 3 function to
get object or list parts of a multpart upload. | You are a Python code analyst, evaluating scripts for potential improvements. |
def post(self, bucket=None, key=None, uploads=missing, upload_id=None):
"""Upload a new object or start/complete a multipart upload.
:param bucket: The bucket (instance or id) to get the object from.
(Default: ``None``)
:param key: The file key. (Default: ``None``)
:param up... | Create a Python 3 function for
uploading a new object or start a multipart upload. | As a Python code analyst, you investigate and solve complex coding mysteries |
def put(self, bucket=None, key=None, upload_id=None):
"""Update a new object or upload a part of a multipart upload.
:param bucket: The bucket (instance or id) to get the object from.
(Default: ``None``)
:param key: The file key. (Default: ``None``)
:param upload_id: The upl... | Can you create a Python 3 function that
updates a new object or upload a part of a multipart upload. | You are a Python code analyst, evaluating scripts for potential improvements. |
def delete(self, bucket=None, key=None, version_id=None, upload_id=None,
uploads=None):
"""Delete an object or abort a multipart upload.
:param bucket: The bucket (instance or id) to get the object from.
(Default: ``None``)
:param key: The file key. (Default: ``None``... | Write a Python 3 script to
delete an object or abort a multipart upload. | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.