output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def combine_xml_points(l, units, handle_units):
"""Combine multiple Point tags into an array."""
ret = {}
for item in l:
for key, value in item.items():
ret.setdefault(key, []).append(value)
for key, value in ret.items():
if key != 'date':
ret[key] = handle_units... | Can you create a Python 3 function that
combines multiple Point tags into an array. | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_xml_dataset(elem, handle_units):
"""Create a netCDF-like dataset from XML data."""
points, units = zip(*[parse_xml_point(p) for p in elem.findall('point')])
# Group points by the contents of each point
datasets = {}
for p in points:
datasets.setdefault(tuple(p), []).append(p)
... | Can you write a function in Python 3 where it
creates a netCDF - like dataset from XML data. | As a Python code composer, you craft elegant and concise scripts. |
def parse_csv_response(data, unit_handler):
"""Handle CSV-formatted HTTP responses."""
return squish([parse_csv_dataset(d, unit_handler) for d in data.split(b'\n\n')]) | How would you code a function in Python 3 to
handle CSV - formatted HTTP responses. | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse_csv_header(line):
"""Parse the CSV header returned by TDS."""
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
names.append(str(var))
continue
else:
names.append(str(var[:start]))
end = var... | Implement a function in Python 3 to
parse the CSV header returned by TDS. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse CSV data into a netCDF - like dataset. | How would you explain what the following Python 3 function does
def parse_csv_dataset(data, handle_units):
fobj = BytesIO(data)
names, units = parse_csv_header(fobj.readline().decode('utf-8'))
arrs = np.genfromtxt(fobj, dtype=None, names=names, delimiter=',', unpack=True,
converters... | You are a Python code generator, capable of creating scripts from specifications. |
def validate_query(self, query):
"""Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : NCSSQuery
The query to validat... | Implement a function in Python 3 to
validate a query. Determines whether `query` is well-formed. This includes checking for all required parameters, as well as checking parameters for valid values. Parameters ---------- query : NCSSQuery The query to validate Returns ------- valid : bool Whether `query` is valid. | As a python code expert, you are capable of creating scripts from specifications. |
Fetch parsed data from a THREDDS server using NCSS. | Given the following Python 3 function, write the documentation
def get_data(self, query):
resp = self.get_query(query)
return response_handlers(resp, self.unit_handler) | As a Python code composer, you craft elegant and concise scripts. |
def projection_box(self, min_x, min_y, max_x, max_y):
"""Add a bounding box in projected (native) coordinates to the query.
This adds a request for a spatial bounding box, bounded by (`min_x`, `max_x`) for
x direction and (`min_y`, `max_y`) for the y direction. This modifies the query
i... | Implement a Python 3 function for
adding a spatial bounding box in projected ( native ) coordinates to the query. | As a Python code composer, you craft elegant and concise scripts. |
Sets time and spatial strides for the NCSSQuery object. | Can you generate a brief explanation for the following Python 3 code
def strides(self, time=None, spatial=None):
if time:
self.add_query_parameter(timeStride=time)
if spatial:
self.add_query_parameter(horizStride=spatial)
return self | As a Python code composer, you craft elegant and concise scripts. |
Register a function to handle a particular mimetype. | Given the following Python 3 function, write the documentation
def register(self, mimetype):
def dec(func):
self._reg[mimetype] = func
return func
return dec | As a Python code translator, you convert algorithms and pseudocode into Python. |
def handle_typed_values(val, type_name, value_type):
"""Translate typed values into the appropriate python object.
Takes an element name, value, and type and returns a list
with the string value(s) properly converted to a python type.
TypedValues are handled in ucar.ma2.DataType in net... | Can you write a function in Python 3 where it
translates typed values into python objects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_data(self, time, site_id):
r"""Download and parse upper air observations from an online archive.
Parameters
----------
time : datetime
The date and time of the desired observation.
site_id : str
The three letter ICAO identifier of the station fo... | How would you code a function in Python 3 to
download and parse upper air observations from an online archive and return a pandas. DataFrame containing the data. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_data_raw(self, time, site_id):
"""Download data from the University of Wyoming's upper air archive.
Parameters
----------
time : datetime
Date and time for which data should be downloaded
site_id : str
Site id for which data should be downloaded
... | Write a Python 3 script to
download data from the University of Wyoming s upper air archive. | You are a Python code architect, reviewing and designing scalable and efficient code |
def read_ncstream_data(fobj):
"""Handle reading an NcStream v1 data block from a file-like object."""
data = read_proto_object(fobj, stream.Data)
if data.dataType in (stream.STRING, stream.OPAQUE) or data.vdata:
log.debug('Reading string/opaque/vlen')
num_obj = read_var_int(fobj)
log... | Write a Python 3 function that can
handle reading an NcStream v1 data block from a file - like object. | You are a Python code generator, capable of creating scripts from specifications. |
def read_ncstream_err(fobj):
"""Handle reading an NcStream error from a file-like object and raise as error."""
err = read_proto_object(fobj, stream.Error)
raise RuntimeError(err.message) | How would you implement a function in Python 3 that
handles reading an NcStream error from a file - like object and raise as error. | You are a Python code analyst, evaluating scripts for potential improvements. |
Read messages from a file - like object until stream is exhausted. | Explain what the following Python 3 code does
def read_messages(fobj, magic_table):
messages = []
while True:
magic = read_magic(fobj)
if not magic:
break
func = magic_table.get(magic)
if func is not None:
messages.append(func(fobj))
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
def read_proto_object(fobj, klass):
"""Read a block of data and parse using the given protobuf object."""
log.debug('%s chunk', klass.__name__)
obj = klass()
obj.ParseFromString(read_block(fobj))
log.debug('Header: %s', str(obj))
return obj | Can you create a Python 3 function that
reads a block of data and parse using the given protobuf object. | You are a Python code generator, capable of creating scripts from specifications. |
def read_block(fobj):
"""Read a block.
Reads a block from a file object by first reading the number of bytes to read, which must
be encoded as a variable-byte length integer.
Parameters
----------
fobj : file-like object
The file to read from.
Returns
-------
bytes
... | Write a Python 3 function that can
read a block from a file - like object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function processes vlen coming back from NCStream v2. | Can you generate a brief explanation for the following Python 3 code
def process_vlen(data_header, array):
source = iter(array)
return np.array([np.fromiter(itertools.islice(source, size), dtype=array.dtype)
for size in data_header.vlens]) | As a Python code composer, you craft elegant and concise scripts. |
def datacol_to_array(datacol):
"""Convert DataCol from NCStream v2 into an array with appropriate type.
Depending on the data type specified, this extracts data from the appropriate members
and packs into a :class:`numpy.ndarray`, recursing as necessary for compound data types.
Parameters
--------... | Can you write a function in Python 3 where it
converts a DataCol from NCStream v2 into an array with appropriate type. | As a Python code composer, you craft elegant and concise scripts. |
def reshape_array(data_header, array):
"""Extract the appropriate array shape from the header.
Can handle taking a data header and either bytes containing data or a StructureData
instance, which will have binary data as well as some additional information.
Parameters
----------
array : :class:... | How would you implement a function in Python 3 that
extracts the appropriate array shape from the header. | As a python code expert, you are capable of creating scripts from specifications. |
Convert an ncstream datatype to a numpy one. | Make a summary of the following Python 3 code
def data_type_to_numpy(datatype, unsigned=False):
basic_type = _dtypeLookup[datatype]
if datatype in (stream.STRING, stream.OPAQUE):
return np.dtype(basic_type)
if unsigned:
basic_type = basic_type.replace('i', 'u')
return np.dtype('=' + ba... | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a Structure specification to a numpy structured dtype. | Can you tell what is the following Python 3 function doing
def struct_to_dtype(struct):
# str() around name necessary because protobuf gives unicode names, but dtype doesn't
# support them on Python 2
fields = [(str(var.name), data_type_to_numpy(var.dataType, var.unsigned))
for var in struct.v... | As a python code expert, you are capable of creating scripts from specifications. |
Unpack an NCStream Variable into a numpy array and a type name. | Here you have a function in Python 3, explain what it does
def unpack_variable(var):
# If we actually get a structure instance, handle turning that into a variable
if var.dataType == stream.STRUCTURE:
return None, struct_to_dtype(var), 'Structure'
elif var.dataType == stream.SEQUENCE:
log.wa... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Unpack an embedded attribute into a python or numpy object. | Can you generate a brief explanation for the following Python 3 code
def unpack_attribute(att):
if att.unsigned:
log.warning('Unsupported unsigned attribute!')
# TDS 5.0 now has a dataType attribute that takes precedence
if att.len == 0: # Empty
val = None
elif att.dataType == stream.S... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reads a variable - length integer from the specified file - like object. | Can you tell what is the following Python 3 function doing
def read_var_int(file_obj):
# Read all bytes from here, stopping with the first one that does not have
# the MSB set. Save the lower 7 bits, and keep stacking to the *left*.
val = 0
shift = 0
while True:
# Read next byte
next... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieve data from CDMRemote for one or more variables. | Here you have a function in Python 3, explain what it does
def fetch_data(self, **var):
varstr = ','.join(name + self._convert_indices(ind)
for name, ind in var.items())
query = self.query().add_query_parameter(req='data', var=varstr)
return self._fetch(query) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate a new query for the object containing the object s ID. | Given the following Python 3 function, write the documentation
def query(self):
q = super(CDMRemote, self).query()
# Turn on compression if it's been set on the object
if self.deflate:
q.add_query_parameter(deflate=self.deflate)
return q | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if access token is valid. | How would you explain what the following Python 3 function does
def check_token(func):
@wraps(func)
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
if response.status_code == 401:
raise InvalidToken('Access token invalid or no longer valid')
else:
r... | You are a Python code generator, capable of creating scripts from specifications. |
def upload(self, remote_path, file_content, ondup=None, **kwargs):
"""上传单个文件(<2G).
| 百度PCS服务目前支持最大2G的单个文件上传。
| 如需支持超大文件(>2G)的断点续传,请参考下面的“分片文件上传”方法。
:param remote_path: 网盘中文件的保存路径(包含文件名)。
必须以 /apps/ 开头。
.. warning::
... | Can you write a function in Python 3 where it
uploads a file to the remote server. | As a Python code composer, you craft elegant and concise scripts. |
Upload a file to a temporary file. | Here you have a function in Python 3, explain what it does
def upload_tmpfile(self, file_content, **kwargs):
params = {
'type': 'tmpfile'
}
files = {'file': ('file', file_content, '')}
url = 'https://c.pcs.baidu.com/rest/2.0/pcs/file'
return self._request('file', 'up... | As a python code expert, you are capable of creating scripts from specifications. |
Upload a superfile to the remote path. | Here you have a function in Python 3, explain what it does
def upload_superfile(self, remote_path, block_list, ondup=None, **kwargs):
params = {
'path': remote_path,
'ondup': ondup
}
data = {
'param': json.dumps({'block_list': block_list}),
}
... | As a python code expert, you are capable of creating scripts from specifications. |
Create a new directory. | How would you explain what the following Python 3 function does
def mkdir(self, remote_path, **kwargs):
data = {
'path': remote_path
}
return self._request('file', 'mkdir', data=data, **kwargs) | As a python code expert, you are capable of creating scripts from specifications. |
def meta(self, remote_path, **kwargs):
"""获取单个文件或目录的元信息.
:param remote_path: 网盘中文件/目录的路径,必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名... | Implement a function in Python 3 to
get file meta data | As a Python code composer, you craft elegant and concise scripts. |
move file from one location to another | Can you generate the documentation for the following Python 3 function
def move(self, from_path, to_path, **kwargs):
data = {
'from': from_path,
'to': to_path,
}
return self._request('file', 'move', data=data, **kwargs) | You are a Python code architect, reviewing and designing scalable and efficient code |
Copy a file from one location to another. | Given the following Python 3 function, write the documentation
def copy(self, from_path, to_path, **kwargs):
data = {
'from': from_path,
'to': to_path,
}
return self._request('file', 'copy', data=data, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Delete a file from the server. | Explain what the following Python 3 code does
def delete(self, remote_path, **kwargs):
data = {
'path': remote_path
}
return self._request('file', 'delete', data=data, **kwargs) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete a list of files. | Explain what the following Python 3 code does
def multi_delete(self, path_list, **kwargs):
data = {
'param': json.dumps({
'list': [{'path': path} for path in path_list]
}),
}
return self._request('file', 'delete', data=data, **kwargs) | As a Python code composer, you craft elegant and concise scripts. |
Get a thumbnail of a file. | Make a summary of the following Python 3 code
def thumbnail(self, remote_path, height, width, quality=100, **kwargs):
params = {
'path': remote_path,
'height': height,
'width': width,
'quality': quality,
}
return self._request('thumbnail', 'genera... | You are a Python code generator, capable of creating scripts from specifications. |
Convert a file to a video type. | Can you generate the documentation for the following Python 3 function
def video_convert(self, remote_path, video_type, **kwargs):
params = {
'path': remote_path,
'type': video_type,
}
return self._request('file', 'streaming', extra_params=params,
... | You are a Python code generator, capable of creating scripts from specifications. |
Download a file from the Baidu server. | Here you have a function in Python 3, explain what it does
def download_stream(self, remote_path, **kwargs):
params = {
'path': remote_path,
}
url = 'https://d.pcs.baidu.com/rest/2.0/pcs/file'
return self._request('stream', 'download', url=url,
e... | As a Python code analyst, you investigate and solve complex coding mysteries |
Upload a file to a rapid server. | Can you generate the documentation for the following Python 3 function
def rapid_upload(self, remote_path, content_length, content_md5,
content_crc32, slice_md5, ondup=None, **kwargs):
"""秒传一个文件.
.. warning::
* 被秒传文件必须大于256KB(即 256*1024 B)。
* 校验段为文件的前256KB,秒传接... | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a download task to the cache. | Can you generate a brief explanation for the following Python 3 code
def add_download_task(self, source_url, remote_path,
rate_limit=None, timeout=60 * 60,
expires=None, callback='', **kwargs):
"""添加离线下载任务,实现单个文件离线下载.
:param source_url: 源文件的URL。
... | As a Python code composer, you craft elegant and concise scripts. |
def query_download_tasks(self, task_ids, operate_type=1,
expires=None, **kwargs):
"""根据任务ID号,查询离线下载任务信息及进度信息。
:param task_ids: 要查询的任务ID列表
:type task_ids: list or tuple
:param operate_type:
* 0:查任务信息
* 1... | Can you write a function in Python 3 where it
queries Cloud DL Task | As a Python code translator, you convert algorithms and pseudocode into Python. |
def list_download_tasks(self, need_task_info=1, start=0, limit=10, asc=0,
create_time=None, status=None, source_url=None,
remote_path=None, expires=None, **kwargs):
"""查询离线下载任务ID列表及任务信息.
:param need_task_info: 是否需要返回任务信息:
... | Implement a function in Python 3 to
list all the tasks in the specified base URL. | You are a Python code analyst, evaluating scripts for potential improvements. |
取消离线下载任务.
:param task_id: 要取消的任务ID号。
:type task_id: str
:param expires: 请求失效时间,如果有,则会校验。
:type expires: int
:return: Response 对象 | Explain what the following Python 3 code does
def cancel_download_task(self, task_id, expires=None, **kwargs):
data = {
'expires': expires,
'task_id': task_id,
}
return self._request('services/cloud_dl', 'cancle_task',
data=data, **kwargs) | As a Python code translator, you convert algorithms and pseudocode into Python. |
List all the files in the current user s archive. | Can you tell what is the following Python 3 function doing
def list_recycle_bin(self, start=0, limit=1000, **kwargs):
params = {
'start': start,
'limit': limit,
}
return self._request('file', 'listrecycle',
extra_params=params, **kwargs) | You are a Python code analyst, evaluating scripts for potential improvements. |
还原单个文件或目录(非强一致接口,调用后请sleep 1秒读取).
:param fs_id: 所还原的文件或目录在PCS的临时唯一标识ID。
:type fs_id: str
:return: Response 对象 | Make a summary of the following Python 3 code
def restore_recycle_bin(self, fs_id, **kwargs):
data = {
'fs_id': fs_id,
}
return self._request('file', 'restore', data=data, **kwargs) | As a Python code composer, you craft elegant and concise scripts. |
def multi_restore_recycle_bin(self, fs_ids, **kwargs):
"""批量还原文件或目录(非强一致接口,调用后请sleep1秒 ).
:param fs_ids: 所还原的文件或目录在 PCS 的临时唯一标识 ID 的列表。
:type fs_ids: list or tuple
:return: Response 对象
"""
data = {
'param': json.dumps({
'list': [{'fs_id': fs_... | Create a Python 3 function to
restore all the files in a set of files | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_new_access_token(refresh_token, client_id, client_secret,
scope=None, **kwargs):
"""使用 Refresh Token 刷新以获得新的 Access Token.
:param refresh_token: 用于刷新 Access Token 用的 Refresh Token;
:param client_id: 应用的 API Key;
:param client_secret: 应用的 Secret Key;
:param scope: 以空... | Can you implement a function in Python 3 that
gets a new Access Token. | As a Python code analyst, you investigate and solve complex coding mysteries |
def login(self):
""" Login to verisure app api
Login before calling any read or write commands
"""
if os.path.exists(self._cookieFileName):
with open(self._cookieFileName, 'r') as cookieFile:
self._vid = cookieFile.read().strip()
try:
... | Can you implement a function in Python 3 that
logs-in to verisure app api api Login before calling any read or write commands getTaxID | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_installations(self):
""" Get information about installations """
response = None
for base_url in urls.BASE_URLS:
urls.BASE_URL = base_url
try:
response = requests.get(
urls.get_installations(self._username),
... | Create a Python 3 function for
getting information about installations | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_overview(self):
""" Get overview for installation """
response = None
try:
response = requests.get(
urls.overview(self._giid),
headers={
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept... | How would you code a function in Python 3 to
get overview for installation | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_smartplug_state(self, device_label, state):
""" Turn on or off smartplug
Args:
device_label (str): Smartplug device label
state (boolean): new status, 'True' or 'False'
"""
response = None
try:
response = requests.post(
... | Can you create a Python 3 function that
turns on or off smartplug on the specified smartplug device label. | You are a Python code generator, capable of creating scripts from specifications. |
def get_history(self, filters=(), pagesize=15, offset=0):
""" Get recent events
Args:
filters (string set): 'ARM', 'DISARM', 'FIRE', 'INTRUSION',
'TECHNICAL', 'SOS', 'WARNING', 'LOCK',
'UNLOCK'
pagesize (int): N... | Can you implement a function in Python 3 that
gets recent events from the object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get climate history from the device. | Make a summary of the following Python 3 code
def get_climate(self, device_label):
response = None
try:
response = requests.get(
urls.climate(self._giid),
headers={
'Accept': 'application/json, text/javascript, */*; q=0.01',
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Set lock state of a lock in a specific device. | Explain what the following Python 3 code does
def set_lock_state(self, code, device_label, state):
response = None
try:
response = requests.put(
urls.set_lockstate(self._giid, device_label, state),
headers={
'Accept': 'application/json, tex... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_lock_state_transaction(self, transaction_id):
""" Get lock state transaction status
Args:
transaction_id: Transaction ID received from set_lock_state
"""
response = None
try:
response = requests.get(
urls.get_lockstate_transaction(... | Can you implement a function in Python 3 that
gets lock state transaction status | You are a Python code analyst, evaluating scripts for potential improvements. |
Get lock configuration of a specific lock in a specific device. | Can you tell what is the following Python 3 function doing
def get_lock_config(self, device_label):
response = None
try:
response = requests.get(
urls.lockconfig(self._giid, device_label),
headers={
'Accept': 'application/json, text/javascr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set lock configuration for a specific lock in the nexus. | Explain what the following Python 3 code does
def set_lock_config(self, device_label, volume=None, voice_level=None,
auto_lock_enabled=None):
""" Set lock configuration
Args:
device_label (str): device label of lock
volume (str): 'SILENCE', 'LOW' or 'HIGH... | You are a Python code architect, reviewing and designing scalable and efficient code |
Capture smartcam image of a specific device label. | Explain what the following Python 3 code does
def capture_image(self, device_label):
response = None
try:
response = requests.post(
urls.imagecapture(self._giid, device_label),
headers={
'Content-Type': 'application/json',
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get smartcam image series | Can you generate a brief explanation for the following Python 3 code
def get_camera_imageseries(self, number_of_imageseries=10, offset=0):
response = None
try:
response = requests.get(
urls.get_imageseries(self._giid),
headers={
'Accept': '... | You are a Python code generator, capable of creating scripts from specifications. |
def download_image(self, device_label, image_id, file_name):
""" Download image taken by a smartcam
Args:
device_label (str): device label of camera
image_id (str): image id from image series
file_name (str): path to file
"""
response = None
t... | Write a Python 3 function that can
download image taken by a smartcam | As a Python code translator, you convert algorithms and pseudocode into Python. |
Logout and remove vid | How would you explain what the following Python 3 function does
def logout(self):
response = None
try:
response = requests.delete(
urls.login(),
headers={
'Cookie': 'vid={}'.format(self._vid)})
except requests.exceptions.RequestExce... | As a python code expert, you are capable of creating scripts from specifications. |
def set_heat_pump_mode(self, device_label, mode):
""" Set heatpump mode
Args:
mode (str): 'HEAT', 'COOL', 'FAN' or 'AUTO'
"""
response = None
try:
response = requests.put(
urls.set_heatpump_state(self._giid, device_label),
h... | Implement a function in Python 3 to
set the heat pump mode for a specific user. | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_heat_pump_feature(self, device_label, feature):
""" Set heatpump mode
Args:
feature: 'QUIET', 'ECONAVI', or 'POWERFUL'
"""
response = None
try:
response = requests.put(
urls.set_heatpump_feature(self._giid, device_label, feature),
... | Write a Python 3 function that can
set the heatpump mode for a specific feature. | You are a Python code architect, reviewing and designing scalable and efficient code |
Print the result of a verisure request. | Make a summary of the following Python 3 code
def print_result(overview, *names):
if names:
for name in names:
toprint = overview
for part in name.split('/'):
toprint = toprint[part]
print(json.dumps(toprint, indent=4, separators=(',', ': ')))
else:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Start verisure command line | Can you generate a brief explanation for the following Python 3 code
def main():
parser = argparse.ArgumentParser(
description='Read or change status of verisure devices')
parser.add_argument(
'username',
help='MyPages username')
parser.add_argument(
'password',
help=... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def type_id(self):
"""
Shortcut to retrieving the ContentType id of the model.
"""
try:
return ContentType.objects.get_for_model(self.model, for_concrete_model=False).id
except DatabaseError as e:
raise DatabaseError("Unable to fetch ContentType object, is... | Create a Python 3 function for
getting the ContentType id of the model. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_output_cache_key(self, placeholder_name, instance):
"""
.. versionadded:: 0.9
Return the default cache key which is used to store a rendered item.
By default, this function generates the cache key using :func:`get_output_cache_base_key`.
"""
cachekey = self.... | Can you implement a function in Python 3 that
returns the cache key which is used to store a rendered item. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the possible cache keys for a rendered item. | Can you generate a brief explanation for the following Python 3 code
def get_output_cache_keys(self, placeholder_name, instance):
base_key = self.get_output_cache_base_key(placeholder_name, instance)
cachekeys = [
base_key,
]
if self.cache_output_per_site:
site_i... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_cached_output(self, placeholder_name, instance):
"""
.. versionadded:: 0.9
Return the cached output for a rendered item, or ``None`` if no output is cached.
This method can be overwritten to implement custom caching mechanisms.
By default, this function generate... | Write a Python 3 script to
get the cached output for a rendered item. | As a python code expert, you are capable of creating scripts from specifications. |
def set_cached_output(self, placeholder_name, instance, output):
"""
.. versionadded:: 0.9
Store the cached output for a rendered item.
This method can be overwritten to implement custom caching mechanisms.
By default, this function generates the cache key using :func:`... | Can you implement a function in Python 3 that
sets the cached output for a rendered item. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a string that can be used to render a single item. | Here you have a function in Python 3, explain what it does
def render(self, request, instance, **kwargs):
render_template = self.get_render_template(request, instance, **kwargs)
if not render_template:
return str(_(u"{No rendering defined for class '%s'}" % self.__class__.__name__))
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Render a custom template with the context as context instance. | Make a summary of the following Python 3 code
def render_to_string(self, request, template, context, content_instance=None):
if not content_instance:
content_instance = PluginContext(request)
content_instance.update(context)
return render_to_string(template, content_instance.flatten... | As a Python code analyst, you investigate and solve complex coding mysteries |
def register_frontend_media(request, media):
"""
Add a :class:`~django.forms.Media` class to the current request.
This will be rendered by the ``render_plugin_media`` template tag.
"""
if not hasattr(request, '_fluent_contents_frontend_media'):
request._fluent_contents_frontend_media = Media... | Create a Python 3 function to
register a Media class to the frontend. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a cache key for the content item output. | How would you explain what the following Python 3 function does
def get_rendering_cache_key(placeholder_name, contentitem):
if not contentitem.pk:
return None
return "contentitem.@{0}.{1}.{2}".format(
placeholder_name,
contentitem.plugin.type_name, # always returns the upcasted name.
... | You are a Python code generator, capable of creating scripts from specifications. |
def get_placeholder_cache_key(placeholder, language_code):
"""
Return a cache key for an existing placeholder object.
This key is used to cache the entire output of a placeholder.
"""
return _get_placeholder_cache_key_for_id(
placeholder.parent_type_id,
placeholder.parent_id,
... | Create a Python 3 function to
return a cache key for an existing placeholder object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a cache key for a placeholder. | Make a summary of the following Python 3 code
def get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code):
parent_type = ContentType.objects.get_for_model(parent_object)
return _get_placeholder_cache_key_for_id(
parent_type.id,
parent_object.pk,
placeholder_n... | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove stale items from the database. | Explain what the following Python 3 code does
def remove_stale_items(self, stale_cts):
stale_ct_ids = list(stale_cts.keys())
items = (ContentItem.objects
.non_polymorphic() # very important, or polymorphic skips them on fetching derived data
.filter(polymorphic_ctype__... | You are a Python code generator, capable of creating scripts from specifications. |
def remove_unreferenced_items(self, stale_cts):
"""
See if there are items that no longer point to an existing parent.
"""
stale_ct_ids = list(stale_cts.keys())
parent_types = (ContentItem.objects.order_by()
.exclude(polymorphic_ctype__in=stale_ct_ids)
... | Implement a Python 3 function for
removing items that no longer point to an existing parent. | As a Python code analyst, you investigate and solve complex coding mysteries |
def __initial_minus_queryset(self):
"""
Gives all elements from self._initial having a slot value that is not already
in self.get_queryset()
"""
queryset = self.get_queryset()
def initial_not_in_queryset(initial):
for x in queryset:
if x.slot ... | Create a Python 3 function for
returning the list of elements that are not already in the queryset | As a python code expert, you are capable of creating scripts from specifications. |
def _get_placeholder_arg(arg_name, placeholder):
"""
Validate and return the Placeholder object that the template variable points to.
"""
if placeholder is None:
raise RuntimeWarning(u"placeholder object is None")
elif isinstance(placeholder, Placeholder):
return placeholder
elif... | Create a Python 3 function for
validating and return the Placeholder object that points to the given placeholder object. | As a Python code composer, you craft elegant and concise scripts. |
Split the local or external URLs from a Media object. | Make a summary of the following Python 3 code
def _split_js(media, domain):
# Read internal property without creating new Media instance.
if not media._js:
return ImmutableMedia.empty_instance
needs_local = domain == 'local'
new_js = []
for url in media._js:
if needs_local == _is_lo... | As a Python code analyst, you investigate and solve complex coding mysteries |
Extract the local or external URLs from a Media object. | Can you tell what is the following Python 3 function doing
def _split_css(media, domain):
# Read internal property without creating new Media instance.
if not media._css:
return ImmutableMedia.empty_instance
needs_local = domain == 'local'
new_css = {}
for medium, url in six.iteritems(media... | As a python code expert, you are capable of creating scripts from specifications. |
def parse(cls, parser, token):
"""
Parse the node syntax:
.. code-block:: html+django
{% page_placeholder parentobj slotname title="test" role="m" %}
"""
bits, as_var = parse_as_var(parser, token)
tag_name, args, kwargs = parse_token_kwargs(parser, bits, all... | Can you write a function in Python 3 where it
parses the node syntax for the national cache object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_title(self):
"""
Return the string literal that is used in the template.
The title is used in the admin screens.
"""
try:
return extract_literal(self.meta_kwargs['title'])
except KeyError:
slot = self.get_slot()
if slot is not N... | Write a Python 3 function for
returning the string literal that is used in the template screens. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the value of a Literal in a FilterExpression. | How would you explain what the following Python 3 function does
def extract_literal(templatevar):
# FilterExpression contains another 'var' that either contains a Variable or SafeData object.
if hasattr(templatevar, 'var'):
templatevar = templatevar.var
if isinstance(templatevar, SafeData):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def extract_literal_bool(templatevar):
"""
See if a template FilterExpression holds a literal boolean value.
:type templatevar: django.template.FilterExpression
:rtype: bool|None
"""
# FilterExpression contains another 'var' that either contains a Variable or SafeData object.
if hasattr(tem... | Write a Python 3 script for
returning True if a template FilterExpression holds a literal boolean value. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a new MarkupPlugin class that represents the plugin type. | How would you explain what the following Python 3 function does
def _create_markup_plugin(language, model):
form = type("{0}MarkupItemForm".format(language.capitalize()), (MarkupItemForm,), {
'default_language': language,
})
classname = "{0}MarkupPlugin".format(language.capitalize())
PluginClas... | You are a Python code generator, capable of creating scripts from specifications. |
def get_parent_lookup_kwargs(parent_object):
"""
Return lookup arguments for the generic ``parent_type`` / ``parent_id`` fields.
:param parent_object: The parent object.
:type parent_object: :class:`~django.db.models.Model`
"""
if parent_object is None:
return dict(
parent_t... | Can you implement a function in Python 3 that
returns a dictionary of keyword arguments for the generic parent_type / parent_id fields. | You are a Python code generator, capable of creating scripts from specifications. |
Get the currently active languages of a parent object. | Can you generate a brief explanation for the following Python 3 code
def get_parent_active_language_choices(parent_object, exclude_current=False):
assert parent_object is not None, "Missing parent_object!"
from .db import ContentItem
qs = ContentItem.objects \
.parent(parent_object, limit_parent_la... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_by_slot(self, parent_object, slot):
"""
Return a placeholder by key.
"""
placeholder = self.parent(parent_object).get(slot=slot)
placeholder.parent = parent_object # fill the reverse cache
return placeholder | Implement a function in Python 3 to
return a placeholder by slot. | As a Python code composer, you craft elegant and concise scripts. |
def create_for_object(self, parent_object, slot, role='m', title=None):
"""
Create a placeholder with the given parameters
"""
from .db import Placeholder
parent_attrs = get_parent_lookup_kwargs(parent_object)
obj = self.create(
slot=slot,
role=rol... | How would you implement a function in Python 3 that
creates a new object with the given parameters and return it. | As a python code expert, you are capable of creating scripts from specifications. |
Return a new QuerySet with translated objects. | Make a summary of the following Python 3 code
def translated(self, *language_codes):
# this API has the same semantics as django-parler's .translated() for familiarity.
# However, since this package doesn't filter in a related field, the ORM limitations don't apply.
if not language_codes:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parent(self, parent_object, limit_parent_language=True):
"""
Return all content items which are associated with a given parent object.
"""
lookup = get_parent_lookup_kwargs(parent_object)
# Filter the items by default, giving the expected "objects for this parent" items
... | Write a Python 3 script for
returning all content items which are associated with a given parent object. | As a Python code composer, you craft elegant and concise scripts. |
Move the entire queryset to a new object. | Here you have a function in Python 3, explain what it does
def move_to_placeholder(self, placeholder, sort_order=None):
qs = self.all() # Get clone
for item in qs:
# Change the item directly in the resultset.
item.move_to_placeholder(placeholder, sort_order=sort_order)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def copy_to_placeholder(self, placeholder, sort_order=None):
"""
.. versionadded: 1.0 Copy the entire queryset to a new object.
Returns a queryset with the newly created objects.
"""
qs = self.all() # Get clone
for item in qs:
# Change the item directly in t... | How would you implement a function in Python 3 that
copies the entire queryset to a new object. | As a python code expert, you are capable of creating scripts from specifications. |
Return all content items which are associated with a given parent object. | How would you explain what the following Python 3 function does
def parent(self, parent_object, limit_parent_language=True):
return self.all().parent(parent_object, limit_parent_language) | As a python code expert, you are capable of creating scripts from specifications. |
Create a new Content Item for a given Placeholder. | Explain what the following Python 3 code does
def create_for_placeholder(self, placeholder, sort_order=1, language_code=None, **kwargs):
if language_code is None:
# Could also use get_language() or appsettings.FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE
# thus avoid the risk of performing an e... | 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.