output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Runs commah code on the given redshift and returns the result. | How would you explain what the following Python 3 function does
def run(cosmology, zi=0, Mi=1e12, z=False, com=True, mah=True,
filename=None, verbose=None, retcosmo=None):
""" Run commah code on halo of mass 'Mi' at redshift 'zi' with
accretion and profile history at higher redshifts 'z'
Thi... | You are a Python code architect, reviewing and designing scalable and efficient code |
Load a configuration and keep it alive for the given context | Given the following Python 3 function, write the documentation
def load(config_path: str):
# we bind the config to _ to keep it alive
if os.path.splitext(config_path)[1] in ('.yaml', '.yml'):
_ = load_yaml_configuration(config_path, translator=PipelineTranslator())
elif os.path.splitext(config_path)... | You are a Python code analyst, evaluating scripts for potential improvements. |
def transform_source(text):
'''Replaces instances of
repeat n:
by
for __VAR_i in range(n):
where __VAR_i is a string that does not appear elsewhere
in the code sample.
'''
loop_keyword = 'repeat'
nb = text.count(loop_keyword)
if nb == 0:
return text
var_... | How would you code a function in Python 3 to
transform source code into a sequence of tokens. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_unique_variable_names(text, nb):
'''returns a list of possible variables names that
are not found in the original text.'''
base_name = '__VAR_'
var_names = []
i = 0
j = 0
while j < nb:
tentative_name = base_name + str(i)
if text.count(tentative_name) == 0 and tenta... | Can you create a Python 3 function that
returns a list of possible variable names that are not found in the original text. | As a python code expert, you are capable of creating scripts from specifications. |
Get a release by tag | Can you generate the documentation for the following Python 3 function
def tag(self, tag):
url = '%s/tags/%s' % (self, tag)
response = self.http.get(url, auth=self.auth)
response.raise_for_status()
return response.json() | You are a Python code generator, capable of creating scripts from specifications. |
Get the assets for a given release | Can you generate a brief explanation for the following Python 3 code
def release_assets(self, release):
release = self.as_id(release)
return self.get_list(url='%s/%s/assets' % (self, release)) | As a Python code composer, you craft elegant and concise scripts. |
Upload a file to a release and return the json object | Can you generate a brief explanation for the following Python 3 code
def upload(self, release, filename, content_type=None):
release = self.as_id(release)
name = os.path.basename(filename)
if not content_type:
content_type, _ = mimetypes.guess_type(name)
if not content_type:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def validate_tag(self, tag_name, prefix=None):
"""Validate ``tag_name`` with the latest tag from github
If ``tag_name`` is a valid candidate, return the latest tag from github
"""
new_version = semantic_version(tag_name)
current = self.latest()
if current:
ta... | Implement a function in Python 3 to
validate tag_name with the latest tag from github . | You are a Python code generator, capable of creating scripts from specifications. |
def full_url(self):
"""Return the full reddit URL associated with the usernote.
Arguments:
subreddit: the subreddit name for the note (PRAW Subreddit object)
"""
if self.link == '':
return None
else:
return Note._expand_url(self.link, self.sub... | Can you implement a function in Python 3 that
returns the full reddit URL associated with the usernote. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _compress_url(link):
"""Convert a reddit URL into the short-hand used by usernotes.
Arguments:
link: a link to a comment, submission, or message (str)
Returns a String of the shorthand URL
"""
comment_re = re.compile(r'/comments/([A-Za-z\d]{2,})(?:/[^\s]+/([A-Za... | Write a Python 3 function that can
convert a reddit URL into the short - hand used by usernotes. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _expand_url(short_link, subreddit=None):
"""Convert a usernote's URL short-hand into a full reddit URL.
Arguments:
subreddit: the subreddit the URL is for (PRAW Subreddit object or str)
short_link: the compressed link from a usernote (str)
Returns a String of the fu... | Create a Python 3 function to
convert a usernote s URL short - hand into a full reddit URL. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_json(self):
"""Get the JSON stored on the usernotes wiki page.
Returns a dict representation of the usernotes (with the notes BLOB
decoded).
Raises:
RuntimeError if the usernotes version is incompatible with this
version of puni.
"""
... | Implement a function in Python 3 to
get the JSON stored on the usernotes wiki page. | As a python code expert, you are capable of creating scripts from specifications. |
Set up the UserNotes page with the initial JSON schema. | Can you tell what is the following Python 3 function doing
def _init_notes(self):
self.cached_json = {
'ver': self.schema,
'users': {},
'constants': {
'users': [x.name for x in self.subreddit.moderator()],
'warnings': Note.warnings
... | You are a Python code generator, capable of creating scripts from specifications. |
def set_json(self, reason='', new_page=False):
"""Send the JSON from the cache to the usernotes wiki page.
Arguments:
reason: the change reason that will be posted to the wiki changelog
(str)
Raises:
OverflowError if the new JSON data is greater than max_... | Write a Python 3 script to
send the JSON data to the usernotes wiki page. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a list of Note objects for the given user. | Can you tell what is the following Python 3 function doing
def get_notes(self, user):
# Try to search for all notes on a user, return an empty list if none
# are found.
try:
users_notes = []
for note in self.cached_json['users'][user]['ns']:
users_notes.a... | As a Python code composer, you craft elegant and concise scripts. |
def _expand_json(self, j):
"""Decompress the BLOB portion of the usernotes.
Arguments:
j: the JSON returned from the wiki page (dict)
Returns a Dict with the 'blob' key removed and a 'users' key added
"""
decompressed_json = copy.copy(j)
decompressed_json.po... | How would you code a function in Python 3 to
decompress the BLOB portion of the usernotes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compress the BLOB data portion of the usernotes. | How would you explain what the following Python 3 function does
def _compress_json(self, j):
compressed_json = copy.copy(j)
compressed_json.pop('users', None)
compressed_data = zlib.compress(
json.dumps(j['users']).encode('utf-8'),
self.zlib_compression_strength
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Adds a note to the usernotes wiki page. | Here you have a function in Python 3, explain what it does
def add_note(self, note):
notes = self.cached_json
if not note.moderator:
note.moderator = self.r.user.me().name
# Get index of moderator in mod list from usernotes
# Add moderator to list if not already there
... | As a python code expert, you are capable of creating scripts from specifications. |
Removes a single usernote from the usernotes. | Here you have a function in Python 3, explain what it does
def remove_note(self, username, index):
self.cached_json['users'][username]['ns'].pop(index)
# Go ahead and remove the user's entry if they have no more notes left
if len(self.cached_json['users'][username]['ns']) == 0:
del ... | You are a Python code generator, capable of creating scripts from specifications. |
def load(self):
""" Function load
Get the list of all objects
@return RETURN: A ForemanItem list
"""
cl_tmp = self.api.list(self.objName, limit=self.searchLimit).values()
cl = []
for i in cl_tmp:
cl.extend(i)
return {x[self.index]: ItemPuppetC... | Can you create a Python 3 function that
functions load Get the list of all objects | As a python code expert, you are capable of creating scripts from specifications. |
def is_related_to(item, app_id, app_ver=None):
"""Return True if the item relates to the given app_id (and app_ver, if passed)."""
versionRange = item.get('versionRange')
if not versionRange:
return True
for vR in versionRange:
if not vR.get('targetApplication'):
return True... | Can you create a Python 3 function that
returns True if the item relates to the given app_id and app_ver. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_related_targetApplication(vR, app_id, app_ver):
"""Return the first matching target application in this version range.
Returns None if there are no target applications or no matching ones."""
targetApplication = vR.get('targetApplication')
if not targetApplication:
return None
for t... | Implement a function in Python 3 to
return the first matching target application in this version range. | You are a Python code generator, capable of creating scripts from specifications. |
def write_addons_items(xml_tree, records, app_id, api_ver=3, app_ver=None):
"""Generate the addons blocklists.
<emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com">
<versionRange minVersion="0" maxVersion="*" severity="3">
<targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
... | Can you write a function in Python 3 where it
writes the addons items to the XML file. | As a Python code composer, you craft elegant and concise scripts. |
Write the plugin items from the records. | Make a summary of the following Python 3 code
def write_plugin_items(xml_tree, records, app_id, api_ver=3, app_ver=None):
if not records:
return
pluginItems = etree.SubElement(xml_tree, 'pluginItems')
for item in records:
for versionRange in item.get('versionRange', []):
if not... | You are a Python code generator, capable of creating scripts from specifications. |
def write_gfx_items(xml_tree, records, app_id, api_ver=3):
"""Generate the gfxBlacklistEntry.
<gfxBlacklistEntry blockID="g35">
<os>WINNT 6.1</os>
<vendor>0x10de</vendor>
<devices>
<device>0x0a6c</device>
</devices>
<feature>DIRECT2D</feature>
<featur... | Create a Python 3 function to
write the gfxBlacklistEntry XML tree. | You are a Python code architect, reviewing and designing scalable and efficient code |
Write the certificate items to the xml file. | Here you have a function in Python 3, explain what it does
def write_cert_items(xml_tree, records, api_ver=3, app_id=None, app_ver=None):
if not records or not should_include_certs(app_id, app_ver):
return
certItems = etree.SubElement(xml_tree, 'certItems')
for item in records:
if item.get(... | As a python code expert, you are capable of creating scripts from specifications. |
def label(self, name, color, update=True):
"""Create or update a label
"""
url = '%s/labels' % self
data = dict(name=name, color=color)
response = self.http.post(
url, json=data, auth=self.auth, headers=self.headers
)
if response.status_code == 201:
... | Can you create a Python 3 function that
creates or update a label in the nova cache. | As a Python code composer, you craft elegant and concise scripts. |
Translate a source file into a dictionary with a one - to - one translation of keywords is used
to provide the transformation. | How would you explain what the following Python 3 function does
def translate(source, dictionary):
'''A dictionary with a one-to-one translation of keywords is used
to provide the transformation.
'''
toks = tokenize.generate_tokens(StringIO(source).readline)
result = []
for toktype, tokvalue, _,... | You are a Python code analyst, evaluating scripts for potential improvements. |
def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'images':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemImages)}) | Can you implement a function in Python 3 that
functions enhance Enhance the object with new item or enhanced items | As a python code expert, you are capable of creating scripts from specifications. |
Start all queued payloads | Can you tell what is the following Python 3 function doing
async def _start_payloads(self):
with self._lock:
for coroutine in self._payloads:
task = self.event_loop.create_task(coroutine())
self._tasks.add(task)
self._payloads.clear()
await asyncio... | As a Python code analyst, you investigate and solve complex coding mysteries |
Clean up all finished payloads | Can you tell what is the following Python 3 function doing
async def _reap_payloads(self):
for task in self._tasks.copy():
if task.done():
self._tasks.remove(task)
if task.exception() is not None:
raise task.exception()
await asyncio.sleep(... | As a Python code composer, you craft elegant and concise scripts. |
async def _cancel_payloads(self):
"""Cancel all remaining payloads"""
for task in self._tasks:
task.cancel()
await asyncio.sleep(0)
for task in self._tasks:
while not task.done():
await asyncio.sleep(0.1)
task.cancel() | Write a Python 3 script for
canceling all remaining payloads | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_password(password: str, encrypted: str) -> bool:
""" Check a plaintext password against a hashed password. """
# some old passwords have {crypt} in lower case, and passlib wants it to be
# in upper case.
if encrypted.startswith("{crypt}"):
encrypted = "{CRYPT}" + encrypted[7:]
retu... | Create a Python 3 function to
check a plaintext password against a hashed password. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def validate(ctx, sandbox):
"""Check if version of repository is semantic
"""
m = RepoManager(ctx.obj['agile'])
if not sandbox or m.can_release('sandbox'):
click.echo(m.validate_version()) | Can you implement a function in Python 3 that
checks if version of repository is semantic | You are a Python code generator, capable of creating scripts from specifications. |
Reset the LDAP wrapper to its original state. | How would you explain what the following Python 3 function does
def reset(self, force_flush_cache: bool = False) -> None:
super(LDAPwrapper, self).reset()
if len(self._transactions) == 0:
raise RuntimeError("reset called outside a transaction.")
self._transactions[-1] = [] | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the attributes of a specific object from the cache. | Explain what the following Python 3 code does
def _cache_get_for_dn(self, dn: str) -> Dict[str, bytes]:
# no cached item, retrieve from ldap
self._do_with_retry(
lambda obj: obj.search(
dn,
'(objectclass=*)',
ldap3.BASE,
attrib... | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_dirty(self) -> bool:
""" Are there uncommitted changes? """
if len(self._transactions) == 0:
raise RuntimeError("is_dirty called outside a transaction.")
if len(self._transactions[-1]) > 0:
return True
return False | Create a Python 3 function for
checking if the current state of the cache is dirty. | As a python code expert, you are capable of creating scripts from specifications. |
def leave_transaction_management(self) -> None:
"""
End a transaction. Must not be dirty when doing so. ie. commit() or
rollback() must be called if changes made. If dirty, changes will be
discarded.
"""
if len(self._transactions) == 0:
raise RuntimeError("lea... | Can you write a function in Python 3 where it
ends a transaction. Must not be dirty when doing so. ie. commit() or rollback() must be called if changes made. If dirty, changes will be discarded. | As a Python code analyst, you investigate and solve complex coding mysteries |
def commit(self) -> None:
"""
Attempt to commit all changes to LDAP database. i.e. forget all
rollbacks. However stay inside transaction management.
"""
if len(self._transactions) == 0:
raise RuntimeError("commit called outside transaction")
# If we have nes... | Can you create a Python 3 function that
commits all changes to LDAP database. | As a Python code composer, you craft elegant and concise scripts. |
Roll back to previous state. | Can you generate a brief explanation for the following Python 3 code
def rollback(self) -> None:
if len(self._transactions) == 0:
raise RuntimeError("rollback called outside transaction")
_debug("rollback:", self._transactions[-1])
# if something goes wrong here, nothing we can do a... | You are a Python code architect, reviewing and designing scalable and efficient code |
Process action. oncommit is a callback to execute action, onrollback is
a callback to execute if the oncommit() has been called and a rollback
is required | How would you explain what the following Python 3 function does
def _process(self, on_commit: UpdateCallable, on_rollback: UpdateCallable) -> Any:
_debug("---> commiting", on_commit)
result = self._do_with_retry(on_commit)
if len(self._transactions) > 0:
# add statement to rollback... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a DN to the LDAP database ; See ldap module. Doesn t return a result
if transactions enabled. | Here you have a function in Python 3, explain what it does
def add(self, dn: str, mod_list: dict) -> None:
_debug("add", self, dn, mod_list)
# if rollback of add required, delete it
def on_commit(obj):
obj.add(dn, None, mod_list)
def on_rollback(obj):
obj.delet... | As a Python code analyst, you investigate and solve complex coding mysteries |
def modify(self, dn: str, mod_list: dict) -> None:
"""
Modify a DN in the LDAP database; See ldap module. Doesn't return a
result if transactions enabled.
"""
_debug("modify", self, dn, mod_list)
# need to work out how to reverse changes in mod_list; result in revlist
... | How would you implement a function in Python 3 that
modifies a DN in the LDAP database. | As a Python code composer, you craft elegant and concise scripts. |
def modify_no_rollback(self, dn: str, mod_list: dict):
"""
Modify a DN in the LDAP database; See ldap module. Doesn't return a
result if transactions enabled.
"""
_debug("modify_no_rollback", self, dn, mod_list)
result = self._do_with_retry(lambda obj: obj.modify_s(dn, m... | Can you implement a function in Python 3 that
modifies a DN in the LDAP database ; See ldap module. Doesn t return a result if transactions enabled. | You are a Python code architect, reviewing and designing scalable and efficient code |
def delete(self, dn: str) -> None:
"""
delete a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
"""
_debug("delete", self)
# get copy of cache
result = self._cache_get_for_dn(dn)
# remove special values that ca... | Can you implement a function in Python 3 that
deletes a entry in the ldap database. | You are a Python code generator, capable of creating scripts from specifications. |
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None:
"""
rename a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
"""
_debug("rename", self, dn, new_rdn, new_base_dn)
# split up the parameters
... | Can you implement a function in Python 3 that
renames a dn in the ldap database ; see ldap module. doesn t return a result if transactions enabled. | You are a Python code generator, capable of creating scripts from specifications. |
Utility function made to reproduce a range of the experimental data structures. | Make a summary of the following Python 3 code
def __experimental_range(start, stop, var, cond, loc={}):
'''Utility function made to reproduce range() with unit integer step
but with the added possibility of specifying a condition
on the looping variable (e.g. var % 2 == 0)
'''
locals().updat... | You are a Python code generator, capable of creating scripts from specifications. |
Create a new for loop line as a replacement for the original code. | How would you explain what the following Python 3 function does
def create_for(line, search_result):
'''Create a new "for loop" line as a replacement for the original code.
'''
try:
return line.format(search_result.group("indented_for"),
search_result.group("var"),
... | You are a Python code generator, capable of creating scripts from specifications. |
def setOverrideValue(self, attributes, hostName):
""" Function __setitem__
Set a parameter of a foreman object as a dict
@param key: The key to modify
@param attribute: The data
@return RETURN: The API result
"""
self['override'] = True
attrType = type(at... | Write a Python 3 script to
function __setitem__ Sets a parameter of a foreman object as a dict | As a Python code analyst, you investigate and solve complex coding mysteries |
Spits out the timedelta in days. | Explain what the following Python 3 code does
def get_interval_timedelta(self):
now_datetime = timezone.now()
current_month_days = monthrange(now_datetime.year, now_datetime.month)[1]
# Two weeks
if self.interval == reminders_choices.INTERVAL_2_WEEKS:
interval_timedelta = d... | You are a Python code architect, reviewing and designing scalable and efficient code |
Execute a runner without blocking the event loop | Here you have a function in Python 3, explain what it does
async def awaitable_runner(runner: BaseRunner):
runner_thread = CapturingThread(target=runner.run)
runner_thread.start()
delay = 0.0
while not runner_thread.join(timeout=0):
await asyncio.sleep(delay)
delay = min(delay + 0.1, 1.0... | As a python code expert, you are capable of creating scripts from specifications. |
def asyncio_main_run(root_runner: BaseRunner):
"""
Create an ``asyncio`` event loop running in the main thread and watching runners
Using ``asyncio`` to handle suprocesses requires a specific loop type to run in the main thread.
This function sets up and runs the correct loop in a portable way.
In ... | Can you create a Python 3 function that
creates an asyncio event loop running in the main thread and watching runners. | As a Python code analyst, you investigate and solve complex coding mysteries |
Function enhance
Enhance the object with new item or enhanced items
| How would you explain what the following Python 3 function does
def enhance(self):
self.update({'os_default_templates':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemOsDefaultTemplate)})
self.update({'oper... | You are a Python code analyst, evaluating scripts for potential improvements. |
def retry(tries=10, delay=1, backoff=2, retry_exception=None):
"""
Retry "tries" times, with initial "delay", increasing delay "delay*backoff" each time.
Without exception success means when function returns valid object.
With exception success when no exceptions
"""
assert tries > 0, "tries mus... | How would you code a function in Python 3 to
retry "tries" times, with initial "delay", increasing delay "delay*backoff" each time. Without exception success means when function returns valid object. With exception success when no exceptions | As a Python code composer, you craft elegant and concise scripts. |
def dump(node):
""" Dump initialized object structure to yaml
"""
from qubell.api.private.platform import Auth, QubellPlatform
from qubell.api.private.organization import Organization
from qubell.api.private.application import Application
from qubell.api.private.instance import Instance
fro... | Write a Python 3 script for
dumping the object structure to yaml | As a python code expert, you are capable of creating scripts from specifications. |
def load_env(file):
"""
Generate environment used for 'org.restore' method
:param file: env file
:return: env
"""
env = yaml.load(open(file))
for org in env.get('organizations', []):
if not org.get('applications'):
org['applications'] = []
if org.get('starter-k... | How would you code a function in Python 3 to
load environment used for org. restore method | You are a Python code architect, reviewing and designing scalable and efficient code |
Set specified value to yaml path. | Can you tell what is the following Python 3 function doing
def patch_env(env, path, value):
def pathGet(dictionary, path):
for item in path.split("/"):
dictionary = dictionary[item]
return dictionary
def pathSet(dictionary, path, value):
path = path.s... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_starter_kit_meta(name):
"""
Extract metadata link for starter kit from platform configs. Starter kit available on add component - starter kit menu.
Beware, config could be changed by deploy scripts during deploy.
:param name: Name of starter kit
:return: Link to metadata
"""
kits = y... | Implement a function in Python 3 to
extract metadata link for starter kit from platform configs. | You are a Python code generator, capable of creating scripts from specifications. |
Extract manifest url from metadata url | Can you generate a brief explanation for the following Python 3 code
def get_manifest_from_meta(metaurl, name):
if 'http' in metaurl:
kit = yaml.safe_load(requests.get(url=metaurl).content)['kit']['applications']
else:
kit = yaml.safe_load(open(metaurl).read())['kit']['applications']
app_url... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def getPayloadStruct(self, attributes, objType=None):
""" Function getPayloadStruct
Get the payload structure to do a creation or a modification
@param key: The key to modify
@param attribute: The data
@param objType: NOT USED in this class
@return RETURN: The API result... | Write a Python 3 function for
functioning getPayloadStruct Get the payload structure to do a creation or modification of a resource. | You are a Python code analyst, evaluating scripts for potential improvements. |
Function log
Decorator to log lasts request before sending a new one | Can you generate the documentation for the following Python 3 function
def log(function):
def _log(self, *args, **kwargs):
ret = function(self, *args, **kwargs)
if len(self.history) > self.maxHistory:
self.history = self.history[1:self.maxHistory]
self.history... | You are a Python code generator, capable of creating scripts from specifications. |
Function clearHistVars
Clear the variables used to get history of all vars
| Can you generate the documentation for the following Python 3 function
def clearReqVars(self):
self.errorMsg = None
self.payload = None
self.url = None
self.resp = None
self.res = None
self.method = None
self.printErrors = None | You are a Python code architect, reviewing and designing scalable and efficient code |
def list(self, obj, filter=False, only_id=False, limit=20):
""" Function list
Get the list of an object
@param obj: object name ('hosts', 'puppetclasses'...)
@param filter: filter for objects
@param only_id: boolean to only return dict with name/id
@return RETURN: the li... | Create a Python 3 function for
functioning list Get the list of an object @param obj: object name ('hosts', 'puppetclasses'...) @param filter: filter for objects @param only_id: boolean to only return dict with name/id @return RETURN: the list of the object | You are a Python code analyst, evaluating scripts for potential improvements. |
def get(self, obj, id, sub_object=None):
""" Function get
Get an object by id
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@return RETURN: the targeted object
"""
self.url = '{}{}/{}'.format(self.base_url, obj... | Implement a function in Python 3 to
function get Get an object by id | As a python code expert, you are capable of creating scripts from specifications. |
def get_id_by_name(self, obj, name):
""" Function get_id_by_name
Get the id of an object
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@return RETURN: the targeted object
"""
list = self.list(obj, filter='name ... | Can you create a Python 3 function that
functions get_id_by_name Get the id of an object by name | You are a Python code generator, capable of creating scripts from specifications. |
Function set
Set an object by id
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@param action: specific action of an object ('power'...)
@param payload: the dict of the payload
@param async: should this request be async... | Can you generate a brief explanation for the following Python 3 code
def set(self, obj, id, payload, action='', async=False):
self.url = '{}{}/{}'.format(self.base_url, obj, id)
self.method = 'PUT'
if action:
self.url += '/{}'.format(action)
self.payload = json.dumps(payload)... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Function create
Create an new object
@param obj: object name ('hosts', 'puppetclasses'...)
@param payload: the dict of the payload
@param async: should this request be async, if true use
return.result() to get the response
@return RETURN: the server respo... | Can you generate a brief explanation for the following Python 3 code
def create(self, obj, payload, async=False):
self.url = self.base_url + obj
self.method = 'POST'
self.payload = json.dumps(payload)
if async:
self.method = 'POST(Async)'
session = FuturesSession(... | As a Python code composer, you craft elegant and concise scripts. |
def delete(self, obj, id):
""" Function delete
Delete an object by id
@param obj: object name ('hosts', 'puppetclasses'...)
@param id: the id of the object (name or id)
@return RETURN: the server response
"""
self.url = '{}{}/{}'.format(self.base_url, obj, id)
... | Write a Python 3 script to
function delete Delete an object by id | You are a Python code generator, capable of creating scripts from specifications. |
Modified run that captures return value and exceptions from target | Can you tell what is the following Python 3 function doing
def run(self):
try:
if self._target:
return_value = self._target(*self._args, **self._kwargs)
if return_value is not None:
self._exception = OrphanedReturn(self, return_value)
excep... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _start_payloads(self):
"""Start all queued payloads"""
with self._lock:
payloads = self._payloads.copy()
self._payloads.clear()
for subroutine in payloads:
thread = CapturingThread(target=subroutine)
thread.start()
self._threads.add... | Can you implement a function in Python 3 that
starts all queued payloads | As a python code expert, you are capable of creating scripts from specifications. |
def _reap_payloads(self):
"""Clean up all finished payloads"""
for thread in self._threads.copy():
# CapturingThread.join will throw
if thread.join(timeout=0):
self._threads.remove(thread)
self._logger.debug('reaped thread %s', thread) | Write a Python 3 function that can
clean up all finished payloads | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorate functions that modify the internally stored usernotes JSON. | How would you explain what the following Python 3 function does
def update_cache(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
"""The wrapper function."""
lazy = kwargs.get('lazy', False)
kwargs.pop('lazy', None)
if not lazy:
self.get_json()
ret = ... | As a python code expert, you are capable of creating scripts from specifications. |
Create an unbound prototype of this class partially applying arguments
| Can you generate the documentation for the following Python 3 function
def s(cls: Type[C], *args, **kwargs) -> Partial[C]:
return Partial(cls, *args, **kwargs) | You are a Python code analyst, evaluating scripts for potential improvements. |
Build the mappings for the base classes and their children. | Explain what the following Python 3 code does
def _build_mappings(
self, classes: Sequence[type]
) -> Tuple[Mapping[type, Sequence[type]], Mapping[type, Sequence[type]]]:
"""
Collect all bases and organize into parent/child mappings.
"""
parents_to_children: MutableMapping[ty... | You are a Python code analyst, evaluating scripts for potential improvements. |
Collect all classes defined in package_paths. | Given the following Python 3 function, write the documentation
def _collect_classes(
self, package_paths: Sequence[str], recurse_subpackages: bool = True
) -> Sequence[type]:
"""
Collect all classes defined in/under ``package_paths``.
"""
import uqbar.apis
classes = ... | As a Python code composer, you craft elegant and concise scripts. |
Return a tuple for authenticating a user
If successful raise AgileError. | Can you tell what is the following Python 3 function doing
def get_auth():
auth = get_auth_from_env()
if auth[0] and auth[1]:
return auth
home = os.path.expanduser("~")
config = os.path.join(home, '.gitconfig')
if not os.path.isfile(config):
raise GithubException('No .gitconfig avai... | You are a Python code analyst, evaluating scripts for potential improvements. |
def checkAndCreate(self, key, payload, osIds):
""" Function checkAndCreate
Check if an architectures exists and create it if not
@param key: The targeted architectures
@param payload: The targeted architectures description
@param osIds: The list of os ids liked with this archite... | Write a Python 3 script to
function checkAndCreate Check if an architectures exists and create it if not | You are a Python code analyst, evaluating scripts for potential improvements. |
Get output from pip command
| Given the following Python 3 function, write the documentation
def pip_command_output(pip_args):
import sys
import pip
from io import StringIO
# as pip will write to stdout we use some nasty hacks
# to substitute system stdout with our own
old_stdout = sys.stdout
sys.stdout = mystdout = Stri... | You are a Python code architect, reviewing and designing scalable and efficient code |
def setup_versioneer():
"""
Generate (temporarily) versioneer.py file in project root directory
:return:
"""
try:
# assume versioneer.py was generated using "versioneer install" command
import versioneer
versioneer.get_version()
except ImportError:
# it looks vers... | Can you implement a function in Python 3 that
generates (temporarily) versioneer.py file in project root directory :return: | You are a Python code generator, capable of creating scripts from specifications. |
This function is used to clean up the cache of module finders. | Here you have a function in Python 3, explain what it does
def clean_cache():
import importlib
try: # Python ver < 3.3
vermod = importlib.import_module("versioneer")
globals()["versioneer"] = vermod
except ImportError:
importlib.invalidate_caches() | You are a Python code generator, capable of creating scripts from specifications. |
Get project version (using versioneer)
:return: string containing version | Make a summary of the following Python 3 code
def get_version():
setup_versioneer()
clean_cache()
import versioneer
version = versioneer.get_version()
parsed_version = parse_version(version)
if '*@' in str(parsed_version):
import time
version += str(int(time.time()))
return v... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find the common prefix of two or more paths. | Can you generate a brief explanation for the following Python 3 code
def find_common_prefix(
paths: Sequence[Union[str, pathlib.Path]]
) -> Optional[pathlib.Path]:
"""
Find the common prefix of two or more paths.
::
>>> import pathlib
>>> one = pathlib.Path('foo/bar/baz')
>>> t... | As a Python code analyst, you investigate and solve complex coding mysteries |
def relative_to(
source_path: Union[str, pathlib.Path], target_path: Union[str, pathlib.Path]
) -> pathlib.Path:
"""
Generates relative path from ``source_path`` to ``target_path``.
Handles the case of paths without a common prefix.
::
>>> import pathlib
>>> source = pathlib.Path(... | Create a Python 3 function for
generating relative path from source_path to target_path. | As a python code expert, you are capable of creating scripts from specifications. |
Walks a directory tree and yields a list of tuples. | Can you generate the documentation for the following Python 3 function
def walk(
root_path: Union[str, pathlib.Path], top_down: bool = True
) -> Generator[
Tuple[pathlib.Path, Sequence[pathlib.Path], Sequence[pathlib.Path]], None, None
]:
"""
Walks a directory tree.
Like :py:func:`os.walk` but yiel... | As a Python code analyst, you investigate and solve complex coding mysteries |
def write(
contents: str,
path: Union[str, pathlib.Path],
verbose: bool = False,
logger_func=None,
) -> bool:
"""
Writes ``contents`` to ``path``.
Checks if ``path`` already exists and only write out new contents if the
old contents do not match.
Creates any intermediate missing di... | Implement a Python 3 function for
writing contents to path. | As a Python code composer, you craft elegant and concise scripts. |
Pretty object reference using module. path : qual. name format | Can you generate a brief explanation for the following Python 3 code
def pretty_ref(obj: Any) -> str:
try:
return obj.__module__ + ':' + obj.__qualname__
except AttributeError:
return pretty_ref(type(obj)) + '(...)' | You are a Python code architect, reviewing and designing scalable and efficient code |
def remote(ctx):
"""Display repo github path
"""
with command():
m = RepoManager(ctx.obj['agile'])
click.echo(m.github_repo().repo_path) | Implement a function in Python 3 to
display repo github path | As a Python code translator, you convert algorithms and pseudocode into Python. |
def graph_order(self):
"""
Get graph-order tuple for node.
::
>>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode
>>> root_container = UniqueTreeContainer(name="root")
>>> outer_container = UniqueTreeContainer(name="outer")
>>> i... | How would you implement a function in Python 3 that
gets the graph - order of the nodes in the tree. | As a Python code analyst, you investigate and solve complex coding mysteries |
def sendQuery(self, cmd, multilines=False):
""" Send command, wait for response (single or multi lines), test for errors and return the returned code.
:param cmd: command to send
:param multilines: True - multiline response, False - single line response.
:return: command return value.
... | How would you implement a function in Python 3 that
sends a command to the Asterisk Manager and wait for response. | You are a Python code generator, capable of creating scripts from specifications. |
Send command without return value wait for completion verify success. | Explain what the following Python 3 code does
def sendQueryVerify(self, cmd):
cmd = cmd.strip()
self.logger.debug("sendQueryVerify(%s)", cmd)
if not self.is_connected():
raise socket.error("sendQueryVerify on a disconnected socket")
resp = self.__sendQueryReply(cmd)
... | As a Python code composer, you craft elegant and concise scripts. |
def find_external_files(self, run_input_dir):
"""
Scan all SHIELDHIT12A config files to find external files used and return them.
Also change paths in config files to match convention that all resources are
symlinked in job_xxxx/symlink
"""
beam_file, geo_file, mat_file, ... | Can you implement a function in Python 3 that
scans all SHIELDHIT12A config files to find external files used and return them. | As a python code expert, you are capable of creating scripts from specifications. |
Scan SH12A BEAM file for references to external files and return them | Given the following Python 3 function, write the documentation
def _parse_beam_file(self, file_path, run_input_dir):
external_files = []
paths_to_replace = []
with open(file_path, 'r') as beam_f:
for line in beam_f.readlines():
split_line = line.split()
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Scan SH12A GEO file for references to external files and return them | Here you have a function in Python 3, explain what it does
def _parse_geo_file(self, file_path, run_input_dir):
external_files = []
paths_to_replace = []
with open(file_path, 'r') as geo_f:
for line in geo_f.readlines():
split_line = line.split()
if le... | As a python code expert, you are capable of creating scripts from specifications. |
def _parse_mat_file(self, file_path):
"""Scan SH12A MAT file for ICRU+LOADEX pairs and return found ICRU numbers"""
mat_file_sections = self._extract_mat_sections(file_path)
return self._analyse_mat_sections(mat_file_sections) | Write a Python 3 function that can
scan SH12A MAT file for ICRU + LOADEX pairs and return found ICRU numbers | As a Python code analyst, you investigate and solve complex coding mysteries |
def _analyse_mat_sections(sections):
"""
Cases:
- ICRU flag present, LOADDEDX flag missing -> data loaded from some data hardcoded in SH12A binary,
no need to load external files
- ICRU flag present, LOADDEDX flag present -> data loaded from external files. ICRU number read from ... | Write a Python 3 function for
analysing the MAT file sections. | As a python code expert, you are capable of creating scripts from specifications. |
Find matching file names for given ICRU numbers | How would you explain what the following Python 3 function does
def _decrypt_icru_files(numbers):
import json
icru_file = resource_string(__name__, os.path.join('data', 'SH12A_ICRU_table.json'))
ref_dict = json.loads(icru_file.decode('ascii'))
try:
return [ref_dict[e] for e i... | As a Python code analyst, you investigate and solve complex coding mysteries |
Rewrite paths in config files to match convention job_xxxx | Can you tell what is the following Python 3 function doing
def _rewrite_paths_in_file(config_file, paths_to_replace):
lines = []
# make a copy of config
import shutil
shutil.copyfile(config_file, str(config_file + '_original'))
with open(config_file) as infile:
for li... | As a python code expert, you are capable of creating scripts from specifications. |
def _check_exists(database: Database, table: LdapObjectClass, key: str, value: str):
""" Check if a given LDAP object exists. """
try:
get_one(table, Q(**{key: value}), database=database)
return True
except ObjectDoesNotExist:
return False | Can you implement a function in Python 3 that
checks if a given LDAP object exists. | You are a Python code architect, reviewing and designing scalable and efficient code |
Modify a changes to add an automatically generated uidNumber. | Given the following Python 3 function, write the documentation
def save_account(changes: Changeset, table: LdapObjectClass, database: Database) -> Changeset:
d = {}
settings = database.settings
uid_number = changes.get_value_as_single('uidNumber')
if uid_number is None:
scheme = settings['NUMBE... | You are a Python code analyst, evaluating scripts for potential improvements. |
def transform_source(text):
'''Replaces instances of
switch expression:
by
for __case in _Switch(n):
and replaces
case expression:
by
if __case(expression):
and
default:
by
if __case():
'''
toks = tokenize.generate_tokens(StringIO... | Write a Python 3 function that can
transform source text into a list of items. | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.