output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type en... | Can you create a Python 3 function that
looks for every file in the directory tree and create the corresponding ReST files. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment :type env: :class:`jinja2.Environment` :param src: the path to the python source files :t... | You are a Python code analyst, evaluating scripts for potential improvements. |
Normalize the excluded directory list. | Can you generate a brief explanation for the following Python 3 code
def normalize_excludes(excludes):
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes] | As a python code expert, you are capable of creating scripts from specifications. |
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root ==... | Can you write a function in Python 3 where it
checks if the directory is in the exclude list. | As a Python code composer, you craft elegant and concise scripts. |
Generate the rst files for a single node. | Explain what the following Python 3 code does
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:para... | As a python code expert, you are capable of creating scripts from specifications. |
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix... | Write a Python 3 script to
parse the config of the app and initiate the generation process :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :returns: None :rtype: None :raises: None | As a Python code composer, you craft elegant and concise scripts. |
Return floating point equality. | Here you have a function in Python 3, explain what it does
def _isclose(obja, objb, rtol=1e-05, atol=1e-08):
return abs(obja - objb) <= (atol + rtol * abs(objb)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def _isreal(obj):
"""
Determine if an object is a real number.
Both Python standard data types and Numpy data types are supported.
:param obj: Object
:type obj: any
:rtype: boolean
"""
# pylint: disable=W0702
if (obj is None) or isinstance(obj, bool):
return False
try... | Implement a Python 3 function for
determining if an object is a real number. | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Converts a number to a string without using scientific notation. | Explain what the following Python 3 code does
def _no_exp(number):
if isinstance(number, bool) or (not isinstance(number, (int, float))):
raise RuntimeError("Argument `number` is not valid")
mant, exp = _to_scientific_tuple(number)
if not exp:
return str(number)
floating_mant = "." in ma... | As a python code expert, you are capable of creating scripts from specifications. |
def gcd(vector):
"""
Calculate the greatest common divisor (GCD) of a sequence of numbers.
The sequence can be a list of numbers or a Numpy vector of numbers. The
computations are carried out with a precision of 1E-12 if the objects are
not `fractions <https://docs.python.org/3/library/fractions.ht... | Can you write a function in Python 3 where it
calculates the greatest common divisor of a list of numbers or a Numpy vector of numbers. | As a python code expert, you are capable of creating scripts from specifications. |
r Scale a value to the range defined by a series. | How would you explain what the following Python 3 function does
def normalize(value, series, offset=0):
if not _isreal(value):
raise RuntimeError("Argument `value` is not valid")
if not _isreal(offset):
raise RuntimeError("Argument `offset` is not valid")
try:
smin = float(min(series... | You are a Python code generator, capable of creating scripts from specifications. |
def pgcd(numa, numb):
"""
Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5... | How would you code a function in Python 3 to
calculate the greatest common divisor of two numbers. | As a Python code analyst, you investigate and solve complex coding mysteries |
def connect_ws(self, post_connect_callback, channels, reconnect=False):
"""
Connect to a websocket
:channels: List of SockChannel instances
"""
self.post_conn_cb = post_connect_callback
self.channels = channels
self.wsendpoint = self.context["conf"]["endpoints"].... | Write a Python 3 function for
connecting to a websocket | You are a Python code generator, capable of creating scripts from specifications. |
Submit a request on the websocket | Can you tell what is the following Python 3 function doing
def wscall(self, method, query=None, callback=None):
if callback is None:
self.sock.emit(method, query)
else:
self.sock.emitack(method, query, callback) | As a Python code composer, you craft elegant and concise scripts. |
def connect_channels(self, channels):
"""Connect the provided channels"""
self.log.info(f"Connecting to channels...")
for chan in channels:
chan.connect(self.sock)
self.log.info(f"\t{chan.channel}") | Can you write a function in Python 3 where it
connects the provided channels to the socket. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _on_set_auth(self, sock, token):
"""Set Auth request received from websocket"""
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) | Write a Python 3 function that can
call when the client wants to set the auth token from the websocket | You are a Python code architect, reviewing and designing scalable and efficient code |
Called when the client is listening and the client is authenticated. | Here you have a function in Python 3, explain what it does
def _on_auth(self, sock, authenticated): # pylint: disable=unused-argument
def ack(eventname, error, data): # pylint: disable=unused-argument
"""Ack"""
if error:
self.log.error(f"""OnAuth: {error}""")
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Called when a websocket connection error occurs. | Can you generate the documentation for the following Python 3 function
def _on_connect_error(self, sock, err): # pylint: disable=unused-argument
if isinstance(err, SystemExit):
self.log.error(f"Shutting down websocket connection")
else:
self.log.error(f"Websocket error: {err}") | You are a Python code analyst, evaluating scripts for potential improvements. |
Attach a given socket to a channel | Can you tell what is the following Python 3 function doing
def connect(self, sock):
def cbwrap(*args, **kwargs):
"""Callback wrapper; passes in response_type"""
self.callback(self.response_type, *args, **kwargs)
self.sock = sock
self.sock.subscribe(self.channel)
... | As a python code expert, you are capable of creating scripts from specifications. |
Run command `cmd`.
It's like that, and that's the way it is. | Explain what the following Python 3 code does
def run_cmd(cmd, input=None, timeout=30, max_try=3, num_try=1):
'''Run command `cmd`.
It's like that, and that's the way it is.
'''
if type(cmd) == str:
cmd = cmd.split()
process = subprocess.Popen(cmd,
stdin=open(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
pop first positional arg from the list of arguments | Given the following Python 3 function, write the documentation
def pop_first_arg(argv):
for arg in argv:
if not arg.startswith('-'):
argv.remove(arg)
return (arg, argv)
return (None, argv) | You are a Python code analyst, evaluating scripts for potential improvements. |
check options requirements print and return exit value | Can you generate the documentation for the following Python 3 function
def check_options(options, parser):
if not options.get('release_environment', None):
print("release environment is required")
parser.print_help()
return os.EX_USAGE
return 0 | You are a Python code analyst, evaluating scripts for potential improvements. |
def write(self):
""" write all needed state info to filesystem """
dumped = self._fax.codec.dump(self.__state, open(self.state_file, 'w')) | Can you create a Python 3 function that
writes all needed state info to filesystem | You are a Python code generator, capable of creating scripts from specifications. |
package the config file at the given path with a config template and file. | Given the following Python 3 function, write the documentation
def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params):
config_fns = []
template_fns = rglob(path, template)
for template_fn in template_fns:
config_template = ConfigTemplate(fn=template_... | As a python code expert, you are capable of creating scripts from specifications. |
def write(self, fn=None, sorted=False, wait=0):
"""write the contents of this config to fn or its __filename__.
"""
config = ConfigParser(interpolation=None)
if sorted==True: keys.sort()
for key in self.__dict__.get('ordered_keys') or self.keys():
config[key] = ... | Write a Python 3 script for
writing the contents of this config to fn or its __filename__. | You are a Python code architect, reviewing and designing scalable and efficient code |
returns a list of params that this ConfigTemplate expects to receive | Given the following Python 3 function, write the documentation
def expected_param_keys(self):
expected_keys = []
r = re.compile('%\(([^\)]+)\)s')
for block in self.keys():
for key in self[block].keys():
s = self[block][key]
if type(s)!=str: conti... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a Config object with the given params formatted via str. format | Can you generate the documentation for the following Python 3 function
def render(self, fn=None, prompt=False, **params):
from getpass import getpass
expected_keys = self.expected_param_keys()
compiled_params = Dict(**params)
for key in expected_keys:
if key not in compi... | As a Python code composer, you craft elegant and concise scripts. |
def main():
"""Takes a crash id, pulls down data from Socorro, generates signature data"""
parser = argparse.ArgumentParser(
formatter_class=WrappedTextHelpFormatter,
description=DESCRIPTION
)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store... | Can you create a Python 3 function that
takes a crash id pulls down data from Socorro generates signature data | As a python code expert, you are capable of creating scripts from specifications. |
def _fill_text(self, text, width, indent):
"""Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs.
"""
parts = text.split('\n\n')
for i, part in enumerate(parts):
# Check to see if it's a bulleted list--if so, then... | How would you code a function in Python 3 to
wrap text like HelpFormatter but doesn t squash lines. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a dict of services by name | Can you tell what is the following Python 3 function doing
def get_api_services_by_name(self):
if not self.services_by_name:
self.services_by_name = dict({s.get('name'): s for s in self.conf
.get("api")
.get("service... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_api_endpoints(self, apiname):
"""Returns the API endpoints"""
try:
return self.services_by_name\
.get(apiname)\
.get("endpoints")\
.copy()
except AttributeError:
raise Exception(f"Couldn't find the API en... | Can you write a function in Python 3 where it
returns the API endpoints for the given API name | As a Python code composer, you craft elegant and concise scripts. |
def get_ws_subscriptions(self, apiname):
"""Returns the websocket subscriptions"""
try:
return self.services_by_name\
.get(apiname)\
.get("subscriptions")\
.copy()
except AttributeError:
raise Exception(f"Couldn'... | How would you implement a function in Python 3 that
returns the websocket subscriptions for the given application | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_api(self, name=None):
"""Returns the API configuration"""
if name is None:
try:
return self.conf.get("api").copy()
except: # NOQA
raise Exception(f"Couldn't find the API configuration") | Can you create a Python 3 function that
returns the API configuration | You are a Python code generator, capable of creating scripts from specifications. |
def get_api_service(self, name=None):
"""Returns the specific service config definition"""
try:
svc = self.services_by_name.get(name, None)
if svc is None:
raise ValueError(f"Couldn't find the API service configuration")
return svc
except: # N... | Can you write a function in Python 3 where it
returns the specific API service configuration definition | You are a Python code generator, capable of creating scripts from specifications. |
Return a string corresponding to the exception type. | Can you generate a brief explanation for the following Python 3 code
def _ex_type_str(exobj):
regexp = re.compile(r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>")
exc_type = str(exobj)
if regexp.match(exc_type):
exc_type = regexp.match(exc_type).groups()[0]
exc_type = exc_type[11:] if exc_type.... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _unicode_to_ascii(obj): # pragma: no cover
"""Convert to ASCII."""
# pylint: disable=E0602,R1717
if isinstance(obj, dict):
return dict(
[
(_unicode_to_ascii(key), _unicode_to_ascii(value))
for key, value in obj.items()
]
)
if i... | Can you create a Python 3 function that
converts unicode to ASCII. | You are a Python code generator, capable of creating scripts from specifications. |
def send_result(self, return_code, output, service_description='', specific_servers=None):
'''
Send results
'''
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.servers).intersection(specific_servers)
... | Can you create a Python 3 function that
sends results to specific servers | As a Python code analyst, you investigate and solve complex coding mysteries |
Get remote hosts from Selenium Grid Hub Console
| Here you have a function in Python 3, explain what it does
def get_remote_executors(hub_ip, port = 4444):
''' Get remote hosts from Selenium Grid Hub Console
@param hub_ip: hub ip of selenium grid hub
@param port: hub port of selenium grid hub
'''
resp = requests.get("http:/... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate remote driver with desired capabilities and command executor | How would you explain what the following Python 3 function does
def gen_remote_driver(executor, capabilities):
''' Generate remote drivers with desired capabilities(self.__caps) and command_executor
@param executor: command executor for selenium remote driver
@param capabilities: A dictionary... | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate localhost drivers with desired capabilities. | Here you have a function in Python 3, explain what it does
def gen_local_driver(browser, capabilities):
''' Generate localhost drivers with desired capabilities(self.__caps)
@param browser: firefox or chrome
@param capabilities: A dictionary of capabilities to request when starting the brow... | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculate total energy production. Not rounded | Given the following Python 3 function, write the documentation
def _production(self):
return self._nuclear + self._diesel + self._gas + self._wind + self._combined + self._vapor + self._solar + self._hydraulic + self._carbon + self._waste + self._other | As a python code expert, you are capable of creating scripts from specifications. |
Calculate total energy production. Not Rounded | Can you generate the documentation for the following Python 3 function
def _links(self):
total = 0.0
for value in self.link.values():
total += value
return total | As a python code expert, you are capable of creating scripts from specifications. |
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer i... | Can you create a Python 3 function that
asks a yes or no question via raw_input and return their answer. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a string representation of the current object. | How would you explain what the following Python 3 function does
def wall_of_name(self):
'''
Appends identifiers for the different databases (such as Entrez id's)
and returns them. Uses the CrossRef class below.
'''
names = []
if self.standard_name:
names.appen... | You are a Python code generator, capable of creating scripts from specifications. |
def save(self, *args, **kwargs):
"""
Override save() method to make sure that standard_name and
systematic_name won't be null or empty, or consist of only space
characters (such as space, tab, new line, etc).
"""
empty_std_name = False
if not self.standard_name or... | Can you create a Python 3 function that
overrides save method to make sure that standard_name and systematic_name aren t empty. | You are a Python code analyst, evaluating scripts for potential improvements. |
def save(self, *args, **kwargs):
"""
Extends save() method of Django models to check that the database name
is not left blank.
Note: 'blank=False' is only checked at a form-validation-stage. A test
using Fixtureless that tries to randomly create a CrossRefDB with an
empty... | Write a Python 3 function for
extending save method to check that the database name is not left blank. | As a Python code composer, you craft elegant and concise scripts. |
def makeProducer(self, request, fileForReading):
"""
Make a L{StaticProducer} that will produce the body of this response.
This method will also set the response code and Content-* headers.
@param request: The L{Request} object.
@param fileForReading: The file object containing... | Can you write a function in Python 3 where it
makes a L{StaticProducer} that will produce the body of this response. This method will also set the response code and Content-* headers. @param request: The L{Request} object. @param fileForReading: The file object containing the resource. @return: A L{StaticProducer}. Cal... | As a Python code composer, you craft elegant and concise scripts. |
Render a GET request. | Can you generate the documentation for the following Python 3 function
def render_GET(self, request):
request.setHeader(b'accept-ranges', b'bytes')
producer = self.makeProducer(request, self.fileObject)
if request.method == b'HEAD':
return b''
def done(ign):
pr... | As a Python code composer, you craft elegant and concise scripts. |
def interface(self, context):
"""Implement the interface for the adapter object"""
self.context = context
self.callback = self.context.get("callback") | How would you implement a function in Python 3 that
implements the interface for the adapter object | You are a Python code generator, capable of creating scripts from specifications. |
Executed on shutdown of application | Can you generate a brief explanation for the following Python 3 code
def shutdown(self):
self.stopped.set()
if hasattr(self.api, "shutdown"):
self.api.shutdown()
for thread in self.thread.values():
thread.join() | As a python code expert, you are capable of creating scripts from specifications. |
Returns the first element with controls | Make a summary of the following Python 3 code
def _element(cls):
''' find the element with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
driver = Web.driver
try:
elements = WebD... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _elements(cls):
''' find the elements with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
driver = Web.driver
try:
elements = WebDriverWait(driver, cls.__control["timeout"]).... | Write a Python 3 function that can
get the elements with controls | As a Python code analyst, you investigate and solve complex coding mysteries |
set dynamic value from the string data of response
| How would you explain what the following Python 3 function does
def DyStrData(cls, name, regx, index = 0):
''' set dynamic value from the string data of response
@param name: glob parameter name
@param regx: re._pattern_type
e.g.
DyStrData("a",re.compile('123'))
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def DyJsonData(cls,name, sequence):
''' set dynamic value from the json data of response
@note: 获取innerHTML json的数据 如, <html><body>{ "code": 1,"desc": "成功"}</body></html>
@param name: glob parameter name
@param sequence: sequence for the json
e.g.
result=... | Can you write a function in Python 3 where it
sets dynamic value from the json data of response | As a python code expert, you are capable of creating scripts from specifications. |
def VerifyURL(cls, url):
""" 获取当前页面的url """
if Web.driver.current_url == url:
return True
else:
print("VerifyURL: %s" % Web.driver.current_url)
return False | Create a Python 3 function for
verifying that the URL is the same as the current URL. | You are a Python code analyst, evaluating scripts for potential improvements. |
def SelectByIndex(cls, index):
''' 通过索引,选择下拉框选项,
@param index: 下拉框 索引
'''
try:
Select(cls._element()).select_by_index(int(index))
except:
return False | Implement a function in Python 3 to
select a specific entry in the list. | As a Python code analyst, you investigate and solve complex coding mysteries |
De - selects the object by index. | Explain what the following Python 3 code does
def DeSelectByIndex(cls, index):
''' 通过索引,取消选择下拉框选项,
@param index: 下拉框 索引
'''
try:
Select(cls._element()).deselect_by_index(int(index))
except:
return False | As a python code expert, you are capable of creating scripts from specifications. |
1. 0. 0 次 | Make a summary of the following Python 3 code
def Click(cls):
''' 左键 点击 1次 '''
element= cls._element()
action = ActionChains(Web.driver)
action.click(element)
action.perform() | You are a Python code architect, reviewing and designing scalable and efficient code |
Double Click 击 2次 | Make a summary of the following Python 3 code
def DoubleClick(cls):
''' 左键点击2次 '''
element = cls._element()
action = ActionChains(Web.driver)
action.double_click(element)
action.perform() | You are a Python code generator, capable of creating scripts from specifications. |
def EnhancedClick(cls):
'''
Description:
Sometimes, one click on the element doesn't work. So wait more time, then click again and again.
Risk:
It may operate more than one click operations.
'''
element = cls._element()
for _ in r... | How would you code a function in Python 3 to
enhance click on the element. | You are a Python code analyst, evaluating scripts for potential improvements. |
Focuses the current page. | Given the following Python 3 function, write the documentation
def Focus(cls):
element = cls._element()
# element.send_keys(Keys.NULL)
action = ActionChains(Web.driver)
action.send_keys_to_element(element, Keys.NULL)
action.perform() | As a Python code composer, you craft elegant and concise scripts. |
Upload a file to the named user. | How would you explain what the following Python 3 function does
def Upload(cls, filename):
raise Exception("to do")
TOOLS_PATH = ""
RESOURCE_PATH = ""
tool_4path = os.path.join(TOOLS_PATH, "upload.exe")
file_4path = os.path.join(RESOURCE_PATH, filename)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Updates the Dict with the given values. Turns internal dicts into Dicts. | Can you generate the documentation for the following Python 3 function
def update(xCqNck7t, **kwargs):
def dict_list_val(inlist):
l = []
for i in inlist:
if type(i)==dict:
l.append(Dict(**i))
elif type(i)==list:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
sort the keys before returning them | Given the following Python 3 function, write the documentation
def keys(self, key=None, reverse=False):
ks = sorted(list(dict.keys(self)), key=key, reverse=reverse)
return ks | You are a Python code analyst, evaluating scripts for potential improvements. |
java - jar selenium - server. jar - role hub - port 4444 | Given the following Python 3 function, write the documentation
def hub(self, port):
''' java -jar selenium-server.jar -role hub -port 4444
@param port: listen port of selenium hub
'''
self._ip = "localhost"
self._port = port
self.command = [self._conf["java_path"... | You are a Python code generator, capable of creating scripts from specifications. |
create a new node and add it to the list of nodes | Given the following Python 3 function, write the documentation
def node(self,port, hub_address=("localhost", 4444)):
''' java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/
@param port: listen port of selenium node
@param hub_address: hub address whi... | As a Python code composer, you craft elegant and concise scripts. |
def start_server(self):
"""start the selenium Remote Server."""
self.__subp = subprocess.Popen(self.command)
#print("\tselenium jar pid[%s] is running." %self.__subp.pid)
time.sleep(2) | How would you code a function in Python 3 to
start the selenium Remote Server. | You are a Python code generator, capable of creating scripts from specifications. |
def is_runnnig(self):
"""Determine whether hub server is running
:return:True or False
"""
resp = None
try:
resp = requests.get("http://%s:%s" %(self._ip, self._port))
if resp.status_code == 200:
return True
else:
... | How would you implement a function in Python 3 that
determines whether hub server is running | As a python code expert, you are capable of creating scripts from specifications. |
Implements two s complement negation. | Can you tell what is the following Python 3 function doing
def negate_gate(wordlen, input='x', output='~x'):
neg = bitwise_negate(wordlen, input, "tmp")
inc = inc_gate(wordlen, "tmp", output)
return neg >> inc | As a python code expert, you are capable of creating scripts from specifications. |
def kmodels(wordlen: int, k: int, input=None, output=None):
"""Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Ch... | Write a Python 3 script to
return a circuit taking a wordlen bitvector where only k - models return True. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def auth(self):
"""
tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the
configuration file.
"""
username = self._settings["username"]
if not username:
raise ValueError("Use... | Can you write a function in Python 3 where it
returns username and password. | You are a Python code analyst, evaluating scripts for potential improvements. |
def load(self, file=CONFIG_FILE):
"""
load a configuration file. loads default config if file is not found
"""
if not os.path.exists(file):
print("Config file was not found under %s. Default file has been created" % CONFIG_FILE)
self._settings = yaml.load(DEFAULT_... | Can you write a function in Python 3 where it
loads a configuration file. | As a Python code composer, you craft elegant and concise scripts. |
Save the current configuration to a file. | Can you generate the documentation for the following Python 3 function
def save(self, file=CONFIG_FILE):
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "w") as f:
yaml.dump(self._settings, f, Dumper=yaml.RoundTripDumper, width=float("inf")) | As a Python code composer, you craft elegant and concise scripts. |
def selection_dialog(self, courses):
"""
opens a curses/picker based interface to select courses that should be downloaded.
"""
selected = list(filter(lambda x: x.course.id in self._settings["selected_courses"], courses))
selection = Picker(
title="Select courses to d... | Write a Python 3 script to
open a curses picker based interface to select courses that should be downloaded. | You are a Python code generator, capable of creating scripts from specifications. |
def create(self):
"""Create the corresponding index. Will overwrite existing indexes of the same name."""
body = dict()
if self.mapping is not None:
body['mappings'] = self.mapping
if self.settings is not None:
body['settings'] = self.settings
else:
... | Create a Python 3 function for
creating the corresponding index. Will overwrite existing indexes of the same name. | You are a Python code analyst, evaluating scripts for potential improvements. |
def search(self, query=None, size=100, unpack=True):
"""Search the index with a query.
Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned.
The default number of hits returned is 100.
"""
logging.in... | Write a Python 3 script for
searching the index with a query. | You are a Python code architect, reviewing and designing scalable and efficient code |
Scan the index with the query and return all the documents with metadata. | Given the following Python 3 function, write the documentation
def scan_index(self, query: Union[Dict[str, str], None] = None) -> List[Dict[str, str]]:
if query is None:
query = self.match_all
logging.info('Download all documents from index %s with query %s.', self.index, query)
resu... | As a python code expert, you are capable of creating scripts from specifications. |
def scroll(self, query=None, scroll='5m', size=100, unpack=True):
"""Scroll an index with the specified search query.
Works as a generator. Will yield `size` results per iteration until all hits are returned.
"""
query = self.match_all if query is None else query
response = self... | Can you create a Python 3 function that
scrolls an index with the specified search query. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get(self, identifier):
"""Fetch document by _id.
Returns None if it is not found. (Will log a warning if not found as well. Should not be used
to search an id.)"""
logging.info('Download document with id ' + str(identifier) + '.')
try:
record = self.instance.get(... | Implement a Python 3 function for
fetching a single record by _id. | As a Python code composer, you craft elegant and concise scripts. |
def index_into(self, document, id) -> bool:
"""Index a single document into the index."""
try:
self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id)
except RequestError as ex:
logging.error(ex)
retu... | Write a Python 3 function that can
index a single document into the index. | You are a Python code architect, reviewing and designing scalable and efficient code |
Delete a document with id. | Can you generate the documentation for the following Python 3 function
def delete(self, doc_id: str) -> bool:
try:
self.instance.delete(self.index, self.doc_type, doc_id)
except RequestError as ex:
logging.error(ex)
return False
else:
return True | As a python code expert, you are capable of creating scripts from specifications. |
def script_update(self, script: str, params: Union[dict, None], doc_id: str):
"""Uses painless script to update a document.
See documentation for more information.
"""
body = {
'script': {
'source': script,
'lang': 'painless'
}
... | Write a Python 3 function for
using painless script to update a document. | As a Python code composer, you craft elegant and concise scripts. |
def bulk(self, data: List[Dict[str, str]], identifier_key: str, op_type='index', upsert=False, keep_id_key=False) -> bool:
"""
Takes a list of dictionaries and an identifier key and indexes everything into this index.
:param data: List of dictionaries containing the data to be indexe... | Write a Python 3 function for
bulking index the data in the specified index. | You are a Python code generator, capable of creating scripts from specifications. |
Reindex the entire index. | Here you have a function in Python 3, explain what it does
def reindex(self, new_index_name: str, identifier_key: str, **kwargs) -> 'ElasticIndex':
if 'url' not in kwargs:
kwargs['url'] = self.url
if 'doc_type' not in kwargs:
kwargs['doc_type'] = self.doc_type
if 'mapping... | As a Python code composer, you craft elegant and concise scripts. |
def dump(self, path: str, file_name: str = "", **kwargs: dict):
"""
Dumps the entire index into a json file.
:param path: The path to directory where the dump should be stored.
:param file_name: Name of the file the dump should be stored in. If empty the index name is used.
:pa... | Can you write a function in Python 3 where it
dumps the entire index into a json file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def main():
"""
parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon
"""
(options, _) = _parse_args()
if options.change_password:
c.keyring_set_password(c["username"])
sys.exit(0)
if options.select:
courses... | Can you implement a function in Python 3 that
parses command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon | You are a Python code analyst, evaluating scripts for potential improvements. |
Takes data and returns a result object | Can you generate the documentation for the following Python 3 function
def generate(self, signature_data):
result = Result()
for rule in self.pipeline:
rule_name = rule.__class__.__name__
try:
if rule.predicate(signature_data, result):
rule.a... | You are a Python code generator, capable of creating scripts from specifications. |
Helper function to expand BLAST str - > int map into str - > bool map. This function is used to send word level inputs to aiger. | Can you generate a brief explanation for the following Python 3 code
def _blast(bvname2vals, name_map):
if len(name_map) == 0:
return dict()
return fn.merge(*(dict(zip(names, bvname2vals[bvname]))
for bvname, names in name_map)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_logger(self):
"""Generates a logger instance from the singleton"""
name = "bors"
if hasattr(self, "name"):
name = self.name
self.log = logging.getLogger(name)
try:
lvl = self.conf.get_log_level()
except AttributeError:
lvl =... | Write a Python 3 function that can
generate a logger instance from the singleton | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_cls(project_name, project_data):
"""
gets class from name and data, sets base level attrs
defaults to facsimile.base.Facsimile
"""
if project_name:
cls = getattr(facsimile.base, project_data.get('class', 'Facsimile'))
cls.name = project_name
else:
cls = facsimile.... | Can you implement a function in Python 3 that
gets class from name and data sets base level attrs defaults to facsimile. base. Facsimile | As a Python code analyst, you investigate and solve complex coding mysteries |
Chech that the entered recaptcha data is correct | Can you tell what is the following Python 3 function doing
def check_recaptcha(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Send a request to the specified endpoint and return the response. | Here you have a function in Python 3, explain what it does
def request(self, endpoint, method="GET", params=None):
# In case they want to pass a full Safecast URL
# i.e. https://api.safecast.org/measurements.json
if endpoint.startswith("http"):
url = endpoint
else:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def post_list(self, request, **kwargs):
"""
(Copied from implementation in
https://github.com/greenelab/adage-server/blob/master/adage/analyze/api.py)
Handle an incoming POST as a GET to work around URI length limitations
"""
# The convert_post_to_VERB() technique is bor... | Implement a Python 3 function for
handling a POST request to get the list of the available resources. | You are a Python code analyst, evaluating scripts for potential improvements. |
def execute(self, context):
"""Execute the strategies on the given context"""
for ware in self.middleware:
ware.premessage(context)
context = ware.bind(context)
ware.postmessage(context)
return context | How would you implement a function in Python 3 that
executes the strategies on the given context | As a python code expert, you are capable of creating scripts from specifications. |
Perform cleanup! We re goin down!!! | Given the following Python 3 function, write the documentation
def shutdown(self):
for ware in self.middleware:
ware.preshutdown()
self._shutdown()
ware.postshutdown() | As a Python code analyst, you investigate and solve complex coding mysteries |
def main(argv=None):
"""Generates documentation for signature generation pipeline"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'pipeline',
help='Python dotted path to rules pipeline to document'
)
parser.add_argument('output', help='output file')
... | Write a Python 3 function for
generating documentation for signature generation pipeline | You are a Python code architect, reviewing and designing scalable and efficient code |
This function is called by the django API to specify how this object is saved to the database. It will create an organism object and update it with the passed parameters. | Can you generate a brief explanation for the following Python 3 code
def handle(self, *args, **options):
taxonomy_id = options['taxonomy_id']
# Remove leading and trailing blank characters in "common_name"
# and "scientific_name
common_name = options['common_name'].strip()
scien... | You are a Python code generator, capable of creating scripts from specifications. |
def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False):
"""Creates a window of given resolution.
:param resolution: the resolution of the windows as (width, height) in
pixels
:type resolution: tuple
:param pygame_flags: modify the creation of the window.
For fu... | Can you write a function in Python 3 where it
creates a window of given resolution. | As a Python code composer, you craft elegant and concise scripts. |
def display(surface):
"""Displays a pygame.Surface in the window.
in pygame the window is represented through a surface, on which you can draw
as on any other pygame.Surface. A refernce to to the screen can be optained
via the :py:func:`pygame.display.get_surface` function. To display the
conte... | How would you implement a function in Python 3 that
displays a pygame. Surface in the window. | You are a Python code generator, capable of creating scripts from specifications. |
def empty_surface(fill_color, size=None):
"""Returns an empty surface filled with fill_color.
:param fill_color: color to fill the surface with
:type fill_color: pygame.Color
:param size: the size of the new surface, if None its created
to be the same size as the screen
:type size: int-2-t... | Can you implement a function in Python 3 that
returns an empty surface filled with fill_color. | You are a Python code architect, reviewing and designing scalable and efficient code |
This method processes a unicode character in a string and returns a new string. | Here you have a function in Python 3, explain what it does
def process_char(buffer: str, char: str, mappings=_char_mappings):
if char in mappings:
return buffer + mappings[char]
elif char == "\u0008":
return buffer[:-1] if len(buffer) > 0 else buffer
else:
return buffer + char | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.