output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def do_dimension_value_list(mc, args):
'''List names of metric dimensions.'''
fields = {}
fields['dimension_name'] = args.dimension_name
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offse... | How would you implement a function in Python 3 that
lists names of metric dimensions. | As a Python code analyst, you investigate and solve complex coding mysteries |
List measurement statistics for the specified metric. | Can you generate a brief explanation for the following Python 3 code
def do_metric_statistics(mc, args):
'''List measurement statistics for the specified metric.'''
statistic_types = ['AVG', 'MIN', 'MAX', 'COUNT', 'SUM']
statlist = args.statistics.split(',')
for stat in statlist:
if stat.upper()... | As a Python code composer, you craft elegant and concise scripts. |
List notifications for this tenant. | Here you have a function in Python 3, explain what it does
def do_notification_list(mc, args):
'''List notifications for this tenant.'''
fields = {}
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.sort_by:
sort_by = args.sort... | As a python code expert, you are capable of creating scripts from specifications. |
def do_notification_update(mc, args):
'''Update notification.'''
fields = {}
fields['notification_id'] = args.id
fields['name'] = args.name
fields['type'] = args.type
fields['address'] = args.address
if not _validate_notification_period(args.period, args.type.upper()):
return
fi... | Write a Python 3 function for
updating a single notification. | As a Python code composer, you craft elegant and concise scripts. |
Create an alarm definition. | Here you have a function in Python 3, explain what it does
def do_alarm_definition_create(mc, args):
'''Create an alarm definition.'''
fields = {}
fields['name'] = args.name
if args.description:
fields['description'] = args.description
fields['expression'] = args.expression
if args.alarm... | You are a Python code architect, reviewing and designing scalable and efficient code |
def do_alarm_definition_list(mc, args):
'''List alarm definitions for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.severity:
if not _validate_severity(arg... | How would you implement a function in Python 3 that
lists alarm definitions for this tenant. | As a Python code composer, you craft elegant and concise scripts. |
def do_alarm_definition_delete(mc, args):
'''Delete the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
try:
mc.alarm_definitions.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
... | Write a Python 3 script for
deleting the alarm definition. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def do_alarm_definition_update(mc, args):
'''Update the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
fields['name'] = args.name
fields['description'] = args.description
fields['expression'] = args.expression
fields['alarm_actions'] = _arg_split_patch_update(args.alarm_action... | Can you implement a function in Python 3 that
updates the alarm definition. | You are a Python code architect, reviewing and designing scalable and efficient code |
def do_alarm_definition_patch(mc, args):
'''Patch the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
if args.name:
fields['name'] = args.name
if args.description:
fields['description'] = args.description
if args.expression:
fields['expression'] = args.expre... | How would you implement a function in Python 3 that
patches the alarm definition. | You are a Python code generator, capable of creating scripts from specifications. |
List alarms for this tenant. | Explain what the following Python 3 code does
def do_alarm_list(mc, args):
'''List alarms for this tenant.'''
fields = {}
if args.alarm_definition_id:
fields['alarm_definition_id'] = args.alarm_definition_id
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.metric... | As a Python code analyst, you investigate and solve complex coding mysteries |
Update the alarm state. | Here you have a function in Python 3, explain what it does
def do_alarm_update(mc, args):
'''Update the alarm state.'''
fields = {}
fields['alarm_id'] = args.id
if args.state.upper() not in state_types:
errmsg = ('Invalid state, not one of [' +
', '.join(state_types) + ... | As a python code expert, you are capable of creating scripts from specifications. |
def do_alarm_history(mc, args):
'''Alarm state transition history.'''
fields = {}
fields['alarm_id'] = args.id
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
try:
alarm = mc.alarms.history(**fields)
except (osc_exc.ClientExc... | Implement a Python 3 function for
alarming state transition history. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def do_alarm_history_list(mc, args):
'''List alarms state history.'''
fields = {}
if args.dimensions:
fields['dimensions'] = utils.format_parameters(args.dimensions)
if args.starttime:
_translate_starttime(args)
fields['start_time'] = args.starttime
if args.endtime:
f... | Implement a Python 3 function for
listing alarms state history. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def do_notification_type_list(mc, args):
'''List notification types supported by monasca.'''
try:
notification_types = mc.notificationtypes.list()
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
if ar... | Can you write a function in Python 3 where it
lists notification types supported by monasca. | As a python code expert, you are capable of creating scripts from specifications. |
def load_auth_token(token, load=True):
"""Validate an auth0 token. Returns the token's payload, or an exception
of the type:"""
assert get_config().jwt_secret, "No JWT secret configured for pymacaron"
assert get_config().jwt_issuer, "No JWT issuer configured for pymacaron"
assert get_config().jwt_a... | Create a Python 3 function to
validate an auth0 token and return the payload or an exception if the token is invalid. | As a Python code composer, you craft elegant and concise scripts. |
Validate auth0 tokens passed in the HTTP request. | Make a summary of the following Python 3 code
def authenticate_http_request(token=None):
if token:
auth = token
else:
auth = request.headers.get('Authorization', None)
if not auth:
auth = request.cookies.get('token', None)
if auth:
auth = unquote_plus(auth)
... | As a Python code composer, you craft elegant and concise scripts. |
Generate a new JWT token for the given user_id. | How would you explain what the following Python 3 function does
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None):
assert user_id, "No user_id passed to generate_token()"
assert isinstance(data, dict), "generate_token(data=) should be a dictionary"
assert get_config().jwt_secret, "... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the authenticated user s auth token | Can you generate a brief explanation for the following Python 3 code
def get_user_token():
if not hasattr(stack.top, 'current_user'):
return ''
current_user = stack.top.current_user
return current_user.get('token', '') | As a python code expert, you are capable of creating scripts from specifications. |
def get_token_issuer():
"""Return the issuer in which this user's token was created"""
try:
current_user = stack.top.current_user
return current_user.get('iss', get_config().jwt_issuer)
except Exception:
pass
return get_config().jwt_issuer | Implement a Python 3 function for
returning the issuer in which this user s token was created | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of result objects with the url for the next page MsCognitive search url. | Explain what the following Python 3 code does
def _search(self, limit, format):
'''
Returns a list of result objects, with the url for the next page MsCognitive search url.
'''
limit = min(limit, self.MAX_SEARCH_PER_QUERY)
payload = {
'q' : self.query,
'count'... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get(self, **kwargs):
"""Get the details for a specific notification."""
# NOTE(trebskit) should actually be find_one, but
# monasca does not support expected response format
url = '%s/%s' % (self.base_url, kwargs['notification_id'])
resp = self.client.list(path=url)
... | Write a Python 3 function that can
get the details for a specific notification. | You are a Python code analyst, evaluating scripts for potential improvements. |
def create(self, **kwargs):
"""Create an alarm definition."""
resp = self.client.create(url=self.base_url,
json=kwargs)
return resp | Write a Python 3 function for
creating an alarm definition. | As a Python code analyst, you investigate and solve complex coding mysteries |
Update a specific alarm definition. | Can you tell what is the following Python 3 function doing
def update(self, **kwargs):
url_str = self.base_url + '/%s' % kwargs['alarm_id']
del kwargs['alarm_id']
resp = self.client.create(url=url_str,
method='PUT',
json=kwargs... | You are a Python code analyst, evaluating scripts for potential improvements. |
Computes the y - values for the domain of x - values in [ 1 num_x ). | Here you have a function in Python 3, explain what it does
def compute_y(self, coefficients, num_x):
y_vals = []
for x in range(1, num_x + 1):
y = sum([c * x ** i for i, c in enumerate(coefficients[::-1])])
y_vals.append(y)
return y_vals | As a python code expert, you are capable of creating scripts from specifications. |
def compute_err(self, solution_y, coefficients):
"""
Return an error value by finding the absolute difference for each
element in a list of solution-generated y-values versus expected values.
Compounds error by 50% for each negative coefficient in the solution.
solution_y: lis... | Can you implement a function in Python 3 that
computes the error value of the current set of values produced by the current set of values. | As a python code expert, you are capable of creating scripts from specifications. |
Evaluate the polynomial equation using coefficients represented by a
solution and chromosome. Returns the error as the solution s fitness. | How would you explain what the following Python 3 function does
def eval_fitness(self, chromosome):
coefficients = self.translator.translate_chromosome(chromosome)
solution_y = self.compute_y(coefficients, self.num_x)
fitness = -1 * self.compute_err(solution_y, coefficients)
return fitn... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Read the current configuration of a myStrom device. | Can you generate the documentation for the following Python 3 function
def read_config(ip, mac):
click.echo("Read configuration from %s" % ip)
request = requests.get(
'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT)
print(request.json()) | As a Python code composer, you craft elegant and concise scripts. |
Write the current configuration of a myStrom button. | How would you explain what the following Python 3 function does
def write_config(ip, mac, single, double, long, touch):
click.echo("Write configuration to device %s" % ip)
data = {
'single': single,
'double': double,
'long': long,
'touch': touch,
}
request = requests.post... | As a python code expert, you are capable of creating scripts from specifications. |
def write_ha_config(ip, mac, hass, port, id):
"""Write the configuration for Home Assistant to a myStrom button."""
click.echo("Write configuration for Home Assistant to device %s..." % ip)
action = "get://{1}:{2}/api/mystrom?{0}={3}"
data = {
'single': action.format('single', hass, port, id),
... | How would you code a function in Python 3 to
write the configuration for Home Assistant to a myStrom button. | As a python code expert, you are capable of creating scripts from specifications. |
Reset the current configuration of a myStrom WiFi Button. | Given the following Python 3 function, write the documentation
def reset_config(ip, mac):
click.echo("Reset configuration of button %s..." % ip)
data = {
'single': "",
'double': "",
'long': "",
'touch': "",
}
request = requests.post(
'http://{}/{}/{}/'.format(ip, ... | You are a Python code generator, capable of creating scripts from specifications. |
Switch the bulb on with the given color. | Can you generate a brief explanation for the following Python 3 code
def color(ip, mac, hue, saturation, value):
bulb = MyStromBulb(ip, mac)
bulb.set_color_hsv(hue, saturation, value) | As a Python code composer, you craft elegant and concise scripts. |
def is_ec2_instance():
"""Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/'
to see if host is on an ec2 instance"""
# Note: this code assumes that docker containers running on ec2 instances
# inherit instances metadata, which they do as of 2016-08-25
global IS_EC2_I... | How would you implement a function in Python 3 that
checks if host is on an ec2 instance | You are a Python code analyst, evaluating scripts for potential improvements. |
def to_epoch(t):
"""Take a datetime, either as a string or a datetime.datetime object,
and return the corresponding epoch"""
if isinstance(t, str):
if '+' not in t:
t = t + '+00:00'
t = parser.parse(t)
elif t.tzinfo is None or t.tzinfo.utcoffset(t) is None:
t = t.repl... | Create a Python 3 function to
take a datetime either as a string or a datetime. datetime object and return the corresponding epoch | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_container_version():
"""Return the version of the docker container running the present server,
or '' if not in a container"""
root_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
version_file = os.path.join(root_dir, 'VERSION')
if os.path.exists(version_file):
with open(version_... | How would you code a function in Python 3 to
return the version of the docker container running the present server or an empty string if not in a container | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a generic name for this app usefull when reporting to monitoring frameworks | How would you explain what the following Python 3 function does
def get_app_name():
conf = get_config()
if is_ec2_instance():
return conf.app_name_live if hasattr(conf, 'app_name_live') else 'PYMACARON_LIVE'
else:
return conf.app_name_dev if hasattr(conf, 'app_name_dev') else 'PYMACARON_DEV' | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_random(cls, length, **kwargs):
"""
Return a new instance of this gene class with random DNA,
with characters chosen from ``GENETIC_MATERIAL_OPTIONS``.
length: the number of characters in the randomized DNA
**kwargs: forwarded to the ``cls`` constructor
... | Can you write a function in Python 3 where it
creates a new instance of this gene class with random DNA and random characters chosen from the GeneMaterIAL_OPTIONS list. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def mutate(self, p_mutate):
"""
Simulate mutation against a probability.
p_mutate: probability for mutation to occur
"""
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
new_bit = bit
while new_bit ==... | How would you code a function in Python 3 to
simulate mutation against a probability. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a copy of this gene with the same DNA. | How would you explain what the following Python 3 function does
def copy(self):
return type(self)(self.dna, suppressed=self.suppressed, name=self.name) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _check_dna(self, dna):
""" Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. """
valid_chars = set(self.GENETIC_MATERIAL_OPTIONS)
assert all(char in valid_chars for char in dna) | Can you write a function in Python 3 where it
checks that a DNA string only contains characters in self. GENETIC_MATERIAL_OPTIONS. | You are a Python code architect, reviewing and designing scalable and efficient code |
Mutate the DNA string. | Explain what the following Python 3 code does
def mutate(self, p_mutate):
new_dna = []
for bit in self.dna:
if random.random() < p_mutate:
bit = '1' if bit == '0' else '0'
new_dna.append(bit)
self.dna = ''.join(new_dn... | As a Python code composer, you craft elegant and concise scripts. |
Returns an monitoring API client. | Here you have a function in Python 3, explain what it does
def make_client(api_version, session=None,
endpoint=None, service_type='monitoring'):
"""Returns an monitoring API client."""
client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP)
c = client_cls(
sessio... | As a Python code composer, you craft elegant and concise scripts. |
def _session(kwargs):
"""Returns or reuses session.
Method takes care of providing instance of
session object for the client.
:param kwargs: all params (without api_version) client was initialized with
:type kwargs: dict
:returns: session object
:rtype keystoneauth1.session.Session
"... | Write a Python 3 script for
returning or reuses session. | As a Python code composer, you craft elegant and concise scripts. |
def load(cls, path):
"""
Loads an instance of the class from a file.
Parameters
----------
path : str
Path to an HDF5 file.
Examples
--------
This is an abstract data type, but let us say that ``Foo`` inherits
from ``Saveable``. To co... | Implement a function in Python 3 to
load an instance of the class from a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator to register a class. | Can you generate a brief explanation for the following Python 3 code
def register(cls, name):
def register_decorator(reg_cls):
def name_func(self):
return name
reg_cls.name = property(name_func)
assert issubclass(reg_cls, cls), \
"Must be subcl... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def construct(cls, name, *args, **kwargs):
"""
Constructs an instance of an object given its name.
"""
return cls.REGISTRY[name](*args, **kwargs) | How would you implement a function in Python 3 that
constructs an instance of the named object given its name. | You are a Python code architect, reviewing and designing scalable and efficient code |
Loads and returns a ConfigParser from ~. deepdish. conf. | Given the following Python 3 function, write the documentation
def config():
conf = ConfigParser()
# Set up defaults
conf.add_section('io')
conf.set('io', 'compression', 'zlib')
conf.read(os.path.expanduser('~/.deepdish.conf'))
return conf | You are a Python code generator, capable of creating scripts from specifications. |
Takes an image and returns its grayscale version by averaging the color
channels. | Explain what the following Python 3 code does
def asgray(im):
if im.ndim == 2:
return im
elif im.ndim == 3 and im.shape[2] in (3, 4):
return im[..., :3].mean(axis=-1)
else:
raise ValueError('Invalid image format') | You are a Python code generator, capable of creating scripts from specifications. |
def crop(im, size):
"""
Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping.
"""
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
re... | Implement a Python 3 function for
cropping an image in the center. | You are a Python code generator, capable of creating scripts from specifications. |
Crop an image or pad it. | Here you have a function in Python 3, explain what it does
def crop_or_pad(im, size, value=0):
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
return im2 | You are a Python code analyst, evaluating scripts for potential improvements. |
def load(path, dtype=np.float64):
"""
Loads an image from file.
Parameters
----------
path : str
Path to image file.
dtype : np.dtype
Defaults to ``np.float64``, which means the image will be returned as a
float with values between 0 and 1. If ``np.uint8`` is specified, ... | Write a Python 3 script for
loading an image from file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load_raw(path):
"""
Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file.... | Write a Python 3 script to
load image using PIL. Image. open with PIL. Pillow without any processing. | As a python code expert, you are capable of creating scripts from specifications. |
def save(path, im):
"""
Saves an image to file.
If the image is type float, it will assume to have values in [0, 1].
Parameters
----------
path : str
Path to which the image will be saved.
im : ndarray (image)
Image.
"""
from PIL import Image
if im.dtype == np.u... | Can you write a function in Python 3 where it
saves an image to file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Integrate the image of a given window over a given top left corner of the block and the bottom right corner of the block. | Can you tell what is the following Python 3 function doing
def integrate(ii, r0, c0, r1, c1):
# This line is modified
S = np.zeros(ii.shape[-1])
S += ii[r1, c1]
if (r0 - 1 >= 0) and (c0 - 1 >= 0):
S += ii[r0 - 1, c0 - 1]
if (r0 - 1 >= 0):
S -= ii[r0 - 1, c1]
if (c0 - 1 >= 0):... | You are a Python code generator, capable of creating scripts from specifications. |
def offset(img, offset, fill_value=0):
"""
Moves the contents of image without changing the image size. The missing
values are given a specified fill value.
Parameters
----------
img : array
Image.
offset : (vertical_offset, horizontal_offset)
Tuple of length 2, specifying t... | Create a Python 3 function to
move the contents of an image with the specified offset along the two axes. | You are a Python code analyst, evaluating scripts for potential improvements. |
def bounding_box(alpha, threshold=0.1):
"""
Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Re... | Create a Python 3 function to
return a bounding box describing the smallest rectangle containing the foreground object. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the bounding box as a binary map. | Here you have a function in Python 3, explain what it does
def bounding_box_as_binary_map(alpha, threshold=0.1):
bb = bounding_box(alpha)
x = np.zeros(alpha.shape, dtype=np.bool_)
x[bb[0]:bb[2], bb[1]:bb[3]] = 1
return x | You are a Python code analyst, evaluating scripts for potential improvements. |
Takes a set of images and yields randomly chosen patches of specified size. | Can you tell what is the following Python 3 function doing
def extract_patches(images, patch_shape, samples_per_image=40, seed=0,
cycle=True):
"""
Takes a set of images and yields randomly chosen patches of specified size.
Parameters
----------
images : iterable
The imag... | As a Python code analyst, you investigate and solve complex coding mysteries |
def bytesize(arr):
"""
Returns the memory byte size of a Numpy array as an integer.
"""
byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize
return byte_size | Write a Python 3 function for
returning the memory byte size of a Numpy array as an integer. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Argmax that returns an index tuple. Note that numpy. argmax will return a
scalar index as if you had flattened the array. | Given the following Python 3 function, write the documentation
def tupled_argmax(a):
return np.unravel_index(np.argmax(a), np.shape(a)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def pad(data, padwidth, value=0.0):
"""
Pad an array with a specific value.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
padwidth : int or tuple
If int, it will pad using this amount at the beginning and end of all
dimensions. If it is a tu... | Can you implement a function in Python 3 that
pads an array with a specific value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a new array with padded data by repeating the borders of each axis. | Can you tell what is the following Python 3 function doing
def pad_repeat_border_corner(data, shape):
new_data = np.empty(shape)
new_data[[slice(upper) for upper in data.shape]] = data
for i in range(len(shape)):
selection = [slice(None)]*i + [slice(data.shape[i], None)]
selection2 = [slice(... | As a Python code composer, you craft elegant and concise scripts. |
def _dict_native_ok(d):
"""
This checks if a dictionary can be saved natively as HDF5 groups.
If it can't, it will be pickled.
"""
if len(d) >= 256:
return False
# All keys must be strings
for k in d:
if not isinstance(k, six.string_types):
return False
ret... | Can you implement a function in Python 3 that
checks if a dictionary can be saved natively as HDF5 groups. | As a python code expert, you are capable of creating scripts from specifications. |
Loads the non - link level and builds appropriate type without handling softlinks | How would you explain what the following Python 3 function does
def _load_nonlink_level(handler, level, pathtable, pathname):
if isinstance(level, tables.Group):
if _sns and (level._v_title.startswith('SimpleNamespace:') or
DEEPDISH_IO_ROOT_IS_SNS in level._v_attrs):
val = S... | As a Python code analyst, you investigate and solve complex coding mysteries |
Loads the level and builds appropriate type if necessary | Can you tell what is the following Python 3 function doing
def _load_level(handler, level, pathtable):
if isinstance(level, tables.link.SoftLink):
# this is a link, so see if target is already loaded, return it
pathname = level.target
node = level()
else:
# not a link, but it mig... | As a Python code analyst, you investigate and solve complex coding mysteries |
def save(path, data, compression='default'):
"""
Save any Python structure to an HDF5 file. It is particularly suited for
Numpy arrays. This function works similar to ``numpy.save``, except if you
save a Python object at the top level, you do not need to issue
``data.flat[0]`` to retrieve it from in... | Can you create a Python 3 function that
saves a Python object to HDF5. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Loads an HDF5 file and returns a dict of the data that was saved with save. | Can you generate a brief explanation for the following Python 3 code
def load(path, group=None, sel=None, unpack=False):
with tables.open_file(path, mode='r') as h5file:
pathtable = {} # dict to keep track of objects already loaded
if group is not None:
if isinstance(group, str):
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def sorted_maybe_numeric(x):
"""
Sorts x with numeric semantics if all keys are nonnegative integers.
Otherwise uses standard string sorting.
"""
all_numeric = all(map(str.isdigit, x))
if all_numeric:
return sorted(x, key=int)
else:
return sorted(x) | Write a Python 3 script to
sort x with numeric semantics. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def abbreviate(s, maxlength=25):
"""Color-aware abbreviator"""
assert maxlength >= 4
skip = False
abbrv = None
i = 0
for j, c in enumerate(s):
if c == '\033':
skip = True
elif skip:
if c == 'm':
skip = False
else:
i += 1... | How would you code a function in Python 3 to
color - aware abbreviator | You are a Python code generator, capable of creating scripts from specifications. |
Extend the settings dictionary with the contents of the object. | Given the following Python 3 function, write the documentation
def extend_settings(self, data_id, files, secrets):
data = Data.objects.select_related('process').get(pk=data_id)
files[ExecutorFiles.DJANGO_SETTINGS].update({
'USE_TZ': settings.USE_TZ,
'FLOW_EXECUTOR_TOOLS_PATHS': ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def resolve_data_path(self, data=None, filename=None):
"""Resolve data path for use with the executor.
:param data: Data object instance
:param filename: Filename to resolve
:return: Resolved filename, which can be used to access the
given data file in programs executed usin... | How would you code a function in Python 3 to
resolve the data path for use with the executor. | As a Python code analyst, you investigate and solve complex coding mysteries |
def resolve_upload_path(self, filename=None):
"""Resolve upload path for use with the executor.
:param filename: Filename to resolve
:return: Resolved filename, which can be used to access the
given uploaded file in programs executed using this
executor
"""
... | Can you write a function in Python 3 where it
resolves the upload path for use with the executor. | As a Python code analyst, you investigate and solve complex coding mysteries |
A context manager that wraps an AccessPolicy PyXB object. | Explain what the following Python 3 code does
def wrap(access_pyxb, read_only=False):
w = AccessPolicyWrapper(access_pyxb)
yield w
if not read_only:
w.get_normalized_pyxb() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def wrap_sysmeta_pyxb(sysmeta_pyxb, read_only=False):
"""Work with the AccessPolicy in a SystemMetadata PyXB object.
Args:
sysmeta_pyxb : SystemMetadata PyXB object
SystemMetadata containing the AccessPolicy to modify.
read_only: bool
Do not update the wrapped AccessPolicy.
Wh... | Create a Python 3 function for
working with the AccessPolicy in a SystemMetadata PyXB object. Args: sysmeta_pyxb : SystemMetadata PyXB object SystemMetadata containing the AccessPolicy to modify. read_only: bool Do not update the wrapped AccessPolicy. When only a single AccessPolicy operation is needed, there's no need... | As a Python code composer, you craft elegant and concise scripts. |
def get_highest_perm_str(self, subj_str):
"""
Args:
subj_str : str
Subject for which to retrieve the highest permission.
Return:
The highest permission for subject or None if subject does not have any permissions.
"""
pres_perm_set = self._present_perm_set_for_subj(self... | Write a Python 3 script to
return the highest permission for a subject. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_effective_perm_list(self, subj_str):
"""
Args:
subj_str : str
Subject for which to retrieve the effective permissions.
Returns:
list of str: List of permissions up to and including the highest permission for
subject, ordered lower to higher, or empty list if subject do... | Can you write a function in Python 3 where it
returns the list of effective permissions for the subject. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_subjects_with_equal_or_higher_perm(self, perm_str):
"""
Args:
perm_str : str
Permission, ``read``, ``write`` or ``changePermission``.
Returns:
set of str : Subj that have perm equal or higher than ``perm_str``.
Since the lowest permission a subject can have is ``read`... | Implement a Python 3 function for
returning a set of subjects with equal or higher permission. | You are a Python code generator, capable of creating scripts from specifications. |
Dump the current state to debug level log. | Can you generate a brief explanation for the following Python 3 code
def dump(self):
logging.debug('AccessPolicy:')
map(
logging.debug,
[
' {}'.format(s)
for s in pprint.pformat(self.get_normalized_perm_list()).splitlines()
],
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def subj_has_perm(self, subj_str, perm_str):
"""Returns:
bool: ``True`` if ``subj_str`` has perm equal to or higher than ``perm_str``.
"""
self._assert_valid_permission(perm_str)
return perm_str in self.get_effective_perm_list(subj_str) | Create a Python 3 function to
return True if subj_str has perm equal to or higher than perm_str. | You are a Python code generator, capable of creating scripts from specifications. |
Add read perm for all authenticated subj. | Can you generate a brief explanation for the following Python 3 code
def add_authenticated_read(self):
self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read')
self.add_perm(d1_common.const.SUBJECT_AUTHENTICATED, 'read') | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_verified_read(self):
"""Add ``read`` perm for all verified subj.
Public ``read`` is removed if present.
"""
self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read')
self.add_perm(d1_common.const.SUBJECT_VERIFIED, 'read') | Write a Python 3 script for
adding verified read perm for all public subj. | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_perm(self, subj_str, perm_str):
"""Add a permission for a subject.
Args:
subj_str : str
Subject for which to add permission(s)
perm_str : str
Permission to add. Implicitly adds all lower permissions. E.g., ``write``
will also add ``read``... | Write a Python 3 function for
adding a permission for a subject. | As a python code expert, you are capable of creating scripts from specifications. |
def remove_perm(self, subj_str, perm_str):
"""Remove permission from a subject.
Args:
subj_str : str
Subject for which to remove permission(s)
perm_str : str
Permission to remove. Implicitly removes all higher permissions. E.g., ``write``
will al... | Can you implement a function in Python 3 that
removes a permission from a subject. | As a python code expert, you are capable of creating scripts from specifications. |
Removes all permissions for a subject. | Can you generate a brief explanation for the following Python 3 code
def remove_subj(self, subj_str):
for subj_set in list(self._perm_dict.values()):
subj_set -= {subj_str} | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return dict representation of AccessPolicy PyXB obj. | Given the following Python 3 function, write the documentation
def _perm_dict_from_pyxb(self, access_pyxb):
subj_dict = self._subj_dict_from_pyxb(access_pyxb)
return self._perm_dict_from_subj_dict(subj_dict) | You are a Python code analyst, evaluating scripts for potential improvements. |
Return dict where keys and values of subj_dict have been flipped
around. | Given the following Python 3 function, write the documentation
def _perm_dict_from_subj_dict(self, subj_dict):
perm_dict = {}
for subj_str, perm_set in list(subj_dict.items()):
for perm_str in perm_set:
perm_dict.setdefault(perm_str, set()).add(subj_str)
return perm_d... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _pyxb_from_perm_dict(self, perm_dict):
"""Return an AccessPolicy PyXB representation of ``perm_dict``
- If ``norm_perm_list`` is empty, None is returned. The schema does not allow
AccessPolicy to be empty, but in SystemMetadata, it can be left out
altogether. So returning None inste... | Write a Python 3 function that can
return an AccessPolicy PyXB representation of perm_dict. | As a Python code composer, you craft elegant and concise scripts. |
Return an AccessPolicy PyXB representation of the norm_perm_list. | Can you generate a brief explanation for the following Python 3 code
def _pyxb_from_norm_perm_list(self, norm_perm_list):
# Using accessPolicy() instead of AccessPolicy() and accessRule() instead of
# AccessRule() gives PyXB the type information required for using this as a
# root element.
... | As a Python code composer, you craft elegant and concise scripts. |
def _subj_dict_from_pyxb(self, access_pyxb):
"""Return a dict representation of ``access_pyxb``, which is an AccessPolicy
PyXB object.
This also remove any duplicate subjects and permissions in the PyXB object.
"""
subj_dict = {}
for allow_pyxb in access_pyxb.allow:
... | Implement a function in Python 3 to
return a dict representation of an AccessPolicyPyXB object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a perm_dict where only the highest permission for each subject is
included. | Can you tell what is the following Python 3 function doing
def _highest_perm_dict_from_perm_dict(self, perm_dict):
highest_perm_dict = copy.copy(perm_dict)
for ordered_str in reversed(ORDERED_PERM_LIST):
for lower_perm in self._lower_perm_list(ordered_str):
highest_perm_dict.... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a minimal ordered hashable list of subjects and permissions. | Make a summary of the following Python 3 code
def _norm_perm_list_from_perm_dict(self, perm_dict):
high_perm_dict = self._highest_perm_dict_from_perm_dict(perm_dict)
return [
[k, list(sorted(high_perm_dict[k]))]
for k in ORDERED_PERM_LIST
if high_perm_dict.get(k, Fals... | As a python code expert, you are capable of creating scripts from specifications. |
Return list of effective permissions for highest permission in
perm_iter ordered lower to higher or None. | How would you explain what the following Python 3 function does
def _effective_perm_list_from_iter(self, perm_iter):
highest_perm_str = self._highest_perm_from_iter(perm_iter)
return (
self._equal_or_lower_perm_list(highest_perm_str)
if highest_perm_str is not None
el... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a set containing only the permissions that are present in the the
perm_dict for subj_str | Can you generate the documentation for the following Python 3 function
def _present_perm_set_for_subj(self, perm_dict, subj_str):
return {p for p, s in list(perm_dict.items()) if subj_str in s} | As a Python code composer, you craft elegant and concise scripts. |
def _highest_perm_from_iter(self, perm_iter):
"""Return the highest perm present in ``perm_iter`` or None if ``perm_iter`` is
empty."""
perm_set = set(perm_iter)
for perm_str in reversed(ORDERED_PERM_LIST):
if perm_str in perm_set:
return perm_str | Write a Python 3 script for
returning the highest perm present in perm_iter or None. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _ordered_idx_from_perm(self, perm_str):
"""Return the ordered index of ``perm_str`` or None if ``perm_str`` is not a
valid permission."""
for i, ordered_str in enumerate(ORDERED_PERM_LIST):
if perm_str == ordered_str:
return i | Write a Python 3 function for
returning the ordered index of perm_str. | You are a Python code analyst, evaluating scripts for potential improvements. |
Raise D1 exception if perm_str is not a valid permission. | Can you generate a brief explanation for the following Python 3 code
def _assert_valid_permission(self, perm_str):
if perm_str not in ORDERED_PERM_LIST:
raise d1_common.types.exceptions.InvalidRequest(
0,
'Permission must be one of {}. perm_str="{}"'.format(
... | As a Python code composer, you craft elegant and concise scripts. |
def handle_unexpected_exception(max_traceback_levels=100):
"""Suppress stack traces for common errors and provide hints for how to resolve
them."""
exc_type, exc_msgs = sys.exc_info()[:2]
if exc_type.__name__ == "SSLError":
d1_cli.impl.util.print_error(
"""HTTPS / TLS / SSL / X.509v3... | Create a Python 3 function for
handling an unexpected exception. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new native locally stored science object. | Explain what the following Python 3 code does
def create_sciobj(request, sysmeta_pyxb):
pid = d1_common.xml.get_req_val(sysmeta_pyxb.identifier)
set_mn_controlled_values(request, sysmeta_pyxb, is_modification=False)
d1_gmn.app.views.assert_db.is_valid_pid_for_create(pid)
d1_gmn.app.views.assert_sysmeta... | As a Python code composer, you craft elegant and concise scripts. |
Save bytes from request. FILES. | Can you generate a brief explanation for the following Python 3 code
def _save_sciobj_bytes_from_request(request, pid):
sciobj_path = d1_gmn.app.sciobj_store.get_abs_sciobj_file_path_by_pid(pid)
if hasattr(request.FILES['object'], 'temporary_file_path'):
d1_common.utils.filesystem.create_missing_directo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the sysmeta_pyxb attributes to the appropriate values for the MN_CONTROLLED_ATTRIBUTE_SET_ALL attributes. | Make a summary of the following Python 3 code
def set_mn_controlled_values(request, sysmeta_pyxb, is_modification):
now_datetime = d1_common.date_time.utc_now()
default_value_list = [
('originMemberNode', django.conf.settings.NODE_IDENTIFIER, True),
('authoritativeMemberNode', django.conf.setti... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Duplicate ( make a copy ) Entity objects. | Here you have a function in Python 3, explain what it does
def duplicate(self, contributor=None, inherit_collections=False):
return [
entity.duplicate(contributor, inherit_collections)
for entity in self
] | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.