output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_activity(self):
"""Check account concurrency limits."""
method = 'GET'
endpoint = '/rest/v1/{}/activity'.format(self.client.sauce_username)
return self.client.request(method, endpoint) | How would you code a function in Python 3 to
get the current activity for the current user. | You are a Python code generator, capable of creating scripts from specifications. |
Get historical account usage data. | Can you generate the documentation for the following Python 3 function
def get_usage(self, start=None, end=None):
method = 'GET'
endpoint = '/rest/v1/users/{}/usage'.format(self.client.sauce_username)
data = {}
if start:
data['start'] = start
if end:
data[... | You are a Python code generator, capable of creating scripts from specifications. |
def get_platforms(self, automation_api='all'):
"""Get a list of objects describing all the OS and browser platforms
currently supported on Sauce Labs."""
method = 'GET'
endpoint = '/rest/v1/info/platforms/{}'.format(automation_api)
return self.client.request(method, endpoint) | Create a Python 3 function to
get a list of objects describing all the OS and browser platforms available on Sauce Labs. | As a python code expert, you are capable of creating scripts from specifications. |
def get_jobs(self, full=None, limit=None, skip=None, start=None, end=None,
output_format=None):
"""List jobs belonging to a specific user."""
method = 'GET'
endpoint = '/rest/v1/{}/jobs'.format(self.client.sauce_username)
data = {}
if full is not None:
... | Implement a function in Python 3 to
list all jobs belonging to a specific user. | As a python code expert, you are capable of creating scripts from specifications. |
Edit an existing job. | Make a summary of the following Python 3 code
def update_job(self, job_id, build=None, custom_data=None,
name=None, passed=None, public=None, tags=None):
"""Edit an existing job."""
method = 'PUT'
endpoint = '/rest/v1/{}/jobs/{}'.format(self.client.sauce_username,
... | You are a Python code generator, capable of creating scripts from specifications. |
Terminates a running job. | Can you tell what is the following Python 3 function doing
def stop_job(self, job_id):
method = 'PUT'
endpoint = '/rest/v1/{}/jobs/{}/stop'.format(
self.client.sauce_username, job_id)
return self.client.request(method, endpoint) | As a Python code composer, you craft elegant and concise scripts. |
def get_job_asset_url(self, job_id, filename):
"""Get details about the static assets collected for a specific job."""
return 'https://saucelabs.com/rest/v1/{}/jobs/{}/assets/{}'.format(
self.client.sauce_username, job_id, filename) | Implement a function in Python 3 to
get details about the static assets collected for a specific job. | You are a Python code generator, capable of creating scripts from specifications. |
Get an auth token to access protected job resources. | Explain what the following Python 3 code does
def get_auth_token(self, job_id, date_range=None):
key = '{}:{}'.format(self.client.sauce_username,
self.client.sauce_access_key)
if date_range:
key = '{}:{}'.format(key, date_range)
return hmac.new(key.encode... | You are a Python code generator, capable of creating scripts from specifications. |
def upload_file(self, filepath, overwrite=True):
"""Uploads a file to the temporary sauce storage."""
method = 'POST'
filename = os.path.split(filepath)[1]
endpoint = '/rest/v1/storage/{}/{}?overwrite={}'.format(
self.client.sauce_username, filename, "true" if overwrite else ... | Implement a Python 3 function for
uploading a file to the temporary sauce storage. | As a python code expert, you are capable of creating scripts from specifications. |
def get_stored_files(self):
"""Check which files are in your temporary storage."""
method = 'GET'
endpoint = '/rest/v1/storage/{}'.format(self.client.sauce_username)
return self.client.request(method, endpoint) | Can you create a Python 3 function that
checks which files are in your temporary storage. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_tunnels(self):
"""Retrieves all running tunnels for a specific user."""
method = 'GET'
endpoint = '/rest/v1/{}/tunnels'.format(self.client.sauce_username)
return self.client.request(method, endpoint) | Can you create a Python 3 function that
retrieves all running tunnels for a specific user. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get information for a tunnel given its ID. | Explain what the following Python 3 code does
def get_tunnel(self, tunnel_id):
method = 'GET'
endpoint = '/rest/v1/{}/tunnels/{}'.format(
self.client.sauce_username, tunnel_id)
return self.client.request(method, endpoint) | You are a Python code generator, capable of creating scripts from specifications. |
def apply(patch):
"""Apply a patch.
The patch's :attr:`~Patch.obj` attribute is injected into the patch's
:attr:`~Patch.destination` under the patch's :attr:`~Patch.name`.
This is a wrapper around calling
``setattr(patch.destination, patch.name, patch.obj)``.
Parameters
----------
pat... | Create a Python 3 function for
applying a patch to the base base. | As a python code expert, you are capable of creating scripts from specifications. |
Decorator to create a patch. | Explain what the following Python 3 code does
def patch(destination, name=None, settings=None):
def decorator(wrapped):
base = _get_base(wrapped)
name_ = base.__name__ if name is None else name
settings_ = copy.deepcopy(settings)
patch = Patch(destination, name_, wrapped, settings=se... | As a python code expert, you are capable of creating scripts from specifications. |
Decorator to create a patch for each member of a module or class. | Can you tell what is the following Python 3 function doing
def patches(destination, settings=None, traverse_bases=True,
filter=default_filter, recursive=True, use_decorators=True):
"""Decorator to create a patch for each member of a module or a class.
Parameters
----------
destination : obj... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorator to update a patch s settings. | Make a summary of the following Python 3 code
def settings(**kwargs):
def decorator(wrapped):
data = get_decorator_data(_get_base(wrapped), set_default=True)
data.override.setdefault('settings', {}).update(kwargs)
return wrapped
return decorator | You are a Python code architect, reviewing and designing scalable and efficient code |
Modifier decorator to force the inclusion or exclusion of an attribute. | Can you tell what is the following Python 3 function doing
def filter(value):
def decorator(wrapped):
data = get_decorator_data(_get_base(wrapped), set_default=True)
data.filter = value
return wrapped
return decorator | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a list of patches for each member of a module or a class. | Here you have a function in Python 3, explain what it does
def create_patches(destination, root, settings=None, traverse_bases=True,
filter=default_filter, recursive=True, use_decorators=True):
"""Create a patch for each member of a module or a class.
Parameters
----------
destinatio... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find all the patches created through decorators. | Explain what the following Python 3 code does
def find_patches(modules, recursive=True):
out = []
modules = (module
for package in modules
for module in _module_iterator(package, recursive=recursive))
for module in modules:
members = _get_members(module, filter=None)
... | You are a Python code generator, capable of creating scripts from specifications. |
Get an attribute while bypassing the descriptor protocol. | Here you have a function in Python 3, explain what it does
def get_attribute(obj, name):
objs = inspect.getmro(obj) if isinstance(obj, _CLASS_TYPES) else [obj]
for obj_ in objs:
try:
return object.__getattribute__(obj_, name)
except AttributeError:
pass
raise Attribu... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_decorator_data(obj, set_default=False):
"""Retrieve any decorator data from an object.
Parameters
----------
obj : object
Object.
set_default : bool
If no data is found, a default one is set on the object and returned,
otherwise ``None`` is returned.
Returns
... | Implement a Python 3 function for
retrieving any decorator data from an object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Unwrap decorators to retrieve the base object. | Can you generate a brief explanation for the following Python 3 code
def _get_base(obj):
if hasattr(obj, '__func__'):
obj = obj.__func__
elif isinstance(obj, property):
obj = obj.fget
elif isinstance(obj, (classmethod, staticmethod)):
# Fallback for Python < 2.7 back when no `__func_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieve the member attributes of a module or a class. | Can you tell what is the following Python 3 function doing
def _get_members(obj, traverse_bases=True, filter=default_filter,
recursive=True):
"""Retrieve the member attributes of a module or a class.
The descriptor protocol is bypassed."""
if filter is None:
filter = _true
out... | As a Python code composer, you craft elegant and concise scripts. |
Update some attributes.
If a 'settings' attribute is passed as a dict, then it updates the
content of the settings, if any, instead of completely overwriting it. | Here you have a function in Python 3, explain what it does
def _update(self, **kwargs):
for key, value in _iteritems(kwargs):
if key == 'settings':
if isinstance(value, dict):
if self.settings is None:
self.settings = Settings(**value)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
To get pagewise data. | Here you have a function in Python 3, explain what it does
def get_collection(self, path):
while True:
items = self.get(path)
req = self.req
for item in items:
yield item
if req.links and req.links['next'] and\
req.links['next']... | As a Python code analyst, you investigate and solve complex coding mysteries |
List projects with searchstring. | Can you generate the documentation for the following Python 3 function
def list_projects_search(self, searchstring):
log.debug('List all projects with: %s' % searchstring)
return self.collection('projects/search/%s.json' %
quote_plus(searchstring)) | As a Python code composer, you craft elegant and concise scripts. |
def update_project(self, ID, data):
"""Update a project."""
# http://teampasswordmanager.com/docs/api-projects/#update_project
log.info('Update project %s with %s' % (ID, data))
self.put('projects/%s.json' % ID, data) | Can you create a Python 3 function that
updates a project with the given data. | You are a Python code architect, reviewing and designing scalable and efficient code |
def change_parent_of_project(self, ID, NewParrentID):
"""Change parent of project."""
# http://teampasswordmanager.com/docs/api-projects/#change_parent
log.info('Change parrent for project %s to %s' % (ID, NewParrentID))
data = {'parent_id': NewParrentID}
self.put('projects/%s/ch... | Implement a function in Python 3 to
change parent of project. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def update_security_of_project(self, ID, data):
"""Update security of project."""
# http://teampasswordmanager.com/docs/api-projects/#update_project_security
log.info('Update project %s security %s' % (ID, data))
self.put('projects/%s/security.json' % ID, data) | Implement a Python 3 function for
updating security of project. | You are a Python code architect, reviewing and designing scalable and efficient code |
List all passwords with searchstring. | Here you have a function in Python 3, explain what it does
def list_passwords_search(self, searchstring):
log.debug('List all passwords with: %s' % searchstring)
return self.collection('passwords/search/%s.json' %
quote_plus(searchstring)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def update_password(self, ID, data):
"""Update a password."""
# http://teampasswordmanager.com/docs/api-passwords/#update_password
log.info('Update Password %s with %s' % (ID, data))
self.put('passwords/%s.json' % ID, data) | How would you code a function in Python 3 to
update a password with the given data. | You are a Python code generator, capable of creating scripts from specifications. |
Update security of a password. | Can you generate a brief explanation for the following Python 3 code
def update_security_of_password(self, ID, data):
# http://teampasswordmanager.com/docs/api-passwords/#update_security_password
log.info('Update security of password %s with %s' % (ID, data))
self.put('passwords/%s/security.json... | You are a Python code architect, reviewing and designing scalable and efficient code |
def update_custom_fields_of_password(self, ID, data):
"""Update custom fields definitions of a password."""
# http://teampasswordmanager.com/docs/api-passwords/#update_cf_password
log.info('Update custom fields of password %s with %s' % (ID, data))
self.put('passwords/%s/custom_fields.js... | Write a Python 3 function that can
update custom fields definitions of a password. | You are a Python code generator, capable of creating scripts from specifications. |
def list_mypasswords_search(self, searchstring):
"""List my passwords with searchstring."""
# http://teampasswordmanager.com/docs/api-my-passwords/#list_passwords
log.debug('List MyPasswords with %s' % searchstring)
return self.collection('my_passwords/search/%s.json' %
... | Create a Python 3 function to
list my passwords with searchstring. | You are a Python code generator, capable of creating scripts from specifications. |
def update_mypassword(self, ID, data):
"""Update my password."""
# http://teampasswordmanager.com/docs/api-my-passwords/#update_password
log.info('Update MyPassword %s with %s' % (ID, data))
self.put('my_passwords/%s.json' % ID, data) | Implement a Python 3 function for
updating my password with data. | You are a Python code architect, reviewing and designing scalable and efficient code |
def update_user(self, ID, data):
"""Update a User."""
# http://teampasswordmanager.com/docs/api-users/#update_user
log.info('Update user %s with %s' % (ID, data))
self.put('users/%s.json' % ID, data) | How would you code a function in Python 3 to
update a User s metadata. | As a Python code composer, you craft elegant and concise scripts. |
def change_user_password(self, ID, data):
"""Change password of a User."""
# http://teampasswordmanager.com/docs/api-users/#change_password
log.info('Change user %s password' % ID)
self.put('users/%s/change_password.json' % ID, data) | Can you write a function in Python 3 where it
changes password of a User. | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert a normal user to an LDAP user. | Here you have a function in Python 3, explain what it does
def convert_user_to_ldap(self, ID, DN):
# http://teampasswordmanager.com/docs/api-users/#convert_to_ldap
data = {'login_dn': DN}
log.info('Convert User %s to LDAP DN %s' % (ID, DN))
self.put('users/%s/convert_to_ldap.json' % ID, ... | You are a Python code generator, capable of creating scripts from specifications. |
def update_group(self, ID, data):
"""Update a Group."""
# http://teampasswordmanager.com/docs/api-groups/#update_group
log.info('Update group %s with %s' % (ID, data))
self.put('groups/%s.json' % ID, data) | Can you create a Python 3 function that
updates a Group with the given data. | As a Python code composer, you craft elegant and concise scripts. |
Add a user to a group. | Here you have a function in Python 3, explain what it does
def add_user_to_group(self, GroupID, UserID):
# http://teampasswordmanager.com/docs/api-groups/#add_user
log.info('Add User %s to Group %s' % (UserID, GroupID))
self.put('groups/%s/add_user/%s.json' % (GroupID, UserID)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def delete_user_from_group(self, GroupID, UserID):
"""Delete a user from a group."""
# http://teampasswordmanager.com/docs/api-groups/#del_user
log.info('Delete user %s from group %s' % (UserID, GroupID))
self.put('groups/%s/delete_user/%s.json' % (GroupID, UserID)) | Write a Python 3 script to
delete a user from a group. | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if Team Password Manager is up to date. | How would you explain what the following Python 3 function does
def up_to_date(self):
VersionInfo = self.get_latest_version()
CurrentVersion = VersionInfo.get('version')
LatestVersion = VersionInfo.get('latest_version')
if CurrentVersion == LatestVersion:
log.info('TeamPassw... | As a Python code analyst, you investigate and solve complex coding mysteries |
def iterate_date_values(d, start_date=None, stop_date=None, default=0):
"""
Convert (date, value) sorted lists into contiguous value-per-day data sets. Great for sparklines.
Example::
[(datetime.date(2011, 1, 1), 1), (datetime.date(2011, 1, 4), 2)] -> [1, 0, 0, 2]
"""
dataiter = iter(d)
... | Write a Python 3 script for
iterating over the date values in a list of data sets. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given a datetime t and a resolution truncate the precision beyond the given resolution. | Here you have a function in Python 3, explain what it does
def truncate_datetime(t, resolution):
resolutions = ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']
if resolution not in resolutions:
raise KeyError("Resolution is not valid: {0}".format(resolution))
args = []
for r... | You are a Python code generator, capable of creating scripts from specifications. |
Return an aware datetime which is dt converted to timezone timezone. | Given the following Python 3 function, write the documentation
def to_timezone(dt, timezone):
if dt.tzinfo is None:
dt = dt.replace(tzinfo=_UTC)
return timezone.normalize(dt.astimezone(timezone)) | As a Python code composer, you craft elegant and concise scripts. |
def now(timezone=None):
"""
Return a naive datetime object for the given ``timezone``. A ``timezone``
is any pytz- like or datetime.tzinfo-like timezone object. If no timezone
is given, then UTC is assumed.
This method is best used with pytz installed::
pip install pytz
"""
d = dat... | Write a Python 3 script to
return a naive datetime object for the given timezone. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def enumerate_query_by_limit(q, limit=1000):
"""
Enumerate over SQLAlchemy query object ``q`` and yield individual results
fetched in batches of size ``limit`` using SQL LIMIT and OFFSET.
"""
for offset in count(0, limit):
r = q.offset(offset).limit(limit).all()
for row in r:
... | Implement a function in Python 3 to
enumerate all the results of a SQLAlchemy query object q and yield individual results in batches of size limit. | You are a Python code analyst, evaluating scripts for potential improvements. |
def validate_many(d, schema):
"""Validate a dictionary of data against the provided schema.
Returns a list of values positioned in the same order as given in ``schema``, each
value is validated with the corresponding validator. Raises formencode.Invalid if
validation failed.
Similar to get_many bu... | How would you implement a function in Python 3 that
validates a dictionary of data against the provided schema. | You are a Python code architect, reviewing and designing scalable and efficient code |
def assert_hashable(*args, **kw):
""" Verify that each argument is hashable.
Passes silently if successful. Raises descriptive TypeError otherwise.
Example::
>>> assert_hashable(1, 'foo', bar='baz')
>>> assert_hashable(1, [], baz='baz')
Traceback (most recent call last):
... | Write a Python 3 function that can
ensure that each argument in the list of arguments is hashable. Raises descriptive TypeError otherwise. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Memoize a class s method. | Explain what the following Python 3 code does
def memoized_method(method=None, cache_factory=None):
if method is None:
return lambda f: memoized_method(f, cache_factory=cache_factory)
cache_factory = cache_factory or dict
@wraps(method)
def memoized_method_property(self):
cache = cach... | As a Python code composer, you craft elegant and concise scripts. |
Decorator for deprecated functions. | Can you generate the documentation for the following Python 3 function
def deprecated(message, exception=PendingDeprecationWarning):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
warnings.warn(message, exception, stacklevel=2)
return func(*args, **kwargs)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def groupby_count(i, key=None, force_keys=None):
""" Aggregate iterator values into buckets based on how frequently the
values appear.
Example::
>>> list(groupby_count([1, 1, 1, 2, 3]))
[(1, 3), (2, 1), (3, 1)]
"""
counter = defaultdict(lambda: 0)
if not key:
key = lamb... | Can you implement a function in Python 3 that
aggregates iterator values into buckets based on how frequently the values appear. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return whether maybe_iter is an iterable unless it s an instance of one
of the base class or tuple of base classes given in unless. | Here you have a function in Python 3, explain what it does
def is_iterable(maybe_iter, unless=(string_types, dict)):
try:
iter(maybe_iter)
except TypeError:
return False
return not isinstance(maybe_iter, unless) | As a python code expert, you are capable of creating scripts from specifications. |
Return a consistent ( key value iterable on dict - like objects and
including lists of tuple pairs. | Can you tell what is the following Python 3 function doing
def iterate_items(dictish):
if hasattr(dictish, 'iteritems'):
return dictish.iteritems()
if hasattr(dictish, 'items'):
return dictish.items()
return dictish | As a python code expert, you are capable of creating scripts from specifications. |
def iterate_chunks(i, size=10):
"""
Iterate over an iterator ``i`` in ``size`` chunks, yield chunks.
Similar to pagination.
Example::
>>> list(iterate_chunks([1, 2, 3, 4], size=2))
[[1, 2], [3, 4]]
"""
accumulator = []
for n, i in enumerate(i):
accumulator.append(i... | How would you implement a function in Python 3 that
iterates over an iterator i in size chunks yield chunks. | As a Python code translator, you convert algorithms and pseudocode into Python. |
A function which returns a list of items in the alphabetical order. | Can you generate the documentation for the following Python 3 function
def listify(fn=None, wrapper=list):
def listify_return(fn):
@wraps(fn)
def listify_helper(*args, **kw):
return wrapper(fn(*args, **kw))
return listify_helper
if fn is None:
return listify_return
... | You are a Python code generator, capable of creating scripts from specifications. |
def is_subclass(o, bases):
"""
Similar to the ``issubclass`` builtin, but does not raise a ``TypeError``
if either ``o`` or ``bases`` is not an instance of ``type``.
Example::
>>> is_subclass(IOError, Exception)
True
>>> is_subclass(Exception, None)
False
>>> is... | Create a Python 3 function for
returning True if o is a subclass of bases. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a predictable number of elements out of d in a list for auto - expanding. | Can you generate the documentation for the following Python 3 function
def get_many(d, required=[], optional=[], one_of=[]):
d = d or {}
r = [d[k] for k in required]
r += [d.get(k)for k in optional]
if one_of:
for k in (k for k in one_of if k in d):
return r + [d[k]]
raise ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def random_string(length=6, alphabet=string.ascii_letters+string.digits):
"""
Return a random string of given length and alphabet.
Default alphabet is url-friendly (base62).
"""
return ''.join([random.choice(alphabet) for i in xrange(length)]) | Can you create a Python 3 function that
returns a random string of given length and alphabet. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given an integer n convert it to a string composed of
the given alphabet mapping where the position of each element in alphabet is its radix value. | Can you generate the documentation for the following Python 3 function
def number_to_string(n, alphabet):
result = ''
base = len(alphabet)
current = int(n)
if current < 0:
raise ValueError("invalid n (must be non-negative): %s", n)
while current:
result = alphabet[current % base] + r... | As a python code expert, you are capable of creating scripts from specifications. |
def string_to_number(s, alphabet):
"""
Given a string ``s``, convert it to an integer composed of the given
``alphabet`` mapping, where the position of each element in ``alphabet`` is
its radix value.
Examples::
>>> string_to_number('101111000110000101001110', '01')
12345678
... | Write a Python 3 function for
giving a string s convert it to an integer composed of the given alphabet mapping where the position of each element in alphabet is the radix value of the string s. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert a string or bytearray to a number. | Can you tell what is the following Python 3 function doing
def bytes_to_number(b, endian='big'):
if endian == 'big':
b = reversed(b)
n = 0
for i, ch in enumerate(bytearray(b)):
n ^= ch << i * 8
return n | As a Python code analyst, you investigate and solve complex coding mysteries |
def number_to_bytes(n, endian='big'):
"""
Convert an integer to a corresponding string of bytes..
:param n:
Integer to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case ve... | Can you implement a function in Python 3 that
converts an integer to a corresponding string of bytes. | As a python code expert, you are capable of creating scripts from specifications. |
r Converts obj into a string if necessary. | Make a summary of the following Python 3 code
def to_str(obj, encoding='utf-8', **encode_args):
# Note: On py3, ``b'x'.__str__()`` returns ``"b'x'"``, so we need to do the
# explicit check first.
if isinstance(obj, binary_type):
return obj
# We coerce to unicode if '__unicode__' is available be... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def to_float(s, default=0.0, allow_nan=False):
"""
Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_... | Write a Python 3 script for
converting input string into a float. If conversion fails return default. | You are a Python code generator, capable of creating scripts from specifications. |
Return a string representation of the given integer n. | Can you tell what is the following Python 3 function doing
def format_int(n, singular=_Default, plural=_Default):
n = int(n)
if singular in (None, _Default):
if plural is _Default:
plural = None
singular = u'{:,}'
elif plural is _Default:
plural = singular + u's'
... | As a python code expert, you are capable of creating scripts from specifications. |
Converts a string or integer representing dollars to an integer of cents. | Explain what the following Python 3 code does
def dollars_to_cents(s, allow_negative=False):
# TODO: Implement cents_to_dollars
if not s:
return
if isinstance(s, string_types):
s = ''.join(RE_NUMBER.findall(s))
dollars = int(round(float(s) * 100))
if not allow_negative and dollars ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Normalize s into ASCII and replace non - word characters with delimiter. | How would you explain what the following Python 3 function does
def slugify(s, delimiter='-'):
s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')
return RE_SLUG.sub(delimiter, s).strip(delimiter).lower() | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_cache_buster(src_path, method='importtime'):
""" Return a string that can be used as a parameter for cache-busting URLs
for this asset.
:param src_path:
Filesystem path to the file we're generating a cache-busting value for.
:param method:
Method for cache-busting. Supported va... | Implement a Python 3 function for
returning a string that can be used as a parameter for cache - busting URLs. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _generate_dom_attrs(attrs, allow_no_value=True):
""" Yield compiled DOM attribute key-value strings.
If the value is `True`, then it is treated as no-value. If `None`, then it
is skipped.
"""
for attr in iterate_items(attrs):
if isinstance(attr, basestring):
attr = (attr, Tr... | How would you code a function in Python 3 to
yield compiled DOM attribute key - value strings. | As a Python code composer, you craft elegant and concise scripts. |
Helper for programmatically building HTML tags. | Can you generate a brief explanation for the following Python 3 code
def tag(tagname, content='', attrs=None):
attrs_str = attrs and ' '.join(_generate_dom_attrs(attrs))
open_tag = tagname
if attrs_str:
open_tag += ' ' + attrs_str
if content is None:
return literal('<%s />' % open_tag)
... | You are a Python code generator, capable of creating scripts from specifications. |
Read the package metadata. | Here you have a function in Python 3, explain what it does
def package_meta():
_version_re = re.compile(r'__version__\s+=\s+(.*)')
_url_re = re.compile(r'__url__\s+=\s+(.*)')
_license_re = re.compile(r'__license__\s+=\s+(.*)')
with open('lambda_uploader/__init__.py', 'rb') as ffinit:
initconten... | As a python code expert, you are capable of creating scripts from specifications. |
Subscribes the lambda to the Kinesis stream | How would you explain what the following Python 3 function does
def subscribe(self):
''' Subscribes the lambda to the Kinesis stream '''
try:
LOG.debug('Creating Kinesis subscription')
if self.starting_position_ts:
self._lambda_client \
.create... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Formats the VPC config as a dictionary. | Here you have a function in Python 3, explain what it does
def _format_vpc_config(self):
'''
Returns {} if the VPC config is set to None by Config,
returns the formatted config otherwise
'''
if self._config.raw['vpc']:
return {
'SubnetIds': self._confi... | You are a Python code generator, capable of creating scripts from specifications. |
Uploads the lambda package to s3 | Here you have a function in Python 3, explain what it does
def _upload_s3(self, zip_file):
'''
Uploads the lambda package to s3
'''
s3_client = self._aws_session.client('s3')
transfer = boto3.s3.transfer.S3Transfer(s3_client)
transfer.upload_file(zip_file, self._config.s3... | You are a Python code generator, capable of creating scripts from specifications. |
This function is the main function of the lambda - uploader. | Explain what the following Python 3 code does
def main(arv=None):
# Check for Python 2.7 or later
if sys.version_info[0] < 3 and not sys.version_info[1] == 7:
raise RuntimeError('lambda-uploader requires Python 2.7 or later')
import argparse
parser = argparse.ArgumentParser(
descri... | You are a Python code analyst, evaluating scripts for potential improvements. |
Builds the zip file and creates the package with it | Can you generate the documentation for the following Python 3 function
def build_package(path, requires, virtualenv=None, ignore=None,
extra_files=None, zipfile_name=ZIPFILE_NAME,
pyexec=None):
'''Builds the zip file and creates the package with it'''
pkg = Package(path, zipf... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def build(self, ignore=None):
'''Calls all necessary methods to build the Lambda Package'''
self._prepare_workspace()
self.install_dependencies()
self.package(ignore) | How would you code a function in Python 3 to
call all necessary methods to build the Lambda Package | As a python code expert, you are capable of creating scripts from specifications. |
Clean up the temporary workspace if one exists | Can you tell what is the following Python 3 function doing
def clean_workspace(self):
'''Clean up the temporary workspace if one exists'''
if os.path.isdir(self._temp_workspace):
shutil.rmtree(self._temp_workspace) | You are a Python code analyst, evaluating scripts for potential improvements. |
def requirements(self, requires):
'''
Sets the requirements for the package.
It will take either a valid path to a requirements file or
a list of requirements.
'''
if requires:
if isinstance(requires, basestring) and \
os.path.isfile(os.path.ab... | Implement a function in Python 3 to
set the requirements for the package. | As a Python code analyst, you investigate and solve complex coding mysteries |
Sets the virtual environment for the lambda package. | Can you generate a brief explanation for the following Python 3 code
def virtualenv(self, virtualenv):
'''
Sets the virtual environment for the lambda package
If this is not set then package_dependencies will create a new one.
Takes a path to a virtualenv or a boolean if the virtualenv... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def install_dependencies(self):
''' Creates a virtualenv and installs requirements '''
# If virtualenv is set to skip then do nothing
if self._skip_virtualenv:
LOG.info('Skip Virtualenv set ... nothing to do')
return
has_reqs = _isfile(self._requirements_file) or... | Can you create a Python 3 function that
creates a new virtualenv and installs requirements | You are a Python code generator, capable of creating scripts from specifications. |
Build a new virtualenvironment if self. _virtualenv is None | Explain what the following Python 3 code does
def _build_new_virtualenv(self):
'''Build a new virtualenvironment if self._virtualenv is set to None'''
if self._virtualenv is None:
# virtualenv was "None" which means "do default"
self._pkg_venv = os.path.join(self._temp_workspace,... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _install_requirements(self):
'''
Create a new virtualenvironment and install requirements
if there are any.
'''
if not hasattr(self, '_pkg_venv'):
err = 'Must call build_new_virtualenv before install_requirements'
raise Exception(err)
cmd = No... | Write a Python 3 script for
installing the requirements. txt file in the virtual environment. | As a Python code composer, you craft elegant and concise scripts. |
Creates a zip file of the lambda script and its dependencies. | How would you explain what the following Python 3 function does
def package(self, ignore=None):
ignore = ignore or []
package = os.path.join(self._temp_workspace, 'lambda_package')
# Copy site packages into package base
LOG.info('Copying site packages')
if hasattr(self, '_pkg_v... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def encode_properties(parameters):
"""
Performs encoding of url parameters from dictionary to a string. It does
not escape backslash because it is not needed.
See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties
"""
result = []
for para... | Write a Python 3 function that can
encode the properties of the url parameters from dictionary to a string. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def splitroot(self, part, sep=sep):
"""
Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is ... | Implement a function in Python 3 to
split a path string into drive root and relative path. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a GET request to url with optional authentication
"""
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return ... | Can you implement a function in Python 3 that
performs a GET request to url with optional authentication | You are a Python code analyst, evaluating scripts for potential improvements. |
Perform a PUT request to url with optional authentication
| Make a summary of the following Python 3 code
def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return res.text, res.status_code | As a Python code translator, you convert algorithms and pseudocode into Python. |
def rest_post(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a PUT request to url with optional authentication
"""
res = requests.post(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
retu... | Write a Python 3 function that can
perform a PUT request to url with optional authentication | As a python code expert, you are capable of creating scripts from specifications. |
Perform a DELETE request to url with optional authentication
| Here you have a function in Python 3, explain what it does
def rest_del(self, url, params=None, auth=None, verify=True, cert=None):
res = requests.delete(url, params=params, auth=auth, verify=verify, cert=cert)
return res.text, res.status_code | As a Python code translator, you convert algorithms and pseudocode into Python. |
Perform a chunked GET request to url with optional authentication
This is specifically to download files. | How would you explain what the following Python 3 function does
def rest_get_stream(self, url, auth=None, verify=True, cert=None):
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert)
return res.raw, res.status_code | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_stat_json(self, pathobj):
"""
Request remote file/directory status info
Returns a json object as specified by Artifactory REST API
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).str... | Write a Python 3 script for
requesting remote file or directory status info info | As a Python code translator, you convert algorithms and pseudocode into Python. |
def open(self, pathobj):
"""
Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek()
"""
url = str(pathobj)
raw, code = self.rest_get_stream(url, auth=pathobj.auth, verify=pathobj.ver... | Can you write a function in Python 3 where it
opens the remote file and returns a file - like object HTTPResponse | As a python code expert, you are capable of creating scripts from specifications. |
def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None):
"""
Uploads a given file-like object
HTTP chunked encoding will be attempted
"""
if isinstance(fobj, urllib3.response.HTTPResponse):
fobj = HTTPResponseWrapper(fobj)
url = str(pathobj)
... | Create a Python 3 function to
upload a given file - like object to the server. | You are a Python code architect, reviewing and designing scalable and efficient code |
def move(self, src, dst):
"""
Move artifact from src to dst
"""
url = '/'.join([src.drive,
'api/move',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/')}
text, code =... | Implement a function in Python 3 to
move artifact from src to dst | You are a Python code analyst, evaluating scripts for potential improvements. |
def relative_to(self, *other):
"""
Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError.
"""
obj = super(ArtifactoryPath, self).relative_to(*other... | Write a Python 3 function for
returning the relative path to another path identified by the passed arguments. | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_properties(self, properties, recursive=True):
"""
Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
... | Create a Python 3 function for
adding new or modifies existing properties listed in properties | As a Python code composer, you craft elegant and concise scripts. |
returns a tuple that contains ( screen_width screen_height | Can you generate the documentation for the following Python 3 function
def getScreenDims(self):
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScreenHeight(self.obj)
return (width,height) | As a Python code analyst, you investigate and solve complex coding mysteries |
This function fills screen_data with the RAW Pixel data | Given the following Python 3 function, write the documentation
def getScreen(self,screen_data=None):
if(screen_data is None):
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScreenWidth(self.obj)
screen_data = np.zeros(width*height,dtype=np.uint8)
ale_lib... | 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.