output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Sends a message to the front - end and returns a promise. | Can you generate a brief explanation for the following Python 3 code
def _send(self, method, **parameters):
msg = {
'index': self._calls,
'method': method,
}
msg.update(parameters)
promise = SimplePromise()
self._callbacks[self._calls] = promise
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def rpc_reply(channel, original_headers, message, properties=None):
"""
Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue.
Parameters
----------
channel: object
Properly initialized AMQP channel to use.
original_headers: dict
The headers of the origin... | Create a Python 3 function to
reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue. Parameters ---------- channel: object Properly initialized AMQP channel to use. original_headers: dict The headers of the originating message that caused this reply. message: string... | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize consuming of messages from an AMQP RPC queue. | Given the following Python 3 function, write the documentation
def consume(self, consumer_callback=None, exclusive=False):
if not hasattr(self, "queue_name") and consumer_callback:
raise ValueError("Trying to set a callback, while no general purpose queue was declared.")
self.rpc_consumer_tag = self.channel.bas... | You are a Python code generator, capable of creating scripts from specifications. |
This method is called by the server when the response is received from the server. | Can you generate the documentation for the following Python 3 function
def _rpc_response_callback(self, channel, method_frame, header_frame, body):
self.logger.debug("Received RPC response with correlation_id: {0}".format(header_frame.correlation_id))
if header_frame.correlation_id in self.responses:
self.respon... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Register the receiving of a RPC response. | How would you explain what the following Python 3 function does
def register_response(self, correlation_id=None):
if not correlation_id:
correlation_id = str(uuid.uuid1())
if correlation_id in self.responses:
raise KeyError("Correlation_id {0} was already registered, and therefor not unique.".format(correlat... | As a Python code composer, you craft elegant and concise scripts. |
def retrieve_response(self, correlation_id):
"""
Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been
received yet, None will be returned. After retrieving the response, the value will be unset internally.
The returned value will inclu... | Write a Python 3 script for
retrieving a registered RPC response. | As a python code expert, you are capable of creating scripts from specifications. |
Publish a message to an AMQP exchange. | Can you tell what is the following Python 3 function doing
def publish(self, exchange, routing_key, message, properties=None, mandatory=False):
return publish_message(self.channel, exchange, routing_key, message, properties, mandatory) | You are a Python code generator, capable of creating scripts from specifications. |
def reply(self, original_headers, message, properties=None):
"""
Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue.
Parameters
----------
original_headers: dict
The headers of the originating message that caused this reply.
message: string
Mes... | Can you create a Python 3 function that
replies to a RPC request. This function will use the default exchange, to directly contact the reply_to queue. Parameters ---------- original_headers: dict The headers of the originating message that caused this reply. message: string Message to reply with properties: dict Proper... | As a python code expert, you are capable of creating scripts from specifications. |
Clear the USERSETTINGS_CACHE for the current site. | Can you tell what is the following Python 3 function doing
def clear_usersettings_cache(sender, **kwargs):
instance = kwargs['instance']
try:
del USERSETTINGS_CACHE[instance.site.pk]
except KeyError:
pass | As a Python code composer, you craft elegant and concise scripts. |
def get_current(self):
"""
Returns the current ``UserSettings`` based on the SITE_ID in the
project's settings. The ``UserSettings`` object is cached the first
time it's retrieved from the database.
"""
from django.conf import settings
try:
site_id = s... | Can you create a Python 3 function that
returns the current UserSettings object based on the SITE_ID in the project s settings. | You are a Python code analyst, evaluating scripts for potential improvements. |
Append path to base_url | Given the following Python 3 function, write the documentation
def append_url(base_url, path):
if base_url[-1] != "/":
base_url += "/"
if path[0] == "/":
path = path[1:]
return urljoin(base_url, path) | As a Python code composer, you craft elegant and concise scripts. |
This function adds per - gene frameshift mutation rates to the output file. | Can you tell what is the following Python 3 function doing
def include_frameshift_rates(path):
with open(path) as handle:
lines = [ x.strip().split('\t') for x in handle ]
nonsense = sum([ 10**(float(x[4])) for x in lines[1:] if x[4] != 'NA' ])
length = sum([ int(x[2]) for x in lines[1:] i... | As a Python code analyst, you investigate and solve complex coding mysteries |
Random string for message signing | Explain what the following Python 3 code does
def _randomString():
return ''.join(
random.choice(string.ascii_uppercase + string.digits)
for x in range(10)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def _callFunc(session, funcName, password, args):
"""Call custom cjdns admin function"""
txid = _randomString()
sock = session.socket
sock.send(bytearray('d1:q6:cookie4:txid10:%se' % txid, 'utf-8'))
msg = _getMessage(session, txid)
cookie = msg['cookie']
txid = _randomString()
tohash = ... | Can you create a Python 3 function that
calls custom cjdns admin function | You are a Python code architect, reviewing and designing scalable and efficient code |
def _receiverThread(session):
"""Receiving messages from cjdns admin server"""
timeOfLastSend = time.time()
timeOfLastRecv = time.time()
try:
while True:
if timeOfLastSend + KEEPALIVE_INTERVAL_SECONDS < time.time():
if timeOfLastRecv + 10 < time.time():
... | Can you create a Python 3 function that
receives messages from cjdns admin server | You are a Python code analyst, evaluating scripts for potential improvements. |
def _getMessage(session, txid):
"""Getting message associated with txid"""
while True:
if txid in session.messages:
msg = session.messages[txid]
del session.messages[txid]
return msg
else:
try:
# apparently any timeout at all allow... | Write a Python 3 script for
getting a message from the queue and store it in session. messages. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _functionFabric(func_name, argList, oargList, password):
"""Function fabric for Session class"""
def functionHandler(self, *args, **kwargs):
call_args = {}
for (key, value) in oargList.items():
call_args[key] = value
for i, arg in enumerate(argList):
if i <... | Implement a function in Python 3 to
function fabric for Session class | As a Python code translator, you convert algorithms and pseudocode into Python. |
def connect(ipAddr, port, password):
"""Connect to cjdns admin with this attributes"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((ipAddr, port))
sock.settimeout(2)
# Make sure it pongs.
sock.send(b'd1:q4:pinge')
data = sock.recv(BUFFER_SIZE)
if not data.endsw... | Can you implement a function in Python 3 that
connects to cjdns admin with this attributes | You are a Python code generator, capable of creating scripts from specifications. |
Connect to cjdns admin with data from user file | Here you have a function in Python 3, explain what it does
def connectWithAdminInfo(path=None):
if path is None:
path = os.path.expanduser('~/.cjdnsadmin')
try:
with open(path, 'r') as adminInfo:
data = json.load(adminInfo)
except IOError:
logger.info('~/.cjdnsadmin not ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def publish_message(channel, exchange, routing_key, message, properties=None, mandatory=False):
"""
Publish a message to an AMQP exchange.
Parameters
----------
channel: object
Properly initialized AMQP channel to use.
exchange: string
Exchange to publish to.
routing_key: string
Routing key to use for thi... | Write a Python 3 function that can
publish a message to an AMQP exchange. | You are a Python code analyst, evaluating scripts for potential improvements. |
Publish a message to an AMQP exchange. | Make a summary of the following Python 3 code
def publish(self, message, properties=None, mandatory=False):
return publish_message(self.channel, self.exchange_name, self.default_routing_key, message, properties, mandatory) | As a Python code composer, you craft elegant and concise scripts. |
def load_genes(path):
""" load a file listing gene and transcript IDs
Args:
path: path to file containing gene IDs and transcript IDs e.g.
gene_1 transcript_1.1 length_1 denovo_count
gene_2 transcript_2.1 length_3 denovo_count
Returns:
dict... | Can you implement a function in Python 3 that
loads a file listing gene and transcript IDs and return a dictionary of transcripts | You are a Python code analyst, evaluating scripts for potential improvements. |
This function determines the mutation rates per functional category for a list of transcripts and the ensembl request object. | Can you generate the documentation for the following Python 3 function
def get_mutation_rates(transcripts, mut_dict, ensembl):
rates = {'missense': 0, 'nonsense': 0, 'splice_lof': 0,
'splice_region': 0, 'synonymous': 0}
combined = None
for tx_id in transcripts:
try:
tx ... | You are a Python code architect, reviewing and designing scalable and efficient code |
get the command line options for the get_command_line_switches | Explain what the following Python 3 code does
def get_options():
parser = argparse.ArgumentParser(description='denovonear cli interface')
############################################################################
# CLI options in common
parent = argparse.ArgumentParser(add_help=False)
pa... | As a Python code composer, you craft elegant and concise scripts. |
def to_ipv6(key):
"""Get IPv6 address from a public key."""
if key[-2:] != '.k':
raise ValueError('Key does not end with .k')
key_bytes = base32.decode(key[:-2])
hash_one = sha512(key_bytes).digest()
hash_two = sha512(hash_one).hexdigest()
return ':'.join([hash_two[i:i+4] for i in ran... | Create a Python 3 function to
get IPv6 address from a public key. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return all absolute filenames of files that match the globbing patterns. | Here you have a function in Python 3, explain what it does
def glob(self):
matches = []
for root, dirnames, filenames in os.walk(self.path):
if not self.recursive:
while len(dirnames) > 0:
dirnames.pop()
for include in self.include:
for filename in fnmatch.filter(filenames, include):
matches... | As a python code expert, you are capable of creating scripts from specifications. |
def select_site_view(self, request, form_url=''):
"""
Display a choice form to select which site to add settings.
"""
if not self.has_add_permission(request):
raise PermissionDenied
extra_qs = ''
if request.META['QUERY_STRING']:
extra_qs = '&' + r... | Can you write a function in Python 3 where it
displays a choice form to select which site to add settings. | You are a Python code analyst, evaluating scripts for potential improvements. |
Render the site choice form. | Explain what the following Python 3 code does
def render_select_site_form(self, request, context, form_url=''):
app_label = self.opts.app_label
context.update({
'has_change_permission': self.has_change_permission(request),
'form_url': mark_safe(form_url),
'opts': self... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate an OAuth token tuple that can be used with clients. ReaderClient. | Explain what the following Python 3 code does
def xauth(base_url_template=DEFAULT_READER_URL_TEMPLATE, **xargs):
consumer_key = xargs.get('consumer_key') or required_from_env('READABILITY_CONSUMER_KEY')
consumer_secret = xargs.get('consumer_secret') or required_from_env('READABILITY_CONSUMER_SECRET')
userna... | As a python code expert, you are capable of creating scripts from specifications. |
log transform a numeric value unless it is zero or negative
| How would you explain what the following Python 3 function does
def log_transform(rates):
transformed = []
for key in ['missense', 'nonsense', 'splice_lof', 'splice_region',
'synonymous']:
try:
value = math.log10(rates[key])
except ValueError:
va... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the UserSettings model that is active in this project. | Explain what the following Python 3 code does
def get_usersettings_model():
try:
from django.apps import apps
get_model = apps.get_model
except ImportError:
from django.db.models.loading import get_model
try:
app_label, model_name = settings.USERSETTINGS_MODEL.split('.')
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the current UserSettings based on the SITE_ID in the project s settings
| How would you explain what the following Python 3 function does
def get_current_usersettings():
USERSETTINGS_MODEL = get_usersettings_model()
try:
current_usersettings = USERSETTINGS_MODEL.objects.get_current()
except USERSETTINGS_MODEL.DoesNotExist:
current_usersettings = USERSETTINGS_MODEL... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function calculates the probability of getting the observed de novos with a mean conservation. | Make a summary of the following Python 3 code
def get_p_value(transcript, rates, iterations, consequence, de_novos):
if len(de_novos) < 2:
return (float('nan'), float('nan'))
rename = {"lof": "loss_of_function"}
if consequence in rename:
consequence = rename[consequence]
w... | As a Python code analyst, you investigate and solve complex coding mysteries |
get the command line options | How would you explain what the following Python 3 function does
def get_options():
parser = argparse.ArgumentParser(description="Script to batch process de"
"novo clustering.")
parser.add_argument("--in", dest="input", required=True, help="Path to"
"file listing known mutations in genes. Se... | You are a Python code architect, reviewing and designing scalable and efficient code |
def count_missense_per_gene(lines):
""" count the number of missense variants in each gene.
"""
counts = {}
for x in lines:
x = x.split("\t")
gene = x[0]
consequence = x[3]
if gene not in counts:
counts[gene] = 0
if consequence !... | Write a Python 3 script to
count the number of missense variants in each gene. | As a Python code composer, you craft elegant and concise scripts. |
split de novos from an input file into files one for each gene
CTYPE | Can you generate a brief explanation for the following Python 3 code
def split_denovos(denovo_path, temp_dir):
# open the de novos, drop the header line, then sort them (which will be by
# HGNC symbol, as the first element of each line)
with open(denovo_path, "r") as handle:
lines = handle.read... | You are a Python code analyst, evaluating scripts for potential improvements. |
make a random string that we can use for bsub job IDs | Here you have a function in Python 3, explain what it does
def get_random_string():
# set up a random string to associate with the run
hash_string = "%8x" % random.getrandbits(32)
hash_string = hash_string.strip()
# done't allow the random strings to be equivalent to a number, since
# the ... | As a Python code composer, you craft elegant and concise scripts. |
Submits a bsub job to the current directory. | Explain what the following Python 3 code does
def submit_bsub_job(command, job_id=None, dependent_id=None, memory=None, requeue_code=None, logfile=None):
if job_id is None:
job_id = get_random_string()
job = "-J \"{0}\"".format(job_id)
mem = ""
if memory is not None:
mem =... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function processes the given file into a single array of directories. | Can you tell what is the following Python 3 function doing
def batch_process(de_novo_path, temp_dir, output_path):
temp_dir = tempfile.mkdtemp(dir=temp_dir)
count = split_denovos(de_novo_path, temp_dir)
# set up run parameters
job_name = "denovonear"
job_id = "{0}[1-{1}]%20".format(job_nam... | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_mutation_rates(path=None):
""" load sequence context-based mutation rates
Args:
path: path to table of sequence context-based mutation rates. If None,
this defaults to per-trinucleotide rates provided by Kaitlin Samocha
(Broad Institute).
Returns:
l... | Write a Python 3 script to
load the per - trinucleotide rates from a file | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the authenticated user by the provided authentication | Can you tell what is the following Python 3 function doing
def authenticated_user(self, auth):
response = self.get("/user", auth=auth)
return GogsUser.from_json(response.json()) | You are a Python code generator, capable of creating scripts from specifications. |
def get_tokens(self, auth, username=None):
"""
Returns the tokens owned by the specified user. If no user is specified,
uses the user authenticated by ``auth``.
:param auth.Authentication auth: authentication for user to retrieve.
Must be a usern... | How would you implement a function in Python 3 that
returns the list of tokens owned by the specified user. | You are a Python code architect, reviewing and designing scalable and efficient code |
def create_token(self, auth, name, username=None):
"""
Creates a new token with the specified name for the specified user.
If no user is specified, uses user authenticated by ``auth``.
:param auth.Authentication auth: authentication for user to retrieve.
... | How would you implement a function in Python 3 that
creates a new token with the specified name for the specified user. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Ensures that a token with the specified name exists for the specified user. Creates a new token if none exists. | Can you generate a brief explanation for the following Python 3 code
def ensure_token(self, auth, name, username=None):
if username is None:
username = self.authenticated_user(auth).username
tokens = [token for token in self.get_tokens(auth, username) if token.name == name]
if len(to... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a new repository and returns it. | Can you generate the documentation for the following Python 3 function
def create_repo(self, auth, name, description=None, private=False, auto_init=False,
gitignore_templates=None, license_template=None, readme_template=None,
organization=None):
"""
Creates a new ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns whether a repository with name repo_name owned by the user with username exists. | Explain what the following Python 3 code does
def repo_exists(self, auth, username, repo_name):
path = "/repos/{u}/{r}".format(u=username, r=repo_name)
return self._get(path, auth=auth).ok | As a Python code composer, you craft elegant and concise scripts. |
def get_repo(self, auth, username, repo_name):
"""
Returns a the repository with name ``repo_name`` owned by
the user with username ``username``.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str repo_n... | How would you code a function in Python 3 to
return a repository with name repo_name owned by username. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_user_repos(self, auth, username):
"""
Returns the repositories owned by
the user with username ``username``.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:return: a list of repositories
:rtyp... | Can you write a function in Python 3 where it
returns the list of repositories owned by the user with username username. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_branch(self, auth, username, repo_name, branch_name):
"""
Returns the branch with name ``branch_name`` in the repository with name ``repo_name``
owned by the user with username ``username``.
:param auth.Authentication auth: authentication object
:param str username: use... | How would you code a function in Python 3 to
return the branch with name branch_name in the repository with name repo_name owned by the user with username username. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the branches owned by the user with username username. | Can you generate a brief explanation for the following Python 3 code
def get_branches(self, auth, username, repo_name):
path = "/repos/{u}/{r}/branches".format(u=username, r=repo_name)
response = self.get(path, auth=auth)
return [GogsBranch.from_json(branch_json) for branch_json in response.json... | You are a Python code analyst, evaluating scripts for potential improvements. |
Deletes the repository with name repo_name owned by the user with username username. | Can you generate the documentation for the following Python 3 function
def delete_repo(self, auth, username, repo_name):
path = "/repos/{u}/{r}".format(u=username, r=repo_name)
self.delete(path, auth=auth) | As a python code expert, you are capable of creating scripts from specifications. |
def migrate_repo(self, auth, clone_addr,
uid, repo_name, auth_username=None, auth_password=None,
mirror=False, private=False, description=None):
"""
Migrate a repository from another Git hosting source for the authenticated user.
:param auth.Authenticat... | Can you create a Python 3 function that
migrates a repository from another Git hosting source for the authenticated user. :param auth.Authentication auth: authentication object :param str clone_addr: Remote Git address (HTTP/HTTPS URL or local path) :param int uid: user ID of repository owner :param str repo_name: Repo... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a new user and returns the created user. | Can you tell what is the following Python 3 function doing
def create_user(self, auth, login_name, username, email, password, send_notify=False):
# Since the source_id parameter was not well-documented at the time this method was
# written, force the default value
data = {
"login_nam... | You are a Python code generator, capable of creating scripts from specifications. |
Returns whether a user with the specified username exists. | Can you generate a brief explanation for the following Python 3 code
def user_exists(self, username):
path = "/users/{}".format(username)
return self._get(path).ok | You are a Python code generator, capable of creating scripts from specifications. |
Search for users whose username matches username_keyword and returns
a list of matched users. | Here you have a function in Python 3, explain what it does
def search_users(self, username_keyword, limit=10):
params = {"q": username_keyword, "limit": limit}
response = self.get("/users/search", params=params)
return [GogsUser.from_json(user_json) for user_json in response.json()["data"]] | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a representing the user with username username. | Explain what the following Python 3 code does
def get_user(self, auth, username):
path = "/users/{}".format(username)
response = self.get(path, auth=auth)
return GogsUser.from_json(response.json()) | You are a Python code analyst, evaluating scripts for potential improvements. |
def update_user(self, auth, username, update):
"""
Updates the user with username ``username`` according to ``update``.
:param auth.Authentication auth: authentication object, must be admin-level
:param str username: username of user to update
:param GogsUserUpdate update: a ``G... | Write a Python 3 function for
updating the user with username according to update. | As a Python code analyst, you investigate and solve complex coding mysteries |
Deletes the user with username username. | Can you generate a brief explanation for the following Python 3 code
def delete_user(self, auth, username):
path = "/admin/users/{}".format(username)
self.delete(path, auth=auth) | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_repo_hooks(self, auth, username, repo_name):
"""
Returns all hooks of repository with name ``repo_name`` owned by
the user with username ``username``.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:par... | Implement a Python 3 function for
returning all hooks owned by the user with username username. | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False):
"""
Creates a new hook, and returns the created hook.
:param auth.Authentication auth: authentication object, must be admin-level
:param str repo_name: the name of the repo for which... | Create a Python 3 function to
create a new hook and returns it. | You are a Python code analyst, evaluating scripts for potential improvements. |
Updates the hook with id hook_id according to update. | Can you generate the documentation for the following Python 3 function
def update_hook(self, auth, repo_name, hook_id, update, organization=None):
if organization is not None:
path = "/repos/{o}/{r}/hooks/{i}".format(o=organization, r=repo_name, i=hook_id)
else:
path = "/repos/{r... | You are a Python code architect, reviewing and designing scalable and efficient code |
Deletes the hook with id hook_id for repo with name repo_name owned by the user with username username. | Here you have a function in Python 3, explain what it does
def delete_hook(self, auth, username, repo_name, hook_id):
path = "/repos/{u}/{r}/hooks/{i}".format(u=username, r=repo_name, i=hook_id)
self.delete(path, auth=auth) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_organization(self, auth, owner_name, org_name, full_name=None, description=None,
website=None, location=None):
"""
Creates a new organization, and returns the created organization.
:param auth.Authentication auth: authentication object, must be admin-level... | Implement a function in Python 3 to
create a new organization and returns the created organization. | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_organization_team(self, auth, org_name, name, description=None, permission="read"):
"""
Creates a new team of the organization.
:param auth.Authentication auth: authentication object, must be admin-level
:param str org_name: Organization user name
:param str name: Ful... | Implement a Python 3 function for
creating a new organization team. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_team_membership(self, auth, team_id, username):
"""
Add user to team.
:param auth.Authentication auth: authentication object, must be admin-level
:param str team_id: Team's id
:param str username: Username of the user to be added to team
:raises NetworkFailure: i... | Implement a Python 3 function for
adding user to team. | As a Python code analyst, you investigate and solve complex coding mysteries |
def remove_team_membership(self, auth, team_id, username):
"""
Remove user from team.
:param auth.Authentication auth: authentication object, must be admin-level
:param str team_id: Team's id
:param str username: Username of the user to be removed from the team
:raises N... | Create a Python 3 function for
removing user from team s cache. | You are a Python code generator, capable of creating scripts from specifications. |
def add_repo_to_team(self, auth, team_id, repo_name):
"""
Add or update repo from team.
:param auth.Authentication auth: authentication object, must be admin-level
:param str team_id: Team's id
:param str repo_name: Name of the repo to be added to the team
:raises Networ... | How would you implement a function in Python 3 that
adds or update a repo from a team. | As a Python code analyst, you investigate and solve complex coding mysteries |
Remove repo from team. | Can you tell what is the following Python 3 function doing
def remove_repo_from_team(self, auth, team_id, repo_name):
url = "/admin/teams/{t}/repos/{r}".format(t=team_id, r=repo_name)
self.delete(url, auth=auth) | You are a Python code analyst, evaluating scripts for potential improvements. |
List deploy keys for the specified repo. | Can you generate the documentation for the following Python 3 function
def list_deploy_keys(self, auth, username, repo_name):
response = self.get("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth)
return [GogsRepo.DeployKey.from_json(key_json) for key_json in response.json()] | As a Python code composer, you craft elegant and concise scripts. |
Get a deploy key for the specified repo. | Given the following Python 3 function, write the documentation
def get_deploy_key(self, auth, username, repo_name, key_id):
response = self.get("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth)
return GogsRepo.DeployKey.from_json(response.json()) | As a Python code analyst, you investigate and solve complex coding mysteries |
Adds a deploy key to the specified repo. | Here you have a function in Python 3, explain what it does
def add_deploy_key(self, auth, username, repo_name, title, key_content):
data = {
"title": title,
"key": key_content
}
response = self.post("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth, data=da... | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove deploy key for the specified repo. | How would you explain what the following Python 3 function does
def delete_deploy_key(self, auth, username, repo_name, key_id):
self.delete("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth) | You are a Python code generator, capable of creating scripts from specifications. |
Manually make a DELETE request. | Given the following Python 3 function, write the documentation
def delete(self, path, auth=None, **kwargs):
return self._check_ok(self._delete(path, auth=auth, **kwargs)) | As a Python code analyst, you investigate and solve complex coding mysteries |
Manually make a GET request. | Can you generate the documentation for the following Python 3 function
def get(self, path, auth=None, **kwargs):
return self._check_ok(self._get(path, auth=auth, **kwargs)) | As a python code expert, you are capable of creating scripts from specifications. |
Manually make a PATCH request. | Can you tell what is the following Python 3 function doing
def patch(self, path, auth=None, **kwargs):
return self._check_ok(self._patch(path, auth=auth, **kwargs)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Manually make a PUT request. | Given the following Python 3 function, write the documentation
def put(self, path, auth=None, **kwargs):
return self._check_ok(self._put(path, auth=auth, **kwargs)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _fail(response):
"""
Raise an ApiFailure pertaining to the given response
"""
message = "Status code: {}-{}, url: {}".format(response.status_code, response.reason, response.url)
try:
message += ", message:{}".format(response.json()["message"])
except (Valu... | How would you implement a function in Python 3 that
raises an ApiFailure pertaining to the given response | As a Python code composer, you craft elegant and concise scripts. |
set the start action for the current session | Make a summary of the following Python 3 code
def setStartAction(self, action, *args, **kwargs):
self.init_action = action
self.init_args = args
self.init_kwargs = kwargs | You are a Python code architect, reviewing and designing scalable and efficient code |
def setStopAction(self, action, *args, **kwargs):
"""
Set a function to call when run() is stopping, after the main action is called.
Parameters
----------
action: function pointer
The function to call.
*args
Positional arguments to pass to action.
**kwargs:
Keyword arguments to pass to action.
... | Write a Python 3 function that can
set a function to call when run() is stopping, after the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. | You are a Python code generator, capable of creating scripts from specifications. |
This method runs the main loop. | Explain what the following Python 3 code does
def run(self):
self.logger.debug("Thread {0} is entering main loop".format(self.name))
if hasattr(self, "init_action"):
self.logger.debug("Thread {0} is calling its init action")
self.init_action(*self.init_args, **self.init_kwargs)
while not self.stop:
sel... | As a Python code composer, you craft elegant and concise scripts. |
Print items with a timestamp. | Here you have a function in Python 3, explain what it does
def Printer(open_file=sys.stdout, closing=False):
try:
while True:
logstr = (yield)
open_file.write(logstr)
open_file.write('\n') # new line
except GeneratorExit:
if closing:
try: open_file... | You are a Python code generator, capable of creating scripts from specifications. |
def FilePrinter(filename, mode='a', closing=True):
path = os.path.abspath(os.path.expanduser(filename))
""" Opens the given file and returns a printer to it. """
f = open(path, mode)
return Printer(f, closing) | Create a Python 3 function for
opening a file and returns a Printer object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Writes messages to a socket. | Given the following Python 3 function, write the documentation
def SocketWriter(host, port, af=None, st=None):
import socket
if af is None:
af = socket.AF_INET
if st is None:
st = socket.SOCK_STREAM
message = '({0}): {1}'
s = socket.socket(af, st)
s.connect(host, port)
try:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Send messages as emails to the given list
ridge s recipients. | Make a summary of the following Python 3 code
def Emailer(recipients, sender=None):
import smtplib
hostname = socket.gethostname()
if not sender:
sender = 'lggr@{0}'.format(hostname)
smtp = smtplib.SMTP('localhost')
try:
while True:
logstr = (yield)
try:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Send messages as emails to the given list of recipients from a GMail account. | How would you explain what the following Python 3 function does
def GMailer(recipients, username, password, subject='Log message from lggr.py'):
import smtplib
srvr = smtplib.SMTP('smtp.gmail.com', 587)
srvr.ehlo()
srvr.starttls()
srvr.ehlo()
srvr.login(username, password)
if not (isinstanc... | As a Python code composer, you craft elegant and concise scripts. |
def add(self, levels, logger):
""" Given a list or tuple of logging levels,
add a logger instance to each. """
if isinstance(levels, (list, tuple)):
for lvl in levels:
self.config[lvl].add(logger)
else:
self.config[levels].add(logger) | Can you create a Python 3 function that
gives a list or tuple of logging levels add a logger instance to each level. | You are a Python code generator, capable of creating scripts from specifications. |
Given a level remove a given logger function
if it is a member of that level close the logger functionEither way. | Here you have a function in Python 3, explain what it does
def remove(self, level, logger):
self.config[level].discard(logger)
logger.close() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove all logger functions from a given level. | How would you explain what the following Python 3 function does
def clear(self, level):
for item in self.config[level]:
item.close()
self.config[level].clear() | As a Python code composer, you craft elegant and concise scripts. |
Create a record from the given parameters and return it. | Can you generate a brief explanation for the following Python 3 code
def _make_record(self,
level,
fmt,
args,
extra,
exc_info,
inc_stackinfo,
inc_multiproc):
""" Cre... | As a Python code composer, you craft elegant and concise scripts. |
def _log(self,
level,
fmt,
args=None,
extra=None,
exc_info=None,
inc_stackinfo=False,
inc_multiproc=False):
""" Send a log message to all of the logging functions
for a given level as well as adding the
... | Write a Python 3 script to
send a log message to all of the logging functions that are currently open and remove the log message from the logger instance. | As a Python code analyst, you investigate and solve complex coding mysteries |
Do logging but handle error suppression. | Can you generate the documentation for the following Python 3 function
def log(self, *args, **kwargs):
if self.suppress_errors:
try:
self._log(*args, **kwargs)
return True
except:
return False
else:
self._log(*args, **kw... | As a Python code composer, you craft elegant and concise scripts. |
Log a message with DEBUG level. | Given the following Python 3 function, write the documentation
def debug(self, msg, *args, **kwargs):
kwargs.setdefault('inc_stackinfo', True)
self.log(DEBUG, msg, args, **kwargs) | As a Python code composer, you craft elegant and concise scripts. |
def error(self, msg, *args, **kwargs):
""" Log a message with ERROR level. Automatically includes stack and
process info unless they are specifically not included. """
kwargs.setdefault('inc_stackinfo', True)
kwargs.setdefault('inc_multiproc', True)
self.log(ERROR, msg, args, **k... | Create a Python 3 function for
logging a message at ERROR level. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def critical(self, msg, *args, **kwargs):
""" Log a message with CRITICAL level. Automatically includes stack and
process info unless they are specifically not included. """
kwargs.setdefault('inc_stackinfo', True)
kwargs.setdefault('inc_multiproc', True)
self.log(CRITICAL, msg, ... | Create a Python 3 function to
log a message with CRITICAL level. | As a Python code analyst, you investigate and solve complex coding mysteries |
Log a message at multiple levels. | How would you explain what the following Python 3 function does
def multi(self, lvl_list, msg, *args, **kwargs):
for level in lvl_list:
self.log(level, msg, args, **kwargs) | You are a Python code architect, reviewing and designing scalable and efficient code |
Log a message at every known log level | Here you have a function in Python 3, explain what it does
def all(self, msg, *args, **kwargs):
self.multi(ALL, msg, args, **kwargs) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _find_caller(self):
"""
Find the stack frame of the caller so that we can note the source file
name, line number, and function name.
"""
rv = ('(unknown file)',
0,
'(unknown function)',
'(code not available)',
[],
... | Write a Python 3 function that can
find the stack frame of the caller so that we can note the source file and line number and function name. | As a Python code analyst, you investigate and solve complex coding mysteries |
Maps a raw deserialized row to proper types | Given the following Python 3 function, write the documentation
def _map_value(self, value):
''' Maps a raw deserialized row to proper types '''
# TODO: Once we've gotten here, we've done the following:
# -> Recieve the full response, copy it from network buffer it into a ByteBuffer (copy 1)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_deprecated_gene_ids(filename):
""" gets a dict of the gene IDs used during in DDD datasets that have been
deprecated in favour of other gene IDs
"""
deprecated = {}
with open(filename) as handle:
for line in handle:
line = line.strip().split()
old = line[... | Can you write a function in Python 3 where it
gets a dict of the gene IDs used during in DDD datasets that have been deprecated in favour of other gene IDs | As a Python code composer, you craft elegant and concise scripts. |
returns a dictionary of length for each transcript in the list transcript_ids | How would you explain what the following Python 3 function does
def get_transcript_lengths(ensembl, transcript_ids):
transcripts = {}
for transcript_id in transcript_ids:
# get the transcript's protein sequence via the ensembl REST API
try:
seq = ensembl.get_protein_seq_for_tran... | 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.