output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def mark(x,y,label=None):
"""Mark a circle on the current image"""
if label is not None:
os.system("xpaset -p ds9 regions color red ")
cmd="echo 'image; text %d %d # text={%s}' | xpaset ds9 regions " % ( x,y,label)
else:
os.system("xpaset -p ds9 regions color blue")
cmd="echo 'image; circle %d ... | Write a Python 3 function for
marking a circle on the current image | As a Python code translator, you convert algorithms and pseudocode into Python. |
Display a file in ds9 | Given the following Python 3 function, write the documentation
def display(url):
import os
oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'" % (url)
logger.debug(oscmd)
os.system(oscmd+' | xpaset ds9 fits')
return | You are a Python code architect, reviewing and designing scalable and efficient code |
def inv(self):
"""Invert the transform.
After calling this method, calling the instance will do the inverse
transform. Calling this twice return the instance to the original
transform.
"""
self.x, self.y = self.y, self.x
self._x_, self._y_ = self._y_, self._x_
... | Create a Python 3 function for
inverting the transform. After calling this method, calling the instance will do the inverse transform. Calling this twice return the instance to the original transform. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the matrix form of the integral transform. | Explain what the following Python 3 code does
def matrix(self, full=False, keeppads=True):
v = np.fft.hfft(self._u, n=self.N) / self.N
idx = sum(np.ogrid[0:self.N, -self.N:0])
C = v[idx] # follow scipy.linalg.{circulant,toeplitz,hankel}
if keeppads:
a = self._yfac_.copy()
... | You are a Python code generator, capable of creating scripts from specifications. |
def _pad(self, a, axis, extrap, out):
"""Add padding to an array.
Parameters
----------
a : (..., Nin, ...) ndarray
array to be padded to size `N`
axis : int
axis along which to pad
extrap : {bool, 'const'} or 2-tuple
Method to extrapo... | Implement a Python 3 function for
adding padding to an array. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _unpad(self, a, axis, out):
"""Undo padding in an array.
Parameters
----------
a : (..., N, ...) ndarray
array to be trimmed to size `Nin`
axis : int
axis along which to unpad
out : bool
trim the output if True, otherwise the input... | How would you code a function in Python 3 to
undo padding in an array. | As a python code expert, you are capable of creating scripts from specifications. |
def check(self, F):
"""Rough sanity checks on the input function.
"""
assert F.ndim == 1, "checker only supports 1D"
f = self.xfac * F
fabs = np.abs(f)
iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum())
assert 0 != iQ1 != iQ3 != self... | Implement a Python 3 function for
roughing sanity checks on the input function. | As a Python code composer, you craft elegant and concise scripts. |
Apply an FFT along the given axis and return a new array with the specified amount of zero - padding | How would you explain what the following Python 3 function does
def fft(x, axis=-1, padding_samples=0):
if padding_samples > 0:
padded = np.concatenate(
[x, np.zeros((len(x), padding_samples), dtype=x.dtype)],
axis=axis)
else:
padded = x
transformed = np.fft.rfft(pad... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a Morlet filter bank of the log - likelihood wavelets of the specified frequency scale and the signal of the specified frequency scale. | Can you generate the documentation for the following Python 3 function
def morlet_filter_bank(
samplerate,
kernel_size,
scale,
scaling_factor,
normalize=True):
"""
Create a :class:`~zounds.core.ArrayWithUnits` instance with a
:class:`~zounds.timeseries.TimeDimension` ... | You are a Python code generator, capable of creating scripts from specifications. |
def set_bias(self, bias):
"""
Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
... | Implement a function in Python 3 to
adjust the image bias. | You are a Python code generator, capable of creating scripts from specifications. |
def set_contrast(self, contrast):
"""
Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
... | Create a Python 3 function to
adjust the image contrast. | As a python code expert, you are capable of creating scripts from specifications. |
def _copy(src, dst, src_is_storage, dst_is_storage):
"""
Copies file from source to destination
Args:
src (str or file-like object): Source file.
dst (str or file-like object): Destination file.
src_is_storage (bool): Source is storage.
dst_is_storage (bool): Destination is ... | Implement a function in Python 3 to
copy file from source to destination. | You are a Python code analyst, evaluating scripts for potential improvements. |
Copies a source file to a destination file or directory. | Here you have a function in Python 3, explain what it does
def copy(src, dst):
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copy"
if not src_is_storage and not ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Copies a source file to a destination file. | Can you tell what is the following Python 3 function doing
def copyfile(src, dst, follow_symlinks=True):
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copyfile"
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Handle boto exception and convert to class
IO exceptions | Can you generate a brief explanation for the following Python 3 code
def _handle_client_error():
try:
yield
except _ClientError as exception:
error = exception.response['Error']
if error['Code'] in _ERROR_CODES:
raise _ERROR_CODES[error['Code']](error['Message'])
rai... | As a Python code analyst, you investigate and solve complex coding mysteries |
def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
copy_source = self.get_client_kwarg... | Implement a Python 3 function for
copying object of the same storage. | As a Python code composer, you craft elegant and concise scripts. |
def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
bucket_name, key = self.split_locator(path)
kwargs = dict(Buc... | Can you create a Python 3 function that
gets base keyword arguments for a specific path. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a boto3. session. Session object. | Can you tell what is the following Python 3 function doing
def _get_session(self):
if self._session is None:
self._session = _boto3.session.Session(
**self._storage_parameters.get('session', dict()))
return self._session | As a Python code composer, you craft elegant and concise scripts. |
Get the client object for the current object. | Make a summary of the following Python 3 code
def _get_client(self):
client_kwargs = self._storage_parameters.get('client', dict())
# Handles unsecure mode
if self._unsecure:
client_kwargs = client_kwargs.copy()
client_kwargs['use_ssl'] = False
return self._get_... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
region = self._get_session().region_name or r'[\w-]+'
return (
# S3 scheme
# - s3://<bucket>/<key>
... | Create a Python 3 function for
returning the URL roots for this storage. | You are a Python code generator, capable of creating scripts from specifications. |
Get time from header
| Given the following Python 3 function, write the documentation
def _get_time(header, keys, name):
for key in keys:
try:
return _to_timestamp(header.pop(key))
except KeyError:
continue
raise _UnsupportedOperation(name) | As a Python code analyst, you investigate and solve complex coding mysteries |
def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
... | Implement a function in Python 3 to
return object or bucket HTTP header. | As a python code expert, you are capable of creating scripts from specifications. |
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.put_object(Body=b'', **client_kwarg... | How would you implement a function in Python 3 that
makes a directory. args: client_kwargs (dict): Client arguments. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_error():
# Object
if 'Key' in client_kwargs:
return self.client.delete_object(**client_kwargs)
... | Write a Python 3 function that can
remove an object from the cache. | You are a Python code architect, reviewing and designing scalable and efficient code |
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | Make a summary of the following Python 3 code
def _list_locators(self):
with _handle_client_error():
response = self.client.list_buckets()
for bucket in response['Buckets']:
yield bucket.pop('Name'), bucket | You are a Python code analyst, evaluating scripts for potential improvements. |
A generator function that returns objects from the object store. | Can you generate the documentation for the following Python 3 function
def _list_objects(self, client_kwargs, path, max_request_entries):
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['MaxKeys'] = max_request_entries
while True:
with _handle_... | As a python code expert, you are capable of creating scripts from specifications. |
Read a range of bytes in stream. | Explain what the following Python 3 code does
def _read_range(self, start, end=0):
# Get object part from S3
try:
with _handle_client_error():
response = self._client.get_object(
Range=self._http_range(start, end), **self._client_kwargs)
# Check f... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_client_error():
self._client.put_object(
Body=buffer.tobytes(), **self._client_kwargs) | Write a Python 3 function that can
flush the write buffers of the given buffer. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Flush the write buffers of the stream. | Can you generate the documentation for the following Python 3 function
def _flush(self):
# Initialize multi-part upload
if 'UploadId' not in self._upload_args:
with _handle_client_error():
self._upload_args[
'UploadId'] = self._client.create_multipart_uplo... | As a Python code analyst, you investigate and solve complex coding mysteries |
Close the object in write mode. | Given the following Python 3 function, write the documentation
def _close_writable(self):
# Wait parts upload completion
for part in self._write_futures:
part['ETag'] = part.pop('response').result()['ETag']
# Complete multipart upload
with _handle_client_error():
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _handle_azure_exception():
"""
Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _AzureHttpError as exception:
if exception.status_code in _ERROR_CODES:
raise _ERROR_CODES[exception.sta... | Implement a Python 3 function for
handling Azure exception and convert to class IO exceptions | As a python code expert, you are capable of creating scripts from specifications. |
Convert properties model to dict. | How would you explain what the following Python 3 function does
def _properties_model_to_dict(properties):
result = {}
for attr in properties.__dict__:
value = getattr(properties, attr)
if hasattr(value, '__module__') and 'models' in value.__module__:
value = _properties_model_to_di... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get endpoint information from storage parameters and update self. _endpoint | Given the following Python 3 function, write the documentation
def _get_endpoint(self, sub_domain):
storage_parameters = self._storage_parameters or dict()
account_name = storage_parameters.get('account_name')
if not account_name:
raise ValueError('"account_name" is required for Azu... | You are a Python code generator, capable of creating scripts from specifications. |
Updates storage parameters with unsecure mode. | Here you have a function in Python 3, explain what it does
def _secured_storage_parameters(self):
parameters = self._storage_parameters or dict()
# Handles unsecure mode
if self._unsecure:
parameters = parameters.copy()
parameters['protocol'] = 'http'
return par... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _format_src_url(self, path, caller_system):
"""
Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
... | Can you write a function in Python 3 where it
formats path for cross Azure storage account copy function. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Updates the client kwargs for listing functions. | Make a summary of the following Python 3 code
def _update_listing_client_kwargs(client_kwargs, max_request_entries):
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['num_results'] = max_request_entries
return client_kwargs | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
... | How would you implement a function in Python 3 that
converts object model to dict. | You are a Python code architect, reviewing and designing scalable and efficient code |
Reads a range of bytes in stream. | Can you generate the documentation for the following Python 3 function
def _read_range(self, start, end=0):
stream = _BytesIO()
try:
with _handle_azure_exception():
self._get_to_stream(
stream=stream, start_range=start,
end_range=(end -... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
stream = _BytesIO()
with _handle_azure_exception():
self._get_to_stream(stream=stream, **self._client_kwargs)
return stream... | Create a Python 3 function for
reading and return all the bytes from the stream until EOF. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Initializes file on a mode. | Can you generate the documentation for the following Python 3 function
def _init_append(self):
if self._content_length:
# Adjust size if content length specified
with _handle_azure_exception():
self._resize(
content_length=self._content_length, **self.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _create(self):
"""
Create the file if not exists.
"""
# Create new file
with _handle_azure_exception():
self._create_from_size(
content_length=self._content_length, **self._client_kwargs) | Can you create a Python 3 function that
creates the file in Azure. | As a python code expert, you are capable of creating scripts from specifications. |
def _flush(self, buffer, start, end):
"""
Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer p... | How would you code a function in Python 3 to
flush the buffer of the stream if applicable. | You are a Python code architect, reviewing and designing scalable and efficient code |
A generator function that returns the previous generator object after having run the first element evaluated
in background task. | Can you tell what is the following Python 3 function doing
def _generate_async(self, generator):
first_value_future = self._workers.submit(next, generator)
def get_first_element(future=first_value_future):
"""
Get first element value from future.
Args:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _handle_client_exception():
"""
Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientException as exception:
if exception.http_status in _ERROR_CODES:
raise _ERROR_CODES[exceptio... | How would you implement a function in Python 3 that
handles Swift exception and convert to class IO exceptions | You are a Python code generator, capable of creating scripts from specifications. |
Copy object of the same storage. | Can you generate the documentation for the following Python 3 function
def copy(self, src, dst, other_system=None):
container, obj = self.split_locator(src)
with _handle_client_exception():
self.client.copy_object(
container=container, obj=obj, destination=self.relpath(dst)) | As a python code expert, you are capable of creating scripts from specifications. |
Get base keyword arguments for a specific path. | Explain what the following Python 3 code does
def get_client_kwargs(self, path):
container, obj = self.split_locator(path)
kwargs = dict(container=container)
if obj:
kwargs['obj'] = obj
return kwargs | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_client(self):
"""
Swift client
Returns:
swiftclient.client.Connection: client
"""
kwargs = self._storage_parameters
# Handles unsecure mode
if self._unsecure:
kwargs = kwargs.copy()
kwargs['ssl_compression'] = False
... | Can you create a Python 3 function that
returns a new instance of the Swift client. | You are a Python code generator, capable of creating scripts from specifications. |
Returns object HTTP header. | Make a summary of the following Python 3 code
def _head(self, client_kwargs):
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.head_object(**client_kwargs)
# Container
return self.client.head_container(**clie... | As a Python code analyst, you investigate and solve complex coding mysteries |
Make a directory.
args:
client_kwargs (dict): Client arguments. | Given the following Python 3 function, write the documentation
def _make_dir(self, client_kwargs):
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.put_object(
client_kwargs['container'], client_kwargs['obj'], b''... | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove an object from the database. | Explain what the following Python 3 code does
def _remove(self, client_kwargs):
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.delete_object(
client_kwargs['container'], client_kwargs['obj'])
# Cont... | As a python code expert, you are capable of creating scripts from specifications. |
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | Can you generate the documentation for the following Python 3 function
def _list_locators(self):
with _handle_client_exception():
response = self.client.get_account()
for container in response[1]:
yield container.pop('name'), container | As a Python code composer, you craft elegant and concise scripts. |
List objects in the current locator. | Make a summary of the following Python 3 code
def _list_objects(self, client_kwargs, path, max_request_entries):
kwargs = dict(prefix=path)
if max_request_entries:
kwargs['limit'] = max_request_entries
else:
kwargs['full_listing'] = True
with _handle_client_excep... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
try:
... | Create a Python 3 function to
read a range of bytes in stream. | You are a Python code generator, capable of creating scripts from specifications. |
def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
container, obj = self._client_args
with _handle_client_exception():
self._client.put_object(container, obj, buffer) | Write a Python 3 script for
flushing the write buffers of the stream if applicable. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Flush the write buffers of the stream. | Explain what the following Python 3 code does
def _flush(self):
# Upload segment with workers
name = self._segment_name % self._seek
response = self._workers.submit(
self._client.put_object, self._container, name,
self._get_buffer())
# Save segment information in... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait segments upload completion
for segment in self._write_futures:
segment['etag'] = segment['etag'].result()
# Upload manifest file
with _handle_client_exception():
sel... | Implement a Python 3 function for
closing the object in write mode. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _init_append(self):
"""
Initializes file on 'a' mode.
"""
# Require to load the full file content in buffer
self._write_buffer[:] = self._readall()
# Make initial seek position to current end of file
self._seek = self._size | Implement a function in Python 3 to
initialize file on a mode. | You are a Python code generator, capable of creating scripts from specifications. |
def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._is_raw_of_buffered and not self._closed:
self._closed = True
if self._write_buffer:
self.flush() | Create a Python 3 function for
flushing the write buffers of the object if applicable and close the object. | As a python code expert, you are capable of creating scripts from specifications. |
def _peek(self, size=-1):
"""
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
"""
with self._seek_lock:
see... | Can you create a Python 3 function that
reads the next size bytes from the stream without advancing the position. | As a Python code composer, you craft elegant and concise scripts. |
Read and return all the bytes from the stream until EOF. | Can you generate the documentation for the following Python 3 function
def readall(self):
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
# Get data starting from seek
with handle_os_exceptions():
if self._seek and self... | As a Python code composer, you craft elegant and concise scripts. |
Reads bytes into a pre - allocated writable bytes - like object b and returns the number of bytes read. | Explain what the following Python 3 code does
def readinto(self, b):
if not self._readable:
raise UnsupportedOperation('read')
# Get and update stream positions
size = len(b)
with self._seek_lock:
start = self._seek
end = start + size
self... | You are a Python code architect, reviewing and designing scalable and efficient code |
Change the stream position to the given byte offset. | Explain what the following Python 3 code does
def seek(self, offset, whence=SEEK_SET):
if not self._seekable:
raise UnsupportedOperation('seek')
seek = self._update_seek(offset, whence)
# If seek move out of file, add padding until new seek position.
if self._writable:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position. | Can you tell what is the following Python 3 function doing
def _update_seek(self, offset, whence):
with self._seek_lock:
if whence == SEEK_SET:
self._seek = offset
elif whence == SEEK_CUR:
self._seek += offset
elif whence == SEEK_END:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Writes the given bytes - like object b to the underlying raw stream and returns the number of bytes written. | Given the following Python 3 function, write the documentation
def write(self, b):
if not self._writable:
raise UnsupportedOperation('write')
# This function write data in a buffer
# "flush()" need to be called to really write content on
# Cloud Storage
size = len(b)... | As a python code expert, you are capable of creating scripts from specifications. |
def _handle_http_errors(response):
"""
Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response
"""
code = response.status_code
if 200 <= code < 400:
return response
elif code in (403, 404)... | Write a Python 3 script to
check for HTTP errors and raise OSError if relevant. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns object HTTP header. | How would you explain what the following Python 3 function does
def _head(self, client_kwargs):
return _handle_http_errors(
self.client.request(
'HEAD', timeout=self._TIMEOUT, **client_kwargs)).headers | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
# Get o... | Write a Python 3 function for
reading a range of bytes in stream. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Read and return all the bytes from the stream until EOF. | Explain what the following Python 3 code does
def _readall(self):
return _handle_http_errors(
self._client.request(
'GET', self.name, timeout=self._TIMEOUT)).content | As a Python code analyst, you investigate and solve complex coding mysteries |
def flush(self):
"""
Flush the write buffers of the stream if applicable and
save the object on the cloud.
"""
if self._writable:
with self._seek_lock:
buffer = self._get_buffer()
# Flush that part of the file
end = sel... | Create a Python 3 function to
flush the write buffers of the stream if applicable and the object on the cloud is saved. | You are a Python code generator, capable of creating scripts from specifications. |
Change the stream position to the given byte offset. | Explain what the following Python 3 code does
def seek(self, offset, whence=SEEK_SET):
if not self._seekable:
raise UnsupportedOperation('seek')
# Flush before moving position
self.flush()
return self._update_seek(offset, whence) | You are a Python code architect, reviewing and designing scalable and efficient code |
def _flush(self):
"""
Flush the write buffers of the stream if applicable.
In write mode, send the buffer content to the cloud object.
"""
# Flush buffer to specified range
buffer = self._get_buffer()
start = self._buffer_size * (self._seek - 1)
end = sta... | Can you write a function in Python 3 where it
flushes the buffer of the stream if applicable. | As a Python code composer, you craft elegant and concise scripts. |
Update the size of the current entry in the cache. | Can you tell what is the following Python 3 function doing
def _update_size(self, size, future):
with self._size_lock:
# Update value
if size > self._size and future.done:
# Size can be lower if seek down on an 'a' mode open file.
self._size = size | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _flush_range(self, buffer, start, end):
"""
Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buf... | Write a Python 3 function that can
flush a buffer to a range of the file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def run(cmd):
""" Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use.
"""
status, output = commands.getstatusoutput(cmd)
if status:
print(output)
return status == 0 | Write a Python 3 script to
execute a shell command. | As a Python code analyst, you investigate and solve complex coding mysteries |
def read_datanommer_entries_from_filedump():
""" Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json
"""
# TODO -- un-hardcode this filename when I need to run this next time.
#filename = "../myfile.json"
filename = "../datanommer-dump-2012-11-22.json"
... | Write a Python 3 script to
read in all datanommer entries from a file created with datanommer - dump > myfile. json | You are a Python code architect, reviewing and designing scalable and efficient code |
def create_or_update(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Tuple[object, bool]:
"""
Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
... | Can you write a function in Python 3 where it
creates or update a model instance. | You are a Python code analyst, evaluating scripts for potential improvements. |
def maybe_convert_values(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Dict[str, Any]:
"""
Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upo... | How would you implement a function in Python 3 that
returns a dictionary of raw values for a specific identifier and data. | You are a Python code analyst, evaluating scripts for potential improvements. |
def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio.storage.azure._AzureBaseSystem subclass):
The source storage system.
"""
... | Write a Python 3 script to
copy a file from src to dst. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
# Remove query string from URL
path = path.split('?', 1)[0]
... | Write a Python 3 script to
get base keyword arguments for a specific path. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs... | Can you create a Python 3 function that
returns object or bucket HTTP header. | As a python code expert, you are capable of creating scripts from specifications. |
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_azure_exception():
for share in self.client.list_shares():
yield share.name, self._model_to_dict(share) | Implement a function in Python 3 to
list locators. Returns: generator of tuple: locator name str, locator header dict | You are a Python code analyst, evaluating scripts for potential improvements. |
A generator that yields objects from the Cloud Storage API. | Can you generate the documentation for the following Python 3 function
def _list_objects(self, client_kwargs, max_request_entries):
client_kwargs = self._update_listing_client_kwargs(
client_kwargs, max_request_entries)
with _handle_azure_exception():
for obj in self.client.list... | As a python code expert, you are capable of creating scripts from specifications. |
Make a directory and a share. | Make a summary of the following Python 3 code
def _make_dir(self, client_kwargs):
with _handle_azure_exception():
# Directory
if 'directory_name' in client_kwargs:
return self.client.create_directory(
share_name=client_kwargs['share_name'],
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove an object from the Cloud Storage. | Given the following Python 3 function, write the documentation
def _remove(self, client_kwargs):
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
return self.client.delete_file(
share_name=client_kwargs['share_name'],
... | As a python code expert, you are capable of creating scripts from specifications. |
Update the range of the data. | Can you generate a brief explanation for the following Python 3 code
def _update_range(self, data, **kwargs):
self._client.update_range(data=data, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Given a bodhi message return the FAS username. | Here you have a function in Python 3, explain what it does
def handle_bodhi(msg):
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submitter']
else:
username = msg.msg.get('u... | As a Python code composer, you craft elegant and concise scripts. |
Given a wiki message return the FAS username. | Explain what the following Python 3 code does
def handle_wiki(msg):
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
R... | Write a Python 3 script to
check if file is a local file or a storage file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def format_and_is_storage(path):
"""
Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is ... | How would you implement a function in Python 3 that
checks if path is storage and format it. | You are a Python code analyst, evaluating scripts for potential improvements. |
def equivalent_to(std_function):
"""
Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function
"""
... | Implement a function in Python 3 to
decorate a cloud object compatible function to provides fall back to standard function if used on local files. Args: std_function (function): standard function to used with local files. Returns: function: new function | You are a Python code generator, capable of creating scripts from specifications. |
Handle OSS exceptions and convert to class IO exceptions | Given the following Python 3 function, write the documentation
def _handle_oss_error():
try:
yield
except _OssError as exception:
if exception.status in _ERROR_CODES:
raise _ERROR_CODES[exception.status](
exception.details.get('Message', ''))
raise | You are a Python code architect, reviewing and designing scalable and efficient code |
Copy object of the same storage. | Can you tell what is the following Python 3 function doing
def copy(self, src, dst, other_system=None):
copy_source = self.get_client_kwargs(src)
copy_destination = self.get_client_kwargs(dst)
with _handle_oss_error():
bucket = self._get_bucket(copy_destination)
bucket.co... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the client object for the current session. | Given the following Python 3 function, write the documentation
def _get_client(self):
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss.Auth if self._storage_parameters
else _oss.AnonymousAuth)(**self._storage_parameters) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
return (
# OSS Scheme
# - oss://<bucket>/<key>
'oss://',
# URL (With common aliyuncs.com endpoint):
... | Can you implement a function in Python 3 that
returns the URL roots for this storage. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the object in the appropriate bucket. | Can you generate the documentation for the following Python 3 function
def _get_bucket(self, client_kwargs):
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_name']) | As a Python code analyst, you investigate and solve complex coding mysteries |
def islink(self, path=None, header=None):
"""
Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink.
"""
if header is None:
he... | Can you create a Python 3 function that
returns True if object is a symbolic link. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
... | How would you code a function in Python 3 to
return object HTTP header. | As a python code expert, you are capable of creating scripts from specifications. |
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
ret... | Write a Python 3 script for
making a directory. args: client_kwargs (dict): Client arguments. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
retur... | How would you implement a function in Python 3 that
removes an object from the cache. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _model_to_dict(model, ignore):
"""
Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version.
"""
return {attr: value for attr, ... | Create a Python 3 function to
convert OSS model to dict. | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.