output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Gets or creates the container.
Given the following Python 3 function, write the documentation def _get_container(self): if not hasattr(self, "_container"): if self.use_pyrax: self._container = self.connection.create_container(self.container_name) else: self._container = None ret...
You are a Python code generator, capable of creating scripts from specifications.
def _set_container(self, container): """ Sets the container (and, if needed, the configured TTL on it), making the container publicly available. """ if self.use_pyrax: if container.cdn_ttl != self.ttl or not container.cdn_enabled: container.make_public...
Write a Python 3 function that can set the container and makes it publicly available.
You are a Python code analyst, evaluating scripts for potential improvements.
Helper function to retrieve the requested object.
Explain what the following Python 3 code does def _get_object(self, name): if self.use_pyrax: try: return self.container.get_object(name) except pyrax.exceptions.NoSuchObject: return None elif swiftclient: try: return se...
As a Python code analyst, you investigate and solve complex coding mysteries
Get an object version object from an object version ID or an object version.
Here you have a function in Python 3, explain what it does def as_object_version(value): return value if isinstance(value, ObjectVersion) \ else ObjectVersion.query.filter_by(version_id=value).one_or_none()
You are a Python code architect, reviewing and designing scalable and efficient code
def update_bucket_size(f): """Decorate to update bucket size after operation.""" @wraps(f) def inner(self, *args, **kwargs): res = f(self, *args, **kwargs) self.bucket.size += self.file.size return res return inner
Write a Python 3 script for decorating to update bucket size after operation.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a decorator factory function that ensures that the state of the current user is in the correct state.
Can you generate a brief explanation for the following Python 3 code def ensure_state(default_getter, exc_class, default_msg=None): def decorator(getter=default_getter, msg=default_msg): def ensure_decorator(f): @wraps(f) def inner(self, *args, **kwargs): if not gette...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the size limit for this bucket.
Explain what the following Python 3 code does def size_limit(self): limits = [ lim for lim in current_files_rest.file_size_limiters( self) if lim.limit is not None ] return min(limits) if limits else None
You are a Python code architect, reviewing and designing scalable and efficient code
Create a snapshot of latest objects in bucket.
Here you have a function in Python 3, explain what it does def snapshot(self, lock=False): with db.session.begin_nested(): bucket = Bucket( default_location=self.default_location, default_storage_class=self.default_storage_class, quota_size=self.quota_...
You are a Python code architect, reviewing and designing scalable and efficient code
r Create a new bucket.
Can you generate a brief explanation for the following Python 3 code def create(cls, location=None, storage_class=None, **kwargs): with db.session.begin_nested(): if location is None: location = Location.get_default() elif isinstance(location, six.string_types): ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get(cls, bucket_id): """Get a bucket object (excluding deleted). :param bucket_id: Bucket identifier. :returns: Bucket instance. """ return cls.query.filter_by( id=bucket_id, deleted=False ).one_or_none()
Can you implement a function in Python 3 that gets a bucket object.
You are a Python code architect, reviewing and designing scalable and efficient code
def delete(cls, bucket_id): """Delete a bucket. Does not actually delete the Bucket, just marks it as deleted. """ bucket = cls.get(bucket_id) if not bucket or bucket.deleted: return False bucket.deleted = True return True
Implement a Python 3 function for deleting a bucket. Does not actually delete the Bucket, just marks it as deleted.
As a Python code analyst, you investigate and solve complex coding mysteries
def create(cls, bucket, key, value): """Create a new tag for bucket.""" with db.session.begin_nested(): obj = cls( bucket_id=as_bucket_id(bucket), key=key, value=value ) db.session.add(obj) return obj
Implement a function in Python 3 to create a new tag for a bucket.
You are a Python code generator, capable of creating scripts from specifications.
Create or update a new tag for bucket.
Can you tell what is the following Python 3 function doing def create_or_update(cls, bucket, key, value): obj = cls.get(bucket, key) if obj: obj.value = value db.session.merge(obj) else: obj = cls.create(bucket, key, value) return obj
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a file instance by URI.
Can you tell what is the following Python 3 function doing def get_by_uri(cls, uri): assert uri is not None return cls.query.filter_by(uri=uri).one_or_none()
As a python code expert, you are capable of creating scripts from specifications.
def create(cls): """Create a file instance. Note, object is only added to the database session. """ obj = cls( id=uuid.uuid4(), writable=True, readable=False, size=0, ) db.session.add(obj) return obj
Implement a Python 3 function for creating a file instance.
As a Python code analyst, you investigate and solve complex coding mysteries
Delete a file instance.
Here you have a function in Python 3, explain what it does def delete(self): self.query.filter_by(id=self.id).delete() return self
As a python code expert, you are capable of creating scripts from specifications.
Update checksum based on file.
Can you tell what is the following Python 3 function doing def update_checksum(self, progress_callback=None, chunk_size=None, checksum_kwargs=None, **kwargs): """Update checksum based on file.""" self.checksum = self.storage(**kwargs).checksum( progress_callback=progr...
As a Python code composer, you craft elegant and concise scripts.
Clear the checksum of the file.
Can you generate a brief explanation for the following Python 3 code def clear_last_check(self): with db.session.begin_nested(): self.last_check = None self.last_check_at = datetime.utcnow() return self
As a Python code composer, you craft elegant and concise scripts.
Verify checksum of file instance.
Can you generate a brief explanation for the following Python 3 code def verify_checksum(self, progress_callback=None, chunk_size=None, throws=True, checksum_kwargs=None, **kwargs): """Verify checksum of file instance. :param bool throws: If `True`, exceptions raised during chec...
As a Python code translator, you convert algorithms and pseudocode into Python.
Save contents of stream to this file.
Can you generate a brief explanation for the following Python 3 code def update_contents(self, stream, seek=0, size=None, chunk_size=None, progress_callback=None, **kwargs): """Save contents of stream to this file. :param obj: ObjectVersion instance from where this file is acces...
As a python code expert, you are capable of creating scripts from specifications.
def set_contents(self, stream, chunk_size=None, size=None, size_limit=None, progress_callback=None, **kwargs): """Save contents of stream to this file. :param obj: ObjectVersion instance from where this file is accessed from. :param stream: File-like stream. ...
Write a Python 3 script to save contents of the object version to this file.
You are a Python code generator, capable of creating scripts from specifications.
def copy_contents(self, fileinstance, progress_callback=None, chunk_size=None, **kwargs): """Copy this file instance into another file instance.""" if not fileinstance.readable: raise ValueError('Source file instance is not readable.') if not self.size == 0: ...
Implement a function in Python 3 to copy this file instance into another file instance.
As a Python code composer, you craft elegant and concise scripts.
def send_file(self, filename, restricted=True, mimetype=None, trusted=False, chunk_size=None, as_attachment=False, **kwargs): """Send file to client.""" return self.storage(**kwargs).send_file( filename, mimetype=mimetype, restricte...
Write a Python 3 function that can send file to the client.
You are a Python code architect, reviewing and designing scalable and efficient code
Set a location of a file.
Explain what the following Python 3 code does def set_uri(self, uri, size, checksum, readable=True, writable=False, storage_class=None): """Set a location of a file.""" self.uri = uri self.size = size self.checksum = checksum self.writable = writable self....
You are a Python code analyst, evaluating scripts for potential improvements.
Save contents of stream to file instance.
Make a summary of the following Python 3 code def set_contents(self, stream, chunk_size=None, size=None, size_limit=None, progress_callback=None): """Save contents of stream to file instance. If a file instance has already been set, this methods raises an ``FileInstanceAlre...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_location(self, uri, size, checksum, storage_class=None): """Set only URI location of for object. Useful to link files on externally controlled storage. If a file instance has already been set, this methods raises an ``FileInstanceAlreadySetError`` exception. :param uri:...
Can you create a Python 3 function that sets only URI location of for object.
As a Python code composer, you craft elegant and concise scripts.
def send_file(self, restricted=True, trusted=False, **kwargs): """Wrap around FileInstance's send file.""" return self.file.send_file( self.basename, restricted=restricted, mimetype=self.mimetype, trusted=trusted, **kwargs )
How would you implement a function in Python 3 that wraps around FileInstance s send file method.
As a Python code analyst, you investigate and solve complex coding mysteries
Copy an object version to a given bucket + object key.
Make a summary of the following Python 3 code def copy(self, bucket=None, key=None): new_ob = ObjectVersion.create( self.bucket if bucket is None else as_bucket(bucket), key or self.key, _file_id=self.file_id ) for tag in self.tags: ObjectVersionT...
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new object in a bucket.
Make a summary of the following Python 3 code def create(cls, bucket, key, _file_id=None, stream=None, mimetype=None, version_id=None, **kwargs): """Create a new object in a bucket. The created object is by default created as a delete marker. You must use ``set_contents()`` or ``...
You are a Python code analyst, evaluating scripts for potential improvements.
def get(cls, bucket, key, version_id=None): """Fetch a specific object. By default the latest object version is returned, if ``version_id`` is not set. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param version_id: Speci...
How would you code a function in Python 3 to fetch a specific object from the database.
As a python code expert, you are capable of creating scripts from specifications.
def get_versions(cls, bucket, key, desc=True): """Fetch all versions of a specific object. :param bucket: The bucket (instance or id) to get the object from. :param key: Key of object. :param desc: Sort results desc if True, asc otherwise. :returns: The query to execute to fetch...
Can you write a function in Python 3 where it fetches all versions of a specific object.
As a Python code composer, you craft elegant and concise scripts.
def delete(cls, bucket, key): """Delete an object. Technically works by creating a new version which works as a delete marker. :param bucket: The bucket (instance or id) to delete the object from. :param key: Key of object. :returns: Created delete marker object if key ...
Write a Python 3 function for deleting an object. Technically works by creating a new version which works as a delete marker. :param bucket: The bucket (instance or id) to delete the object from. :param key: Key of object. :returns: Created delete marker object if key exists else ``None``.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a query that fetches all the objects in a given bucket.
Given the following Python 3 function, write the documentation def get_by_bucket(cls, bucket, versions=False, with_deleted=False): bucket_id = bucket.id if isinstance(bucket, Bucket) else bucket filters = [ cls.bucket_id == bucket_id, ] if not versions: filters....
As a Python code translator, you convert algorithms and pseudocode into Python.
Relink all object versions for a given file to a new file.
Explain what the following Python 3 code does def relink_all(cls, old_file, new_file): assert old_file.checksum == new_file.checksum assert old_file.id assert new_file.id with db.session.begin_nested(): ObjectVersion.query.filter_by(file_id=str(old_file.id)).update({ ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def copy(self, object_version=None, key=None): """Copy a tag to a given object version. :param object_version: The object version instance to copy the tag to. Default: current object version. :param key: Key of destination tag. Default: current tag key. :return: ...
Can you implement a function in Python 3 that copies a tag to a given object version.
As a Python code analyst, you investigate and solve complex coding mysteries
def get(cls, object_version, key): """Get the tag object.""" return cls.query.filter_by( version_id=as_object_version_id(object_version), key=key, ).one_or_none()
How would you code a function in Python 3 to get the tag object.
You are a Python code architect, reviewing and designing scalable and efficient code
def create(cls, object_version, key, value): """Create a new tag for a given object version.""" assert len(key) < 256 assert len(value) < 256 with db.session.begin_nested(): obj = cls(version_id=as_object_version_id(object_version), key=key, ...
Can you create a Python 3 function that creates a new tag for a given object version.
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_or_update(cls, object_version, key, value): """Create or update a new tag for a given object version.""" assert len(key) < 256 assert len(value) < 256 obj = cls.get(object_version, key) if obj: obj.value = value db.session.merge(obj) els...
Implement a function in Python 3 to create or update a new tag for a given object version.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_value(cls, object_version, key): """Get the tag value.""" obj = cls.get(object_version, key) return obj.value if obj else None
Write a Python 3 function for getting the tag value.
As a Python code analyst, you investigate and solve complex coding mysteries
def delete(cls, object_version, key=None): """Delete tags. :param object_version: The object version instance or id. :param key: Key of the tag to delete. Default: delete all tags. """ with db.session.begin_nested(): q = cls.query.filter_by( ...
Can you create a Python 3 function that deletes tags. :param object_version: The object version instance or id. :param key: Key of the tag to delete. Default: delete all tags.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get last part number.
Can you generate a brief explanation for the following Python 3 code def last_part_number(self): return int(self.size / self.chunk_size) \ if self.size % self.chunk_size else \ int(self.size / self.chunk_size) - 1
As a Python code analyst, you investigate and solve complex coding mysteries
Check if size is valid.
Given the following Python 3 function, write the documentation def is_valid_chunksize(chunk_size): min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MAX'] return chunk_size >= min_csize and chunk_size <= max_csize
As a Python code translator, you convert algorithms and pseudocode into Python.
def is_valid_size(size, chunk_size): """Validate max theoretical size.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_size = \ chunk_size * current_app.config['FILES_REST_MULTIPART_MAX_PARTS'] return size > min_csize and size <= max_size
Write a Python 3 script for validating max theoretical size.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the expected part size for a particular part number.
How would you explain what the following Python 3 function does def expected_part_size(self, part_number): last_part = self.multipart.last_part_number if part_number == last_part: return self.multipart.last_part_size elif part_number >= 0 and part_number < last_part: ret...
As a python code expert, you are capable of creating scripts from specifications.
def complete(self): """Mark a multipart object as complete.""" if Part.count(self) != self.last_part_number + 1: raise MultipartMissingParts() with db.session.begin_nested(): self.completed = True self.file.readable = True self.file.writable = Fal...
Can you write a function in Python 3 where it marks a multipart object as complete.
As a Python code composer, you craft elegant and concise scripts.
def merge_parts(self, version_id=None, **kwargs): """Merge parts into object version.""" self.file.update_checksum(**kwargs) with db.session.begin_nested(): obj = ObjectVersion.create( self.bucket, self.key, _file_id=self.file_id, ...
Implement a Python 3 function for merging parts into object version.
You are a Python code analyst, evaluating scripts for potential improvements.
def delete(self): """Delete a multipart object.""" # Update bucket size. self.bucket.size -= self.size # Remove parts Part.query_by_multipart(self).delete() # Remove self self.query.filter_by(upload_id=self.upload_id).delete()
Write a Python 3 function for deleting a multipart object.
You are a Python code analyst, evaluating scripts for potential improvements.
def create(cls, bucket, key, size, chunk_size): """Create a new object in a bucket.""" bucket = as_bucket(bucket) if bucket.locked: raise BucketLockedError() # Validate chunk size. if not cls.is_valid_chunksize(chunk_size): raise MultipartInvalidChunkSiz...
Create a Python 3 function for creating a new object in a bucket.
You are a Python code architect, reviewing and designing scalable and efficient code
def get(cls, bucket, key, upload_id, with_completed=False): """Fetch a specific multipart object.""" q = cls.query.filter_by( upload_id=upload_id, bucket_id=as_bucket_id(bucket), key=key, ) if not with_completed: q = q.filter(cls.completed....
Implement a Python 3 function for fetching a specific multipart object.
You are a Python code generator, capable of creating scripts from specifications.
def query_expired(cls, dt, bucket=None): """Query all uncompleted multipart uploads.""" q = cls.query.filter(cls.created < dt).filter_by(completed=True) if bucket: q = q.filter(cls.bucket_id == as_bucket_id(bucket)) return q
Can you implement a function in Python 3 that queries all uncompleted multipart uploads.
You are a Python code analyst, evaluating scripts for potential improvements.
def query_by_bucket(cls, bucket): """Query all uncompleted multipart uploads.""" return cls.query.filter(cls.bucket_id == as_bucket_id(bucket))
Create a Python 3 function for querying all uncompleted multipart uploads.
As a Python code analyst, you investigate and solve complex coding mysteries
def end_byte(self): """Get end byte in file for this part.""" return min( (self.part_number + 1) * self.multipart.chunk_size, self.multipart.size )
How would you implement a function in Python 3 that gets the end byte of the file for this part.
As a Python code translator, you convert algorithms and pseudocode into Python.
def create(cls, mp, part_number, stream=None, **kwargs): """Create a new part object in a multipart object.""" if part_number < 0 or part_number > mp.last_part_number: raise MultipartInvalidPartNumber() with db.session.begin_nested(): obj = cls( multipart...
Write a Python 3 function for creating a new part object in a multipart object.
As a Python code composer, you craft elegant and concise scripts.
def get_or_none(cls, mp, part_number): """Get part number.""" return cls.query.filter_by( upload_id=mp.upload_id, part_number=part_number ).one_or_none()
Create a Python 3 function for getting or create a new instance of the class based on the given part number.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_or_create(cls, mp, part_number): """Get or create a part.""" obj = cls.get_or_none(mp, part_number) if obj: return obj return cls.create(mp, part_number)
Implement a function in Python 3 to get or create a part.
As a Python code analyst, you investigate and solve complex coding mysteries
def delete(cls, mp, part_number): """Get part number.""" return cls.query.filter_by( upload_id=mp.upload_id, part_number=part_number ).delete()
How would you code a function in Python 3 to delete a single entry from the database.
You are a Python code generator, capable of creating scripts from specifications.
def query_by_multipart(cls, multipart): """Get all parts for a specific multipart upload. :param multipart: A :class:`invenio_files_rest.models.MultipartObject` instance. :returns: A :class:`invenio_files_rest.models.Part` instance. """ upload_id = multipart.upload_i...
How would you code a function in Python 3 to return a QuerySet of Part objects for a specific multipart upload.
As a python code expert, you are capable of creating scripts from specifications.
Save contents of stream to part of file instance.
Can you tell what is the following Python 3 function doing def set_contents(self, stream, progress_callback=None): size, checksum = self.multipart.file.update_contents( stream, seek=self.start_byte, size=self.part_size, progress_callback=progress_callback, ) self.checksum...
As a python code expert, you are capable of creating scripts from specifications.
A context processor that exposes the full CDN URL in templates.
How would you explain what the following Python 3 function does def cdn_url(request): cdn_url, ssl_url = _get_container_urls(CumulusStorage()) static_url = settings.STATIC_URL return { "CDN_URL": cdn_url + static_url, "CDN_SSL_URL": ssl_url + static_url, }
As a Python code composer, you craft elegant and concise scripts.
A context processor that exposes the full static CDN URL as static URL in templates.
Here you have a function in Python 3, explain what it does def static_cdn_url(request): cdn_url, ssl_url = _get_container_urls(CumulusStaticStorage()) static_url = settings.STATIC_URL return { "STATIC_URL": cdn_url + static_url, "STATIC_SSL_URL": ssl_url + static_url, "LOCAL_STATIC_...
As a python code expert, you are capable of creating scripts from specifications.
def _serialize_parameters(parameters): """Serialize some parameters to match python native types with formats specified in google api docs like: * True/False -> "true"/"false", * {"a": 1, "b":2} -> "a:1|b:2" :type parameters: dict oif query parameters """ for ke...
Implement a Python 3 function for serializing some parameters to match python native types with formats
You are a Python code generator, capable of creating scripts from specifications.
Make http request to Google API.
Make a summary of the following Python 3 code def _make_request(self, url, parameters, result_key): url = urlparse.urljoin(urlparse.urljoin(self.base, url), "json") # drop all None values and use defaults if not set parameters = {key: value for key, value in parameters.items() if ...
You are a Python code analyst, evaluating scripts for potential improvements.
Reverse geocoding with given latitude and longitude.
Can you generate a brief explanation for the following Python 3 code def reverse(self, lat, lon, result_type=None, location_type=None, language=None, sensor=None): """Reverse geocode with given latitude and longitude. :param lat: latitude of queried point :param lon: longitude o...
You are a Python code architect, reviewing and designing scalable and efficient code
Checks if the size limit is exceeded.
How would you explain what the following Python 3 function does def check_sizelimit(size_limit, bytes_written, total_size): if size_limit is not None and bytes_written > size_limit: desc = 'File size limit exceeded.' \ if isinstance(size_limit, int) else size_limit.reason raise FileSizeE...
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a file to the client.
Explain what the following Python 3 code does def send_file(self, filename, mimetype=None, restricted=True, checksum=None, trusted=False, chunk_size=None, as_attachment=False): """Send the file to the client.""" try: fp = self.open(mode='rb') excep...
You are a Python code generator, capable of creating scripts from specifications.
def checksum(self, chunk_size=None, progress_callback=None, **kwargs): """Compute checksum of file.""" fp = self.open(mode='rb') try: value = self._compute_checksum( fp, size=self._size, chunk_size=None, progress_callback=progress_callback) exc...
Write a Python 3 script for computing checksum of file.
As a Python code analyst, you investigate and solve complex coding mysteries
def copy(self, src, chunk_size=None, progress_callback=None): """Copy data from another file instance. :param src: Source stream. :param chunk_size: Chunk size to read from source stream. """ fp = src.open(mode='rb') try: return self.save( fp,...
How would you code a function in Python 3 to copy data from another file instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def _compute_checksum(self, stream, size=None, chunk_size=None, progress_callback=None, **kwargs): """Get helper method to compute checksum from a stream. Naive implementation that can be overwritten by subclasses in order to provide more efficient implementation. ...
How would you code a function in Python 3 to compute checksum of a file.
You are a Python code generator, capable of creating scripts from specifications.
def _write_stream(self, src, dst, size=None, size_limit=None, chunk_size=None, progress_callback=None): """Get helper to save stream from src to dest + compute checksum. :param src: Source stream. :param dst: Destination stream. :param size: If provided, this exact...
Can you write a function in Python 3 where it gets helper to save stream from src to dest + compute checksum. :param src: Source stream. :param dst: Destination stream. :param size: If provided, this exact amount of bytes will be written to the destination file. :param size_limit: ``FileSizeLimit`` instance to limit nu...
As a python code expert, you are capable of creating scripts from specifications.
def unixtimestamp(datetime): """Get unix time stamp from that given datetime. If datetime is not tzaware then it's assumed that it is UTC """ epoch = UTC.localize(datetime.utcfromtimestamp(0)) if not datetime.tzinfo: dt = UTC.localize(datetime) else: dt = UTC.normalize(datetime) ...
Write a Python 3 function for getting unix time stamp from that given datetime.
As a Python code translator, you convert algorithms and pseudocode into Python.
def timezone(self, lat, lon, datetime, language=None, sensor=None): """Get time offset data for given location. :param lat: Latitude of queried point :param lon: Longitude of queried point :param language: The language in which to return results. For full list ...
Write a Python 3 script for getting time offset data for given location.
You are a Python code architect, reviewing and designing scalable and efficient code
Encodes a list of locations into a polyline string.
Make a summary of the following Python 3 code def encode(locations): encoded = ( (_encode_value(lat, prev_lat), _encode_value(lon, prev_lon)) for (prev_lat, prev_lon), (lat, lon) in _iterate_with_previous(locations, first=(0, 0)) ) encoded = chain.from_iterable(encoded) return ''...
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator for methods that check that record is in defined status.
Can you generate the documentation for the following Python 3 function def _writable(method): @wraps(method) def wrapper(self, *args, **kwargs): """Send record for indexing. :returns: Execution result of the decorated method. :raises InvalidOperationError: It occurs when the bucket is ...
As a Python code analyst, you investigate and solve complex coding mysteries
Return specific version of the object.
Can you generate the documentation for the following Python 3 function def get_version(self, version_id=None): return ObjectVersion.get(bucket=self.obj.bucket, key=self.obj.key, version_id=version_id)
You are a Python code architect, reviewing and designing scalable and efficient code
Create a dump of the metadata associated to the record.
Make a summary of the following Python 3 code def dumps(self): self.data.update({ 'bucket': str(self.obj.bucket_id), 'checksum': self.obj.file.checksum, 'key': self.obj.key, # IMPORTANT it must stay here! 'size': self.obj.file.size, 'version_id': str(...
You are a Python code analyst, evaluating scripts for potential improvements.
def flush(self): """Flush changes to record.""" files = self.dumps() # Do not create `_files` when there has not been `_files` field before # and the record still has no files attached. if files or '_files' in self.record: self.record['_files'] = files
Create a Python 3 function for flushing changes to record.
As a Python code analyst, you investigate and solve complex coding mysteries
Update files order. :param ids: List of ids specifying the final status of the list.
Explain what the following Python 3 code does def sort_by(self, *ids): # Support sorting by file_ids or keys. files = {str(f_.file_id): f_.key for f_ in self} # self.record['_files'] = [{'key': files.get(id_, id_)} for id_ in ids] self.filesmap = OrderedDict([ (files.get(id_,...
You are a Python code architect, reviewing and designing scalable and efficient code
Rename an object in the object store.
Can you generate the documentation for the following Python 3 function def rename(self, old_key, new_key): assert new_key not in self assert old_key != new_key file_ = self[old_key] old_data = self.filesmap[old_key] # Create a new version with the new name obj = ObjectV...
As a Python code translator, you convert algorithms and pseudocode into Python.
Serialize files from a bucket.
Explain what the following Python 3 code does def dumps(self, bucket=None): return [ self.file_cls(o, self.filesmap.get(o.key, {})).dumps() for o in sorted_files_from_bucket(bucket or self.bucket, self.keys) ]
As a python code expert, you are capable of creating scripts from specifications.
def files(self): """Get files iterator. :returns: Files iterator. """ if self.model is None: raise MissingModelError() records_buckets = RecordsBuckets.query.filter_by( record_id=self.id).first() if not records_buckets: bucket = self...
Create a Python 3 function for getting files iterator. :returns: Files iterator.
As a Python code composer, you craft elegant and concise scripts.
Set files from data.
Given the following Python 3 function, write the documentation def files(self, data): current_files = self.files if current_files: raise RuntimeError('Can not update existing files.') for key in data: current_files[key] = data[key]
As a python code expert, you are capable of creating scripts from specifications.
Delete a record and also remove the RecordsBuckets if necessary.
Explain what the following Python 3 code does def delete(self, force=False): if force: RecordsBuckets.query.filter_by( record=self.model, bucket=self.files.bucket ).delete() return super(Record, self).delete(force)
As a python code expert, you are capable of creating scripts from specifications.
Create a new RecordsBuckets and adds it to the session.
Here you have a function in Python 3, explain what it does def create(cls, record, bucket): rb = cls(record=record, bucket=bucket) db.session.add(rb) return rb
As a Python code composer, you craft elegant and concise scripts.
def sorted_files_from_bucket(bucket, keys=None): """Return files from bucket sorted by given keys. :param bucket: :class:`~invenio_files_rest.models.Bucket` containing the files. :param keys: Keys order to be used. :returns: Sorted list of bucket items. """ keys = keys or [] total =...
Can you implement a function in Python 3 that returns files from bucket sorted by given keys.
You are a Python code analyst, evaluating scripts for potential improvements.
def record_file_factory(pid, record, filename): """Get file from a record. :param pid: Not used. It keeps the function signature. :param record: Record which contains the files. :param filename: Name of the file to be returned. :returns: File object or ``None`` if not found. """ try: ...
Write a Python 3 function for returning a file from a record.
As a Python code composer, you craft elegant and concise scripts.
def file_download_ui(pid, record, _record_file_factory=None, **kwargs): """File download view for a given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... ro...
Implement a function in Python 3 to file download view for a given record.
You are a Python code generator, capable of creating scripts from specifications.
Factory for record bucket generation.
Make a summary of the following Python 3 code def default_bucket_link_factory(pid): try: record = Record.get_record(pid.get_assigned_object()) bucket = record.files.bucket return url_for('invenio_files_rest.bucket_api', bucket_id=bucket.id, _external=True) except ...
As a Python code analyst, you investigate and solve complex coding mysteries
def flake(self, message): """Print an error message to stdout.""" self.stdout.write(str(message)) self.stdout.write('\n')
Create a Python 3 function for printing an error message to stdout.
As a Python code translator, you convert algorithms and pseudocode into Python.
def node_name(node): """ Convenience function: Returns node.id, or node.name, or None """ return hasattr(node, 'id') and node.id or hasattr(node, 'name') and node.name
Write a Python 3 script to return node. id or node. name
You are a Python code analyst, evaluating scripts for potential improvements.
Return a list of the names referenced by this binding.
Can you generate the documentation for the following Python 3 function def names(self): names = [] if isinstance(self.source, ast.List): for node in self.source.elts: if isinstance(node, ast.Str): names.append(node.s) return names
You are a Python code architect, reviewing and designing scalable and efficient code
Return a generator for the assignments which have not been used.
Here you have a function in Python 3, explain what it does def unusedAssignments(self): for name, binding in self.items(): if (not binding.used and name not in self.globals and not self.uses_locals and isinstance(binding, Assignment)): yield na...
As a Python code analyst, you investigate and solve complex coding mysteries
def check_plugins(self): """ collect plugins from entry point 'frosted.plugins' and run their check() method, passing the filename """ checkers = {} for ep in pkg_resources.iter_entry_points(group='frosted.plugins'): checkers.update({ep.name: ep.load()}) for...
Write a Python 3 function that can collect plugins from entry point frosted. plugins and run their check method passing the filename SetException
As a python code expert, you are capable of creating scripts from specifications.
Schedule a function handler to be called just before completion.
Can you generate the documentation for the following Python 3 function def defer_function(self, callable): self._deferred_functions.append((callable, self.scope_stack[:], self.offset))
You are a Python code analyst, evaluating scripts for potential improvements.
Schedule an assignment handler to be called just after deferred function handlers.
Given the following Python 3 function, write the documentation def defer_assignment(self, callable): self._deferred_assignments.append((callable, self.scope_stack[:], self.offset))
You are a Python code generator, capable of creating scripts from specifications.
Run the callables in deferred using their associated scope stack and offset.
Here you have a function in Python 3, explain what it does def run_deferred(self, deferred): for handler, scope, offset in deferred: self.scope_stack = scope self.offset = offset handler()
You are a Python code architect, reviewing and designing scalable and efficient code
Look at scopes which have been fully examined and report names in they which were imported but unused.
Given the following Python 3 function, write the documentation def check_dead_scopes(self): for scope in self.dead_scopes: export = isinstance(scope.get('__all__'), ExportBinding) if export: all = scope['__all__'].names() # Look for possible mistakes in th...
As a python code expert, you are capable of creating scripts from specifications.
def different_forks(self, lnode, rnode): """True, if lnode and rnode are located on different forks of IF/TRY.""" ancestor = self.get_common_ancestor(lnode, rnode) if isinstance(ancestor, ast.If): for fork in (ancestor.body, ancestor.orelse): if self.on_fork(a...
Create a Python 3 function for truing if lnode and rnode are located on different forks of IF or TRY.
You are a Python code analyst, evaluating scripts for potential improvements.
Called when a binding is added to the current scope.
Explain what the following Python 3 code does def add_binding(self, node, value, report_redef=True): redefinedWhileUnused = False if not isinstance(self.scope, ClassScope): for scope in self.scope_stack[::-1]: existing = scope.get(value.name) if (isinstance(ex...
As a Python code translator, you convert algorithms and pseudocode into Python.
Determine if the given node is a docstring.
Can you generate the documentation for the following Python 3 function def is_docstring(self, node): return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str))
As a Python code composer, you craft elegant and concise scripts.
Finds and returns a return statment that has an argument.
Explain what the following Python 3 code does def find_return_with_argument(self, node): for item in node.body: if isinstance(item, ast.Return) and item.value: return item elif not isinstance(item, ast.FunctionDef) and hasattr(item, 'body'): return_with_ar...
As a Python code translator, you convert algorithms and pseudocode into Python.